diff --git a/AGENTS.md b/AGENTS.md index f178c0a15f..3fbd8d1e6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ The first four ship per-language today across the five ports (TS / C# / Java / P ## Status -_Last refreshed 2026-10-30._ +_Last refreshed 2026-11-17._ **1.0 gating — the quiet period is RETIRED (2026-09-06).** `docs/1.0-readiness.md` §G3 no longer asks for "one coordinated release with no metamodel-breaking change." It measured a @@ -39,14 +39,16 @@ because a conformance corpus gates the ports against each other and never agains in ADR-0035 **Amendment 3**. Do not reintroduce a waiting gate in any form. -**Where the versions are.** `latest` is **`1.2.0`** on npm, **`8.2.0`** on Maven Central, -**`1.2.0`** on PyPI and **`1.2.0`** on NuGet (the Maven major is always **npm major + 7**, so -1.2.0 is 8.2.0). **1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4 and 1.2.0 are released.** 1.0.13 is the last 1.0.x release; the four registries moved together on 1.0.13, 1.0.12, 1.0.11, 1.0.10 and 1.0.9 (Maven skipped 8.0.8), and earlier Maven alone took 1.0.6 (8.0.6) while the other three skipped that +**Where the versions are.** `latest` is **`1.2.3`** on npm, **`8.2.3`** on Maven Central, +**`1.2.3`** on PyPI and **`1.2.3`** on NuGet (the Maven major is always **npm major + 7**, so +1.2.3 is 8.2.3). **1.1.0 through 1.2.0, 1.2.1 (Python only), 1.2.2 and 1.2.3 are released.** +`CHANGELOG.md` carries a dated **[1.3.0]** section, but no registry has published it yet (the +npm publish prep is still open); and the 1.2.x line has `1.2.4-rc.N` candidates cut. 1.0.13 is the last 1.0.x release; the four registries moved together on 1.0.13, 1.0.12, 1.0.11, 1.0.10 and 1.0.9 (Maven skipped 8.0.8), and earlier Maven alone took 1.0.6 (8.0.6) while the other three skipped that number. Both patterns are the convergent-publishing rule working as intended. **1.0 is CUT** and **1.1 is released**: the 1.0.0-rc candidates through 1.0.13 are superseded, and npm's `next` tag is REPOINTED onto each release — not deleted, because `dist-tag rm` 403s for every token we hold (`docs/RELEASING.md` §4). `metamodelVersion` read **`1.0`** through 1.0.13 — C4 landed and G4 shipped it, and no 1.0.x patch moved it (1.0.4 relaxed `@sourceRefField` onto `@cardinality: one` with a prose-only -manifest footprint, and was ruled a hold). `metamodelVersion` read **`1.1`** from 1.1.0 through 1.1.3 for the FR-044 reporting vocabulary and the requirements slice 1 (the first slice of two, covering existence gates and per-entity coverage). **It reads `1.2` from 1.1.4** for calendar-aligned relative report windows (`startOf` on a relative date). Per-release detail lives in **`CHANGELOG.md`** — it is the log, and this file does +manifest footprint, and was ruled a hold). `metamodelVersion` read **`1.1`** from 1.1.0 through 1.1.3 for the FR-044 reporting vocabulary and the requirements slice 1 (the first slice of two, covering existence gates and per-entity coverage). **It reads `1.2` from 1.1.4** through every published release since, for calendar-aligned relative report windows (`startOf` on a relative date). The merged tree claims **`1.3`** (`METAMODEL_VERSION` in every port) — main's 1.3.0 and the line's 1.2.4 both carry it, and neither is published. Per-release detail lives in **`CHANGELOG.md`** — it is the log, and this file does not duplicate it. The npm surface is **14 `@metaobjectsdev/*` packages in full lockstep**; the two `angular` @@ -72,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (510 fixtures; 42 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (526 fixtures; 42 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. @@ -81,7 +83,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. **Key cross-language features shipped:** FR5 family (a/b/c/d/e + WARN envelope-shape — actionable loader errors per ADR-0009); FR-003 (Java RDB runtime persistence + projections; schema migrations are TS-only — the Java migration engine was removed); FR-006 (template.output parser-on-receipt codegen per ADR-0010 in all 5 ports); FR-008 + FR-009 (cross-port REST API contract + the nine filter operators); FR-018 (M:N relationship codegen in all 5 ports — entity navigation + idiomatic ORM wiring [Drizzle m2m / EF Core `UsingEntity` / Spring repo+JPA / Exposed / Pydantic+route as the SQLAlchemy-secondary equivalent] + REST traversal `GET //{id}/` + Tier-2 docs, gated by the shared api-contract m2m corpus in both lanes + persistence-conformance; the TanStack M:N client hook is a deferred client-ergonomics follow-up); SP-H (field-subtype end-to-end hardening: every concrete `field.*` subtype write+read round-trips cross-port via the persistence `op: roundtrip` gate; cut `field.byte`/`field.short`/`field.class` non-functional stubs; cross-port filter-op reconciliation for uuid/currency); source v2 paradigm (ADR-0007); metadata-ktx Kotlin facade; per-target output directories (TS codegen); FR-044 (the reporting vocabulary — `dimension.attribute`/`dimension.time`, `measure.aggregate`/`measure.ratio`, `segment.filter`, `object.report`, `@spine` on a report to take rows from a to-one dimension entity, `@default` on a measure for empty aggregates, plus the relative-date filter value — registered and loader-validated in all five ports; a report that declares a read-only `source.rdb @kind: view` is lowered to a SQL view by `meta migrate` and read by every port, and served by a generated read-only list route in every port, gated by the api-contract `report/` sub-corpus; the TypeScript `cube-model` reference generator writes the vocabulary as Cube data-model files, gated by the `fixtures/cube-model/` corpus and a `cube` lane that loads the output into a real Cube; a served report gets the generated TanStack list hook (`use`, or `useList` when the plural is the name) but no grid or form, see [docs/features/reporting.md](docs/features/reporting.md) and [docs/features/cube-export.md](docs/features/cube-export.md)). -**Release 1.1.0** (released; npm `1.1.0`, PyPI `1.1.0`, NuGet `1.1.0` and Maven Central `8.1.0`; the latest is 1.2.0 / 8.2.0). The reporting release (FR-044): declare dimensions, measures, segments and an `object.report`, and get a SQL view, a served read-only list route in every port, a generated TanStack list hook, and a Cube data model, with `@spine` for rows that have no facts and `@default` for an empty measure. Also carries the first slice of requirements (the gate in every port's `verify`), the derived-key parity fix across the ports, and the list-hook and nested-average fixes found by the first adopter. See the `CHANGELOG.md` 1.1.0 section for the full scope, pre-release RC history, and the diffs to expect when you upgrade (ejected generators and keyless projections). It also makes documentation a set of generators in every port (ADR-0034 Amendment 9): the docs commands are removed, and `docs/features/migrations/docs-are-generators.md` is the upgrade path. The last 1.0.x release, 1.0.13 (2026-10-03), was a PATCH on 1.0.x. +**Release 1.1.0** (released; npm `1.1.0`, PyPI `1.1.0`, NuGet `1.1.0` and Maven Central `8.1.0`; the latest is 1.2.3 / 8.2.3). The reporting release (FR-044): declare dimensions, measures, segments and an `object.report`, and get a SQL view, a served read-only list route in every port, a generated TanStack list hook, and a Cube data model, with `@spine` for rows that have no facts and `@default` for an empty measure. Also carries the first slice of requirements (the gate in every port's `verify`), the derived-key parity fix across the ports, and the list-hook and nested-average fixes found by the first adopter. See the `CHANGELOG.md` 1.1.0 section for the full scope, pre-release RC history, and the diffs to expect when you upgrade (ejected generators and keyless projections). It also makes documentation a set of generators in every port (ADR-0034 Amendment 9): the docs commands are removed, and `docs/features/migrations/docs-are-generators.md` is the upgrade path. The last 1.0.x release, 1.0.13 (2026-10-03), was a PATCH on 1.0.x. Active and planned work lives in GitHub: issues labelled `FR`, milestones for releases, and the MetaObjects Roadmap project board. `spec/roadmap.md` keeps the release direction and the FR → issue → spec index. Process: `docs/ROADMAP-PROCESS.md`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ce0d232df..2667ad5c34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,14 +41,20 @@ here.** ## [1.3.0] — 2026-11-17 + _npm `1.3.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ **`metamodelVersion` moves to `1.3`.** This release adds vocabulary (`field.duration`, `validator.exactlyOne`, `@constraintName`, `@condition`, `@maxLength` on `field.enum`, `@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule, `@collectionName`, `measure.derived` and its `@expr` arithmetic, the `case` and `now` -expression nodes, `@segment` on `origin.first` / `origin.aggregate`, and the `isDistinctFrom` / `isNotDistinctFrom` filter ops) and no metadata that -loaded before stops loading; the generated and runtime behavior changes are under "Upgrading from 1.2.0" +expression nodes, `@segment` on `origin.first` / `origin.aggregate`, the `isDistinctFrom` / `isNotDistinctFrom` filter ops, +`@dbCheck`, `@stringValueMap`, and the view vocabulary a projection needs to replace a hand-written +`@sql` view: `origin.function`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`, the text +`@dbColumnType` spellings, and the `cast` node and function set of `attr.expression`) and no metadata that +loaded before stops loading (one exception: a cross-field `@condition` that used `case`, `now` or +another view-only expression node, which no CHECK emitter could render and `meta migrate` threw on, +is now refused at load); the generated and runtime behavior changes are under "Upgrading from 1.2.0" below. The registry gains two fields on a type or attr entry, carried into the registry manifest: `implementedIn` (cross-port vocabulary only the named ports implement so far, e.g. the `view.*` controls, `["typescript"]`) and @@ -57,6 +63,14 @@ the JVM runtime both share acts on it). The manifest's row set grows by the `implementedIn` rows that used to be carved out. A port that reports `1.2` does not know that vocabulary; upgrade every port together. +**One release carries both lines of work.** This is the 1.3.0 that was cut from `main` together with +everything on the `1.2.x` release line since 1.2.0 that 1.2.2 and 1.2.3 did not ship (its work was +prepared as `1.2.4` release candidates; there is no 1.2.4). Where the two lines differ, the released +`main` behavior stands: the default generated layout stays flat (`outputLayout: "package"` is the +opt-in, in every port that has the key), and `@dbSetName` is `@collectionName`. The registry manifest +(`fixtures/registry-conformance/expected-registry.json`) is the union of both lines' vocabulary under +the one `metamodelVersion` value, `1.3`. + ### Upgrading from 1.2.0 Each item below is described in full under Security, Added, Changed or Fixed; this list is where to start. @@ -159,6 +173,37 @@ Each item below is described in full under Security, Added, Changed or Fixed; th line, carried forward. Adopters with ejected (owned) generators need the same change made by hand. +- **Fix, C#: a credential could be returned in every response under a snake or kebab JSON naming + policy, and under a property-naming rename (rc.22).** The generated routes omitted a credential + (`view.password` field) from a body by comparing the serialized key to the field name, ignoring + case. An entity property's key is the host's naming policy applied to the property name, so under + `JsonNamingPolicy.SnakeCaseLower`, `SnakeCaseUpper`, `KebabCaseLower` or `KebabCaseUpper` a + multi-word credential (`pinHash` serialized as `pin_hash`) was sent in every read, list, create, + update (PATCH and PUT) and M:N response. **This leak exists in the released 1.2.x** with no + property-naming resolver at all; a resolver rename beyond case (`pinHash` spelled `Secret`) leaked + the same way under any policy. Only single-word credentials, or a host with the default + camelCase policy and no rename, were safe. 1.3.0 fixes it: the omit list and the PATCH and PUT + key lookup read the key from the serializer's own contract (`JsonSerializerOptions.GetTypeInfo`), + so a naming policy, a rename or an attribute cannot escape them. Stripping **fails closed**: when + the contract cannot be read (a custom converter for the row type, a custom type-info resolver or a + modifier that leaves a property without its reflection member, a contract that lacks the + credential), the generated route mapping throws at startup, and a response that reaches + `CredentialOmittingResult` anyway is refused with an exception naming the type and the credential + property (never a value), instead of being sent unstripped. A key that spells the credential + ignoring case, `_` and `-` is also removed. A host that sets a custom `TypeInfoResolver` or a + source-generated `JsonSerializerContext` must give the entity properties their reflection member + (the default reflection resolver does), or the app will not start. The write side of the released + 1.2.0, 1.2.2 and 1.2.3 was not exploitable: a PATCH or PUT body key that missed the deny list also missed + the property and was dropped. **In 1.2.3-rc.1** (the first release with `GenConfig.PropertyNaming`), + a rename beyond case let `PATCH {"secret":"x"}` or `PUT` write a credential or a `@formExclude` + field, because the deny arm matched the field name only and the generic lookup found the renamed + property case-insensitively; 1.3.0 closes that too. Regenerate every project whose host sets a + snake or kebab policy or `GenConfig.PropertyNaming`; a project on the default policy with no + rename is unaffected. **Known limit, not fixed here:** a credential (`view.password`) declared on a + value-object member is not listed, checked or stripped. Only an entity's top-level fields are + treated as credentials, and stripping does not recurse into nested objects. Declare credentials + as top-level entity fields until that is fixed. + ### Added - **A working loop first in the agent context.** The always-on file `meta init` scaffolds @@ -844,6 +889,135 @@ Each item below is described in full under Security, Added, Changed or Fixed; th `email-text/` each drift one part of a `WelcomeEmail`, and every port's runner checks that the subject, the html body and the text body each raise. No generated code changes. +- **The rc.21 view vocabulary: what a projection needs to replace a hand-written `@sql` view.** + Every construct is closed and typed, never free SQL; the TypeScript view emitter lowers them on + Postgres and SQLite (SQLite spells each with its own functions, or refuses what it cannot mean), + C# validates them at load with the TypeScript rules, and Java and Python register them so a + strict load accepts them. In `attr.expression`: `{ cast: , as: , + dbColumnType? }` (an enum casts to an integer only when stored as one, `@intValueMap`, which is + how an int-stored enum and an int share a `case`); the functions `greatest`, `least`, `nullif`, + `lower`, `upper`, `btrim`, `splitPart`, `concat`, `concatWs`, `substring`, `replace`, `left`, + `right` and `length` beside `coalesce`, each argument typed; a `{ field }` ref to a scalar + `origin.aggregate` (read on the grouped row, not filterable); and, on a projection, a path of + to-one hops (`"customerId.regionId"`) in an expression or as a correlated + `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`, `@params`, + `@returns`) is a value computed by a database function the project owns: each argument's field + type must be its declared parameter type (cast it through an `origin.computed` field otherwise), + `@returns` must be the carrying field's subtype, and the view casts the call to the field's full + column type, the one its table column would have (length or `@dbColumnType` spelling, precision and + scale, a local or zoned timestamp). The signature is a declaration: `meta verify --db` reads each + function from `pg_proc` and fails on a missing function or a parameter or return type that + differs, so the cast never hides a wrong `@returns` (a defaulted parameter may be left out; json, + array, enum and user-defined kinds are not type-checked, and a domain is compared by its name). Declared on an entity it is entity-derived + (Postgres only). On + `object.projection`: `@grain` / `@grainOrdinal`, one row per element of a jsonb `field.object` + array, its members read through `origin.passthrough @from: .`; and + `@union` / `@unionAll`, a view that is the UNION (or UNION ALL) of projections of one shape, + checked at load (enum members and value maps included; a member's own `@union` is refused). A + `@grain` row whose value is not a JSON array (null, an object, a scalar) has no element. A cast + between a boolean and a number exists only for `int`, and the count of `left`, `right`, + `substring` and `splitPart` is an `int`, as in Postgres. `@dbColumnType` takes the text spellings `text`, `varchar`, `character + varying`, `varchar(n)`, `character varying(n)` and `character(n)` on a `field.string` (`meta + migrate`, Drizzle, the C# EF context, the Kotlin Exposed table and the view cast honour them; the Java OMDB runtime binds them as text, and a table OMDB itself creates keeps its VARCHAR or TEXT column; a `@maxLength` over n is + refused), and the registry drops its `allowedValues`. A cross-field `@condition` takes only + the CHECK subset of the grammar (fields, literals, comparisons, null tests, and/or/not, + coalesce), refused at load otherwise. Rulings: the cast names a field subtype, the type + `@convert` casts to, with an optional text spelling; two-word functions are camelCase + (`splitPart`, `concatWs`) and `btrim` keeps Postgres's name; `concat` ignores NULLs, as SQL's + `concat()` does, and there is no separate NULL-propagating `||`; a union defaults to UNION, + SQL's own default. Fixtures `fixtures/conformance/projection-view-vocabulary-rc21` and + `error-origin-function-free-sql`, `error-projection-union-shape`, + `error-projection-grain-not-object-array`, `error-computed-cast-enum-not-int-stored`, + `error-db-column-type-sized-max-length`; the live run is + `integration-tests/test/view-vocabulary-rc21-pg.test.ts`. **Upgrade note:** `meta migrate` now + reads a Postgres `character(n)` column as itself, so a model that declared a plain + `field.string` over one sees a type change until it declares `@dbColumnType: character(n)`. + +- **`@stringValueMap`: a field.enum member's stored string (rc.21).** A string-stored enum may + declare the string each member is stored as, `{ member: string }`, for a legacy column whose + spelling differs from the member symbols (lowercase `draft`, `LEGACY_A`). The generated native + type and the wire keep the members; the column, its CHECK, its length, a `@default` and a + `@condition` or `@equals` literal hold the stored strings. It is the string twin of + `@intValueMap` (attr subtype `properties`): keys must match `@values` exactly, values are + unique non-empty strings, a shared enum declares it on the shared declaration + (`ERR_ENUM_EXTENDS_VALUES_CONFLICT`), and it is refused beside `@intValueMap` and on an array + enum (`ERR_BAD_ATTR_VALUE`; no port maps a text[] element through it). Every port registers + and validates it. It is honoured by the C# EF converter (a per-member chain ending in a + throwing helper, as the int-backed pair) and CHECK; by `meta migrate`, `meta verify --db`, the + Drizzle column (a member/stored-string codec), the TypeScript runtime ObjectManager (write, + read, filter) and the view, report and Cube lowerings; by the Java OMDB codec; by the Kotlin + Exposed table (a VARCHAR `customEnumeration`); by the generated Spring enum (`dbValue()` / + `fromDbValue(String)`, for a hand-written repository, a shared declaration included); and by the + Python ObjectManager. A view-backed report's row carries it from its type source, in every + port. A stored string that maps to no member throws on read, and a member with no stored string + throws on write and in a runtime filter, in every port (the map is total, so only a value outside + `@values` can reach that). Ruling (rc.21 part B, N4): a filter does not pass such a member + through to match nothing, as an `@intValueMap` symbol does, because a passed-through symbol can + equal another member's stored string and match that member's rows; the TypeScript runtime and + Python now refuse it, as the Java OMDB bind and the Drizzle codec already did (C# and Kotlin + have no value outside the enum). `metamodelVersion` stays + `1.3`: the addition lands in the same unreleased minor. Fixtures + `fixtures/conformance/enum-string-value-map` and four `error-enum-stringvaluemap-*`; the shared + CHECK corpus gains `input/meta.stored.json`. + +- **`@dbCheck: false`: a validator or enum with no database CHECK (rc.20).** A CHECK-generating + validator (`numeric`, `length`, `regex`, `comparison`, `requiredWhen`, `presentIff`, + `atLeastOne`) or a `field.enum` takes an optional db-provider boolean `@dbCheck`, default `true`. + With `false` on a `numeric`, `length` or `regex` validator or a `field.enum`, `meta migrate`, + `meta verify --db`, the Prisma schema's CHECKs, the Drizzle schema's enum CHECK and the C# EF + context's declared CHECKs leave that one node's CHECK out; every other CHECK on the table, and `migrate.checks.skipRedundant`, are + unchanged. It is for a column whose legacy rows break a rule: a CHECK added `NOT VALID` still + refuses an UPDATE of such a row. The generated app-level validation is unchanged, so the + validator and an enum's members still hold every write. A cross-field validator is enforced only + by its CHECK, so `@dbCheck: false` on one is refused at load in every port + (`ERR_CROSS_FIELD_WITHOUT_CHECK`; remove the validator instead), and so is `@dbCheck: false` with + `@constraintName` (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`). Fixtures + `fixtures/conformance/validator-db-check`, `error-db-check-constraint-name` and + `error-db-check-cross-field`; the shared CHECK corpus (`fixtures/check-constraint-conformance`) + pins the omissions for TypeScript and C#. **Upgrade note:** a live CHECK whose node now says + `@dbCheck: false` is proposed for dropping by the next `meta migrate` (`--allow drop-check` on + Postgres), and by the next EF migration a C# model scaffolds. + +- **C#: an orphan sweep for a self-hosted runner that makes several runs (G5).** A runner that + calls `CodegenRunner.Run` once per target could not sweep: `SweepOrphans` sweeps one run's + directories, where another run's files look orphaned, and a runner with no `GenStateDir` had no + manifest at all, so a layout change (R39) left the old files behind. `RunResult.EmittedPaths` (new) + holds every path a run emitted; the runner gives each run the same `GenStateDir`, then calls + `OrphanSweep.Sweep` once with the runs' directories and the union of their paths. Only files the + manifest records with a matching hash are deleted, and edited ones are refused by name. New + `Sweep` options: `dryRun`, and `reportUnrecorded`, which lists (never deletes) files carrying + MetaObjects' `Generated by MetaObjects` header that a manifest-less run wrote. The sweep now + compares paths case-insensitively, `meta gen`'s own sweep included, so a case-only rename on + macOS or Windows keeps its file. The default behaviour is otherwise unchanged. + +- **Kind-1 vocabulary: cross-port, implemented in some ports so far (ruling R40).** A registry + type or attr may name the ports that implement it so far (`"implementedIn": ["typescript"]` on + its `spec/metamodel` entry, carried into the registry manifest). It is cross-port vocabulary: + every port registers it and loads it strictly, and a port that has not implemented it ignores + it. The 13 generic `view.*` controls, `view.textarea @rows` and the five `view.image` attrs are + `["typescript"]`; `object.* @object` is `["java"]`. They were carved out of the manifest + (`PRESENTATION_ONLY`, `NATIVE_BINDING`); both carve-outs are gone, and the registry canonical + grows by those rows. `meta types` marks them `[ts; pending elsewhere]` / `[java; pending + elsewhere]` (it used to say `[ts-only]`, "the cross-port contract does not carry it"; its JSON + change is under Changed), and the metamodel docs now cover the view controls. + `@objectAdapter` is kind 2 (`"ports": ["java", "kotlin"]`). C# now registers the + `metaobjects-ui-web` attrs and `@object` / `@objectAdapter`. Java, Kotlin and Python do not yet, + so their registry-conformance and the new `view-kind1-controls` fixture fail there until they + catch up (tracked in `docs/CONFORMANCE.md`). + +- **Port-scoped vocabulary (ruling R40).** A registry attr may name the ports that act on it + (`"ports": ["java", "kotlin"]` on its `spec/metamodel` entry, carried into the registry + manifest). Every port registers and type-checks it, so a model that carries it loads under every + port's strict loader; a port not named does nothing with it. An attr the registry does not carry + still fails, and a wrong value type fails in every port (Java now refuses a list given to a scalar + string attr, as the other ports did). `meta types` marks such an attr `[-only]` + (`[java+kotlin]` for `@objectAdapter`) and its JSON carries `ports`. The first one is + `@objectAdapter`, which the JVM runtime acts on. + +- **C#: `expression-indexes` generator.** The `@expr` indexes EF Core cannot model, written as one + SQL file (`CREATE [UNIQUE] INDEX IF NOT EXISTS`, in the source's `@schema`, with `@using` and + `@where`) to apply after the schema EF builds. C#-only; ejectable. + ### Documentation - **ADR-0015 Amendment 1: EF Core Migrations is a supported second C# path.** `meta migrate` stays @@ -1222,6 +1396,188 @@ Each item below is described in full under Security, Added, Changed or Fixed; th metadata package builds its sandbox under `$DEV_SCRATCH` (the system temp directory when unset) and stops its test runners with it. Contributor steps are in [CONTRIBUTING.md](CONTRIBUTING.md). +- **Behaviour change, C#: with a property rename beyond case, the accepted `?sort=` key is the + resolved property name (rc.22).** The sort allowlist, `@sortableDefaultOrder` keys and the + `EF.Property` names carry the resolved name (EF matches the model's property name, so before + this any rename made a sort return 500). A project with no resolver, or one whose rename differs + only in case, is unchanged (the key is matched case-insensitively). With `ownerRef` spelled + `OwnerKey`, `?sort=ownerRef` becomes `400 invalid_sort` and `?sort=OwnerKey` is accepted. + `?filter[]` keeps the field name. + +- **Behaviour change, C#: a `PropertyName` hook that disagrees with `GenConfig.PropertyNaming` is + refused (rc.22).** `EntityGenerator.PropertyName` and `DbContextGenerator.PropertyName` default to + the resolver and are now `[Obsolete]`. Only the resolver reaches every generator (routes, callable, + extractor, report export, filter map), so an override that names any field differently from it + stops the run with an error naming the field and saying to set `GenConfig.PropertyNaming`. Move + the override's logic into the resolver. An override that agrees with the resolver is unaffected. + +- **Behaviour change: the registry manifest no longer lists `@dbColumnType`'s `allowedValues` + (rc.21).** The sized text spellings (`varchar(n)`, `character varying(n)`, `character(n)`) are no + closed set, so the value is parsed by each port's loader instead (a misspelling is still + `ERR_BAD_ATTR_VALUE` in every port). Tooling that read the enumeration from the manifest (an + editor schema) now sees a free string; the legal spellings are in the attr's description. + +- **Behaviour change, TypeScript and C#: a projection that extends another keeps its super's + identity anchor (rc.21).** An extender that declared no identity of its own took its base from + its own fields' `extends`. So a projection over a TPH root that added a subtype's column moved + its base to that subtype, and its view returned only the subtype's rows. It now keeps the + identity its super anchors with: the base is the TPH base, and the view returns **every** row of + the shared table, the subtype column NULL on the others. A field bound to a TPH relative of the + base reads the shared table's column (it read a column named after the projection field). The + load now warns in exactly the case whose output widened: an extender with no identity of its + own, anchored by its super on a TPH base, whose own fields bind a subtype-only column, and no + `@filter` on the discriminator (an abstract extender emits no view, so it is never warned + about). `meta gen`, `meta migrate`, `meta verify` and `dotnet meta gen` print that warning (the + loader's warning channel is not otherwise printed). **Upgrade note:** to get the subtype-scoped view back, either add + `@filter: { : }` to the extender, or anchor it on the subtype: declare + `identity.primary { name: id, extends: .primary }` with a field extending + `.id`. + +- **C#: the generated EF context declares the CHECKs `meta migrate` creates** (rc.19 item 13, + ruling R55). Every validator that can carry one (`numeric`, `length`, `regex`, and the + cross-field `comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, with `@condition`) and + every scalar `field.enum` is a `ToTable(t => t.HasCheckConstraint(name, sql))` line, with + migrate's names (`__numeric_chk`, …, or `@constraintName`) and migrate's + expression text, so an EF migration and `meta migrate` build the same table. Declared only for + `migrate.dialect` `postgres`, `sqlite` or `d1` (the text is dialect-specific); a self-hosted + runner sets `GenConfig.Dialect`, and `GenConfig.SkipRedundantChecks` follows + `migrate.checks.skipRedundant`. Pinned by the shared corpus + `fixtures/check-constraint-conformance/`, which `meta migrate` passes too. **Upgrade note:** the + next `dotnet ef migrations add` scaffolds an `AddCheckConstraint` for every such CHECK. On a + database `meta migrate` built, they already exist under the same names: empty those operations + from the migration. On a database built some other way, existing rows may violate one; add it + `NOT VALID` and `VALIDATE` it once the data is clean. + +- **C#: each shared enum is its own file, with its integers and its docs** (rc.19 item 12). A + materialized shared enum (a root-level abstract `field.enum`) was one line in a single + `Enums.g.cs`; it is now `/.g.cs`, placed like every other per-object file + (ruling R39), in the same namespace as before (`GenConfig.Namespace`; namespaces are unchanged). + Its members carry their `@intValueMap` integers (`DRAFT = 0, PUBLISHED = 5`), and the + declaration's `@description` and each member's `@enumDoc` become XML doc comments. The EF + conversion still maps member by member, so stored values do not change. **Upgrade note:** the + next `dotnet meta gen` removes `Enums.g.cs` (the orphan sweep) and writes one file per enum; + code that cast an int-mapped shared enum to `int` now gets its mapped integer, not its + position. A nested per-entity enum is unchanged. + +- **Breaking, C#: a value object is never renamed; one claim registry refuses real collisions** + (ruling R52, amending ADR-0044 and ADR-0056). The package-qualified derived name + (`acme::alpha::Note` emitted as `AcmeAlphaNote` when another object shared `Note`) is gone: the + type is `Note`, in its package's namespace. Two objects that emit one type into one namespace + now fail with `ERR_NAME_COLLISION`, naming both and the remedy. Every generator claims each name + as it emits it (`GenContext.Claim(scope, name, claimant, remedy)`): a type per namespace, a + DbSet per context, a route segment per routes entry, a finder per class, an expression index + per schema. An object that emits nothing (abstract, sourceless) claims nothing, and an + adopter's own generator can claim too. `CSharpNaming.AssertUniqueInScope` is removed (`ValueObjectNames.Names` stays as an + `[Obsolete]` identity map, under Deprecated). **Upgrade note:** a model whose value + objects were renamed now gets the collision error; map the packages apart + (`GenConfig.PackageNamespaces`) or rename one object, and update the references to the old + `AcmeAlphaNote`-style names. + +- **C#: a JSON column's comment reaches the database through the design-time differ (ruling + R59).** EF 8's `JsonColumn` carries no comment, so a `field.object` stored as JSON (`ToJson`) + never got its `@description`. The generated model now puts the text — the field's + `@description`, else its value object's — on the owned type as the + `MetaObjects:JsonColumnComment` annotation, and the generated design-time services (emitted for + a Postgres context with an increment key or such a comment) scaffold a change of it as + `COMMENT ON COLUMN … IS …` / `IS NULL`, Up and Down; the snapshot records it. Off Postgres the + run warns and leaves the comment to `meta migrate`. A `field.map` now takes its comment like any + column, and comments are set through `Metadata.GetProperty` (it throws), not `FindProperty?.`. + **Upgrade note:** the next migration scaffolds a comment for each described JSON column and map. + A database built by `EnsureCreated` gets no JSON-column comment (it runs the runtime differ). + +- **C#: `@sequenceName` warns once instead of being silently dropped** (ruling R56): EF never names + an identity's sequence and Npgsql cannot express it; the run names the objects that declare it. + +- **Fix, C#: every `OnModelCreating` entry is one statement** (item 8). The `@using` index method + was emitted as a provider guard and its statement as two entries, so a `ConfigureModelNN` split + could fall between them; the guard and statement are one entry now, and the invariant is + documented on the model-line list. + +- **C#: generated files can be keyed by the metadata package (ruling R39); the default layout stays flat.** + With `csharp.outputLayout: "package"` in `.metaobjects/config.json` (`GenConfig.OutputLayout = + OutputLayout.Package`; `dotnet meta init` writes it for a new project) every per-object generator + (entity, names, filter-allowlist, routes, callable, reverse finders, report export, the extract + mirrors and the template tier) writes `/.g.cs` through one helper, + `OutputPaths.Of` (`acme::alpha::Note` → `acme/alpha/Note.g.cs`); a root-level object, the + context, the shared enums and the run-wide helpers stay at the root. The layout never changes + a namespace (the package binding decides them, `GenConfig.PackageNamespaces`), so two same-named + types in one namespace are still refused by the claim registry. TypeScript's `outputLayout: + "package"` is the same opt-in, and TypeScript's default stays `"flat"`, as in 1.2.0. **Upgrade + note:** none for an existing project: with no `outputLayout`, no generated path moves. Opting in + writes every generated file under its package directory and sweeps the old flat copies; update + any build globs or `` items that named the flat files. Python and the JVM ports follow + in #544–#549 (`docs/CONFORMANCE.md`, "Generated paths keyed by package"). + +- **Breaking, C#: a generated type's namespace is its metadata package (rulings R64, R65).** With + no binding for it, a packaged type's namespace is the package itself, each `::` segment + PascalCased (`acme::alpha` → `Acme.Alpha`), as the Java and Kotlin ports map packages, whether + or not a namespace is configured. `--namespace` / `csharp.namespace` (`GenConfig.Namespace`) now + places only the objects with no package and the artifacts of no single object: the context and + its design-time services, the callable wrappers, the template tier (render helpers, parsers, + extractors, output prompts) and the shared runtime helpers. A per-object companion follows its + object into the package namespace: `Names`, `FilterAllowlist`, `Routes`, `Queries` + (reverse finders), `Export` and a materialized shared enum. Every generated file names every + generated type it reaches in another namespace `global::`-qualified (the context, entities, + value objects, shared enums, names classes, and `System`/`Microsoft` framework types), so no + namespace can capture another (`CS0234`: a package `acme::app::system` derives `Acme.App.System`) + and no two `using`s can make a name ambiguous (`CS0104`); the routes and callable files no + longer carry `using` lines for package namespaces. Two same-named entities or value objects in + two packages are two types with no remedy needed; two objects bound to ONE namespace that share a + name are still refused (`ERR_NAME_COLLISION`). So are two same-named callables, and two + same-named templates (render helper, output parser, output prompt, extractor), in two packages: + the callable wrappers and the template tier stay in the configured namespace whatever their + package, so packages do not keep them apart and a package mapping does not help; rename one (the + refusal says so). `GenConfig.PackageNamespaces`, `TypeOverrides` and `Convention` + win as before, and an explicit `UnmappedStrategy.Error` or `Derive` under a configured namespace + keeps its meaning (the package mapping applies only to the default `Flatten`). A hook override + on `DbContextGenerator` receives the `global::`-qualified type as its `owner` argument + (`global::Acme.Alpha.Note`), which it can splice into `Entity<{owner}>` as before. A `@provided` + enum is the adopter's type and is named as configured, unchanged. **Upgrade note:** on the next + `gen`, every generated type in a package that no `PackageNamespaces`, `TypeOverrides` or + `Convention` entry maps moves once, from the configured namespace to its package's namespace, + together with its routes, reverse finders, names, filter allowlist and report export; update + the `using` lines of the code that names them (an app that mounts `MapRoutes` adds the + entity's package namespace). To keep a package where it was, map it: + `PackageNamespaces = { ["acme::alpha"] = "Acme.Generated" }`. A project whose every package is + already bound (a `Convention`, or `TypeOverrides` for each object) sees no type move, only the + `global::` spelling in the regenerated files. + +- **Fix, C# and TypeScript: a file that meets two same-named types from two packages names each + unambiguously.** C#: the routes (`List` / `Dictionary` deserialization + types), the callable wrapper (its result and its arguments object) and an entity's `field.map` + property named a value object bare under `using`s of both namespaces (`CS0104`); each is now + `global::`-qualified when another object shares the short name, and the routes and callable + classes are claimed in `Config.Namespace`. TypeScript: the callable wrapper imported its + arguments object from `./.js` whatever the layout, and bare — a duplicate identifier when + the result shared its name; it is now imported from its own module under a local alias. Pinned + by the shared corpus `fixtures/codegen-conformance/xpkg-value-object-refs/`. + +- **C#, upgrade note: identity starts never RESTART, and the fix is design-time only** (rulings + R50, R51). A Postgres project's context now carries `identity.primary @sequenceStart` in its + model, and a Postgres context with an increment key gets + `DesignTimeServices.g.cs` (ruling R60: one class for every design-time concern, + identity starts and JSON-column comments): an `IDesignTimeServices` that wraps the + context's own model differ, so `dotnet ef migrations add` scaffolds every start-only change — a + start added, changed or removed — as SQL, Up and Down, never as Npgsql's `RESTART`. The SQL is + `SET START WITH n` (a removed start goes back to the identity default) and, for a declared start, + moves the counter forward to `GREATEST(n, max(id) + 1)` when it is below that, never back. The + first migration after upgrading shows, for each table that declares a start, that SQL (or, from a + project that does not find the services, an `AlterColumn`); review it before applying. + **Nothing is registered at runtime.** rc.18's `UseIdentityStartMigrations()`, the model-build + check that demanded it, and the generated SQL-generator subclass are gone: delete every + `.UseIdentityStartMigrations()` call. EF finds the services in the startup project, and through + the `[assembly: DesignTimeServicesReference]` the file carries when it knows the context's + assembly name (`GenConfig.ContextAssemblyName`, else the `.csproj` it is written into). EF + reads that attribute only from the startup and migrations assemblies, so **whenever the + context's assembly is neither, add the attribute to the migrations project** + (`docs/ports/csharp.md`) — including a context in a class library whose migrations project is + also the `dotnet ef` startup project. `dotnet meta gen` warns with the exact line whenever it + cannot show the line is unnecessary (it looks for `ModelSnapshot.cs` in the context's + project, or a migrations project that already carries the line). Without the line a changed + start still scaffolds as RESTART, which is the accepted residual risk. An adopter's own differ + is kept: the services wrap it. The `.csproj` the name is read from is an input of `dotnet meta + gen`'s skip key (ADR-0064), so renaming the assembly renders again. + ### Deprecated - **C#: `ValueObjectNames.Names(root)`.** A value object is never renamed, so it now returns the @@ -1416,7 +1772,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th was left for EF to discover as an entity (model validation failed with "requires a primary key"), and a timestamp, enum, decimal precision, array, map, duration or `@readOnly` column lost the mapping the same field gets on the root. Each concrete subtype now configures the - fields it adds, on its own builder. The integration corpus's `CopayAuth.copayAmount` gains its + fields it adds, on its own builder. The integration corpus's `CouponAuth.couponAmount` gains its `HasPrecision(10, 2)`. - **C#: under `EmitAbstractShapes`, a concrete entity extends its abstract shape and keeps the @@ -1667,6 +2023,490 @@ Each item below is described in full under Security, Added, Changed or Fixed; th claimed twice (`ERR_COLLECTION_NAME_COLLISION`) were checked by the generate goal only, so a project could verify clean on a model generate would refuse. Java and Kotlin. +- **Fix, C#: `verify --codegen` renders the design-time services file `gen` wrote.** With no + `GenConfig.ContextAssemblyName`, `gen` reads the context's assembly name from the `.csproj` in or + above `--out` and writes `[assembly: DesignTimeServicesReference(...)]` into + `DesignTimeServices.g.cs`. The drift render ran under a temporary directory with no + project, left that line out, and reported the file as drift on every rendering `verify` (always + in CI) for a Postgres project laid out that way. The render now uses the name `gen` resolved. + Locally the stored-key answer (ADR-0064) hid it; `verify --codegen --full` showed it. + +- **Fix, C#: a query can test an optional value-mapped enum against a list (rc.22).** + `DbContextGenerator` handed a scalar `@intValueMap` or `@stringValueMap` enum's two conversion + lambdas straight to `HasConversion(...)`, so EF typed the converter on the property: an optional + field got `ValueConverter` (or ``). EF Core 8 cannot build the JSON collection + reader for a parameterised collection over that converter, and a query such as + `db.Widgets.Where(w => active.Contains(w.Status))` failed at runtime on Npgsql + (`InvalidOperationException` or `MissingMethodException` on + `JsonNullableStructCollectionReaderWriter`, by patch version). The pair is now wrapped in + `new ValueConverter(...)`, typed on the non-nullable enum for required and optional + fields alike, as an enum array's element converter already was. The stored values, the throw on an + unmapped value and `HasMaxLength` are unchanged. Regenerating changes every such line; an override + of `EnumConversionCall` that edits the returned text by pattern should be checked against it. + +- **Fix, C#: PATCH and PUT apply a multi-word field under a snake or kebab JSON naming policy + (rc.22).** The merge matched a body key to a property by name, so `seat_count` never found + `SeatCount` and the update returned 200 with the field silently unchanged. The key is now resolved + through the serializer's own key map. + +- **Fix, C#: the generators name a field's property through the one property-naming resolver + (rc.22).** Since rc.20 `GenConfig.PropertyNaming` renamed a field's property in the entity, the + context's model lines, the reverse finders and the composite key, but these emit sites still + spelled `Pascal(field.Name)`: the `@sequenceStart` identity annotation in `DbContextGenerator` (a + key renamed `WidgetID` got `.Property(x => x.WidgetId)`, CS1061), the argument properties in + `CallableGenerator`, the mapper targets in `ExtractorGenerator`, the row cells in + `ReportExportGenerator`, and the `RoutesGenerator` key, sort-allowlist, `EF.Property`, frozen, + auto-set, value-object, create-reset, TPH discriminator and M:N junction names. The runtime filter + dispatch looked a property up by the field name, so `?filter[]` on a property renamed + beyond case threw (500); the generated allowlist now carries a field-to-property map, emitted only + when a rename goes beyond case, and `EfCoreFilterDispatch.ApplyFilter` and `Validate` take it as an + optional argument. With no resolver set the output is unchanged except for the security change + above: regenerating changes every routes file (the PATCH key lookup) and the credential-bearing + ones further; a golden test pins the rest byte for byte. + +- **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row + references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused + (`ERR_ORIGIN_CARDINALITY`). When the holder declares an `identity.primary` or + `identity.secondary` over exactly the reference's fields, the hop is to-one for a passthrough; + an aggregate over it stays legal. A partial (`@where`) or expression (`@expr`) unique index is + unique only over a subset or a value, so it never makes the hop to-one. + +- **Fix, TypeScript: a grouped view groups the joined columns its expressions read (rc.21).** A + computed column or an `origin.first` correlation that read a joined column outside an aggregate + was not in the GROUP BY. Where the joined row's primary key was not grouped, Postgres refused + the view; it is valid now. The generated view text changes for every grouped view whose + expressions read a joined column, also where the view already worked (SQLite, or a Postgres + view the joined key's grouping made valid), so the next `meta migrate` replaces such a view + once. Every added column is on a to-one join, so the rows are the same. The base row's columns + stay out (its primary key is grouped). + +- **Fix, C#: a reference over a flattened member configures the owned type's own navigation + (rc.21, U6).** `identity.reference { @fields: address.countryId, @references: Country }` emitted + `OwnsOne(x => x.Address).HasOne().WithMany().HasForeignKey(e => e.CountryId)`. When the + owned type also carries a `Country` navigation (an adopter's partial class, say), EF's + convention builds a relationship from it as the owned type joins the model, so the + navigation-less call made a second one, with a shadow FK property (`CountryId1`) and a second + foreign key. The relationship is now configured through the owned type's navigation to the + target, read from the model at build time (`OwnsOne(x => x.Address, b => + b.HasOne()…)`): its only navigation to the target, + whatever its name (`HomeCountry` over `CountryId` too); with several, the one whose foreign key + is these properties, and with none of those the model build throws, naming the owner; with none, + navigation-less. When the entity declares a second reference from the same owned member to the + same target, codegen emits only the foreign-key match: a sole navigation may be the other + reference's, so this one takes the navigation over its own properties or none (rc.21 part B, + N3). One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. + Generated output changes for every reference over a flattened member. + +- **Breaking, TypeScript and C#: `Names` has no entry for a derived field with no column + (rc.21, U7).** A derived (`origin.*`) field of an entity read from its table is no column of + that table (a projection that reaches it lowers it inline), yet the names artifact emitted a + `…Field`/`…Column` pair (C#) or a `fields..column` (TypeScript) for it, and a + `ColumnsByField` entry, all naming a column that does not exist. It now emits no entry for such + a field, so code reading one fails to compile instead of querying a missing column. A + projection's derived field is a column of its view, and a write-through entity's is a column of + its read view: both keep their entry; a write-through entity extending an abstract entity + declares the derived columns it inherits itself, since the abstract fragment drops them. Java + and Kotlin are unchanged (no entity-derived fields). **Upgrade note:** code that reads + `Names.Field` / `Column` (C#), `fields.` (TypeScript) or a + `ColumnsByField` entry for such a field no longer compiles; use `nameof(...)` or the metamodel + name as a literal instead, since there is no column to name. + +- **Fix, TypeScript and C#: a `@via` hop under a guessed name lists the reverse hops (rc.21, U9).** + The first hop from a projection's base entity already walks an `identity.reference` backwards + (`Order.orderEvent` for `OrderEvent.orderId`), named by the holder's collection name, first + letter lowercased. A holder whose `@collectionName` is singular (`OrderEvent`) makes that name + hard to guess, and the refusal (`no such relationship or reference "events" on Order`) did not + say what it was. It now ends `The reverse hops from Order are: "orderEvent" (walks + OrderEvent.orderId backwards) — …`. No hop name changes: an `@inverseName` spelling is not + accepted, because no registered vocabulary declares one. Java and Python keep their message. + **Naming note (this entry and U1's):** neither was a resolution bug. A dotted `extends` names an + identity by its name (an unnamed `identity.primary` is `primary`), and a reverse hop by the + holder's collection name; both already resolved under those names, and the errors now say what + the names are. + +- **Fix, TypeScript and C#: a dotted `extends` whose member is missing names the owner's members + (rc.21, U1).** `extends: "Shipment.id"` on an `identity.primary`, where `Shipment` + inherits its identity from an abstract base, failed with `ERR_UNRESOLVED_SUPER` and the advice to + qualify `Shipment` with its package, although `Shipment` had resolved. The member was + the problem: an identity declared without a name is named after its subtype (`primary`), and the + inherited one resolves as `Shipment.primary`, which already worked. The error now says + so: `'acme::shipping::Shipment' has no identity named "id"; its identity children are: + "primary" (identity.primary). An identity.primary declared without a name is named "primary".` + The package advice is given only when the owner itself did not resolve. Java and Python keep + their message. + +- **Fix, TypeScript: a projection extender that declares only its own source gets its view + (rc.21).** `meta migrate` decided whether a projection's view is derived from the projection's + OWN children, so a projection that extends another projection and adds nothing but its own + `source.rdb` (`@kind: view`) had no anchor or origin of its own and was dropped from the + expected schema with no error. It now reads the effective children, as the view builder already + does (G13). The same audit fixed an `@sql` extender's dependencies: they now include the anchor + tables it inherits, so a column change on its base table drops and recreates it. + +- **Fix, TypeScript and C#: a TPH subtype's columns get their CHECKs (rc.21).** `meta migrate`, + `meta verify --db` and the C# EF context built the CHECKs of a discriminator base's table from + the base's own fields only, so an enum or validator on a column a concrete subtype (or an + abstract level under the base) folds into the shared table had no database CHECK, and a + cross-field validator a subtype declared was enforced nowhere. The base's table now carries + them. A subtype-only column's field-level CHECK is the text a base column gets, with no + discriminator guard: a CHECK refuses only FALSE, and a sibling subtype's row holds NULL there. + Sibling subtypes that declare one column with DIFFERENT checks (different `@values`, a different + pattern) each get their own, guarded by their discriminator values and named + `
___…`; identical ones share one. A subtype's cross-field validator is + guarded by the discriminator, as an `@condition` ANDed with its own, listing every concrete + subtype it reaches, and its default name carries its declarer. On Postgres a declarer-qualified + default name longer than 63 bytes keeps its first 54 bytes plus `_` and 8 hex digits of its + SHA-256 (the same spelling in `meta migrate`, Drizzle and C#), so Postgres never truncates it. + Two different CHECKs under one name on a table (a pre-existing hazard too: two comparisons with + one left field) are refused where the database requires unique names: on Postgres, by `meta + migrate`, `meta verify --db`, Drizzle and C#, naming both, instead of a CREATE TABLE the database + refuses. SQLite and D1 accept and enforce both (probed on SQLite 3.51 and Miniflare's D1), so + `meta migrate` and Drizzle keep both there, a declared `@constraintName` included, and the + SQLite CHECK diff now matches a name to a list so it converges. C# refuses the pair on every + dialect: EF Core keys a check constraint by name and would keep only the last (verified on EF + Core 8.0.18). The Drizzle schema already declared the subtype enum CHECKs, so the two now agree. Pinned by `input/meta.tph.json` in the shared CHECK + corpus. **Upgrade note:** the next `meta migrate` (or EF migration) adds these CHECKs to an + existing TPH table; a legacy row outside a rule needs `@dbCheck: false` on that node first. + +- **Fix, C#: a described `field.object` an `OwnedTypeConfig` override maps as a column no longer + breaks the model build (G1).** `DbContextGenerator` assumed a non-flattened object field with no + map is owned JSON, and whenever the field or its value object carried a `@description` it + emitted `Metadata.FindNavigation("")!.TargetEntityType.SetAnnotation(...)`. An override + that maps the field as a property (a jsonb POCO column) leaves no navigation, so every model + build threw a `NullReferenceException` in `OnModelCreating`. The comment line now follows the + mapping the emitted lines declare: an owned JSON navigation (`OwnsOne`/`OwnsMany` with + `ToJson`) keeps the annotation, byte for byte; a `Property(x => x.)` takes + `GetProperty("").SetComment(...)` on its column; any other mapping gets no comment line + and a warning naming the field (`meta migrate` still writes the comment). + +- **Fix, TypeScript: the Drizzle schema's enum CHECK takes the field's `@constraintName`.** The + table's `check()` was always named `
__chk`, so an enum whose CHECK `meta migrate` + names by `@constraintName` reported drift and `drizzle-kit push` proposed a second CHECK. + +- **Fix, C#: narrowed `EntityGenerator` entries declare each shared enum once (G2).** With + `Include`, the materialized shared enums were still collected from every in-scope object, so every + entry splitting the model declared all of them (`CS0101` where two outputs build together). A + narrowed entry now declares only the enums used by the objects it accepts and the value objects it + emits beyond them, and an enum several entries use is declared by one: the entry that emits its + first consumer by resolution key. Each entry reaches that answer from the model alone, in its own + run. An enum whose first consumer no entry emits is declared by none; give that object an entry, + or use an un-narrowed entry, which declares every enum as before. Placing an enum in a project of + its own choosing is G3, not built. + +- **Fix, TypeScript docs: an identity reference's target links to its page (G4).** The Identity + section printed ``**Reference:** `x` → `Target` `` unlinked, bare or package-qualified. The target + now links through the same `docPageHref` the field table's foreign-key links use + (``→ [`acme::crm::Customer`](../crm/Customer.md)``), keeping the authored spelling as the label; + a target the loader did not bind stays plain text. **Upgrade note:** committed docs pages with an + identity reference regenerate once with the link. + +- **Fix, C#: the `DurationInterval` mapping names framework types `global::`-qualified (G8).** The + runtime text the DbContext generator writes after the context class (the `field.duration` + interval mapping) spelled `System.Type`, `System.TimeSpan`, `Microsoft.EntityFrameworkCore…` + bare inside the home namespace, so a package deriving `.System` (`acme::system` beside a + context in `Acme`) captured them (`CS0234`). They are `global::`-qualified now. The design-time + services and the `DecimalWire`/`DurationWire` copies already name framework types only through + top-level `using`s, which no namespace captures; a test builds all of them beside `Acme.System`. + +- **Fix, TypeScript views: two references onto one target entity read their own rows.** A + projection whose origins reach the same entity through two different references + (`Account.owner` and `Account.approver`, both `User`) got two joins (`u`, `u0`), but every origin + looked its alias up by target entity, so both columns selected from the first join and the + second read the wrong row. An origin with a `@via` now reads from the join its own hop chain + built (passthroughs and every aggregate arm); reports already resolved by path. Fixture + `fixtures/conformance/origin-passthrough-two-references-one-target`. **Upgrade note:** a + generated view with such a pair is re-proposed once as `replace-view`, and its second column now + holds the row its reference names. + +- **A projection that extends another projection gets a view with the inherited fields** + (rc.19 Phase 5, bug G13). The loader could not derive the base entity of an extender that + anchors nothing of its own (TypeScript and C#), and view codegen read only the extender's own + fields, so the inherited columns and joins were dropped. The extender now has its super's base + entity, and its view carries the effective fields and their origins, base first. An extender + that would inherit its base's source is still refused at load: it declares its own. Pinned by + `fixtures/conformance/projection-extends-abstract-projection`. + +- **Every generated view join is `LEFT OUTER`** (rc.19 ruling R62, review item 9). #209 joined a + belongs-to hop over a required foreign key `INNER`, which silently dropped a base row whose + reference names no row — possible for an `@enforce: false` reference, and for a TPH-subtype + target whose join carries its discriminator. Every view and report join is now `LEFT OUTER`, + in every case. To require the related row, say so: + `@filter: { ".id": { isNull: false } }` on the projection (no new vocabulary). A report + dimension's `required` no longer reads "every join is INNER"; it comes from the model, in + TypeScript and C# (`ReportShape`): the `@of` field is required, and every hop is a belongs-to + reference over a required, enforced foreign key onto a target that hides no rows (not a TPH + subtype) — exactly when `LEFT` and `INNER` return the same rows. Pinned by + `fixtures/conformance/report-dimension-required-by-model`. The inner joins of a multi-hop + `origin.first` subquery stay `INNER`: they choose which related row is first and cannot drop + or add a view row. **Upgrade notes:** every generated view that had an `INNER JOIN` changes + body, so the next `meta migrate` re-proposes it once as `replace-view`; where the foreign keys + are enforced the rows are unchanged. A report row type is unchanged where every hop is + required and enforced; a dimension reached through an `@enforce: false` hop or onto a TPH + subtype becomes nullable. A view that relied on an unenforced `INNER` join to exclude rows + (a legacy column holding ids of two kinds) now includes them until it declares the `isNull` + filter. + +- **C#: two contexts' design-time services wrap the model differ once** (rc.19 fix round, M3). + EF applies every `DesignTimeServicesReference` it reads, so two Postgres contexts in one + assembly each wrapped the differ and every JSON-column `COMMENT ON` was scaffolded twice. The + generated services now recognise one another's marker and wrap once between them. + +- **C#: every generator that emits a class claims its name** (rc.19 fix round, I2). With + package-keyed paths two same-named objects no longer collide on one output file, so only a + claim stopped a duplicate type — and `FilterAllowlist`, `Names`, `Export` and + the template tier (`RenderHelper`, the parser, the response format, the extractor) claimed + nothing, so the pair reached the compiler as CS0101. Each now claims where it emits and a + duplicate is a named `ERR_NAME_COLLISION`. **Upgrade note:** `FilterAllowlist` is now + emitted in its entity's namespace (as `Names` already was), so `GenConfig.PackageNamespaces` + separates the allowlists too; the generated routes already import that namespace. A refusal's + remedy says "rename one" where the class always lives in `GenConfig.Namespace` (the reverse + finders, a shared enum, the template tier, a report export), since mapping the packages cannot + help there. + +- **No CHECK for a derived field** (rc.19 fix round, I5). `meta migrate` and the C# EF context + built a CHECK from a derived (origin-bearing) field's enum values or validators, and a + cross-field CHECK naming one, though such a field has no column — so `CREATE TABLE` and the EF + migration failed. rc.19 made it reachable: an entity may now host an `origin.first` or + `origin.computed` field a projection reaches. Both ports skip such a field. Pinned by `band` in + `fixtures/check-constraint-conformance`, which now also covers D1, SQLite with + `skipRedundant`, a string-stored enum with a `validator.length`, and a `@constraintName` + validator under `skipRedundant`. + +- **An extender keeps its base projection's `@filter`** (rc.19 fix round, C1). Codegen read only + the extender's own `@filter`, so a projection extending a gated projection (an access or + eligibility gate on an abstract base) emitted an ungated view, with no error. A projection's effective + `@filter` is now every level of its `extends` chain, root-most first, ANDed — it composes, it + never overrides — and that is what the view's `WHERE` applies and what both loaders check + (against the extender's effective fields, so an extender may filter on an inherited + projection field). An extender with an `@sql` body that inherits a `@filter` is refused + (`ERR_ORIGIN_UNDER_SQL_BODY`), as one that declares it is. Pinned by + `fixtures/conformance/projection-extends-filtered-projection` and + `error-projection-extends-filter-sql-body`. + +- **A projection `@filter` no longer fails because the base entity has a derived field it + never names** (rc.19 fix round, I1). The rc.19 base-field fallback (G7) inlined every + unprojected base field, so an entity with a derived `origin.passthrough` or `origin.aggregate` + field made any `@filter` over it fail `meta gen`. Only the fields the filter names are reached. + +- **An origin `@filter` keeps every operator of a field clause** (rc.19 Phase 5, bug + multi-op). `{ ordinal: { gte: 1, lte: 5 } }` on an `origin.aggregate` or `origin.first` kept + only `gte`, so the aggregate spanned a wider row set than declared, silently; each operator is + now its own comparison, AND-composed, as the projection-level `@filter` already did. + **Upgrade note:** a view with such a filter changes body and is re-proposed once. + +- **A view over a TPH subtype carries its discriminator** (rc.19 Phase 5, bug TPH-scope). A + subtype shares its base's table, so a projection whose base is a subtype read every row of the + table, and a join or `origin.first` that landed on a subtype matched rows of its siblings. A + subtype base now adds `WHERE . = `; a join onto one adds it to the + `ON` clause (a base row with no match survives), and an `origin.first` to its subquery's + `WHERE`. An int-backed discriminator stores its integer. Report joins follow the same rule. + **Upgrade note:** such a view's body changes, and it is re-proposed once as `replace-view`. + An abstract level between the base and its concrete subtypes reads the rows of every concrete + subtype beneath it (` IN (…)`), and a concrete subtype with concrete subtypes of + its own reads theirs too. **Not yet:** inside a multi-hop `origin.first @via`, only the `@of` + entity is scoped; an intermediate hop that lands on a TPH subtype is not, so the path can read + a sibling subtype's rows. + +- **A projection `@filter` reads a base-entity field the view does not output** (rc.19 Phase + 5, bug G7). `@filter: { deleted: false }` on a projection that exposes no `deleted` column + lowers to `WHERE t.deleted = FALSE` on the base row; the loader refused it in TypeScript and C# + ("not a declared field of the projection"). A projection field of the same name wins. Pinned by + `fixtures/conformance/projection-filter-unprojected-base-field`. + +- **A projection `@filter` reads a joined field the view does not output** (rc.19 Phase 5, bug + G7, joined half). A filter key may be a path of to-one hops from the base entity, named as an + origin's `@via` names them, then a field of the entity reached: `@filter: { "consignmentId.status": + "open" }` joins `consignments` (sharing a join an origin already walks) and lowers to + `WHERE c.status = 'open'`. A to-many hop is refused (`ERR_BAD_ATTR_FILTER`): it would multiply + the base rows. Pinned by `fixtures/conformance/projection-filter-joined-path` and + `error-projection-filter-path-to-many`. + +- **A Postgres view column takes its declared type** (rc.19 Phase 5, bug `cast`). A bare + `NULL` (`origin.computed { @expr: { value: null } }`) is `text` in a view, so a `field.int` or + `field.timestamp` declared that way became a text column; an `@convert: true` passthrough read + the source column unconverted. Both are now `CAST(… AS )`, with the type `meta migrate` + gives the field's column (`fieldSqlType`, `pgType`, now exported from + `@metaobjectsdev/migrate-ts/expected`). A text NULL stays bare; SQLite views are untyped and + are not cast. **Upgrade note:** a view with such a column is re-proposed once as `replace-view`. + +- **A multi-hop `origin.first @via` is lowered along its path** (rc.19 Phase 5, bug + first-multihop). The loader accepted it, but view codegen never read `origin.first`'s `@via`: + it correlated the base directly to the `@of` entity and, with no direct reference, dropped the + column from the view without a word. A `@via` of two or more hops is now a subquery whose first + hop is correlated to the base row and whose later hops are `INNER JOIN`s inside it; the + ordering, `@filter` and tie-breaker are the `@of` entity's, and the view depends on every table + on the path. A path that does not reach the `@of` entity is refused. One hop is unchanged. + +- **A passthrough reads a member of a flattened value object** (rc.19 Phase 5, bug G6). + `@from: Plan.address.city`, where `address` is a `field.object` with `@storage: flattened`, + reads the owning table's `address_city` column (an empty `@flattenedColumnPrefix` reads the + bare member column). The loader refused the path in TypeScript and C# ("no such field"). + Pinned by `fixtures/conformance/origin-passthrough-flattened-member`. + +- **The Tier 2 view vocabulary** (rc.19 Phase 6, ruling R58; loaders in C# and TypeScript, view + SQL in TypeScript, which builds every port's views). See `docs/features/relationships.md` + "Filtering and computing over joined rows". + - *entity-derived*: an entity may declare an `origin.first` / `origin.computed` field with no + read source when a projection reaches it (a `@filter` key or path, a passthrough `@from`); + it is no column and no ORM property, and is inlined where reached. + - *origin-segment*: `@segment` on `origin.first` and `origin.aggregate`. + - *now*: relative dates in a projection `@filter` and an origin `@filter`, and `{ now }` as an + expression leaf. **Changed:** the loader no longer refuses them there (rule F1); the corpus + fixtures `error-relative-date-wrong-host` and `error-relative-date-origin-host` became + `projection-filter-relative-now` and `origin-filter-relative-now`. + **Upgrade note: `now` is the UTC clock, not the session time zone.** A relative value is + evaluated when the view is queried, on the UTC wall clock, in the compared field's kind (the + report rule): against a `field.date` or a naive timestamp, today is the UTC date, and a + `startOf: day` boundary is UTC midnight; a `timestamptz` instant compares with `now()` itself. + SQL that compares with `CURRENT_DATE` or `CURRENT_TIMESTAMP` reads the session zone instead, + so near midnight the two disagree by a day: in a session at UTC−5, from 19:00 local time the + view's "today" is already tomorrow's date. A hand-written function you replace with a + `now` filter (a contract or eligibility window, say) can include or exclude a row for those + hours that it did not before. Keep the session zone UTC, or compare a `timestamptz` + instant, if the two must agree. + - *correlated-filter*: `{ field: "" }` operands in an origin `@filter`, with the + null-safe `isDistinctFrom` / `isNotDistinctFrom`. + - *computed-over-joined*: `origin.computed` refs name the projection's own fields first. + - *case*: searched and simple `case` expression nodes. + C# entity classes never carry a derived field. Pinned by the fixtures + `entity-derived-league-gate`, `origin-computed-case-over-joined`, + `origin-correlated-filter-and-segment`, `error-origin-computed-case-mixed-types`, + `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`. + +- **A reference over a flattened value-object member** (rc.19 Phase 5, bug G6, reference half). + `identity.reference { @fields: address.countryId, @references: Country }` declares the foreign + key a flattened `Address` carries: a `@via` hop over it joins on `address_country_id`, + `meta migrate` puts the foreign key on that column, and C# configures it on the owned type + (`OwnsOne(x => x.Address).HasOne().WithMany().HasForeignKey(e => e.CountryId)`). + Neither port generates a reverse finder for such a reference. Fields spread over the entity and + a value object have no EF mapping; C# warns and configures none. Pinned by + `fixtures/conformance/reference-flattened-member`. + +- **An origin's `@via` walks the reverse of a reference** (rc.19 Phase 5, bug R-walk). A hop + named by the referencing entity's collection name (`Player.contracts` for + `Contract.player`) walks that identity.reference backwards, to-many, with no relationship + declared; the loader refused it ("no such relationship or reference") in TypeScript and C#, + and TypeScript view codegen silently dropped the join. A declared relationship or reference of + the same name wins; two references onto the parent make the hop `ERR_AMBIGUOUS_PATH`. Pinned + by `fixtures/conformance/origin-reverse-reference-hop` and + `error-origin-reverse-hop-ambiguous` (Java, Kotlin and Python follow in #544–#549). + +- **TypeScript docs: a field's "References" link reaches the target's page** (rc.19 item 11). + Docs pages sit under their package path, but the foreign-key link was the bare + `.md`, which resolved only beside the page. It now goes through `docPageHref`, as the + index and template links do: `../crm/Customer.md` from `acme/sales/Order.md`, and + `./Order.md` within one package. + +## [1.2.3] — 2026-11-15 + +_npm `1.2.3` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ + +_Also PyPI `1.2.3`, NuGet `1.2.3` and Maven Central `8.2.3`: every port changed. PyPI skips +`1.2.2`. No vocabulary or `metamodelVersion` change._ + +### Changed + +- **`gen` skips rendering when nothing it is built from changed, in every port (ADR-0062).** + The skip key is computed after the metadata loads and before anything renders. Its model half + hashes each loaded root-level node in its canonical effective form (`extends` and overlays + applied), rolled up per package and for the model, so reformatting or splitting a metadata file + changes nothing while an edit to an inherited parent changes every child. Its generator half + hashes the built engine code, the codegen config and every owned generator, the template + roots, declared extra inputs, the project config and the output-changing flags. `gen` skips + when the key matches the last successful run and every generated file still has the bytes + that run left; a skipped run renders and writes nothing. The key is stored, uncommitted, in + `.metaobjects/.gen-state/.fingerprint-.json`. `--force` (`meta gen`, `metaobjects gen`, + `dotnet meta gen`; `-Dmetaobjects.force=true` on Maven) renders everything, and a generator + that cannot declare what it reads opts out with `cache: false` (or its port's equivalent). +- **`verify --codegen` may answer locally without rendering, and never writes a temp tree.** In + CI (`CI` set) it always renders and compares everything. Locally it answers "no drift" when the + key matches and every generated file still hashes to its record; `--full` + (`-Dmetaobjects.verify.full=true` on Maven) renders. When it renders, every port compares the + rendered bytes with disk in memory. +- **The hash manifest is written once per run, and only when an entry changed** (TypeScript, + Python and C#, matching Java and Kotlin). A file whose fresh bytes equal what is on disk is never + rewritten in any port, so its timestamp stays. Python `gen` no longer reports unchanged files + as written. +- **TypeScript runs `git merge-file` only for a file edited by hand since it was generated**, and + deletes the merge's temporary files in every case, under `$DEV_SCRATCH` when set. An untouched + file is overwritten directly. + +### Upgrading + +- **Add `**/.metaobjects/.gen-state/*` and `!**/.metaobjects/.gen-state/.hashes.json` to your + `.gitignore`.** Otherwise the new `.fingerprint-.json` file shows as untracked (in each + Maven module, for Java and Kotlin). The exception matters: the fingerprint files stay + uncommitted, but `.hashes.json` stays committed, so do not ignore the whole `.metaobjects/` + directory. +- **Generated TypeScript docs change if you are coming from 1.2.0.** Since 1.2.2 an update schema + leaves out every primary-key field, so the documented `UpdateSchema` type, the update + function's patch type and the PATCH/PUT body no longer list the key (the `id` row is gone). + Regenerate the docs and commit them, or `meta verify --codegen` reports drift. +- **Committed generated code changes too, not only the docs.** Because primary-key fields leave + the update schemas, and because of 1.2.2's create-route fixes in Java, Kotlin and C#, regenerate + and commit your generated code when you upgrade from 1.2.0 or 1.2.1. Otherwise the drift gate + fails against the new generators. + +## [1.2.2] — 2026-11-13 + +_npm `1.2.2` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ + +_Proposed as npm `1.2.2` (all 14 `@metaobjectsdev/*` packages), NuGet `1.2.2` and Maven Central +`8.2.2`; `1.2.1` was spent by the Python-only release. PyPI stays at `1.2.1`: no Python product +file changes. No vocabulary or `metamodelVersion` change._ + +### Security + +- **Generated create routes in Java, Kotlin and C#, and TypeScript updates, let a client write + fields it must never set.** The same class of hole the Python 1.2.1 patch closed, found by an + audit of the other four ports after it. Every adopter serving these generated routes should + upgrade and regenerate; an ejected (owned) generator needs the same change made by hand. + + - **Java (`codegen-spring`).** The create route passed the bound DTO to the repository as + sent, so a client `id` on a generated key and a `@mutability: readOnly` or derived field + reached it. On a TPH per-subtype route the body's discriminator and a sibling subtype's + columns did too. The route now rebuilds the DTO with each of those components set to null + before the repository call; the route's subtype still comes from the URL. A `@required` + `readOnly` or derived value-object column no longer fails create validation once nulled. + - **Kotlin (`codegen-kotlin`).** The create route wrote `readOnly` and derived columns from the + body, and a TPH per-subtype route wrote a sibling subtype's columns. It now writes only the + route subtype's own settable columns. + - **C# (`MetaObjects.Codegen`).** The create route bound the EF Core entity from the body, so a + client `id` on a generated key was inserted, a TPH create stored the body's discriminator (a + POST to the Bridge route could create a Coupon row), and a TPH subtype's `readOnly` field and + an M:N navigation graph were written. The route now resets the generated key and the + discriminator to their defaults and empties the M:N navigations before `Add`, and a + `readOnly` property of every shape, a TPH subtype's included, has a private setter, which + System.Text.Json does not bind. A `@required` `readOnly` field is therefore neither demanded + of the create body nor held to its `[Required]` there, so such an entity stays creatable. + - **TypeScript (`codegen-ts`).** The `UpdateSchema` kept an assigned (non-generated) + primary key, so a PUT or PATCH could re-key the row. The update schema now leaves out every + primary-key field; the insert schema still takes an assigned key, which is the caller's on + create. + + Each of these values is dropped silently, never answered with a 400. A key the model does not + declare is dropped silently in TypeScript, C# and Python. In Java and Kotlin the answer to an + undeclared key is the host's Jackson `ObjectMapper`'s: Spring Boot's default ignores it, and a + plain `ObjectMapper` (`FAIL_ON_UNKNOWN_PROPERTIES` on) answers 400. This patch leaves that as + it was. + + Gated by the shared api-contract scenarios `input-server-owned-dropped`, + `tph-input-server-owned-dropped` and `tph-input-foreign-discriminator-dropped`, and a `readOnly` + `role` on the `secret-fields` corpus, in every port's generated lane and in the reference lanes. + Python's generated TPH routes answer a foreign body discriminator with a 400 rather than + dropping it (nothing is stored); its runner skips that one scenario, recorded in the Python + codegen `KNOWN_GAPS.md`. + +### Fixed + +- **C#: concurrent reads of a loaded model no longer corrupt its cache.** `MetaData.Cached` + memoized derived reads (`Validators()`, `ResolvedIsArray()`, `OwnAttrs()`, …) in a plain + `Dictionary`, so two threads touching a frozen node for the first time could corrupt it, and + every later read in the process then failed with "Operations that change non-concurrent + collections must have exclusive access". A host that loads metadata once and serves requests + from it in parallel, or a parallel test run, hit this. The cache is now a + `ConcurrentDictionary`. + ## [1.2.1] — Python only _PyPI `1.2.1` only. npm, NuGet and Maven Central stay at `1.2.0` (`8.2.0`): none of them has a @@ -9697,8 +10537,8 @@ reintroduced one level up. On the persistence corpus's three-subtype TPH hierarc the C# output sheds 30 restated lines. The shape is per-language, the guarantee is not. **C# and Java** use real inheritance — -`class CopayAuthNames : AuthNames` / `extends AuthNames` — since both languages inherit -static members, so `CopayAuthNames.IdColumn` resolves through the base. **TypeScript** +`class CouponAuthNames : AuthNames` / `extends AuthNames` — since both languages inherit +static members, so `CouponAuthNames.IdColumn` resolves through the base. **TypeScript** spreads (`...AuthNames.fields`). **Kotlin and Python** have no static inheritance at all, so they re-export the parent's constants BY REFERENCE. diff --git a/agent-context/skills/metaobjects-audit/SKILL.md b/agent-context/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/agent-context/skills/metaobjects-audit/SKILL.md +++ b/agent-context/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md b/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md b/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/agent-context/skills/metaobjects-codegen/SKILL.md b/agent-context/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/agent-context/skills/metaobjects-codegen/SKILL.md +++ b/agent-context/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index d86cf4cea2..5807adbd34 100644 --- a/agent-context/skills/metaobjects-codegen/references/csharp.md +++ b/agent-context/skills/metaobjects-codegen/references/csharp.md @@ -118,7 +118,7 @@ init properties say otherwise — documentation does (below). | `filter-allowlist` | `FilterAllowlistGenerator()` | per-entity `FilterAllowlist` (FR-009 — the server-side field+operator allowlist the routes validate against). | | `callable` | `CallableGenerator()` | `.callable.g.cs` — an FR-015 calling method for a `source.rdb @kind="storedProc"|"tableFunction"`, via EF `FromSqlInterpolated` (args from the `@parameterRef` value object in declaration order). | | `output-parser` / `extractor` / `output-prompt` / `render-helper` | `OutputParserGenerator()`, `ExtractorGenerator()`, `OutputPromptGenerator()`, `RenderHelperGenerator("prompts")` (its constructor argument is the template root its refs resolve from) | the prompt-pillar artifacts for a **responding `template.prompt`** — one carrying `@responseRef` (ADR-0052: these tiers are INBOUND; `template.output` is outbound only and emits no parser). The strict parser, the tolerant `extract`, the **output-format prompt fragment** (`output-prompt`; presentation via `@promptStyle: guide`/`inline`/`exampleOnly`), and the typed render helper. They reference the value objects' POCOs from `entity` and declare no payload type — wire `entity` too (`--list` says so). See the **prompts** reference. | -| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CopayAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CopayAuthNames.IdColumn` and `CopayAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | +| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CouponAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CouponAuthNames.IdColumn` and `CouponAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | | `template` | `TemplateGenerator.Create(name, template, walk, provider)` (a factory, not `new`) | the generic Mustache `templateGenerator()` primitive. | Metadata lives in the directory the gen run's positional `` argument @@ -313,7 +313,7 @@ redeclare them; only an emitted abstract shape is a base); an `object.value`'s d **Shared + externally-provided enums (FR-019).** A package-level abstract `field.enum` (`abstract: true`, `@values`) extended by concrete entity fields is -materialized **once** (`Enums.g.cs`) and referenced — no per-entity nested enum. +materialized **once** (`/.g.cs`, its `@intValueMap` ints and `@enumDoc` docs on the members) and referenced — no per-entity nested enum. Adding `@provided: true` to that declaration suppresses materialization entirely: consuming fields reference a hand-written/third-party enum, and the C# namespace **binds to the enum's declaring metadata package** via diff --git a/agent-context/skills/metaobjects-codegen/references/java.md b/agent-context/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/agent-context/skills/metaobjects-codegen/references/java.md +++ b/agent-context/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/agent-context/skills/metaobjects-codegen/references/physical-names.md b/agent-context/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/agent-context/skills/metaobjects-codegen/references/physical-names.md +++ b/agent-context/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md index 671794f9b3..6fd985d885 100644 --- a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md +++ b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md @@ -83,7 +83,12 @@ base emits polymorphic `GET /(+/{id})` plus a per-subtype CRUD set at `//` (create injects the discriminator, cross-subtype get/update/delete → 404). Wire it after registering the context: +The routes class lives in its entity's package namespace (`acme::blog` → `Acme.Blog`), so add a +`using` for it: + ```csharp +using Acme.Blog; // the entity's package namespace + var app = builder.Build(); app.MapAuthorRoutes("/api"); // the generated extension; you pass the prefix at mount time (default "/api") app.Run(); diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d2b273b373..e0f40a99eb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 510 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 526 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -42,7 +42,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 6 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers | ✓ | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/codegen-conformance/`](../fixtures/codegen-conformance/) | 7 shared inputs; `shared-provided-enum` carries the enum-type decision table and `cross-package-binding` the reference-binding decision table (ADR-0059) every port answers; `xpkg-value-object-refs` (ruling R52) is run by C# and TypeScript only so far — Java, Kotlin and Python in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/template-codegen-conformance/`](../fixtures/template-codegen-conformance/) | 3 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/template-output-render-conformance/`](../fixtures/template-output-render-conformance/) | 5 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/generator-registry-conformance/`](../fixtures/generator-registry-conformance/) | 1 canonical manifest | ✓ | ✓ | ✓ | ✓ | ✓ | @@ -178,6 +178,27 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). - *Port-scoped, for comparison* (`ports`, language-specific by nature, never "pending"): `@objectAdapter` (`["java", "kotlin"]`). +**Generated paths keyed by package** (ruling R39). Every port's generated output is keyed by +the metadata package, so two packages that each declare an object of the same name never +collide on an output path. State per port: + +- *Done, C#:* every per-object generator writes through `OutputPaths.Of` + (`/`; root-level objects at the root). The path follows the metadata + package, not `PackageNamespaces`. Since rc.19 R65 the namespace follows the package too + (`acme::alpha` → `Acme.Alpha`) unless a binding maps it; every cross-namespace reference is + `global::`-qualified. Tests: `OutputPathsTests`, `PackageNamespaceTests`. +- *Done, TypeScript:* `outputLayout` defaults to `"flat"`; `"package"` is opt-in (ruling + R63). Tests: `barrel-layout.test.ts` (the barrel exports the same + names in both layouts), `naming/name-claims.test.ts`. +- *Done, Python:* `outputLayout` mirrors TypeScript — `"flat"` the default, `"package"` opt-in, + and `metaobjects init` writes `outputLayout: package` into a new project. Tests: + `tests/codegen/test_package_layout.py`. +- *Done, Java and Kotlin:* every per-object file lands in the directory of its metadata package + (`a::b` → `a/b`), and a run where two metadata packages would land in one directory is + refused (`OutputPackageCollisions`), not silently overwritten. Tests: `PackageKeyedOutputTest` + (spring, kotlin). +- Tracked in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549. + **Native index vocabulary and `@description` in the ORM models.** `meta migrate` creates every index (`identity.secondary`, `index.lookup`, a field's `@unique`, with `@where`, `@using`, `@orders`, `@expr` and the resolved name) and writes `@description` as `COMMENT ON`. What each @@ -377,7 +398,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (510) +### `fixtures/conformance/` — metamodel loader + canonical serializer (526) | Fixture prefix | Feature doc | |---|---| @@ -755,7 +776,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 510 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 526 + yaml 16 + verify 45 + render 18 + persistence 67 + api-contract 139 + source-resolution 25 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/abstracts-and-inheritance.md b/docs/features/abstracts-and-inheritance.md index 38c5d8dff3..8397848e99 100644 --- a/docs/features/abstracts-and-inheritance.md +++ b/docs/features/abstracts-and-inheritance.md @@ -190,7 +190,7 @@ metadata: - field.long: { name: id } - field.enum: name: type - "@values": ["Bridge", "Copay", "PriorAuth"] + "@values": ["Bridge", "Coupon", "Permit"] - field.string: { name: reference, "@required": true } - identity.primary: { "@fields": id } @@ -202,16 +202,16 @@ metadata: - field.int: { name: quantity, "@required": true } - object.entity: - name: CopayAuth + name: CouponAuth extends: Auth - "@discriminatorValue": Copay + "@discriminatorValue": Coupon children: - - field.decimal: { name: copayAmount, "@precision": 10, "@scale": 2 } + - field.decimal: { name: couponAmount, "@precision": 10, "@scale": 2 } - object.entity: - name: PriorAuthAuth + name: PermitAuth extends: Auth - "@discriminatorValue": PriorAuth + "@discriminatorValue": Permit children: - field.string: { name: approver } ``` @@ -219,7 +219,7 @@ metadata: ### Single-table persistence Every subtype persists to the base's one table (`auths`). Subtype-only columns -(`quantity`, `copay_amount`, `approver`) are folded into that table **nullable** — +(`quantity`, `coupon_amount`, `approver`) are folded into that table **nullable** — a row of any other subtype stores `NULL` there, **even when the field is `@required`** on its subtype (a required rule can't hold across the shared table, so it is dropped on the folded column; an enum `CHECK` still passes because `NULL IN @@ -265,13 +265,13 @@ The generated polymorphic surface enforces a consistent subtype contract across every port: - **Per-subtype route segment** = the `@discriminatorValue` **lowercased**: - `/auths/bridge`, `/auths/copay`, `/auths/priorauth` (not the subtype entity + `/auths/bridge`, `/auths/coupon`, `/auths/permit` (not the subtype entity name). There is intentionally **no polymorphic `POST /auths`** — you can't create the abstract base. - **Create injects the discriminator** from the URL — `POST /auths/bridge` stamps `type = "Bridge"`; the request body omits it. - **Reads/updates/deletes are scoped to the subtype** — `GET|PATCH|DELETE - /auths/bridge/{id}` on a `Copay` row → **404** (a different-subtype row is + /auths/bridge/{id}` on a `Coupon` row → **404** (a different-subtype row is invisible to a subtype-scoped operation). - **M:N traversal is served inside the hierarchy** — a relationship declared on the base mounts at the base path (`GET /auths/{id}/tags`: every row of the diff --git a/docs/features/adopting-existing-models.md b/docs/features/adopting-existing-models.md index cd9f13a89b..c4412e9e75 100644 --- a/docs/features/adopting-existing-models.md +++ b/docs/features/adopting-existing-models.md @@ -76,6 +76,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -168,6 +169,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/docs/features/contract-emitters.md b/docs/features/contract-emitters.md index 75818dcf6e..fa016e75d7 100644 --- a/docs/features/contract-emitters.md +++ b/docs/features/contract-emitters.md @@ -4,8 +4,9 @@ _`jsonSchemaFile()` and `openApiFile()`: write the model's wire contract as plai and OpenAPI 3.1, so a consumer in any language can work from a standard document instead of a fourth hand-kept source of truth._ -**Status:** TypeScript reference helpers, unreleased, targeting 1.2.1 (FR-022; -[ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md) Amendment 10). They are listed +**Status:** TypeScript reference helpers, unreleased (FR-022; +[ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md) Amendment 10; the changelog's +unpublished `[1.3.0]` / `[1.2.4]` sections carry them). They are listed by `meta gen --list`, imported from `@metaobjectsdev/codegen-ts/generators` to run as shipped, copied with `meta eject contract-schema openapi` to change them, and checked by `meta verify --codegen`. They are not core: what MetaObjects guarantees is the model, and a generator that writes files into your diff --git a/docs/features/entities.md b/docs/features/entities.md index bde41e9586..f31c4b276f 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -127,6 +127,35 @@ you don't own (rather than extending it) must say `overlay: true`, so its remova upstream fails loudly instead of silently becoming a new, disconnected object — see [`abstracts-and-inheritance.md`](abstracts-and-inheritance.md#the-same-rule-across-a-repository-boundary). +## Collection names (`@collectionName`) + +An object's **collection name** is what a port calls "the set of these": the C# `DbSet` +property, the REST collection segment (snake_cased: `ConsignmentHistory` → `/consignment_history`), the +TypeScript collection exports (`listConsignmentHistory`, `findConsignmentHistoryByConsignment`, the Drizzle +collection variable `consignmentHistory`) and the reverse `@via` hop another object walks to reach its +rows (`Consignment.consignmentHistory`). Declare it in the object's own casing; it need not be a grammatical +plural: + +```yaml +- object.entity: + name: ConsignmentHistory + "@collectionName": ConsignmentHistory +``` + +Absent, the project's **pluralizer** derives it from the object's name. One setting, +`naming.collections` in `.metaobjects/config.json`, selects it by name, exactly as `naming.columns` +selects a column rule. Built in: `standard` (the default — the rule every port shares: an +already-plural name stays, else `-s`/`-es`/`-ies`) and `none` (the name as it is). An application +registers its own (`namingStrategies.collections` in `metaobjects.config.ts`; `registerPluralizer` +in TypeScript and Java, `NamingStrategies.RegisterPluralizer` in C#, `register_pluralizer` in +Python), and a name nothing answers is refused when the config is read. An object's own +`@collectionName` always wins. + +`@collectionName` and `naming.collections` are implemented in every port (ruling R40 kind 1): +each port's route/controller path (and the C# `DbSet` name) reads the declared name or the +configured pluralizer. In C#, a project that configures no pluralizer keeps its historical DbSet names (which +add C#'s `-sis` → `-ses` rule). + ## What each port generates ### TypeScript diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 39c63b5b29..76c759c50b 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -258,6 +258,26 @@ Two rules follow from int-backing being a **persistence-layer codec**: to the database: an unmapped symbol binds unchanged, so the column type and its `CHECK` reject it. +**A stored spelling per member (rc.21):** `@stringValueMap` gives each member of a +string-stored enum the string its column holds, when the database's spelling is not the +member symbol — a legacy column holding lowercase `draft`, or `LEGACY_A`: + +```json +{ "field.enum": { "name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } } } +``` + +The generated enum type and the wire keep the members (`Draft`); the column, its `CHECK`, +its length (`@maxLength` must fit the longest stored string), a `@default` and a `@condition` +or `@equals` literal hold the stored strings. It is the string twin of `@intValueMap`, with its +rules: keys must match `@values` exactly, values are unique non-empty strings, and a shared +enum declares it on the shared declaration. It is refused beside `@intValueMap` and on an array +enum (`ERR_BAD_ATTR_VALUE`). A stored string that maps to no member throws on read, as an +unmapped integer does. Where each port maps it: the C# EF converter and `CHECK`; `meta migrate`, +the Drizzle column codec, the runtime ObjectManager and the view, report and Cube lowerings +(TypeScript); the OMDB codec (Java); the Exposed `customEnumeration` (Kotlin); the generated +Spring enum's `dbValue()` (for a hand-written repository); the Python ObjectManager. + ### Sharing one enum — abstract `field.enum` + `extends` Reuse a constraint set across entities by declaring one **abstract** `field.enum` diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 7ede1738b7..b59d8c57cb 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -418,7 +418,7 @@ the re-diff is empty afterwards. Postgres keeps `IS [NOT] DISTINCT FROM`. A `validator.*` node and a `field.enum`'s member list each become a CHECK constraint. A validator on a derived field — one carrying an `origin.*`, or a cross-field validator naming one — makes none: the field is no column of the table, so a CHECK on it would fail `CREATE TABLE`; the C# -context skips the same validators. Three +context skips the same validators. Four attributes shape it, all database-only (no generated code reads them): - **`@constraintName`** names the CHECK, for a database whose CHECKs were named by hand. On the @@ -431,6 +431,18 @@ attributes shape it, all database-only (no generated code reads them): (Postgres would truncate it, and the CHECK would never match its declaration). A CHECK with a declared name is always emitted, even where `migrate.checks.skipRedundant` (below) would leave it out. +- **`@dbCheck: false`** leaves the CHECK out: `meta migrate`, `meta verify --db` and a generated + EF model declare none for that validator or enum (absent, `true`). It is per node, on a + `numeric`, `length` or `regex` validator and on `field.enum`. Use it for a column whose legacy + rows break the rule: a CHECK added `NOT VALID` still refuses an `UPDATE` of such a row, whatever + the update changes. The generated app-level validation is unchanged, so the validator still holds + every write and an enum's members still bound the property. A cross-field validator + (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, `exactlyOne`) is enforced only by its CHECK, so + `false` on one is refused (`ERR_CROSS_FIELD_WITHOUT_CHECK`): remove the validator instead. + A live CHECK the model no longer declares is proposed for dropping (under `--allow drop-check` + on Postgres). Declaring `@constraintName` too is refused (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`): + there is no CHECK for the name to name. `migrate.checks.skipRedundant` (below) is independent: + it only ever leaves more out. - **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, `exactlyOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. It refuses `case` and `now` (`ERR_BAD_ATTR_VALUE`): a database CHECK can hold neither. diff --git a/docs/features/migrations/emit-attrs-to-generator-config.md b/docs/features/migrations/emit-attrs-to-generator-config.md index 64cf3dd4f1..056a6a48f9 100644 --- a/docs/features/migrations/emit-attrs-to-generator-config.md +++ b/docs/features/migrations/emit-attrs-to-generator-config.md @@ -72,7 +72,7 @@ Because a `filter` only narrows, it cannot express an opt-*in*. Per-subtype grid TPH subtypes therefore moved to a generator **option**: ```ts -const tphGrids = (e) => e.name === "Copay"; +const tphGrids = (e) => e.name === "Coupon"; export default defineConfig({ generators: [ diff --git a/docs/features/migrations/physical-naming.md b/docs/features/migrations/physical-naming.md index 7ba8c87712..0ebed594ac 100644 --- a/docs/features/migrations/physical-naming.md +++ b/docs/features/migrations/physical-naming.md @@ -133,6 +133,14 @@ example: It never falls back to the default, because the old value may be the one that matches your database, and the default would rename every column. +### Collection names (`naming.collections`) + +`naming.collections` selects the **pluralizer** an object without `@collectionName` takes its +collection name from (rc.19): `standard` (the default) or `none`, or one the application +registers — `namingStrategies: { collections: { … } }` / `registerPluralizer` (TypeScript), +`NamingStrategies.RegisterPluralizer` (C#). It is not a physical name; it lives under `naming` +because it is chosen and validated the same way. See [entities](../entities.md#collection-names-collectionname). + ## TypeScript Default unchanged (`snake_case`). diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index f8d5c5c356..353aaf5c07 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -615,6 +615,21 @@ handles those files by one rule: that name is not mistaken for generated output. - **A dry run** (`meta gen --dry-run`) reports what it would remove and removes nothing. +On **C#**, a self-hosted runner that makes one `CodegenRunner.Run` per target sweeps once, after +all of them. Give every run the same `GenStateDir` and `ProjectRoot` and leave `SweepOrphans` off +(one run's files look orphaned to another), then call `OrphanSweep.Sweep(genStateDir, projectRoot, +dirs, emitted)` with every run's output directories and the union of their +`RunResult.EmittedPaths`. It is the rule above: only a file the manifest records with its hash is +deleted, an edited one is refused by name, and `` alone proves nothing (it is the +.NET convention, which Roslyn source generators and hand-written partials carry too). Paths compare +case-insensitively, so a case-only rename on macOS or Windows keeps its file. `dryRun: true` +reports and changes nothing. A runner that wrote files before it kept a manifest passes +`reportUnrecorded: true` once: `Result.Unrecorded` lists the files whose header says +`Generated by MetaObjects` but that the manifest does not record, for you to delete by hand; with no +recorded hash, an edited one cannot be told from an untouched one, so none is deleted. The first run +over files already on disk records the ones that match the fresh output and refuses the rest, as +any first `gen` with a manifest does; `Baseline = "adopt"` records what is on disk instead. + On **Java and Kotlin** every `mvn metaobjects:generate` execution runs the whole `` list, since there is no `--generators` narrowing; a run narrowed by `meta.entities` is the one exception, and it deletes no orphaned file (see diff --git a/docs/features/relationships.md b/docs/features/relationships.md index aceaeafac9..873c063677 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -173,12 +173,151 @@ reverse-engineered model can `@via` its reference directly: ``` A reference hop is inherently **to-one** (a child names the parent it points at), so it -is valid in a `passthrough` and rejected in an `aggregate`. An origin `@via` hop may -also walk an `identity.reference` **backwards** (parent → many children), named by the -holder's collection name in lowerCamel (`Patient.consents`). A reverse hop is to-many, so -it is valid in an `aggregate` and rejected in a `passthrough` (`ERR_ORIGIN_CARDINALITY`); -two candidate holders give `ERR_AMBIGUOUS_PATH`, and a declared relationship or reference -of the same name wins. Single-hop-unique inference stays relationship-only. +is valid in a `passthrough` and rejected in an `aggregate`. + +The same reference can be walked **backwards**, parent → many children, with no relationship +declared for it: the hop is named by the referencing entity's collection name, lowerFirst +(`contracts` for `Contract`; its `@collectionName`, else the project's pluralizer — see +[entities](entities.md#collection-names-collectionname)), and it is to-many, so it is valid in an +`aggregate` or `first` and rejected in a `passthrough`: + +```yaml +# Contract has `identity.reference: { name: player, references: Player }`; Player declares nothing: +- origin.aggregate: { agg: count, of: "Contract.id", via: "Player.contracts" } +``` + +A relationship or reference of that name on the parent wins. Two references from `Contract` +to `Player` make `Player.contracts` ambiguous, and the loader refuses it naming both +(`ERR_AMBIGUOUS_PATH`); declare a relationship for the hop instead. Explicit `@via` resolves +every kind; single-hop-unique inference stays relationship-only. + +## Filtering and computing over joined rows (rc.19) + +A projection view can read more than the columns it outputs. Each form below lowers to SQL in +the view `meta migrate` creates (every port's view is built by that one lowering; C# and the +other ports validate the metadata the same way and map the view's columns). + +**A filter path** (G7). A projection `@filter` key may name a base-entity field the view does +not output, or a *path* of to-one hops from the base — named as an `@via` names them — then a +field of the entity reached. The view joins along the path (sharing any join an origin already +walks) and filters on the column. A to-many hop would multiply the base rows and is refused +(`ERR_BAD_ATTR_FILTER`). + +```yaml +"@filter": { "orderId.status": open } # JOIN orders o … WHERE o.status = 'open' +``` + +**A derived field declared once on an entity** (entity-derived). An entity may declare an +`origin.first` or `origin.computed` field with no read source of its own, as long as some +projection reaches it — through a filter key or path, a passthrough `@from`, or a field bound +to it. It is no column of the table (no ORM property either); where a projection reaches it, +its derivation is inlined: an `origin.computed` as its expression on the reached row, an +`origin.first` as its correlated subquery keyed on the reached row. An `origin.aggregate` is +not inlinable. Unreached, the entity still needs a read source (`ERR_DERIVED_FIELD_NO_READ_SOURCE`). + +**A segment on an origin** (origin-segment). `@segment` on `origin.first` or `origin.aggregate` +names a `segment.filter` of the related entity; its predicate scopes the related rows, ANDed +with `@filter`, exactly as `measure.aggregate @segment` does. An unknown name is +`ERR_INVALID_ORIGIN`. + +**Relative dates** (now). `{ now: "", startOf? }` is legal in a +projection's `@filter` and an origin's `@filter` as well as on the reporting hosts, on a date +or timestamp field, under `gt`/`gte`/`lt`/`lte`; and as an expression leaf, where it takes the +kind of the field it is compared with. It is evaluated when the view is queried, on the UTC +clock. + +**A base-row operand** (correlated-filter). In an origin's `@filter`, `{ field: "" }` +is the base row's column: `{ statusId: { eq: { field: statusId } } }`. It takes +`eq`/`ne`/`gt`/`gte`/`lt`/`lte` and the null-safe `isDistinctFrom` / `isNotDistinctFrom` +(`IS [NOT] DISTINCT FROM` on Postgres, `IS [NOT]` on SQLite), which take only such an operand. + +**Expressions over joined fields and CASE** (computed-over-joined, case). In an +`origin.computed` expression, `{ field: X }` names one of the projection's own fields first — a +passthrough (joined or not), an `origin.first`, or another `origin.computed` — else a base +field; never an aggregate, and a cycle is refused. A `case` node is searched +(`{ case: [ { when: , then: } ], else: }`) or, with `operand`, simple +(each `when` a value compared with it); every result has one type. + +The league-gate shape uses all of them at once: a `segment.filter` on `Contract` with `now`, a +boolean on `Player` declared as `origin.first { @via: Player.contracts, @segment: … }`, and +`@filter: { "campId.playerId.hasActiveLeagueContract": true }` on every gated projection. +`fixtures/conformance/entity-derived-league-gate` pins the metadata; +`codegen-ts/test/projection/league-gate-entity-derived.test.ts` pins the view and runs it. + +### rc.21: the rest of what a view needs + +These constructs let a projection build the views that needed a hand-written `@sql` body. Every +one is a closed, typed construct: nothing is free SQL. Only the TypeScript view emitter lowers +them (C# validates them at load; Java and Python accept them under strict load). + +**A cast** (`{ cast: , as: , dbColumnType? }`). `as` is one of `string`, +`int`, `long`, `double`, `float`, `decimal`, `boolean`, `date`, `timestamp`, `uuid`, and the +column type is that subtype's. A string cast may name a text `@dbColumnType` spelling (`text`, +`varchar`, `character varying`, `varchar(n)`, `character varying(n)`, `character(n)`): a typed +NULL of an unbounded varchar is `{ cast: { value: null }, as: string, dbColumnType: varchar }`. +An enum casts to an integer only when it is stored as one (`@intValueMap`), which is also how an +int-stored enum and an int meet in one `case`: `then: { cast: { field: status }, as: int }`. + +**Functions** (`{ fn, args }`). Beside `coalesce`: `greatest` and `least` (ordered arguments of +one type), `nullif` (two of one type), `lower`, `upper`, `btrim` (a string, optionally the +characters), `splitPart` (string, delimiter, integer), `concat` (scalars; NULL reads as empty), +`concatWs` (a separator, then scalars), `substring` (string, start, optional length), `replace`, +`left` and `right` (string, integer), and `length` (string to int). Each argument is typed; a +NULL literal fits any. On SQLite each is spelled with SQLite's own functions where the meaning +is the same (`greatest` keeps Postgres's NULL-skipping), and refused where it is not: +`splitPart` beyond the first part. + +**A path in an expression or an operand.** On a projection, `{ field: "customerId.regionId" }` +in an `origin.computed` expression, or `{ field: "orderId.customerId" }` as a correlated operand in an +origin's `@filter`, is a path of to-one hops from the base and a field of the entity reached: +the view joins it without outputting it. + +**An expression over an aggregate.** `{ field }` may name a scalar `origin.aggregate` of the +projection (`count`/`sum`/`avg`/`min`/`max`, `any`/`all`), read on the grouped row: +`{ fn: greatest, args: [ { field: updatedAt }, { field: lastEvent } ] }`. Such a value is not +filterable (it exists only after grouping). A grouped view also groups every joined column its +expressions read. + +**A database function the project owns** (`origin.function`). `@function` and `@schema` name it +(plain identifiers), `@args` the fields passed to it in order, `@params` their declared types and +`@returns` the result's (field subtypes). Each argument must have its parameter's type — pass an +`origin.computed` field that casts it (`{ cast: { field: x }, as: int }`) otherwise — and +`@returns` must be the carrying field's subtype; the view casts the call to the field's full +column type, the one its table column would have (length or `@dbColumnType` spelling, precision and +scale, a local or zoned timestamp). The signature is a declaration that `meta verify --db` checks: +it reads the function from `pg_proc` and fails on a missing function, or a parameter or return +type that differs, so the cast never hides a wrong `@returns`. A declared arity between the +function's required and full parameter counts matches (the rest take their defaults). The +comparison is by plain type name: a json, array, enum or user-defined kind is not type-checked +(only the arity is), and a domain is compared by its own name, so a domain-typed parameter or +result is reported as a mismatch. Declared on an entity, it is +entity-derived: a projection reaching the entity reads it like any derived field. MetaObjects +never creates the function (it is owned SQL, created before the view). Postgres only. + +```yaml +- field.int: + name: riskScore + children: [ { origin.function: { "@function": compute_risk_score, "@schema": app, "@args": [id], "@params": [long], "@returns": int } } ] +``` + +**One row per array element** (`@grain`, `@grainOrdinal`). A projection whose `@grain` names a +base-entity `field.object` array stored as jsonb has one row per element (`jsonb_array_elements +… WITH ORDINALITY` on Postgres, `json_each` on SQLite); a base row with no element has no row. A +field whose `origin.passthrough @from` names the array's value object (`Contact.kind`) reads that +member of the element, cast to the field's type; the base's own fields read the parent row. +`@grainOrdinal` names a `field.int`/`field.long` of the projection that holds the 1-based +position. No `origin.aggregate` on such a projection. + +**A union** (`@union`, `@unionAll`). A projection that extends one branch and names the others in +`@union` is the UNION of their rows; each branch has its own base, joins and `@filter`, and every +branch has the same fields in order (name, subtype, array-ness, `@column`), checked at load +(`ERR_BAD_ATTR_VALUE`). Duplicates are removed (UNION, SQL's default) unless `@unionAll: true`. + +**Two related rules.** A reference walked backwards is to-one for a passthrough when its holder +declares a unique identity (`identity.primary` or `identity.secondary`) over exactly its fields. +And a projection that extends another and declares no identity of its own keeps the identity its +super anchors with, so a TPH root's projection can add a subtype's column and still read the +root's shared table. ## When one entity has two references to the same target @@ -281,7 +420,7 @@ level between the base and a subtype. Both cases are treated the same way: - field.long: { name: id } - field.enum: name: type - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] - field.long: { name: approverId } # FK to the approver - identity.reference: name: fkApprover diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 001f08b549..9bcc947696 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -269,7 +269,7 @@ physical column name is your naming strategy applied to the **derived field name | Item | Column | Type | Never null? | |---|---|---|---| -| `dimension.attribute` | the dimension's name | the `@of` field's type | only when the `@of` field is required (`@required: true` or a `validator.required` child) and the dimension has no `@via`, or every hop of its `@via` is an enforced belongs-to reference over a required foreign key (below) | +| `dimension.attribute` | the dimension's name | the `@of` field's type | only when the `@of` field is required (`@required: true` or a `validator.required` child) and the dimension has no `@via`, or every hop of its `@via` is a required, enforced reference onto a target that hides no rows (below) | | `dimension.time` at `hour` | `Hour` | `timestamp` | same rule | | `dimension.time` at `day`, `week`, `month`, `quarter`, `year` | `` | `date`, the first day of the bucket | same rule | | `count` (with or without `@distinct`) | the measure's name | `long` | yes: a count is never null | @@ -287,19 +287,19 @@ physical column name is your naming strategy applied to the **derived field name | any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads its `@default` instead of null | | in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the `@of` field is required (`@required` or a `validator.required` child) or one of the spine entity's `identity.primary` `@fields`; no for a dimension reached beyond the spine entity | -The last two rows, and the enforced-reference rule above, are the only ways a measure other than -`count`, or a dimension reached through `@via`, is never null. The key clause applies only under +The last two rows, and the path rule above, are the only ways a measure other than `count`, +or a dimension reached through `@via`, is never null. The key clause applies only under `@spine`, where the key is the row's own. Without `@spine`, a dimension reached through `@via` is never null when its `@of` field is -required and **every hop is an enforced belongs-to reference over a required foreign key**: the -entity the hop leaves holds the `identity.reference`, its first `@fields` entry is required, and -the reference is enforced (`@enforce` defaults to true), so the join always finds a match. Every -hop a view or report makes joins `LEFT OUTER` (this changed — a required reference is no longer -inner-joined), so a join never drops a base row, whatever the reference's `@enforce` says; for -these hops the match is guaranteed, so the outer join never nulls the column either. A hop over -an optional foreign key, a to-one relationship whose foreign -key the other entity holds, or any hop under `@spine` stays nullable. Every port derives the same answer +required and **every hop is certain to match**: the entity the hop leaves holds the +`identity.reference`, its first `@fields` entry is required, the reference is enforced (not +`@enforce: false`, which can name a row that does not exist), and the target hides no rows (it +is not a TPH subtype, whose join carries the discriminator). Every join is `LEFT OUTER` (rc.19), +and over such a path it returns exactly what `INNER` would, so the column is never +null-extended. A hop over an optional or unenforced foreign key, onto a TPH subtype, a to-one +relationship whose foreign key the other entity holds, or any hop under `@spine` leaves the +dimension nullable. Every port derives the same answer (`fixtures/persistence-conformance/report-shapes.json`). A derived column carries the type-shaping attributes of its `@of` field where they apply @@ -491,13 +491,13 @@ Every other join of a `@spine` report is `LEFT OUTER` too, so no join can drop a COUNT(p."id") FILTER (WHERE p."status" = 'active') AS "purchases", COALESCE(CAST(SUM(p."amountCents") FILTER (WHERE p."status" = 'active') AS BIGINT), 0) AS "revenue", CAST(COALESCE(CAST(SUM(p."amountCents") FILTER (WHERE p."status" = 'active') AS BIGINT), 0) AS NUMERIC) / NULLIF(COUNT(DISTINCT p."customerEmail"), 0) AS "revenuePerBuyer" - FROM "programs" p0 - LEFT OUTER JOIN "purchases" p ON p0."id" = p."programId" + FROM "public"."programs" p0 + LEFT OUTER JOIN "public"."purchases" p ON p0."id" = p."programId" GROUP BY p0."id", p0."title" ``` With `"@segment": "active"` on the report, the join would read -`LEFT OUTER JOIN "purchases" p ON p0."id" = p."programId" AND p."status" = 'active'`. The +`LEFT OUTER JOIN "public"."purchases" p ON p0."id" = p."programId" AND p."status" = 'active'`. The aliases are the ones the same report would get without `@spine`. `meta migrate` refuses a derived `@spine` report, naming the report and the spine, when: diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 86094d6ddb..d75e41ef9a 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -186,8 +186,8 @@ inherited rather than re-invented per project: ``` L1 Security (an ISO/IEC 25010 characteristic) └ L2 Confidentiality (its sub-characteristic — or a control - │ catalogue's own category, e.g. a HIPAA - │ safeguard class, when one applies) + │ catalogue's own category, e.g. a SOC 2 + │ trust-services criterion, when one applies) └ L4 invoiceTotalsAreEncryptedAtRest (the claim, bound to the model) ``` diff --git a/docs/features/source-kinds.md b/docs/features/source-kinds.md index 5e564bafc5..c9bde08ed1 100644 --- a/docs/features/source-kinds.md +++ b/docs/features/source-kinds.md @@ -157,6 +157,12 @@ set operation) blocks projection authoring — then carry that body in the `sour which keeps it tool-managed (registered, fingerprinted, drift-checked) instead of accidentally-unmanaged in a hand-edited migration file. +On Postgres every relation a generated view reads is **schema-qualified**: its `@schema`, or +`public` when none is declared (`FROM public.orders o`, `JOIN crm.customers c`; ruling R54). A +bare name binds through the `search_path` current when the view is created, so a view in +`reporting` over a bare `orders` is one `search_path` away from reading a `reporting.orders`. +SQLite and D1 have no schemas there and stay bare. A report view follows the same rule. + ```json { "object.projection": { diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 7bcb8c9d15..bf128e5071 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -465,7 +465,7 @@ differently (an acronym, say), set one resolver on the config, `GenConfig.Proper `[PrimaryKey(nameof(...))]`, every `AppDbContext` model line and the reverse finders all read it, so the declaration and every reference agree. The hooks `EntityGenerator.PropertyName` and `DbContextGenerator.PropertyName` default to it; a subclass that overrides one must override the -other the same way. The routes generator and the filter runtime still use the PascalCased name. +other the same way. The routes generator, the filter map and the credential stripping read the same resolver, and a hook that disagrees with it is refused. **Class attributes.** `EntityGenerator.EmitClassAttributes(sb, entity, className, kind, ctx)` is called for every class it emits (mapped entity, TPH subtype, abstract shape, value object), after @@ -540,6 +540,17 @@ The start in the model, and the services, are emitted only for a project whose package. `UseIdentityStartMigrations()`, the registration of an earlier runtime SQL rewrite, is kept as an `[Obsolete]` no-op so a call to it still compiles; remove the call. + +**CHECK constraints** are the ones `meta migrate` creates: each scalar `field.enum` +and each validator that can carry one (`numeric`, `length`, `regex`, `comparison`, +`requiredWhen`, `presentIff`, `atLeastOne`, `exactlyOne`, with `@condition`) is a +`modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(name, sql))` line, with migrate's name +(`
__numeric_chk`, … or the validator's `@constraintName`) and its expression text, +so a table built by an EF migration and one built by `meta migrate` carry the same constraints. +They are declared for `migrate.dialect` `postgres`, `sqlite` or `d1` only, because the text is +dialect-specific (`~`, `IS DISTINCT FROM`, `num_nonnulls` on Postgres); `migrate.checks.skipRedundant` +(`GenConfig.SkipRedundantChecks`) leaves out the ones the column already enforces, as migrate does. +The shared corpus `fixtures/check-constraint-conformance/` pins the names and text in both ports. ### Decimals and null members on the wire What the generated API writes is the project setting `wire` in `.metaobjects/config.json` @@ -683,15 +694,15 @@ can be inherited — and an object that extends another produces a class that ex other's: ```csharp -public abstract class CopayAuthNames : AuthNames +public abstract class CouponAuthNames : AuthNames { - public const string CopayAmountField = "copayAmount"; - public const string CopayAmountColumn = "copay_cents"; + public const string CouponAmountField = "couponAmount"; + public const string CouponAmountColumn = "coupon_cents"; public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "CopayAuth"; + public new const string Name = "CouponAuth"; // SourcePrimaryTable / IdColumn / … are the base's. A C# const is inherited, so - // CopayAuthNames.SourcePrimaryTable and CopayAuthNames.IdColumn both resolve. + // CouponAuthNames.SourcePrimaryTable and CouponAuthNames.IdColumn both resolve. } ``` diff --git a/docs/ports/java.md b/docs/ports/java.md index 9f5235f82b..275fbe043c 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -725,15 +725,15 @@ implicit `super()` has to reach it), and an object that extends another produces a class that extends the other's: ```java -public abstract class CopayAuthNames extends AuthNames { +public abstract class CouponAuthNames extends AuthNames { public static final String TYPE = "object"; public static final String SUB_TYPE = "entity"; - public static final String NAME = "CopayAuth"; // its OWN name, not the base's + public static final String NAME = "CouponAuth"; // its OWN name, not the base's - public static final String COPAY_AMOUNT_FIELD = "copayAmount"; - public static final String COPAY_AMOUNT_COLUMN = "copay_cents"; + public static final String COUPON_AMOUNT_FIELD = "couponAmount"; + public static final String COUPON_AMOUNT_COLUMN = "coupon_cents"; // SOURCE_PRIMARY_* / ID_COLUMN / … are the base's. Java inherits static members, - // so CopayAuthNames.SOURCE_PRIMARY_TABLE and CopayAuthNames.ID_COLUMN both resolve. + // so CouponAuthNames.SOURCE_PRIMARY_TABLE and CouponAuthNames.ID_COLUMN both resolve. } ``` @@ -741,8 +741,8 @@ Which members a class declares is structural, and follows one rule: it declares what the object DECLARES, and inherits the rest. A TPH subtype sharing its base's single table declares no source of its own, so its whole `SOURCE_PRIMARY_*` block comes from the base. Its `TYPE`/`SUB_TYPE`/`NAME` are -always restated, because they differ — `CopayAuthNames.NAME` has to say -`"CopayAuth"`. An abstract base a persisted entity extends gets a class of its +always restated, because they differ — `CouponAuthNames.NAME` has to say +`"CouponAuth"`. An abstract base a persisted entity extends gets a class of its own carrying the columns and keys it declares and **no `SOURCE_*` block at all** — it has no table, and must never acquire one. `COLUMNS_BY_FIELD` stays complete on every class, inherited entries included. diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index f208af6050..17b9253da9 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -822,9 +822,9 @@ Kotlin has no static inheritance — an `object` cannot extend another — so an object extends another re-exports the inherited constants by REFERENCE: ```kotlin -object CopayAuthNames { - const val NAME: String = "CopayAuth" // its OWN name, always restated - const val COPAY_AMOUNT_COLUMN: String = "copay_cents" +object CouponAuthNames { + const val NAME: String = "CouponAuth" // its OWN name, always restated + const val COUPON_AMOUNT_COLUMN: String = "coupon_cents" // A TPH subtype declares no source of its own, so the SHARED table — and every // inherited column — is re-exported by reference and spelled once, on the base. diff --git a/docs/ports/python.md b/docs/ports/python.md index 5b198ec5d6..4fbb3f3991 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -553,16 +553,16 @@ from its parent's.** Python has no static inheritance, so an artifact whose object extends another re-exports the inherited constants by REFERENCE: ```python -# generated/copay_auth_names.py (excerpt) +# generated/coupon_auth_names.py (excerpt) from .auth_names import ( AUTH_ID_COLUMN, AUTH_ID_FIELD, AUTH_IDENTITY_PK_NAME, AUTH_SOURCE_PRIMARY_KIND, AUTH_SOURCE_PRIMARY_TABLE, ) -COPAYAUTH_NAME: Final[str] = "CopayAuth" # its own name, always -COPAYAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE # SHARED, spelled once -COPAYAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN -COPAYAUTH_COPAY_AMOUNT_COLUMN: Final[str] = "copay_cents" +COUPONAUTH_NAME: Final[str] = "CouponAuth" # its own name, always +COUPONAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE # SHARED, spelled once +COUPONAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +COUPONAUTH_COUPON_AMOUNT_COLUMN: Final[str] = "coupon_cents" ``` Two forms, and which one you get is structural. An object with its OWN source diff --git a/docs/ports/typescript-client.md b/docs/ports/typescript-client.md index 72dfbeffa5..76c4ffb776 100644 --- a/docs/ports/typescript-client.md +++ b/docs/ports/typescript-client.md @@ -596,7 +596,7 @@ are opt-**IN**. Opting in WIDENS, which a `filter` cannot express — it is a generator option instead, defaulting to `() => false`: ```ts -const perSubtypeGrid = (e: MetaObject) => e.name === "CopayAuth"; +const perSubtypeGrid = (e: MetaObject) => e.name === "CouponAuth"; tanstackGrid({ tphSubtypeGrids: perSubtypeGrid }), tanstackGridHook({ tphSubtypeGrids: perSubtypeGrid }), diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 0fa58d429c..c61e92fd4a 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -647,14 +647,14 @@ a log line, an external system's column mapping. object extends another spreads the parent's collections rather than restating them: ```ts -export const CopayAuthNames = { +export const CouponAuthNames = { type: "object", subType: "entity", - name: "CopayAuth", + name: "CouponAuth", sources: { ...AuthNames.sources }, // the SHARED table, named once on the base fields: { ...AuthNames.fields, - copayAmount: { name: "copayAmount", column: "copay_cents" }, + couponAmount: { name: "couponAmount", column: "coupon_cents" }, }, identities: { ...AuthNames.identities }, indexes: { ...AuthNames.indexes }, @@ -669,7 +669,7 @@ which is what a single-table hierarchy legitimately has two of. An abstract base a persisted entity extends gets an artifact of its own, carrying the columns it declares and an **empty `sources`** — it has no table, and must never acquire -one. Reading `CopayAuthNames.sources.primary.table` still works: the spread resolves it, +one. Reading `CouponAuthNames.sources.primary.table` still works: the spread resolves it, with the literal types intact. ## Use @@ -701,7 +701,7 @@ export const db = drizzle(createClient({ url: "file:dev.sqlite" })); ```ts // src/server.ts import Fastify from "fastify"; -import { authorRoutes } from "./generated/Author.routes.js"; +import { authorRoutes } from "./generated/acme/blog/Author.routes.js"; const app = Fastify(); await app.register(authorRoutes); // mounts GET/POST/PATCH/PUT/DELETE for Author @@ -715,7 +715,7 @@ module-level singleton wired above, so `server.ts` never passes it explicitly. (`apiPrefix` in `metaobjects.config.ts` wraps the registration in a `fastify.register(..., { prefix })` block when set — see [`features/api-contract.md`](../features/api-contract.md).) The per-verb query -helpers (`findAuthorById`, ...) live in the sibling `./generated/Author.queries` +helpers (`findAuthorById`, ...) live in the sibling `./generated/acme/blog/Author.queries` file and take `db` as an explicit first argument — useful directly in request handlers, tests, or any runtime where a module singleton doesn't fit (see the recipe above). @@ -732,7 +732,7 @@ npx tsx src/server.ts # stock Node Node's built-in TypeScript support is **not** enough here — `node src/server.ts` (type stripping, on by default in Node 24; `--experimental-strip-types` before that) strips the types but deliberately does not rewrite module specifiers, so -the generated `import … from "./generated/Author.routes.js"` fails with +the generated `import … from "./generated/acme/blog/Author.routes.js"` fails with `ERR_MODULE_NOT_FOUND`. Run it through `tsx` as above, or compile with `npx tsc` first and run the emitted JavaScript. @@ -827,7 +827,7 @@ binding exists only on `env`, so build the client and mount inside `fetch`: ```ts import { Hono } from "hono"; import { drizzle } from "drizzle-orm/d1"; -import { registerAuthorRoutes } from "./generated/Author.routes.hono.js"; +import { registerAuthorRoutes } from "./generated/acme/blog/Author.routes.hono.js"; interface Env { DB: D1Database } diff --git a/docs/recipes/cloudflare-workers.md b/docs/recipes/cloudflare-workers.md index 7243d1a51c..cf659a8143 100644 --- a/docs/recipes/cloudflare-workers.md +++ b/docs/recipes/cloudflare-workers.md @@ -143,6 +143,7 @@ import { entityFile, queriesFile, routesFileHono, barrel } from "@metaobjectsdev export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "sqlite", // D1 is SQLite extStyle: "js", apiPrefix: "/api", diff --git a/docs/recipes/drizzle-kit-migrations.md b/docs/recipes/drizzle-kit-migrations.md index b13bb998f5..88d4af2803 100644 --- a/docs/recipes/drizzle-kit-migrations.md +++ b/docs/recipes/drizzle-kit-migrations.md @@ -17,6 +17,7 @@ schema file that exports them. `meta migrate` never has to run. export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", // must match the database drizzle-kit migrates generators: [entityFile(), queriesFile(), barrel()], }); diff --git a/docs/recipes/guarding-generated-routes.md b/docs/recipes/guarding-generated-routes.md index 2eeed7bcee..4e7dd44c6c 100644 --- a/docs/recipes/guarding-generated-routes.md +++ b/docs/recipes/guarding-generated-routes.md @@ -17,6 +17,8 @@ Register the generated handler inside a scope that carries your hook. Fastify ho encapsulated per plugin and inherited by child scopes, so the hook reaches through the generated handler's own `register(..., { prefix })`: +The paths below assume `outputLayout: "flat"`; under the default (`package`) each module sits in its metadata package's directory (`./generated//Note.routes.js`). + ```ts import { noteRoutes } from "./generated/Note.routes.js"; diff --git a/docs/recipes/nextjs-vercel.md b/docs/recipes/nextjs-vercel.md index e4946a27e4..9857b5b047 100644 --- a/docs/recipes/nextjs-vercel.md +++ b/docs/recipes/nextjs-vercel.md @@ -36,6 +36,7 @@ import { entityFile, queriesFile, routesFileHono, barrel } from "@metaobjectsdev export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", apiPrefix: "/api", diff --git a/docs/recipes/wiring-generated-queries.md b/docs/recipes/wiring-generated-queries.md index 80262a3a0d..b8ac7ed983 100644 --- a/docs/recipes/wiring-generated-queries.md +++ b/docs/recipes/wiring-generated-queries.md @@ -274,6 +274,7 @@ import { honoRoutesFile } from "./metaobjects-routes-hono"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "sqlite", apiPrefix: "/api", generators: [entityFile(), queriesFile(), honoRoutesFile(), barrel()], diff --git a/docs/superpowers/plans/2026-05-20-schema-namespacing.md b/docs/superpowers/plans/2026-05-20-schema-namespacing.md index 4553805b4f..c000639954 100644 --- a/docs/superpowers/plans/2026-05-20-schema-namespacing.md +++ b/docs/superpowers/plans/2026-05-20-schema-namespacing.md @@ -844,11 +844,11 @@ Create `fixtures/conformance/source-db-table-with-schema/input/meta.demo.json`: "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ - { "source.dbTable": { "@name": "Cases", "@schema": "public" } }, + { "source.dbTable": { "@name": "Consignments", "@schema": "public" } }, { "field.long": { "name": "id" } }, - { "field.string": { "name": "caseNumber" } }, + { "field.string": { "name": "consignmentNumber" } }, { "identity.primary": { "@fields": "id" } } ] } @@ -867,11 +867,11 @@ Create `fixtures/conformance/source-db-table-with-schema/expected.json` with the "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ - { "source.dbTable": { "@name": "Cases", "@schema": "public" } }, + { "source.dbTable": { "@name": "Consignments", "@schema": "public" } }, { "field.long": { "name": "id" } }, - { "field.string": { "name": "caseNumber" } }, + { "field.string": { "name": "consignmentNumber" } }, { "identity.primary": { "@fields": ["id"] } } ] } diff --git a/docs/superpowers/plans/2026-05-22-field-object-storage.md b/docs/superpowers/plans/2026-05-22-field-object-storage.md index 6f53557716..8384faaaca 100644 --- a/docs/superpowers/plans/2026-05-22-field-object-storage.md +++ b/docs/superpowers/plans/2026-05-22-field-object-storage.md @@ -299,8 +299,8 @@ describe("@storage cross-attribute validation", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.dbTable": { "@name": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.dbTable": { "@name": "players" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "field.long": { name: "id" } }, { "identity.primary": { "@fields": "id" } }, @@ -439,8 +439,8 @@ describe("buildExpectedSchema — field.object @storage", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.dbTable": { "@name": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.dbTable": { "@name": "players" } }, { "field.long": { name: "id" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": "id" } }, @@ -449,8 +449,8 @@ describe("buildExpectedSchema — field.object @storage", () => { }, }); const snap = buildExpectedSchema(root, { dialect: "postgres" }); - const patients = snap.tables.find((t) => t.name === "patients")!; - const contactInfos = patients.columns.find((c) => c.name === "contact_infos"); + const players = snap.tables.find((t) => t.name === "players")!; + const contactInfos = players.columns.find((c) => c.name === "contact_infos"); expect(contactInfos?.sqlType.kind).toBe("json"); }); @@ -883,9 +883,9 @@ Expected: PASS. Adjust expected if needed. }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.long": { "name": "id" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": "id" } } @@ -918,9 +918,9 @@ Expected: PASS. Adjust expected if needed. }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.long": { "name": "id" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": ["id"] } } diff --git a/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md b/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md index 2315caa5ca..4f78d07b4f 100644 --- a/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md +++ b/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md @@ -306,9 +306,9 @@ public class FieldObjectStorageValidationTests ]}}, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } diff --git a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md index 0390f55989..788a417864 100644 --- a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md +++ b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md @@ -174,7 +174,7 @@ The FR specifies how the **calling code** emits. It does NOT specify whether sto - **Opt-in:** an additive attribute `@exposeAsRoute: true` on `source.rdb` causes `routesFile` to emit a `POST /procs/` (or whatever path the project's `apiPrefix` + naming convention dictates) accepting the `@parameterRef` value-object as the request body, returning the projection array. - **Generator surfaces gated by `@exposeAsRoute: true`** (when set): - `server/typescript/packages/codegen-ts/src/generators/routesFile.ts` — Fastify POST handler. - - `server/typescript/packages/codegen-ts-tanstack/src/generators/tanstackQuery.ts` — `useGetPhaseSummaryPerCase(args)` hook (a `useQuery` wrapping the POST since the args are a body). + - `server/typescript/packages/codegen-ts-tanstack/src/generators/tanstackQuery.ts` — `useGetStageSummaryPerConsignment(args)` hook (a `useQuery` wrapping the POST since the args are a body). - `server/typescript/packages/codegen-ts/src/generators/entityFile.ts` — Zod schema for the parameter value-object (already covered by the value-object's existing codegen path — should be no-op). - `server/java/codegen-spring/ControllerGenerator.java` — Spring `@PostMapping` analog. - C# / Kotlin / Python equivalents. @@ -202,15 +202,15 @@ After TS reference + REST decision, port the attr-registration + repo-emission p FR-014 covers the metamodel + ORM-layer emission. FR-017 covers everything else — the generator surfaces that surround a polymorphic entity. The next session writes FR-017 covering: -- **Discriminated TS union types.** `entityFile` emits `type Auth = BridgeAuth | CopayAuth | PriorAuthAuth | QuickStartAuth | UnknownAuth` as a tagged-union keyed by the discriminator field. -- **Per-subtype Zod schemas.** `entityFile` emits `BridgeAuthSchema`, `CopayAuthSchema`, etc., each `.merge(BaseAuthSchema)`. The TS reference + runtime `parse(json)` dispatch on the discriminator value. +- **Discriminated TS union types.** `entityFile` emits `type Auth = BridgeAuth | CouponAuth | PermitAuth | QuickStartAuth | UnknownAuth` as a tagged-union keyed by the discriminator field. +- **Per-subtype Zod schemas.** `entityFile` emits `BridgeAuthSchema`, `CouponAuthSchema`, etc., each `.merge(BaseAuthSchema)`. The TS reference + runtime `parse(json)` dispatch on the discriminator value. - **Polymorphic queries.** `queriesFile` always projects the discriminator column on `findAll/findById` for a discriminated base; row → subtype constructor dispatch. - **REST contract decisions** (and the design must MAKE these decisions, not punt): - `GET /auths` returns polymorphic rows tagged with the discriminator → `@type` field. - - `POST /auths` — choose: (a) removed in favor of per-subtype `POST /bridge-auths`, `POST /copay-auths`; (b) accepts a discriminated body with `type: "Bridge"` keying the validation branch. + - `POST /auths` — choose: (a) removed in favor of per-subtype `POST /bridge-auths`, `POST /coupon-auths`; (b) accepts a discriminated body with `type: "Bridge"` keying the validation branch. - **TanStack hooks.** `useAuths()` returns the union. Per-subtype hooks `useBridgeAuths()` filter on discriminator. Per-subtype mutations `useCreateBridgeAuth()`, etc. - **TanStack grid.** Decide: single polymorphic grid with mixed rows + a `@type` column, OR per-subtype grids? Specify. -- **React forms.** Per-subtype ``, `` etc. (you can't create an abstract `Auth`). +- **React forms.** Per-subtype ``, `` etc. (you can't create an abstract `Auth`). - **Filter allowlists.** Per-subtype filter allowlist auto-includes the discriminator field, pinned to that subtype's value. - **Spring (Java) generator stack.** `EntityGenerator` (JPA `@Inheritance`), `PayloadGenerator` (per-subtype request DTOs), `ControllerGenerator` (polymorphic GET + per-subtype POST), `RepositoryGenerator` (Spring Data repo on the base; per-subtype repos optional), filter-allowlist generator per subtype. - **Kotlin generator stack.** Sealed class hierarchy in `EntityGenerator`; per-subtype `ControllerGenerator`, `PayloadGenerator`, `FilterAllowlistGenerator`. diff --git a/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md b/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md index 3dd8fdabce..3802baf4f0 100644 --- a/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md +++ b/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md @@ -22,7 +22,7 @@ > **What's already shipped (read first):** > - Design + status: [FR-017 spec](../specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md) → see the **Realization status** section (Tier-4 TS foundations + Tier-5 corpora). > - **The oracle (do not modify — make each port match it):** -> - api-contract: `fixtures/api-contract-conformance/tph/` (Auth base + BridgeAuth/CopayAuth/PriorAuthAuth, 4 scenarios, both lanes). +> - api-contract: `fixtures/api-contract-conformance/tph/` (Auth base + BridgeAuth/CouponAuth/PermitAuth, 4 scenarios, both lanes). > - persistence: `fixtures/persistence-conformance/queries/tph-*.yaml` (4 scenarios) + `Auth`/subtypes in `canonical/meta.fitness.json` + the committed `canonical/schema.postgres.sql` (single `auths` table). The query DSL gained `create`/`update` ops + an `expectError` flag — each port's persistence runner must implement these. > - **migrate-ts TPH single-table EMISSION (Task C.1 + C.2 below) is DONE** — `expected-schema.ts` now folds subtype-only columns (nullable) into the single base table and skips subtype tables; the canonical `schema.postgres.sql` is regenerated + drift-checked green. The verify-time **drift rules (C.3/C.4 — `WARN_DISCRIMINATOR_VALUE_UNKNOWN` etc.) remain open** in this plan. Schema is TS-owned per ADR-0015, so **no per-port schema work** — every port executes the committed `schema.postgres.sql`. > - **TS reference to mirror** (per the cross-language-porting skill — mirror, don't re-derive): `server/typescript/packages/codegen-ts/src/templates/{tph-discriminator,drizzle-schema,routes-file}.ts`, `runtime-ts/src/drizzle-fastify/index.ts` (the `discriminator: {column,value}` option), and `runtime-ts/src/{tph.ts,object-manager.ts}` (effective-children resolution + discriminator inject/scope/strip — the runtime-layer reference). @@ -32,7 +32,7 @@ > 2. **Runtime/data-access TPH** so the port passes the `tph-*` persistence scenarios (inherited fields/identity/single-table resolution + discriminator inject/scope/strip + the new `create`/`update`/`expectError` DSL ops in the port's persistence-conformance runner). NB: Java/Kotlin/Python persistence-conformance runs the **generated** controller + a consumer-supplied repo seam per the api-contract README — confirm how each port's query runner executes writes. > 3. **Conformance, both corpora:** make the port green against `api-contract-conformance/tph/` (reference lane + GENERATED artifact over HTTP) and `persistence-conformance/queries/tph-*.yaml`. Until a port's slice lands it **skips** `tph-*` (the m2n-* convention) — do not delete fixtures. > -> **Cross-port invariants (byte-identical):** single `auths` table, subtype cols nullable; `GET /auths` polymorphic union + `GET|POST|PATCH|DELETE /auths/{bridge|copay|priorauth}` per subtype (segment = `@discriminatorValue` lowercased); discriminator injected from the URL on create (never the body); cross-subtype get/delete → 404; response always carries the discriminator field by value. +> **Cross-port invariants (byte-identical):** single `auths` table, subtype cols nullable; `GET /auths` polymorphic union + `GET|POST|PATCH|DELETE /auths/{bridge|coupon|permit}` per subtype (segment = `@discriminatorValue` lowercased); discriminator injected from the URL on create (never the body); cross-subtype get/delete → 404; response always carries the discriminator field by value. > > Use `superpowers:subagent-driven-development` to fan the three ports out. Each is gated by the corpus (the oracle), TDD-first. @@ -173,7 +173,7 @@ Recognize a TPH root by: an `object.entity` carrying `@discriminator` + at least #### C.2 — Single `CREATE TABLE` for the base Emit one `CREATE TABLE` for the discriminated base. Include: - All base fields as columns (nullability per their own `@required`). -- All subtype-only fields as columns, **automatically nullable** (TPH rule — a row that's a `Bridge` won't have `Copay`'s columns populated). +- All subtype-only fields as columns, **automatically nullable** (TPH rule — a row that's a `Bridge` won't have `Coupon`'s columns populated). - The discriminator column with the right type derived from the named field's subtype: - `field.enum` → `varchar` with `CHECK` constraint enumerating all subtype values. - `field.int` → `integer`. diff --git a/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md b/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md index fce0cd804e..0559b83bf3 100644 --- a/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md +++ b/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md @@ -809,7 +809,7 @@ live): DDL applies + converges; the discriminator column is `integer` with an in CHECK; a generated per-subtype create stores both enums as integers (asserted with raw SQL, bypassing the codec); the per-subtype read schema decodes a raw-SQL-inserted integer row; the per-subtype filter compares the integer; the polymorphic read dispatches on the -decoded value; and find-by-id is discriminator-scoped (a Copay row asked for as a Bridge +decoded value; and find-by-id is discriminator-scoped (a Coupon row asked for as a Bridge must MISS). **Two things the run surfaced, both pre-existing and both identical for a string-backed diff --git a/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md b/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md index 77b75ea781..1dc4e2fa3b 100644 --- a/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md +++ b/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md @@ -475,9 +475,9 @@ Edit `fixtures/api-contract-conformance/tph/seed.json` — add both columns set ```json "auths": [ - { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "copayAmount": null, "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 2, "type": "Copay", "reference": "REF-2", "quantity": null, "copayAmount": "12.50", "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 3, "type": "PriorAuth", "reference": "REF-3", "quantity": null, "copayAmount": null, "approver": "Dr. Smith","autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } + { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "couponAmount": null, "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 2, "type": "Coupon", "reference": "REF-2", "quantity": null, "couponAmount": "12.50", "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 3, "type": "Permit", "reference": "REF-3", "quantity": null, "couponAmount": null, "approver": "Dr. Smith","autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } ] ``` diff --git a/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md b/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md index e7be6c9e07..5d012a1da5 100644 --- a/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md @@ -51,7 +51,7 @@ Add two logical attributes on `object.entity`: { "field.enum": { // the discriminator field itself "name": "type", "@column": "Type", // physical column name lives here, not on source.rdb - "@values": ["Unknown", "Bridge", "Copay", "PriorAuth", "QuickStart"] + "@values": ["Unknown", "Bridge", "Coupon", "Permit", "QuickStart"] }}, { "field.string": { "name": "number" } }, { "identity.primary": { "@fields": "id" } } @@ -69,11 +69,11 @@ Add two logical attributes on `object.entity`: }} { "object.entity": { - "name": "CopayAuthorization", + "name": "CouponAuthorization", "extends": "Authorization", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 18, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 18, "@scale": 2 } } ] }} ``` @@ -133,7 +133,7 @@ Multi-level hierarchies (`Base → Mid → Leaf`) are supported. `@discriminator | Port | Emission | |---|---| -| **TypeScript** | Discriminated union type: `type Auth = Bridge \| Copay \| ...`; per-subtype Zod schemas via `.merge(BaseSchema)`; Drizzle: one `pgTable` for the base + per-subtype TypeScript narrowing. | +| **TypeScript** | Discriminated union type: `type Auth = Bridge \| Coupon \| ...`; per-subtype Zod schemas via `.merge(BaseSchema)`; Drizzle: one `pgTable` for the base + per-subtype TypeScript narrowing. | | **Java** | `@Inheritance(strategy = InheritanceType.SINGLE_TABLE)` + `@DiscriminatorColumn(name="...")` on the base + `@DiscriminatorValue("...")` on each subtype. Spring repo methods on the base; per-subtype query methods optional. | | **Kotlin** | Sealed class hierarchy with KotlinPoet: `sealed class Auth` + per-subtype `data class` with `@DiscriminatorValue`-equivalent. Exposed: single-table query with subtype dispatch. | | **C#** | EF Core: `modelBuilder.Entity().HasDiscriminator(x => x.Type).HasValue(AuthType.Bridge)...`; subtype POCOs inherit from base; `OfType()` polymorphic queries. | @@ -146,7 +146,7 @@ Each port also emits polymorphic query helpers (e.g., `.OfType()` in C#, Per [ADR-0015](../../../spec/decisions/ADR-0015-single-shared-migrate-engine.md), schema migration is TS-only. The TS reference work: - **TPH detection.** `migrate-ts/src/expected-schema.ts` recognizes a TPH root by: an `object.entity` carrying `@discriminator` + the presence of one or more entities `extends:`-ing it with `@discriminatorValue`. -- **DDL emission.** A single `CREATE TABLE` for the base. Every subtype's own fields become columns on the base table, **automatically nullable** if any subtype omits them (the TPH nullability rule — a row that's a `Bridge` won't have `Copay`'s columns populated). +- **DDL emission.** A single `CREATE TABLE` for the base. Every subtype's own fields become columns on the base table, **automatically nullable** if any subtype omits them (the TPH nullability rule — a row that's a `Bridge` won't have `Coupon`'s columns populated). - **Discriminator-column type derivation.** The discriminator column's type follows from the named field's subtype (`field.enum` → `varchar` with CHECK; `field.int` → `integer`; `field.string` → `varchar`). - **Introspection round-trip.** Reading the live DB recovers the column set but **not** the discriminator semantic (which column IS the discriminator). Drift detection compares the metadata-declared expected column set against the actual columns; the discriminator-column identity itself is metadata-declared, not introspected. diff --git a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md index e1b60b40e0..9c9a2b1bcb 100644 --- a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md @@ -30,13 +30,13 @@ Add one attribute, `@parameterRef`, to `source.rdb`'s attribute schema in `persi // 1. The input shape — an ordinary object.value with typed fields. // Fields may carry origin.passthrough to drift-protect against the entities they reference. { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ - { "origin.passthrough": { "@from": "Case.id" } } + { "origin.passthrough": { "@from": "Consignment.id" } } ] }}, { "field.timestamp": { "name": "asOfDate" } } @@ -46,13 +46,13 @@ Add one attribute, `@parameterRef`, to `source.rdb`'s attribute schema in `persi // 2. The proc-backed entity references the input value-object via @parameterRef, // exactly as templates reference their payload via @payloadRef. { "object.entity": { - "name": "PhaseSummaryPerCase", + "name": "StageSummaryPerConsignment", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary_per_case", // see FR-016 / ADR-0018: kind-aware physical-name attr + "@proc": "fn_get_stage_summary_per_consignment", // see FR-016 / ADR-0018: kind-aware physical-name attr "@schema": "analytics", - "@parameterRef": "PhaseSummaryArgs" + "@parameterRef": "StageSummaryArgs" } }, // Return columns are ordinary fields, as today. { "field.long": { "name": "phaseId" } }, @@ -132,15 +132,15 @@ Some stored procedures (especially in legacy SQL Server / Oracle codebases) have ## Per-port codegen mapping -| Port | Emission for a `source.rdb @kind: "storedProc" @parameterRef: "PhaseSummaryArgs"` | +| Port | Emission for a `source.rdb @kind: "storedProc" @parameterRef: "StageSummaryArgs"` | |---|---| -| **TypeScript** | Method on the generated repo / service: `getPhaseSummaryPerCase(args: PhaseSummaryArgs): Promise`. The `PhaseSummaryArgs` type comes from the value-object's TS codegen. Drizzle: `sql.raw` wrapper helper. | -| **Java** | Spring repo method with `@Query(value = "{ call fn_get_phase_summary_per_case(:caseId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `PhaseSummaryArgs` field order. | -| **Kotlin** | Exposed `transaction { ... }` block with stored-function call wrapper; typed arguments via the `PhaseSummaryArgs` data class. | -| **C#** | EF Core: `context.PhaseSummaryPerCase.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_phase_summary_per_case({args.CaseId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | -| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_phase_summary_per_case(:case_id, :as_of_date)"), args.model_dump())`. Pydantic `PhaseSummaryArgs` validates inputs at call site. | +| **TypeScript** | Method on the generated repo / service: `getStageSummaryPerConsignment(args: StageSummaryArgs): Promise`. The `StageSummaryArgs` type comes from the value-object's TS codegen. Drizzle: `sql.raw` wrapper helper. | +| **Java** | Spring repo method with `@Query(value = "{ call fn_get_stage_summary_per_consignment(:consignmentId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `StageSummaryArgs` field order. | +| **Kotlin** | Exposed `transaction { ... }` block with stored-function call wrapper; typed arguments via the `StageSummaryArgs` data class. | +| **C#** | EF Core: `context.StageSummaryPerConsignment.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_stage_summary_per_consignment({args.ConsignmentId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | +| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_stage_summary_per_consignment(:consignment_id, :as_of_date)"), args.model_dump())`. Pydantic `StageSummaryArgs` validates inputs at call site. | -Every port emits the `object.value` shape (`PhaseSummaryArgs`) as a native type per its existing object.value codegen path. **No new codegen mechanics are required** — both the value-object and the source-with-parameter-ref reuse already-shipped per-port pipelines. +Every port emits the `object.value` shape (`StageSummaryArgs`) as a native type per its existing object.value codegen path. **No new codegen mechanics are required** — both the value-object and the source-with-parameter-ref reuse already-shipped per-port pipelines. ## `migrate-ts` impact @@ -162,7 +162,7 @@ Under `fixtures/conformance/`: 1. `parameter-ref-on-stored-proc/` — full shape: `source.rdb @kind: "storedProc" @parameterRef + object.value with 2 fields + return columns`. 2. `parameter-ref-on-table-function/` — same shape with `@kind: "tableFunction"`. -3. `parameter-ref-with-origin-passthrough/` — at least one parameter field uses `origin.passthrough @from: "Case.id"`; loader's effective-tree resolution links the parameter type to the source field's type. +3. `parameter-ref-with-origin-passthrough/` — at least one parameter field uses `origin.passthrough @from: "Consignment.id"`; loader's effective-tree resolution links the parameter type to the source field's type. 4. `parameter-ref-shared-across-procs/` — two `source.rdb` instances on different entities both reference the same `object.value`. Confirms reusability. 5. `parameter-ref-optional-parameter/` — one required, one optional parameter (`@required: false` on a field child); call signature reflects optionality per port. 6. `parameter-ref-no-args/` — `@kind: "storedProc"` with `@parameterRef` omitted (a zero-argument procedure). Loader accepts; codegen emits a no-arg method. diff --git a/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md b/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md index 4e9d157c72..228a686d8f 100644 --- a/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md @@ -14,7 +14,7 @@ 2. **[ADR-0018](../../../spec/decisions/ADR-0018-per-kind-physical-name-attrs.md)** (issued alongside this FR) revises ADR-0007's choice of a universal `@table` within rdb to per-kind physical-name aliases — `@view` / `@materializedView` / `@proc` / `@function` for the non-table kinds. Same single internal slot; the canonical attr key matches the kind. Both gaps surface together when authoring stored-proc and view declarations: -- Reader sees `@table: "fn_get_phase_summary_per_case"` with `@kind: "storedProc"` and translates mentally that this isn't actually a table. +- Reader sees `@table: "fn_get_stage_summary_per_consignment"` with `@kind: "storedProc"` and translates mentally that this isn't actually a table. - Reader sees a `source.rdb` with no `name` attr and no way to disambiguate it from other sources on the same entity in error messages. This FR closes both gaps in one focused pass — same files, same registration points, same conformance corpus refresh. diff --git a/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md b/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md index b27525955b..ab9193012a 100644 --- a/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md +++ b/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md @@ -53,10 +53,10 @@ For an entity that carries `@discriminator`, `entityFile` emits one TS union typ ```ts // Generated from object.entity "Auth" with @discriminator: "type" -// and subtypes BridgeAuth / CopayAuth / PriorAuthAuth declaring values -// "Bridge" / "Copay" / "PriorAuth". +// and subtypes BridgeAuth / CouponAuth / PermitAuth declaring values +// "Bridge" / "Coupon" / "Permit". -export type Auth = BridgeAuth | CopayAuth | PriorAuthAuth; +export type Auth = BridgeAuth | CouponAuth | PermitAuth; // Type guard helpers — one per subtype. export function isBridgeAuth(a: Auth): a is BridgeAuth { @@ -77,7 +77,7 @@ For each concrete subtype, `entityFile` emits a Zod schema that is the base enti // Base Zod schema (already emitted today for any entity). export const AuthSchema = z.object({ id: z.number().int(), - type: z.enum(["Bridge", "Copay", "PriorAuth"]), + type: z.enum(["Bridge", "Coupon", "Permit"]), }); // Per-subtype schemas — each merges the base, pins the discriminator value, @@ -88,14 +88,14 @@ export const BridgeAuthSchema = AuthSchema.merge(z.object({ })); export type BridgeAuth = z.infer; -export const CopayAuthSchema = AuthSchema.merge(z.object({ - type: z.literal("Copay"), - copayAmount: z.number(), +export const CouponAuthSchema = AuthSchema.merge(z.object({ + type: z.literal("Coupon"), + couponAmount: z.number(), })); -export type CopayAuth = z.infer; +export type CouponAuth = z.infer; ``` -**Discriminator pin via `z.literal`.** Each subtype schema pins its `type` field to the literal value. So `BridgeAuthSchema.parse({type: "Copay", ...})` throws — typed gatekeeping is enforced by Zod, not just TypeScript. +**Discriminator pin via `z.literal`.** Each subtype schema pins its `type` field to the literal value. So `BridgeAuthSchema.parse({type: "Coupon", ...})` throws — typed gatekeeping is enforced by Zod, not just TypeScript. ### Discriminator dispatch @@ -105,11 +105,11 @@ export type CopayAuth = z.infer; /** Parse a row from the auths table, dispatching by the discriminator value. */ export function parseAuth(row: unknown): Auth { // Read the discriminator without committing the row to any subtype yet. - const head = z.object({ type: z.enum(["Bridge", "Copay", "PriorAuth"]) }).parse(row); + const head = z.object({ type: z.enum(["Bridge", "Coupon", "Permit"]) }).parse(row); switch (head.type) { case "Bridge": return BridgeAuthSchema.parse(row); - case "Copay": return CopayAuthSchema.parse(row); - case "PriorAuth": return PriorAuthAuthSchema.parse(row); + case "Coupon": return CouponAuthSchema.parse(row); + case "Permit": return PermitAuthSchema.parse(row); } } ``` @@ -128,7 +128,7 @@ Concrete shape of `entityFile` output: |---|---| | `Auth.ts` (base) | `AuthSchema` (full union of fields across all subtypes), `Auth` type alias to the discriminated union, type guards, `parseAuth` dispatcher. | | `BridgeAuth.ts` (subtype) | `BridgeAuthSchema` (base merged + own), `BridgeAuth` type, no separate type guard file. | -| `CopayAuth.ts` (subtype) | same as above. | +| `CouponAuth.ts` (subtype) | same as above. | The subtype files each `import { AuthSchema } from "./Auth.js"` — base must be emitted first / locatable. @@ -151,10 +151,10 @@ export const auths = pgTable("auths", { // BridgeAuth-only columns: nullable, since rows of any other subtype have NULL here. quantity: integer("quantity"), - // CopayAuth-only columns: nullable. - copay_amount: numeric("copay_amount", { precision: 10, scale: 2 }), + // CouponAuth-only columns: nullable. + coupon_amount: numeric("coupon_amount", { precision: 10, scale: 2 }), - // PriorAuthAuth-only columns: nullable. + // PermitAuth-only columns: nullable. // ... }); ``` @@ -224,7 +224,7 @@ export async function updateBridgeAuth( } ``` -The discriminator field is **never updatable** — clients can't change a Bridge into a Copay. Generated `updateXxx` strips the discriminator field from any patch. +The discriminator field is **never updatable** — clients can't change a Bridge into a Coupon. Generated `updateXxx` strips the discriminator field from any patch. ### REST contract (TS routes) @@ -342,7 +342,7 @@ New fixtures pinning the polymorphic CRUD shape cross-port: - `tph-polymorphic-list-and-get` — `GET /auths` returns subtype-tagged rows; `GET /auths/:id` returns one row. - `tph-per-subtype-list-and-create` — `GET /auths/bridge` filtered; `POST /auths/bridge` create. - `tph-per-subtype-update-and-delete` — subtype-only mutations. -- `tph-cross-subtype-404` — `GET /auths/bridge/123` for an id that exists but is a Copay returns 404. +- `tph-cross-subtype-404` — `GET /auths/bridge/123` for an id that exists but is a Coupon returns 404. Each fixture asserts request shape (URL + body) and response shape (status + body) cross-port byte-equivalently. @@ -353,7 +353,7 @@ New TPH query scenarios: - `tph-insert-then-find-by-id` — insert a `BridgeAuth`, find by id; the result's subtype-only columns are NULL on other-subtype reads. - `tph-insert-three-subtypes-list` — insert one of each subtype; `findAllAuths()` returns three rows tagged by `@type`. - `tph-update-subtype-only-column` — update a Bridge's `quantity`; verify storage. -- `tph-no-cross-subtype-update` — attempt to update a Bridge with Copay-only fields; verify they're stripped / rejected. +- `tph-no-cross-subtype-update` — attempt to update a Bridge with Coupon-only fields; verify they're stripped / rejected. ## Open questions @@ -421,7 +421,7 @@ New TPH query scenarios: - codegen-ts + codegen-ts-tanstack + codegen-ts-react suites: 652/0. - **Tier 5 (conformance corpora):** **authored + TS-green** (both corpora). - **api-contract** `fixtures/api-contract-conformance/tph/` — Auth base + - BridgeAuth/CopayAuth/PriorAuthAuth over one `auths` table; 4 scenarios + BridgeAuth/CouponAuth/PermitAuth over one `auths` table; 4 scenarios (polymorphic list/get, per-subtype list/create, per-subtype update/delete, cross-subtype 404). TS runs **both lanes** (hand-rolled reference + GENERATED `Auth.routes.ts`) over one Testcontainers Postgres per scenario per diff --git a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md index f2375610bc..c5580bdfc7 100644 --- a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md +++ b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md @@ -7,7 +7,7 @@ ## Why this doc exists -FR-019 introduced the C# `GenConfig.PackageNamespaces: Dictionary` map and a single `ProvidedEnumNamespace` fallback **scoped to `@provided` enums only**. That map is exactly the right primitive — bind a metadata package (`acme::cases`, `acme::domain::dataEnums::authorizations`) to a per-port output identity (a C# namespace, a TS module specifier, a Java package, …). Three gaps in the current shape: +FR-019 introduced the C# `GenConfig.PackageNamespaces: Dictionary` map and a single `ProvidedEnumNamespace` fallback **scoped to `@provided` enums only**. That map is exactly the right primitive — bind a metadata package (`acme::orders`, `acme::domain::dataEnums::authorizations`) to a per-port output identity (a C# namespace, a TS module specifier, a Java package, …). Three gaps in the current shape: 1. **It's only wired for `@provided` enums.** The same primitive should govern where entities and value-objects land in each port's emitted output. The pattern is identical; only the consumer differs. 2. **Only the C# port has it.** TS has a single `providedEnumModule` string with no map; Java and Python have nothing. Cross-port symmetry is missing. @@ -30,11 +30,11 @@ Each language has its own term for "where this lands." The cross-port config use | Port | Section | Field | Example value | |---|---|---|---| -| **C#** | `csharp:` | `namespace` | `Acme.Domain.Entities.Cases` | -| **Java** | `java:` | `package` | `com.acme.app.cases` | -| **Kotlin** | `kotlin:` | `package` | `com.acme.app.cases` | -| **TS** | `typescript:` | `module` | `@acme/app/cases` | -| **Python** | `python:` | `module` | `acme.app.cases` | +| **C#** | `csharp:` | `namespace` | `Acme.Domain.Entities.Orders` | +| **Java** | `java:` | `package` | `com.acme.app.orders` | +| **Kotlin** | `kotlin:` | `package` | `com.acme.app.orders` | +| **TS** | `typescript:` | `module` | `@acme/app/orders` | +| **Python** | `python:` | `module` | `acme.app.orders` | Rationale: a Java developer reading `java: { package: ... }` sees their language's term, not `javaPackage`. The port section already carries the language identity; doubling it as a key prefix is redundant. The retired `@csEnumType` attr was wrong for the *opposite* reason — it carried language vocabulary into metadata where it didn't belong. @@ -93,14 +93,14 @@ Resolution is **per named type**, not per package. The resolver receives `(metad | 5 | Join segments by `convention.separator` (`.`) | `UsersAccess` | | 6 | Prepend `convention.prepend` + `convention.separator` | `Acme.Domain.Entities.UsersAccess` | -Multi-segment example, `acme::cases::custom-properties`: +Multi-segment example, `acme::orders::custom-properties`: | Step | Result | |---|---| -| Strip `acme::` | `cases::custom-properties` | -| Split by `::` | `["cases", "custom-properties"]` | -| PascalCase each | `["Cases", "CustomProperties"]` | -| Join by `.` | `Cases.CustomProperties` | -| Prepend base | `Acme.Domain.Entities.Cases.CustomProperties` | +| Strip `acme::` | `orders::custom-properties` | +| Split by `::` | `["orders", "custom-properties"]` | +| PascalCase each | `["Orders", "CustomProperties"]` | +| Join by `.` | `Orders.CustomProperties` | +| Prepend base | `Acme.Domain.Entities.Orders.CustomProperties` | The metadata separator (`::`) is **never** configurable — it's part of the metaobjects spec. The convention rule's `separator` is the per-port output joiner: `.` for C#, `/` for TS module paths, `.` for Java packages, etc. @@ -118,7 +118,7 @@ csharp: # Most acme::lookups types land in .Entities.Lookups via the convention, # but Currency is a top-level concept owned elsewhere in the codebase. "acme::lookups::Currency": "Acme.Domain.Shared" - # Authorization's value-objects live in the Dto namespace by P3 convention, + # Authorization's value-objects live in the Dto namespace by the adopter's convention, # while the entities live in the Entities namespace. "acme::authorizations::InsuranceParameters": "Acme.Domain.Dto" ``` @@ -155,7 +155,7 @@ Resolution order on either path: 4. (port-level legacy fallback, e.g. FR-019's `providedEnumNamespace` single-string) 5. `unmappedStrategy` -Adopters whose `@provided` enums are FLAT in a single namespace (no per-package sub-tree) skip `providedEnumPrepend` entirely and use the FR-019 single-string `providedEnumNamespace` fallback + `typeOverrides` for sub-namespace exceptions. This is exactly what the P3 C# adopter does (see worked example below). +Adopters whose `@provided` enums are FLAT in a single namespace (no per-package sub-tree) skip `providedEnumPrepend` entirely and use the FR-019 single-string `providedEnumNamespace` fallback + `typeOverrides` for sub-namespace exceptions. This is exactly what the the adopter C# adopter does (see worked example below). **Why not a general rule/predicate engine.** We explicitly chose NOT to add `perKindOverrides`, `rules: when {}`, or a `NamedKind` enum. Reasons: - `NamedKind` would be a closed set of values the framework knows about today; metadata kinds grow over time and the enum would need amendments + a new release every time a new kind appears. @@ -177,7 +177,7 @@ Adopters whose `@provided` enums are FLAT in a single namespace (no per-package ### Worked examples -**P3 C# adopter** (the driving case — `@provided` enums live FLAT in `DataEnums`, with 12 sub-namespace exceptions): +**The driving C# adopter** (the driving case — `@provided` enums live FLAT in `DataEnums`, with 12 sub-namespace exceptions): ```yaml csharp: namespace: @@ -198,19 +198,19 @@ csharp: # The 12 @provided enums that live in DataEnums sub-namespaces "acme::authorizations::AuthorizationType": "Acme.Domain.DataEnums.Authorizations" "acme::authorizations::AuthorizationStatus": "Acme.Domain.DataEnums.Authorizations" - "acme::authorizations::CopayCardStatus": "Acme.Domain.DataEnums.CopayCards" - # ... 6 more Copay* enums in acme::authorizations - "acme::integrations::DataExportRunStatusEnum": "Acme.Domain.DataEnums.DataExportIntegration" - "acme::integrations::SPFileType": "Acme.Domain.DataEnums.SPIntegration" - "acme::integrations::SPProcessLogStatus": "Acme.Domain.DataEnums.SPIntegration" + "acme::authorizations::CouponCardStatus": "Acme.Domain.DataEnums.CouponCards" + # ... 6 more Coupon* enums in acme::authorizations + "acme::integrations::WarehouseFeedRunStatusEnum": "Acme.Domain.DataEnums.WarehouseFeed" + "acme::integrations::EDIFileType": "Acme.Domain.DataEnums.EDIIntegration" + "acme::integrations::EDIProcessLogStatus": "Acme.Domain.DataEnums.EDIIntegration" unmappedStrategy: error ``` Resolves: -- `acme::cases` → convention → `Acme.Domain.Entities.Cases` +- `acme::orders` → convention → `Acme.Domain.Entities.Orders` - `acme::users-access` → convention → `Acme.Domain.Entities.UsersAccess` - `acme::reporting` → override → `Acme.Domain.Entities.ReportEntities` -- `acme::patients::Gender` (provided enum) → `providedEnumNamespace` → `Acme.Domain.DataEnums.Gender` +- `acme::players::Gender` (provided enum) → `providedEnumNamespace` → `Acme.Domain.DataEnums.Gender` - `acme::authorizations::AuthorizationType` (provided enum) → `typeOverrides` → `Acme.Domain.DataEnums.Authorizations.AuthorizationType` ~18 entries instead of ~80 — convention covers 13 entity packages, 3 entity overrides, the `providedEnumNamespace` single-string fallback covers ~51 flat enums, and 12 `typeOverrides` pin the sub-namespace exceptions. @@ -247,7 +247,7 @@ typescript: ``` Resolves: -- `acme::cases` → `@acme/app/cases` +- `acme::orders` → `@acme/app/orders` - `acme::users-access` → `@acme/app/users-access` **Hypothetical Java adopter:** @@ -263,7 +263,7 @@ java: ``` Resolves: -- `acme::cases` → `com.acme.app.cases` +- `acme::orders` → `com.acme.app.orders` - `acme::usersaccess` → `com.acme.app.usersaccess` ## Per-port codegen surface diff --git a/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md b/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md index b591be58bc..cf6430888f 100644 --- a/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md +++ b/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md @@ -127,7 +127,7 @@ This mechanism is **universal**, not projection-specific: column: customer_id }`: shape (type/docs/validators) pulls through; the rename is the own-`@column`; presence in the projection = presence in the inclusive list. - **Value fields** — proc parameters and command inputs whose fields are entity ids: - `field.int: { name: caseId, extends: Case.id }` pulls shape through with **no** + `field.int: { name: consignmentId, extends: Consignment.id }` pulls shape through with **no** identity semantics, **no** population, **no** referential (FK) claim. - **Entity derived fields** — optional shape pull-through alongside the origin (§7). @@ -136,8 +136,8 @@ What every use gets: **load-time drift protection**. Renaming or retyping input that references it — the contract breaks the build, not production. This is a *stronger* gate than verify-time origin resolution: it fires at load. -What it also makes computable: "this parameter is a Case identifier" (the extends -target IS `Case`'s identity field) — doc-gen, FR-022 emission, and future MCP tool +What it also makes computable: "this parameter is a Consignment identifier" (the extends +target IS `Consignment`'s identity field) — doc-gen, FR-022 emission, and future MCP tool schemas derive the semantic with zero new attrs. Inheritance semantics are the existing `extends` semantics: child attrs override diff --git a/examples/advanced-modeling/codegen/generators/entity.ts b/examples/advanced-modeling/codegen/generators/entity.ts index ced0ea9be7..6d3c2234c6 100644 --- a/examples/advanced-modeling/codegen/generators/entity.ts +++ b/examples/advanced-modeling/codegen/generators/entity.ts @@ -56,6 +56,7 @@ import { hasWritableRdbSource, formatTs, ownedRuntimeImport, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, namesRef, namesConstArg, @@ -186,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), content: await formatTs(renderEntity(entity, renderContext, { allowlists })), }; }); diff --git a/examples/advanced-modeling/codegen/generators/queries.ts b/examples/advanced-modeling/codegen/generators/queries.ts index 6933c4c227..8d03e08142 100644 --- a/examples/advanced-modeling/codegen/generators/queries.ts +++ b/examples/advanced-modeling/codegen/generators/queries.ts @@ -44,6 +44,7 @@ import { isWriteThrough, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, GENERATED_EDIT_NOTE, @@ -171,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat } claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.queries.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), content: await formatTs(renderQueries(entity, ctx.renderContext)), }; }), diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index 1cd10a6824..16837743da 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -74,6 +74,7 @@ import { knownFieldsLine, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, crossEntitySpecifier, @@ -666,7 +667,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, @@ -768,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.routes.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), }; }); diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts index 14cc548338..9eb84fd2a9 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts @@ -349,7 +349,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index 2a9c7ea955..e687d1acdb 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -26,17 +26,22 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, resolveIndexName } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, resolveIndexName, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { flattenedMembersOf } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; import { foreignKeyIndexesOf, storedIndexName } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -186,7 +191,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -200,16 +205,31 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -218,6 +238,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -303,8 +325,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -443,6 +469,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -812,6 +854,60 @@ function renderColumn( : columnLine; } +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): CheckEntry[] | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: CheckEntry[] = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + const name = typeof declared === "string" && declared.length > 0 + ? declared + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); + }); + return out; +} + /** * Drizzle's identity options for what the model declares, the same two meta migrate writes * (`SEQUENCE NAME … START WITH n`): `{ name: "Old_Id_seq", startWith: 1000 }`, or nothing. diff --git a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts index c02b3dc950..c9392157cb 100644 --- a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts +++ b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,37 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts index fd7406700b..eb5392b047 100644 --- a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts @@ -23,6 +23,7 @@ import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { httpRuntimeSpecifier } from "@metaobjectsdev/codegen-ts/engine"; +import { DEFAULT_OUTPUT_LAYOUT } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; /** @@ -31,7 +32,7 @@ import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; * (`owned-runtime.ts`). Absent `ctx`, or with no `httpRuntimeImport`, the package: the * byte-identical default. */ -const PACKAGE_DEFAULT = { outputLayout: "flat", extStyle: "none" } as const; +const PACKAGE_DEFAULT = { outputLayout: DEFAULT_OUTPUT_LAYOUT, extStyle: "none" } as const; function allowlistTypesFrom(entity: MetaObject, ctx: RenderContext | undefined): string { return httpRuntimeSpecifier("allowlists", ctx ?? PACKAGE_DEFAULT, effectivePackage(entity)); diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index 049c8f2d60..99723899aa 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -712,6 +712,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); diff --git a/examples/advanced-modeling/metaobjects.config.ts b/examples/advanced-modeling/metaobjects.config.ts index 24721e78ed..a1d8c1ce4a 100644 --- a/examples/advanced-modeling/metaobjects.config.ts +++ b/examples/advanced-modeling/metaobjects.config.ts @@ -40,6 +40,9 @@ const isPersisted = (e: MetaObject): boolean => export default defineConfig({ outDir: "src/generated", + // The modules sit in one directory, which this example's own code imports from; the + // package layout would put them in a directory per package. + outputLayout: "flat", extStyle: "none", dbImport: "../db", dialect: "postgres", diff --git a/examples/brownfield/drizzle/metaobjects.config.ts b/examples/brownfield/drizzle/metaobjects.config.ts index 14ad007140..46ac2de9dc 100644 --- a/examples/brownfield/drizzle/metaobjects.config.ts +++ b/examples/brownfield/drizzle/metaobjects.config.ts @@ -2,6 +2,9 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + // The modules sit in one directory, which this example's own code imports from; the + // package layout would put them in a directory per package. + outputLayout: "flat", dialect: "postgres", timestampMode: "date", // the existing timestamp columns read as Date generators: ["entity"], diff --git a/examples/brownfield/zod/metaobjects.config.ts b/examples/brownfield/zod/metaobjects.config.ts index 812f4d40f8..8c3e5141e4 100644 --- a/examples/brownfield/zod/metaobjects.config.ts +++ b/examples/brownfield/zod/metaobjects.config.ts @@ -3,6 +3,9 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + // The modules sit in one directory, which this example's own code imports from; the + // package layout would put them in a directory per package. + outputLayout: "flat", dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json index e6cb64c5db..f4df6e4669 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json @@ -4,7 +4,7 @@ "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", - "generated/csharp/SubscriberRoutes.g.cs": "2b7ebe7f23e912f38ca923fce0df4cf82c89f9b909ea9bf5b2d4c9d16e4064a8", + "generated/csharp/SubscriberRoutes.g.cs": "2a217ff5a37674ce5038802631b1d8fd90b22b9849e0288f7daf3bba7f9e862f", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", "generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd", "generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5", diff --git a/examples/showcase/codegen/generators/entity.ts b/examples/showcase/codegen/generators/entity.ts index ced0ea9be7..6d3c2234c6 100644 --- a/examples/showcase/codegen/generators/entity.ts +++ b/examples/showcase/codegen/generators/entity.ts @@ -56,6 +56,7 @@ import { hasWritableRdbSource, formatTs, ownedRuntimeImport, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, namesRef, namesConstArg, @@ -186,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), content: await formatTs(renderEntity(entity, renderContext, { allowlists })), }; }); diff --git a/examples/showcase/codegen/generators/queries.ts b/examples/showcase/codegen/generators/queries.ts index 6933c4c227..8d03e08142 100644 --- a/examples/showcase/codegen/generators/queries.ts +++ b/examples/showcase/codegen/generators/queries.ts @@ -44,6 +44,7 @@ import { isWriteThrough, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, GENERATED_EDIT_NOTE, @@ -171,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat } claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.queries.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), content: await formatTs(renderQueries(entity, ctx.renderContext)), }; }), diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index 1cd10a6824..16837743da 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -74,6 +74,7 @@ import { knownFieldsLine, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, crossEntitySpecifier, @@ -666,7 +667,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, @@ -768,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.routes.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), }; }); diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts index 14cc548338..9eb84fd2a9 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts @@ -349,7 +349,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index 2a9c7ea955..e687d1acdb 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -26,17 +26,22 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, resolveIndexName } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, resolveIndexName, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { flattenedMembersOf } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; import { foreignKeyIndexesOf, storedIndexName } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -186,7 +191,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -200,16 +205,31 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -218,6 +238,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -303,8 +325,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -443,6 +469,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -812,6 +854,60 @@ function renderColumn( : columnLine; } +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): CheckEntry[] | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: CheckEntry[] = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + const name = typeof declared === "string" && declared.length > 0 + ? declared + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); + }); + return out; +} + /** * Drizzle's identity options for what the model declares, the same two meta migrate writes * (`SEQUENCE NAME … START WITH n`): `{ name: "Old_Id_seq", startWith: 1000 }`, or nothing. diff --git a/examples/showcase/codegen/templates/enum-int-codec.ts b/examples/showcase/codegen/templates/enum-int-codec.ts index c02b3dc950..c9392157cb 100644 --- a/examples/showcase/codegen/templates/enum-int-codec.ts +++ b/examples/showcase/codegen/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,37 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/examples/showcase/codegen/templates/filter-allowlist.ts b/examples/showcase/codegen/templates/filter-allowlist.ts index fd7406700b..eb5392b047 100644 --- a/examples/showcase/codegen/templates/filter-allowlist.ts +++ b/examples/showcase/codegen/templates/filter-allowlist.ts @@ -23,6 +23,7 @@ import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { httpRuntimeSpecifier } from "@metaobjectsdev/codegen-ts/engine"; +import { DEFAULT_OUTPUT_LAYOUT } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; /** @@ -31,7 +32,7 @@ import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; * (`owned-runtime.ts`). Absent `ctx`, or with no `httpRuntimeImport`, the package: the * byte-identical default. */ -const PACKAGE_DEFAULT = { outputLayout: "flat", extStyle: "none" } as const; +const PACKAGE_DEFAULT = { outputLayout: DEFAULT_OUTPUT_LAYOUT, extStyle: "none" } as const; function allowlistTypesFrom(entity: MetaObject, ctx: RenderContext | undefined): string { return httpRuntimeSpecifier("allowlists", ctx ?? PACKAGE_DEFAULT, effectivePackage(entity)); diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index 049c8f2d60..99723899aa 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -712,6 +712,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs index f3805b901f..859eb0d48f 100644 --- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs +++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs @@ -147,10 +147,13 @@ async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); var __issues = new ValidationIssues(); foreach (var prop in body.RootElement.EnumerateObject()) { - var target = entry.Metadata.FindProperty(prop.Name) + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); diff --git a/examples/showcase/metaobjects.config.ts b/examples/showcase/metaobjects.config.ts index f3cc3ba720..651635b580 100644 --- a/examples/showcase/metaobjects.config.ts +++ b/examples/showcase/metaobjects.config.ts @@ -20,6 +20,9 @@ import { export default defineConfig({ outDir: "generated/ts", + // The modules sit in one directory, which this example's own code imports from; the + // package layout would put them in a directory per package. + outputLayout: "flat", extStyle: "none", dbImport: "../db", dialect: "sqlite", diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 4bf1d151db..2e8db74b6a 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 510, + "fixtures": 526, "corpora": 42, "baseTypes": 17 }, diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md index d86cf4cea2..5807adbd34 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md @@ -118,7 +118,7 @@ init properties say otherwise — documentation does (below). | `filter-allowlist` | `FilterAllowlistGenerator()` | per-entity `FilterAllowlist` (FR-009 — the server-side field+operator allowlist the routes validate against). | | `callable` | `CallableGenerator()` | `.callable.g.cs` — an FR-015 calling method for a `source.rdb @kind="storedProc"|"tableFunction"`, via EF `FromSqlInterpolated` (args from the `@parameterRef` value object in declaration order). | | `output-parser` / `extractor` / `output-prompt` / `render-helper` | `OutputParserGenerator()`, `ExtractorGenerator()`, `OutputPromptGenerator()`, `RenderHelperGenerator("prompts")` (its constructor argument is the template root its refs resolve from) | the prompt-pillar artifacts for a **responding `template.prompt`** — one carrying `@responseRef` (ADR-0052: these tiers are INBOUND; `template.output` is outbound only and emits no parser). The strict parser, the tolerant `extract`, the **output-format prompt fragment** (`output-prompt`; presentation via `@promptStyle: guide`/`inline`/`exampleOnly`), and the typed render helper. They reference the value objects' POCOs from `entity` and declare no payload type — wire `entity` too (`--list` says so). See the **prompts** reference. | -| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CopayAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CopayAuthNames.IdColumn` and `CopayAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | +| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CouponAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CouponAuthNames.IdColumn` and `CouponAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | | `template` | `TemplateGenerator.Create(name, template, walk, provider)` (a factory, not `new`) | the generic Mustache `templateGenerator()` primitive. | Metadata lives in the directory the gen run's positional `` argument @@ -313,7 +313,7 @@ redeclare them; only an emitted abstract shape is a base); an `object.value`'s d **Shared + externally-provided enums (FR-019).** A package-level abstract `field.enum` (`abstract: true`, `@values`) extended by concrete entity fields is -materialized **once** (`Enums.g.cs`) and referenced — no per-entity nested enum. +materialized **once** (`/.g.cs`, its `@intValueMap` ints and `@enumDoc` docs on the members) and referenced — no per-entity nested enum. Adding `@provided: true` to that declaration suppresses materialization entirely: consuming fields reference a hand-written/third-party enum, and the C# namespace **binds to the enum's declaring metadata package** via diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md index 671794f9b3..6fd985d885 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md @@ -83,7 +83,12 @@ base emits polymorphic `GET /(+/{id})` plus a per-subtype CRUD set at `//` (create injects the discriminator, cross-subtype get/update/delete → 404). Wire it after registering the context: +The routes class lives in its entity's package namespace (`acme::blog` → `Acme.Blog`), so add a +`using` for it: + ```csharp +using Acme.Blog; // the entity's package namespace + var app = builder.Build(); app.MapAuthorRoutes("/api"); // the generated extension; you pass the prefix at mount time (default "/api") app.Run(); diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md index a50a9e32c7..36be5db541 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -87,7 +87,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid all of them: **unmodified owned-generator lines / all owned-generator lines**, where unmodified counts only copies proven unmodified. Report the proven copies together as one finding, `owned-generator-stock-copies`, listing each copy and the port's undo command. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index c605cd7a0e..6b9e72a398 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -33,7 +33,7 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). - **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index d35d70fe22..6854ed810c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,6 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -159,6 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index a337e663e3..4ec8b55048 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -456,6 +456,20 @@ language-native console tool, or a build-plugin goal). A dry-run mode previews without writing; a watch mode re-runs on metadata changes where supported. Pass specific entity names to scope a run to those entities. +**`gen` skips a run when nothing changed.** After loading, every port computes a key from the +loaded model and everything the generators are built from; when it matches the last successful run +and every generated file still holds the bytes that run left, `gen` says so and writes nothing +(ADR-0064). Pass `--force` (Maven: `-Dmetaobjects.force=true`) to render anyway, and +`verify --codegen --full` to render and compare in a local run. A generator that reads something +the key does not cover declares it as an input or sets `cache: false`. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity classes, the +`AppDbContext`, the reverse finders, the routes, the filter map and the credential stripping all +read it, so they agree. A subclass hook (`EntityGenerator.PropertyName`, +`DbContextGenerator.PropertyName`) that disagrees with the resolver is refused rather than +emitting two spellings. + --- For this project's codegen specifics, read the `references/.md` file for each server diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 27bf59a63b..5be9c8b5c7 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 3630771911..5e46840049 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -38,6 +38,7 @@ fixtures/api-contract-conformance/ ├── patch-empty-noop.yaml # FR-037 PATCH-5 a patch stripping to zero assignments is a no-op read-back ├── writeonce-patch-stripped.yaml # FR-037 R1 @mutability:"writeOnce" — stripped on PATCH, never rejected ├── autoset-patch.yaml # #203 @autoSet — PATCH bumps onUpdate, leaves onCreate alone + ├── input-server-owned-dropped.yaml # 1.2.x security: a client id / undeclared key never reaches storage ├── delete-204-and-404.yaml ├── invalid-sort-400.yaml ├── filter-eq.yaml # FR-009 filter operators diff --git a/fixtures/api-contract-conformance/tph/README.md b/fixtures/api-contract-conformance/tph/README.md index f41a420575..c942e8efe0 100644 --- a/fixtures/api-contract-conformance/tph/README.md +++ b/fixtures/api-contract-conformance/tph/README.md @@ -17,14 +17,14 @@ DELETE {prefix}/auths//:id → per-subtype delete (404 cross-subtype) ``` The per-subtype URL segment is the **`@discriminatorValue` lowercased** — -`"Bridge"` → `/auths/bridge`, `"PriorAuth"` → `/auths/priorauth` — NOT the subtype +`"Bridge"` → `/auths/bridge`, `"Permit"` → `/auths/permit` — NOT the subtype entity name. There is intentionally **no polymorphic `POST /auths`** (you can't create an abstract base). ## The three cross-port invariants (must hold byte-identically) 1. **Single-table TPH storage.** One physical `auths` table; every subtype-only - column (`quantity` / `copay_amount` / `approver`) is **nullable** (a row of any + column (`quantity` / `coupon_amount` / `approver`) is **nullable** (a row of any other subtype stores NULL there), even when the field is `@required`. 2. **Polymorphic GET / per-subtype POST URLs.** `GET /auths` returns the union; `POST /auths/bridge` etc. create per subtype. The URL paths are identical @@ -37,7 +37,7 @@ create an abstract base). ``` tph/ ├── README.md # this file -├── meta.json # Auth (base, @discriminator "type") + BridgeAuth / CopayAuth / PriorAuthAuth +├── meta.json # Auth (base, @discriminator "type") + BridgeAuth / CouponAuth / PermitAuth ├── seed.json # 3 seed rows (one per subtype) into the single `auths` table └── scenarios/ ├── tph-polymorphic-list-and-get.yaml # polymorphic GET: the /auths union + get-by-id of any subtype @@ -60,10 +60,10 @@ tph/ | Entity | Discriminator | Own fields (a subtype inherits everything on `Auth`) | |---|---|---| -| `Auth` (base) | `@discriminator: "type"`, `@table "auths"` | `id` (long, pk), `type` (enum `Bridge`/`Copay`/`PriorAuth`), `reference` (string, `@required`, `@maxLength` 80), `issuedCurrency` (string, `@maxLength` 3, `@mutability` "writeOnce"), `autoCreatedAt` / `autoUpdatedAt` (timestamp, `@autoSet` onCreate / onUpdate) | +| `Auth` (base) | `@discriminator: "type"`, `@table "auths"` | `id` (long, pk), `type` (enum `Bridge`/`Coupon`/`Permit`), `reference` (string, `@required`, `@maxLength` 80), `issuedCurrency` (string, `@maxLength` 3, `@mutability` "writeOnce"), `autoCreatedAt` / `autoUpdatedAt` (timestamp, `@autoSet` onCreate / onUpdate) | | `BridgeAuth` | `@discriminatorValue: "Bridge"` | `quantity` (int, required → nullable in the single table) | -| `CopayAuth` | `@discriminatorValue: "Copay"` | `copayAmount` (decimal 10,2) | -| `PriorAuthAuth` | `@discriminatorValue: "PriorAuth"` | `approver` (string, `@maxLength` 80) | +| `CouponAuth` | `@discriminatorValue: "Coupon"` | `couponAmount` (decimal 10,2) | +| `PermitAuth` | `@discriminatorValue: "Permit"` | `approver` (string, `@maxLength` 80) | `seed.json` is applied fresh before every scenario (truncate-then-insert into the single `auths` table). Subtype-only columns are `null` for rows of other subtypes. @@ -75,7 +75,7 @@ Identical to the parent `api-contract-conformance` corpus `ids` / `length` / `row` (subset key-match) / `error` / `empty` / `fieldsNotEqual` cover TPH (the last pins the `@autoSet` leg: `autoCreatedAt` preserved vs `autoUpdatedAt` bumped). -A subtype's decimal is asserted over the wire as the canonical string (`copayAmount` `"12.50"` +A subtype's decimal is asserted over the wire as the canonical string (`couponAmount` `"12.50"` is `"12.5"`, ADR-0019 Amendment 1), filters exactly on its subtype segment, and refuses a value with more digits than its `@scale` with `400 validation`. The `row` assertions pin the discriminator value (`type`) and the integer/string subtype-only columns. diff --git a/fixtures/api-contract-conformance/tph/meta.json b/fixtures/api-contract-conformance/tph/meta.json index 99ac47a3ca..20bfe1e7c3 100644 --- a/fixtures/api-contract-conformance/tph/meta.json +++ b/fixtures/api-contract-conformance/tph/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true } }, { "field.string": { "name": "issuedCurrency", "@maxLength": 3, "@mutability": "writeOnce" } }, { "field.timestamp": { "name": "autoCreatedAt", "@autoSet": "onCreate" } }, @@ -25,17 +25,17 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true } } ] diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml index 8e6c8bd563..d2c971bfce 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml @@ -3,7 +3,7 @@ description: > FR-017: the polymorphic base collection filters by its own discriminator. The base allowlist includes the discriminator field (`type` is `@filterable`), so `GET /auths?filter[type][eq]=Bridge` narrows the union to - one subtype and `filter[type][in]=Bridge,Copay` to two — the query a list + one subtype and `filter[type][in]=Bridge,Coupon` to two — the query a list page with a "kind" facet sends on its first render. The JVM generators removed the discriminator from the base allowlist, so both @@ -28,7 +28,7 @@ requests: - id: r2 method: GET - path: /api/auths?filter[type][in]=Bridge,Copay&sort=id:asc + path: /api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc expect: status: 200 body: @@ -38,7 +38,7 @@ requests: # Bare-value sugar for `eq`. - id: r3 method: GET - path: /api/auths?filter[type]=PriorAuth + path: /api/auths?filter[type]=Permit expect: status: 200 body: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml index 8c22016417..2c14be9b16 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml @@ -13,22 +13,22 @@ description: > discriminator is injected from the URL, never the body). A well-formed create still succeeds (201) — the guard rejects only violations, never valid bodies. requests: - # r1 — a valid PriorAuth create still succeeds (positive control: the constraint + # r1 — a valid Permit create still succeeds (positive control: the constraint # guard must not over-reject a well-formed body). - id: r1 method: POST - path: /api/auths/priorauth + path: /api/auths/permit body: reference: "REF-OK" approver: "Dr. Smith" expect: status: 201 body: - row: { type: "PriorAuth", reference: "REF-OK", approver: "Dr. Smith" } - # r2 — an over-@maxLength(80) `reference` on the PriorAuth segment → 400 validation. + row: { type: "Permit", reference: "REF-OK", approver: "Dr. Smith" } + # r2 — an over-@maxLength(80) `reference` on the Permit segment → 400 validation. - id: r2 method: POST - path: /api/auths/priorauth + path: /api/auths/permit body: reference: "RXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" approver: "Dr. Smith" diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml index f3aced914a..8e50b7de6f 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml @@ -12,21 +12,21 @@ requests: status: 404 - id: r2 method: GET - path: /api/auths/copay/1 + path: /api/auths/coupon/1 expect: status: 404 - id: r3 method: DELETE - path: /api/auths/copay/1 + path: /api/auths/coupon/1 expect: status: 404 - id: r4 method: GET - path: /api/auths/copay/2 + path: /api/auths/coupon/2 expect: status: 200 body: - row: { id: 2, type: "Copay", reference: "REF-2" } + row: { id: 2, type: "Coupon", reference: "REF-2" } - id: r5 method: GET path: /api/auths?sort=id:asc diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml index c15da35b12..8c96bffbf3 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml @@ -2,14 +2,14 @@ name: tph-input-foreign-discriminator-dropped description: > A per-subtype route takes the row's subtype from the URL, never from the body (the 1.2.x security fix). A `type` naming a different subtype, sent to the Bridge route, is DROPPED - SILENTLY on create and on update: the created row is a Bridge, no Copay row appears, and an + SILENTLY on create and on update: the created row is a Bridge, no Coupon row appears, and an updated Bridge stays a Bridge. Every port answers the same way. requests: - id: r1 method: POST path: /api/auths/bridge body: - type: "Copay" + type: "Coupon" reference: "REF-DISC" quantity: 4 expect: @@ -19,7 +19,7 @@ requests: hasId: true - id: r2 method: GET - path: /api/auths/copay?filter[reference][eq]=REF-DISC + path: /api/auths/coupon?filter[reference][eq]=REF-DISC expect: status: 200 body: @@ -28,7 +28,7 @@ requests: method: PATCH path: /api/auths/bridge/1 body: - type: "Copay" + type: "Coupon" reference: "REF-1-DISC" expect: status: 200 @@ -36,7 +36,7 @@ requests: row: { id: 1, type: "Bridge", reference: "REF-1-DISC" } - id: r4 method: GET - path: /api/auths/copay?filter[reference][eq]=REF-1-DISC + path: /api/auths/coupon?filter[reference][eq]=REF-1-DISC expect: status: 200 body: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml index f1b841fd47..cd789a501c 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml @@ -2,7 +2,7 @@ name: tph-input-server-owned-dropped description: > The per-subtype write routes hand storage only what the client may set, the same rule as `input-server-owned-dropped` in the core corpus. A client-sent `id` on the generated key, the - discriminator (`type`), a column only a SIBLING subtype declares (`copayAmount` sent to the + discriminator (`type`), a column only a SIBLING subtype declares (`couponAmount` sent to the Bridge route) and, on update, a `writeOnce` field are declared somewhere in the hierarchy but not settable on this route, so they are DROPPED SILENTLY (201/200, never 400): the row keeps its server-assigned id, its subtype comes from the URL, and the sibling's column is neither @@ -13,16 +13,16 @@ requests: path: /api/auths/bridge body: id: 999 - type: "Copay" + type: "Coupon" reference: "REF-INPUT" quantity: 3 - copayAmount: "7.77" + couponAmount: "7.77" expect: status: 201 body: row: { type: "Bridge", reference: "REF-INPUT", quantity: 3 } hasId: true - unset: [copayAmount] + unset: [couponAmount] - id: r2 method: GET path: /api/auths/999 @@ -30,7 +30,7 @@ requests: status: 404 - id: r3 method: GET - path: /api/auths/copay?filter[copayAmount][eq]=7.77 + path: /api/auths/coupon?filter[couponAmount][eq]=7.77 expect: status: 200 body: @@ -40,7 +40,7 @@ requests: path: /api/auths/bridge/1 body: id: 998 - type: "Copay" + type: "Coupon" reference: "REF-1-INPUT" issuedCurrency: "JPY" expect: @@ -49,14 +49,14 @@ requests: row: { id: 1, type: "Bridge", reference: "REF-1-INPUT", issuedCurrency: "USD" } - id: r5 method: PUT - path: /api/auths/copay/2 + path: /api/auths/coupon/2 body: id: 997 reference: "REF-2-INPUT" expect: status: 200 body: - row: { id: 2, type: "Copay", reference: "REF-2-INPUT" } + row: { id: 2, type: "Coupon", reference: "REF-2-INPUT" } - id: r6 method: GET path: /api/auths/998 diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml index 9a18b245c6..706ba8f523 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml @@ -5,7 +5,7 @@ description: > subtype; POST creates a row of that subtype — the discriminator is injected by the route handler from the URL, NEVER taken from the body (the body omits it). The created row joins the polymorphic collection. A subtype's decimal - (`CopayAuth.copayAmount`, decimal 10,2) is the canonical string on the wire, filters + (`CouponAuth.couponAmount`, decimal 10,2) is the canonical string on the wire, filters exactly on its own segment, and refuses more digits than its declared scale (ADR-0019 Amendment 1). requests: @@ -49,34 +49,34 @@ requests: length: 4 - id: r6 method: POST - path: /api/auths/copay + path: /api/auths/coupon body: - reference: "REF-COPAY" - copayAmount: "8.10" + reference: "REF-COUPON" + couponAmount: "8.10" expect: status: 201 body: - row: { type: "Copay", reference: "REF-COPAY", copayAmount: "8.1" } + row: { type: "Coupon", reference: "REF-COUPON", couponAmount: "8.1" } - id: r7 method: GET - path: /api/auths/copay?filter[copayAmount][gt]=10&sort=id:asc + path: /api/auths/coupon?filter[couponAmount][gt]=10&sort=id:asc expect: status: 200 body: ids: [2] - id: r8 method: GET - path: /api/auths/copay?filter[copayAmount][eq]=8.1 + path: /api/auths/coupon?filter[couponAmount][eq]=8.1 expect: status: 200 body: length: 1 - id: r9 method: POST - path: /api/auths/copay + path: /api/auths/coupon body: - reference: "REF-COPAY-2" - copayAmount: "1.234" + reference: "REF-COUPON-2" + couponAmount: "1.234" expect: status: 400 body: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml index 1e7453b654..72958f7648 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml @@ -25,14 +25,14 @@ requests: expect: status: 200 body: - row: { id: 2, type: "Copay", reference: "REF-2", copayAmount: "12.5" } + row: { id: 2, type: "Coupon", reference: "REF-2", couponAmount: "12.5" } - id: r4 method: GET path: /api/auths/3 expect: status: 200 body: - row: { id: 3, type: "PriorAuth", reference: "REF-3", approver: "Dr. Smith" } + row: { id: 3, type: "Permit", reference: "REF-3", approver: "Dr. Smith" } - id: r5 method: GET path: /api/auths/999 diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml index 7f29926635..2fa3bd9ebf 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml @@ -12,16 +12,16 @@ description: > This gates only PRESENT-VALUE constraints — the FR-035 null semantics (present-null clears / present-null-on-@required → 400 / omitted → untouched) are gated separately - by tph-update-explicit-null-clears. Uses the PriorAuth subtype (id=3): `reference` is + by tph-update-explicit-null-clears. Uses the Permit subtype (id=3): `reference` is the @required @maxLength:80 BASE column shared by every subtype; `approver` is the - @maxLength:80 PriorAuth-only column (folded nullable into the union, hence unannotated + @maxLength:80 Permit-only column (folded nullable into the union, hence unannotated there). A well-formed PATCH still succeeds (200) — the guard rejects only violations. requests: # r1 — positive control: a valid present value on the constrained base `reference` # column still succeeds (the guard must not over-reject a well-formed body). - id: r1 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: "REF-UPDATED" expect: @@ -29,25 +29,25 @@ requests: body: row: id: 3 - type: "PriorAuth" + type: "Permit" reference: "REF-UPDATED" # r2 — an over-@maxLength(80) present value on the @required base `reference` → 400 # validation. The annotation-free union would silently accept it; the subtype's # annotated shape rejects it. - id: r2 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: "RXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" expect: status: 400 body: error: "validation" - # r3 — an over-@maxLength(80) present value on the PriorAuth-only `approver` column → + # r3 — an over-@maxLength(80) present value on the Permit-only `approver` column → # 400 validation (the subtype-own constraint is enforced, not just the base's). - id: r3 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" expect: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml index 459d107d0d..42458658ea 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml @@ -13,7 +13,7 @@ description: > - a cleared column is settable again → 200 - present null on a @required base column → 400 {error:"validation"} - Uses the PriorAuth subtype (id=3): the nullable `approver` is cleared and reset, + Uses the Permit subtype (id=3): the nullable `approver` is cleared and reset, while the @required base `reference` (REF-3) and the discriminator `type` are OMITTED and must survive untouched. Runs on all five ports, BOTH lanes. @@ -22,7 +22,7 @@ requests: # `type` are OMITTED from the patch and must survive (must NOT 400). - id: r1 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: null expect: @@ -30,13 +30,13 @@ requests: body: row: id: 3 - type: "PriorAuth" + type: "Permit" reference: "REF-3" # omitted from the PATCH → untouched (still the seed) approver: null # explicit null → column cleared # r2 — the clear PERSISTED: re-read from the DB, not the mutation's echo. - id: r2 method: GET - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 expect: status: 200 body: @@ -47,7 +47,7 @@ requests: # r3 — the cleared column is settable again. - id: r3 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: "Dr. Jones" expect: @@ -60,7 +60,7 @@ requests: # cross-port validation envelope. - id: r4 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: null expect: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml index cafe01af40..60dfdf9b19 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-validation-lists-issues.yaml @@ -3,7 +3,7 @@ description: > The per-subtype routes list every validation issue, in the shape of the core `validation-lists-issues` scenario: {"error": "validation", "issues": [{code, path, message}]}. r1 sends a reference over its @maxLength and omits the BridgeAuth subtype's @required - quantity. r2 nulls the base's @required reference and sends a PriorAuth approver over its + quantity. r2 nulls the base's @required reference and sends a PermitAuth approver over its @maxLength. r3 and r4 prove that nothing was written. requests: - id: r1 @@ -20,7 +20,7 @@ requests: - { path: [quantity], code: invalid_type } - id: r2 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: null approver: "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" diff --git a/fixtures/api-contract-conformance/tph/seed.json b/fixtures/api-contract-conformance/tph/seed.json index 8cfe72e2cb..adf9bdc412 100644 --- a/fixtures/api-contract-conformance/tph/seed.json +++ b/fixtures/api-contract-conformance/tph/seed.json @@ -1,7 +1,7 @@ { "auths": [ - { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "copayAmount": null, "approver": null, "issuedCurrency": "USD", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 2, "type": "Copay", "reference": "REF-2", "quantity": null, "copayAmount": "12.50", "approver": null, "issuedCurrency": "GBP", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 3, "type": "PriorAuth", "reference": "REF-3", "quantity": null, "copayAmount": null, "approver": "Dr. Smith", "issuedCurrency": "EUR", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } + { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "couponAmount": null, "approver": null, "issuedCurrency": "USD", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 2, "type": "Coupon", "reference": "REF-2", "quantity": null, "couponAmount": "12.50", "approver": null, "issuedCurrency": "GBP", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 3, "type": "Permit", "reference": "REF-3", "quantity": null, "couponAmount": null, "approver": "Dr. Smith", "issuedCurrency": "EUR", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } ] } diff --git a/fixtures/check-constraint-conformance/README.md b/fixtures/check-constraint-conformance/README.md index d467d90252..40de74bea7 100644 --- a/fixtures/check-constraint-conformance/README.md +++ b/fixtures/check-constraint-conformance/README.md @@ -1,34 +1,53 @@ -# CHECK constraint conformance +# `check-constraint-conformance/` — the CHECKs one model gets, through either delivery path -The CHECK constraints `meta migrate` derives from a model, pinned by name and by expression -text, per dialect, with and without `migrate.checks.skipRedundant`. A port that declares CHECKs -in its own generated model must declare exactly these, so one model builds one database whether -`meta migrate` or the port's own migrations create it. +The metadata input (`input/`) and the CHECK constraints `meta migrate` derives for it: every +validator that can carry one (`validator.numeric`, `validator.length`, `validator.regex`, the +cross-field `comparison` / `requiredWhen` / `presentIff` / `exactlyOne` / `atLeastOne`, with an `@condition`) +and every scalar `field.enum`. Each expected file maps a table to its CHECKs, in order, as a name +and an expression (the text inside `CHECK (…)`, as written, never Postgres's normalized +`pg_get_constraintdef` form). -## Layout +| File | Dialect | `migrate.checks.skipRedundant` | +|---|---|---| +| `expected.postgres.json` | `postgres` | false | +| `expected.postgres.skip-redundant.json` | `postgres` | true | +| `expected.sqlite.json` | `sqlite` | false | +| `expected.sqlite.skip-redundant.json` | `sqlite` | true (a no-op: SQLite stores past a declared length) | +| `expected.d1.json` | `d1` (the same as SQLite) | false | -- `input/meta.checks.json`: the model. `Gadget` carries one of every CHECK source: scalar enums - (string and int-backed), an enum array (no CHECK), `validator.numeric`, `validator.length`, - `validator.regex`, `validator.comparison` (with `@condition`), `validator.requiredWhen`, - `validator.presentIff`, `validator.exactlyOne` and `validator.atLeastOne`, plus explicit - `@constraintName`s. It also has a replica view, so its derived field `band` exists, and - `band` gets no CHECK (nor does the `requiredWhen` that names it). `Parcel` adds an - `origin.passthrough` field (`ownerName`, from `Owner.name`) that carries a length validator: - a derived field is no column, so it gets no CHECK either. -- `expected..json`: `{ "
": [{ "name", "expression" }] }` for every table with a - CHECK, in the order `meta migrate` emits them. `postgres`, `sqlite` and `d1` (SQLite and D1 are - identical), and `*.skip-redundant.json` for `migrate.checks.skipRedundant: true`. +The rules the corpus pins (ruling R55, which follows `meta migrate`): -## Runners +- names `
__chk` (enum), `_numeric_chk`, `_length_chk`, `_regex_chk`, `_cmp_chk`, + `_reqwhen_chk`, `_presentiff_chk`, `_exactlyone_chk`, `_atleastone_chk`; a declared `@constraintName` replaces the + name and is kept even where `skipRedundant` would leave the CHECK out; +- `@dbCheck: false` leaves a numeric, length or regex validator's or an enum's CHECK out, under + `skipRedundant` too (`npi`, `legacyState`, `rank`'s minimum); a sibling validator on the same + field keeps its own (`rank`'s maximum), and `@dbCheck: true` is the default (`floor`). A + cross-field validator always keeps its CHECK: `false` on one is a load error; +- comparisons, not `BETWEEN`; columns double-quoted; an int-backed enum lists its integers; a + duration literal is the interval text on Postgres and microseconds on SQLite; +- no CHECK on an array column, and none on a derived (origin-bearing) field — it has no column, whether it comes from an `origin.computed` or an `origin.passthrough` (`Parcel.ownerName`, from `Owner.name`, which carries a length validator) — + nor a cross-field CHECK naming one (`band`, an `origin.computed` reached by the `HighGadgets` + projection's `@filter`); +- FR-017 TPH (`input/meta.tph.json`): the discriminator base's table carries its concrete + subtypes' CHECKs (`devices`), subtypes in name order (a concrete subtype is one declaring its own + `@discriminatorValue`; `SmartMeter` is a concrete child of the concrete `Meter`). A column ONE + field node owns (`voltage`, declared once on the abstract `Powered`), or that sibling nodes + declare with identical CHECKs (`note`), gets the base-column text, unguarded: a CHECK refuses + only FALSE, and a sibling's row holds NULL there. Sibling nodes that DISAGREE (`grade` with + different `@values`, `serial` with different patterns) each get their own CHECK, guarded by the + discriminator values of the subtypes carrying that node (`Meter`'s reaches `METER` and + `SMART_METER`) and named `
___…`. A cross-field validator a subtype (or an + abstract level, or a parent subtype) adds is guarded the same way, as an `@condition` ANDed with + its own, and named after its declarer, so the same rule on two siblings does not collide + (`devices_sensor_note_reqwhen_chk`, `devices_switch_note_reqwhen_chk`). Two different CHECKs + under one name are refused at build; +- a string-stored enum gets its membership CHECK and its `validator.length` CHECK, under + `skipRedundant` too (`channel`); no regex CHECK on SQLite; `IS DISTINCT FROM` on Postgres, `IS NOT` + on SQLite; `num_nonnulls` on Postgres, a sum of presence tests on SQLite. -- TypeScript: `server/typescript/packages/migrate-ts/test/check-constraint-conformance.test.ts` - builds the expected schema with `buildExpectedSchema` and compares each file. It is the reference: - `META_WRITE_CHECKS=1 bun test test/check-constraint-conformance.test.ts` (in `migrate-ts`) - rewrites the files after a deliberate change, which is then reviewed by hand. -- C#: `server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs` reads the - `HasCheckConstraint` declarations the generated EF context makes and compares them with the - same files. `MetaObjects.IntegrationTests` also creates the schema with `EnsureCreated` on a - live Postgres and checks the constraint names and that a violating row is refused. - -Java, Kotlin and Python declare no CHECK in a generated model (schema comes from `meta migrate`, -ADR-0015), so they do not run it. +Run by TypeScript (`migrate-ts/test/check-constraint-conformance.test.ts`, the reference; it +regenerates these files with `META_WRITE_CHECKS=1`) and C# +(`MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs`, which also proves the generated +EF context declares them, and `EfModelGapsTests` on live Postgres). The other ports declare no +CHECK in a generated model, so they do not run it. diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index 610a5ec8f9..79557eb7f7 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" @@ -70,5 +74,77 @@ "name": "parcels_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 20" } + ], + "jobs": [ + { + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" + }, + { + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" + } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_sensor_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index 69ed35e209..5469520722 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -40,6 +40,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" @@ -74,5 +78,85 @@ "name": "parcels_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 20" } + ], + "jobs": [ + { + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" + }, + { + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'q_failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" + } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_meter_serial_regex_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"serial\" ~ '^M[0-9]+$')" + }, + { + "name": "devices_sensor_serial_regex_chk", + "expression": "(\"kind\" <> 'SENSOR') OR (\"serial\" ~ '^S[0-9]+$')" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_sensor_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS DISTINCT FROM 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS DISTINCT FROM 'OFF') OR (\"note\" IS NOT NULL))" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index 86ccaa2a9d..c158dfd87e 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -40,6 +40,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" @@ -74,5 +78,85 @@ "name": "parcels_label_length_chk", "expression": "length(\"label\") >= 1" } + ], + "jobs": [ + { + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" + }, + { + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'q_failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" + } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_meter_serial_regex_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"serial\" ~ '^M[0-9]+$')" + }, + { + "name": "devices_sensor_serial_regex_chk", + "expression": "(\"kind\" <> 'SENSOR') OR (\"serial\" ~ '^S[0-9]+$')" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_sensor_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS DISTINCT FROM 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS DISTINCT FROM 'OFF') OR (\"note\" IS NOT NULL))" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index 610a5ec8f9..79557eb7f7 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" @@ -70,5 +74,77 @@ "name": "parcels_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 20" } + ], + "jobs": [ + { + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" + }, + { + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" + } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_sensor_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 9ff57adba4..a8a32f9b5b 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" @@ -70,5 +74,77 @@ "name": "parcels_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 20" } + ], + "jobs": [ + { + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" + }, + { + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" + } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_sensor_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" + } ] } diff --git a/fixtures/check-constraint-conformance/input/meta.checks.json b/fixtures/check-constraint-conformance/input/meta.checks.json index cac7994440..44bc8d6790 100644 --- a/fixtures/check-constraint-conformance/input/meta.checks.json +++ b/fixtures/check-constraint-conformance/input/meta.checks.json @@ -14,7 +14,7 @@ { "field.enum": { "name": "tags", "isArray": true, "@values": ["A", "B"] } }, { "field.string": { "name": "kind", "@required": true } }, { "field.int": { "name": "score", "children": [ { "validator.numeric": { "@min": 1, "@max": 5 } } ] } }, - { "field.int": { "name": "floor", "children": [ { "validator.numeric": { "@min": 0 } } ] } }, + { "field.int": { "name": "floor", "children": [ { "validator.numeric": { "@min": 0, "@dbCheck": true } } ] } }, { "field.string": { "name": "code", "@maxLength": 10, "children": [ { "validator.length": { "@min": 2, "@max": 20 } } ] } }, { "field.string": { "name": "label", "@maxLength": 40, "children": [ { "validator.length": { "@min": 0, "@max": 30 } } ] } }, { "field.string": { "name": "sku", "children": [ { "validator.regex": { "@pattern": "^[A-Z]{3}-'\\d+$", "@constraintName": "gadgets_sku_shape" } } ] } }, @@ -30,6 +30,13 @@ { "field.string": { "name": "fax" } }, { "field.enum": { "name": "channel", "@values": ["EMAIL", "SMS"], "children": [ { "validator.length": { "@min": 1, "@max": 5 } } ] } }, { "field.string": { "name": "ref", "@maxLength": 10, "children": [ { "validator.length": { "@max": 10, "@constraintName": "gadgets_ref_fits" } } ] } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false } }, + { "validator.length": { "name": "npiLength", "@max": 12, "@dbCheck": false } } ] } }, + { "field.enum": { "name": "legacyState", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.int": { "name": "rank", "children": [ + { "validator.numeric": { "name": "rankFloor", "@min": 1, "@dbCheck": false } }, + { "validator.numeric": { "name": "rankCeiling", "@max": 99 } } ] } }, { "field.string": { "name": "band", "children": [ { "validator.length": { "@max": 4 } }, { "origin.computed": { "@expr": { "case": [ { "when": { "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } }, "then": { "value": "HIGH" } } ], @@ -78,6 +85,17 @@ { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } + }, + { + "object.projection": { + "name": "HighGadgets", + "@filter": { "band": "HIGH" }, + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_high_gadgets" } }, + { "field.long": { "name": "id", "extends": "Gadget.id" } }, + { "identity.primary": { "name": "id", "extends": "Gadget.id" } } + ] + } } ] } diff --git a/fixtures/check-constraint-conformance/input/meta.stored.json b/fixtures/check-constraint-conformance/input/meta.stored.json new file mode 100644 index 0000000000..84c5358eef --- /dev/null +++ b/fixtures/check-constraint-conformance/input/meta.stored.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme::checks", + "children": [ + { + "object.entity": { + "name": "Job", + "children": [ + { "source.rdb": { "@table": "jobs" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@required": true, "@values": ["Queued", "Done", "Failed"], + "@stringValueMap": { "Queued": "q_queued", "Done": "q_done", "Failed": "q_failed" } } }, + { "field.string": { "name": "error" } }, + { "field.timestamp": { "name": "startedAt" } }, + { "field.timestamp": { "name": "doneAt" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "validator.requiredWhen": { "name": "failureReason", "@field": "error", "@when": "status", "@equals": "Failed" } }, + { "validator.comparison": { "name": "finished", "@left": "doneAt", "@op": "gte", "@right": "startedAt", + "@condition": { "op": "eq", "left": { "field": "status" }, "right": { "value": "Done" } } } } + ] + } + } + ] + } +} diff --git a/fixtures/check-constraint-conformance/input/meta.tph.json b/fixtures/check-constraint-conformance/input/meta.tph.json new file mode 100644 index 0000000000..0588849f56 --- /dev/null +++ b/fixtures/check-constraint-conformance/input/meta.tph.json @@ -0,0 +1,279 @@ +{ + "metadata.root": { + "package": "acme::checks", + "children": [ + { + "object.entity": { + "name": "Device", + "@discriminator": "kind", + "children": [ + { + "source.rdb": { + "@table": "devices" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "kind", + "@required": true, + "@values": [ + "METER", + "SENSOR", + "SMART_METER", + "SWITCH" + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id", + "@generation": "increment" + } + } + ] + } + }, + { + "object.entity": { + "name": "Powered", + "abstract": true, + "extends": "Device", + "children": [ + { + "field.int": { + "name": "voltage", + "children": [ + { + "validator.numeric": { + "@min": 1, + "@max": 480 + } + } + ] + } + }, + { + "field.int": { + "name": "watts" + } + }, + { + "validator.atLeastOne": { + "name": "powerRating", + "@fields": [ + "voltage", + "watts" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Meter", + "extends": "Powered", + "@discriminatorValue": "METER", + "children": [ + { + "field.string": { + "name": "serial", + "@required": true, + "children": [ + { + "validator.regex": { + "@pattern": "^M[0-9]+$" + } + } + ] + } + }, + { + "field.enum": { + "name": "grade", + "@values": [ + "A", + "B" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "SmartMeter", + "extends": "Meter", + "@discriminatorValue": "SMART_METER", + "children": [ + { + "field.string": { + "name": "firmware", + "children": [ + { + "validator.length": { + "@min": 1 + } + } + ] + } + }, + { + "validator.requiredWhen": { + "name": "gradedFirmware", + "@field": "firmware", + "@when": "grade", + "@equals": "A" + } + } + ] + } + }, + { + "object.entity": { + "name": "Sensor", + "extends": "Powered", + "@discriminatorValue": "SENSOR", + "children": [ + { + "field.string": { + "name": "serial", + "children": [ + { + "validator.regex": { + "@pattern": "^S[0-9]+$" + } + } + ] + } + }, + { + "field.string": { + "name": "note", + "children": [ + { + "validator.length": { + "@max": 40 + } + } + ] + } + }, + { + "field.enum": { + "name": "mode", + "@required": true, + "@values": [ + "AUTO", + "MANUAL" + ] + } + }, + { + "field.string": { + "name": "unit" + } + }, + { + "validator.requiredWhen": { + "name": "manualUnit", + "@field": "unit", + "@when": "mode", + "@equals": "MANUAL" + } + }, + { + "validator.requiredWhen": { + "name": "manualNote", + "@field": "note", + "@when": "mode", + "@equals": "MANUAL" + } + } + ] + } + }, + { + "object.entity": { + "name": "Switch", + "extends": "Device", + "@discriminatorValue": "SWITCH", + "children": [ + { + "field.enum": { + "name": "grade", + "@values": [ + "X", + "Y" + ] + } + }, + { + "field.string": { + "name": "note", + "children": [ + { + "validator.length": { + "@max": 40 + } + } + ] + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "validator.length": { + "@min": 1, + "@max": 12 + } + } + ] + } + }, + { + "field.enum": { + "name": "legacyPosition", + "@values": [ + "ON", + "OFF" + ], + "@dbCheck": false + } + }, + { + "validator.comparison": { + "name": "labelled", + "@left": "label", + "@op": "ne", + "@right": "kind", + "@condition": { + "op": "isNotNull", + "arg": { + "field": "label" + } + } + } + }, + { + "validator.requiredWhen": { + "name": "offNote", + "@field": "note", + "@when": "legacyPosition", + "@equals": "OFF" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/codegen-conformance/xpkg-value-object-refs/README.md b/fixtures/codegen-conformance/xpkg-value-object-refs/README.md index 22fd9f53e0..261255e461 100644 --- a/fixtures/codegen-conformance/xpkg-value-object-refs/README.md +++ b/fixtures/codegen-conformance/xpkg-value-object-refs/README.md @@ -11,7 +11,7 @@ must tell them apart without a rename. A port that writes every package into one namespace or module directory refuses this model with `ERR_NAME_COLLISION` (two `Note`s, two `Summary`s); the corpus is run with the packages -kept apart — C# by default (each package is its own namespace), TypeScript `outputLayout: "package"` (the default). With them apart, every +kept apart — C# by default (each package is its own namespace), TypeScript `outputLayout: "package"` (opt-in; the default is `flat`). With them apart, every generated file that names one of the pair must name it unambiguously: - **C#:** every generated file names a type of another namespace `global::`-qualified (a bare diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index eda6d07de6..9322a6e9db 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -56,6 +56,8 @@ "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", + "ERR_CROSS_FIELD_WITHOUT_CHECK": "A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) sets @dbCheck: false. Nothing but its database CHECK enforces a cross-field validator, so false would leave the rule enforced nowhere: the validator is refused. Remove the validator instead.", + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A numeric, length or regex validator or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/conformance/entity-derived-league-gate/expected.json b/fixtures/conformance/entity-derived-league-gate/expected.json new file mode 100644 index 0000000000..432c8e5c2c --- /dev/null +++ b/fixtures/conformance/entity-derived-league-gate/expected.json @@ -0,0 +1,328 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Player", + "children": [ + { + "source.rdb": { + "@table": "players" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.boolean": { + "name": "hasActiveLeagueContract", + "children": [ + { + "origin.first": { + "@of": "acme::Contract.contractIsOnFile", + "@orderBy": [ + "id:desc" + ], + "@segment": "leagueDecisive", + "@via": "acme::Player.contracts" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Contract", + "children": [ + { + "source.rdb": { + "@table": "contracts" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "playerId", + "@required": true + } + }, + { + "field.int": { + "name": "contractTypeId" + } + }, + { + "field.boolean": { + "name": "contractIsOnFile" + } + }, + { + "field.boolean": { + "name": "playerContract" + } + }, + { + "field.date": { + "name": "dateReceived" + } + }, + { + "field.date": { + "name": "effectiveEndDate" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "playerId", + "@fields": [ + "playerId" + ], + "@references": "acme::Player" + } + }, + { + "segment.filter": { + "name": "leagueDecisive", + "@filter": { + "contractTypeId": { + "eq": 1 + }, + "or": [ + { + "contractIsOnFile": { + "eq": false + } + }, + { + "and": [ + { + "contractIsOnFile": { + "eq": true + } + }, + { + "or": [ + { + "playerContract": { + "isNull": true + } + }, + { + "playerContract": { + "eq": true + } + } + ] + }, + { + "dateReceived": { + "lte": { + "now": "P0D" + } + } + }, + { + "or": [ + { + "effectiveEndDate": { + "isNull": true + } + }, + { + "effectiveEndDate": { + "gte": { + "now": "P0D" + } + } + } + ] + } + ] + } + ] + } + } + } + ] + } + }, + { + "object.entity": { + "name": "Camp", + "children": [ + { + "source.rdb": { + "@table": "camps" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "playerId", + "@required": true + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "playerId", + "@fields": [ + "playerId" + ], + "@references": "acme::Player" + } + } + ] + } + }, + { + "object.entity": { + "name": "Authorization", + "children": [ + { + "source.rdb": { + "@table": "authorizations" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "campId", + "@required": true + } + }, + { + "field.string": { + "name": "code" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "campId", + "@fields": [ + "campId" + ], + "@references": "acme::Camp" + } + } + ] + } + }, + { + "object.projection": { + "name": "AuthorizationExtract", + "@filter": { + "campId.playerId.hasActiveLeagueContract": { + "eq": true + } + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_authorization_extract" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::Authorization.id" + } + }, + { + "field.string": { + "name": "code", + "extends": "acme::Authorization.code" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::Authorization.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "PlayerExtract", + "@filter": { + "hasActiveLeagueContract": { + "eq": true + } + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_player_extract" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::Player.id" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::Player.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/entity-derived-league-gate/input/meta.contract.json b/fixtures/conformance/entity-derived-league-gate/input/meta.contract.json new file mode 100644 index 0000000000..daaf8395d5 --- /dev/null +++ b/fixtures/conformance/entity-derived-league-gate/input/meta.contract.json @@ -0,0 +1,298 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Player", + "children": [ + { + "source.rdb": { + "@table": "players" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.boolean": { + "name": "hasActiveLeagueContract", + "children": [ + { + "origin.first": { + "@via": "acme::Player.contracts", + "@of": "acme::Contract.contractIsOnFile", + "@orderBy": [ + "id:desc" + ], + "@segment": "leagueDecisive" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Contract", + "children": [ + { + "source.rdb": { + "@table": "contracts" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "playerId", + "@required": true + } + }, + { + "field.int": { + "name": "contractTypeId" + } + }, + { + "field.boolean": { + "name": "contractIsOnFile" + } + }, + { + "field.boolean": { + "name": "playerContract" + } + }, + { + "field.date": { + "name": "dateReceived" + } + }, + { + "field.date": { + "name": "effectiveEndDate" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "playerId", + "@fields": "playerId", + "@references": "acme::Player" + } + }, + { + "segment.filter": { + "name": "leagueDecisive", + "@filter": { + "contractTypeId": 1, + "or": [ + { + "contractIsOnFile": false + }, + { + "and": [ + { + "contractIsOnFile": true + }, + { + "or": [ + { + "playerContract": null + }, + { + "playerContract": true + } + ] + }, + { + "dateReceived": { + "lte": { + "now": "P0D" + } + } + }, + { + "or": [ + { + "effectiveEndDate": null + }, + { + "effectiveEndDate": { + "gte": { + "now": "P0D" + } + } + } + ] + } + ] + } + ] + } + } + } + ] + } + }, + { + "object.entity": { + "name": "Camp", + "children": [ + { + "source.rdb": { + "@table": "camps" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "playerId", + "@required": true + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "playerId", + "@fields": "playerId", + "@references": "acme::Player" + } + } + ] + } + }, + { + "object.entity": { + "name": "Authorization", + "children": [ + { + "source.rdb": { + "@table": "authorizations" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "campId", + "@required": true + } + }, + { + "field.string": { + "name": "code" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "campId", + "@fields": "campId", + "@references": "acme::Camp" + } + } + ] + } + }, + { + "object.projection": { + "name": "AuthorizationExtract", + "@filter": { + "campId.playerId.hasActiveLeagueContract": true + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_authorization_extract" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::Authorization.id" + } + }, + { + "field.string": { + "name": "code", + "extends": "acme::Authorization.code" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::Authorization.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "PlayerExtract", + "@filter": { + "hasActiveLeagueContract": true + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_player_extract" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::Player.id" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::Player.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/entity-derived-league-gate/providers.json b/fixtures/conformance/entity-derived-league-gate/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/entity-derived-league-gate/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/enum-string-value-map/expected.json b/fixtures/conformance/enum-string-value-map/expected.json new file mode 100644 index 0000000000..f08172f0ad --- /dev/null +++ b/fixtures/conformance/enum-string-value-map/expected.json @@ -0,0 +1,59 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "status", + "@default": "Draft", + "@stringValueMap": { + "Draft": "draft", + "Published": "published", + "Retracted": "retracted" + }, + "@values": [ + "Draft", + "Published", + "Retracted" + ] + } + }, + { + "field.enum": { + "name": "channel", + "@maxLength": 16, + "@stringValueMap": { + "Email": "EMAIL_V1", + "None": "None", + "TextMessage": "SMS_LEGACY" + }, + "@values": [ + "None", + "Email", + "TextMessage" + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/enum-string-value-map/input/meta.enums.json b/fixtures/conformance/enum-string-value-map/input/meta.enums.json new file mode 100644 index 0000000000..8da81e43dc --- /dev/null +++ b/fixtures/conformance/enum-string-value-map/input/meta.enums.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Draft", "Published", "Retracted"], + "@stringValueMap": { "Draft": "draft", "Published": "published", "Retracted": "retracted" }, + "@default": "Draft" + } + }, + { + "field.enum": { + "name": "channel", + "@values": ["None", "Email", "TextMessage"], + "@stringValueMap": { "None": "None", "Email": "EMAIL_V1", "TextMessage": "SMS_LEGACY" }, + "@maxLength": 16 + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json new file mode 100644 index 0000000000..16a68b392d --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection'].children[2]['field.int'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json new file mode 100644 index 0000000000..6a6d328c77 --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json @@ -0,0 +1,13 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "k", "children": [ { "origin.computed": { "@expr": { "cast": { "field": "kind" }, "as": "int" } } } ] } } + ] } } +] } } diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-db-check-constraint-name/expected-errors.json b/fixtures/conformance/error-db-check-constraint-name/expected-errors.json new file mode 100644 index 0000000000..57beb78b35 --- /dev/null +++ b/fixtures/conformance/error-db-check-constraint-name/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['field.enum']" + } + }, + { + "code": "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[3]['field.string'].children[0]['validator.regex']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json b/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json new file mode 100644 index 0000000000..da1ac33e40 --- /dev/null +++ b/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json @@ -0,0 +1,21 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { "source.rdb": { "@table": "providers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false, "@constraintName": "providers_state_ok" } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false, "@constraintName": "providers_npi_shape" } } + ] } }, + { "identity.primary": { "name": "pk", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-db-check-cross-field/expected-errors.json b/fixtures/conformance/error-db-check-cross-field/expected-errors.json new file mode 100644 index 0000000000..e33dfc4598 --- /dev/null +++ b/fixtures/conformance/error-db-check-cross-field/expected-errors.json @@ -0,0 +1,45 @@ +{ + "errors": [ + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[8]['validator.comparison']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[9]['validator.requiredWhen']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[10]['validator.presentIff']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[11]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json new file mode 100644 index 0000000000..342bed122e --- /dev/null +++ b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json @@ -0,0 +1,26 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { "source.rdb": { "@table": "visits" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "field.timestamp": { "name": "startsAt" } }, + { "field.timestamp": { "name": "endsAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } }, + { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": false } }, + { "validator.requiredWhen": { "name": "depotEmail", "@field": "email", "@when": "kind", "@equals": "depot", "@dbCheck": false } }, + { "validator.presentIff": { "name": "depotStart", "@field": "startsAt", "@when": "kind", "@equals": "depot", "@dbCheck": false } }, + { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": false, "@constraintName": "visits_contact_ok" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json b/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json new file mode 100644 index 0000000000..2a8045ee08 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json b/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json new file mode 100644 index 0000000000..8da2de0e99 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json @@ -0,0 +1,8 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Region", "children": [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)", "@maxLength": 10 } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } } +] } } diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/providers.json b/fixtures/conformance/error-db-column-type-sized-max-length/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json new file mode 100644 index 0000000000..60a9e4b0ce --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "tags", + "isArray": true, + "@values": ["Hot", "Cold"], + "@stringValueMap": { "Hot": "hot", "Cold": "cold" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json new file mode 100644 index 0000000000..8c9ceb902d --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Draft", "Queued"], + "@stringValueMap": { "Draft": "draft", "Queued": "draft" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json new file mode 100644 index 0000000000..3dd0e8ecfa --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Archived": "archived" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json new file mode 100644 index 0000000000..ab0d7cfe89 --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Draft", "Published"], + "@intValueMap": { "Draft": 0, "Published": 1 }, + "@stringValueMap": { "Draft": "draft", "Published": "published" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json index 54d52403ec..c0bbeedf0e 100644 --- a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json +++ b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,18 +87,18 @@ }, { "object.projection": { - "name": "BadCase", + "name": "BadConsignment", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_badcase" + "@view": "v_badconsignment" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -136,7 +136,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json b/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json index a0b9f911a2..203fc192f9 100644 --- a/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json +++ b/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "min", - "@of": "acme::views::CaseHistory.createdDate", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.createdDate", + "@via": "acme::views::Consignment.consignmentHistory", "@filter": { "statusId": { "eq": { @@ -185,7 +185,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-origin-function-free-sql/expected-errors.json b/fixtures/conformance/error-origin-function-free-sql/expected-errors.json new file mode 100644 index 0000000000..61b9704fc4 --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[3]['field.string'].children[0]['origin.function']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json new file mode 100644 index 0000000000..8ce97fbb47 --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json @@ -0,0 +1,13 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of(id); drop table customers", "@args": ["id"], "@params": ["long"], "@returns": "string" } } ] } } + ] } }, + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Customer.id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "Customer.tier" } } ] } } + ] } } +] } } diff --git a/fixtures/conformance/error-origin-function-free-sql/providers.json b/fixtures/conformance/error-origin-function-free-sql/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json b/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json index 213b9028b8..cb1c2f0ac8 100644 --- a/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json +++ b/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json @@ -5,11 +5,11 @@ "source": { "format": "resolved", "files": [ - "meta.care.json" + "meta.league.json" ], "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.aggregate']", - "referrer": "PatientConsentSummary::consentCount", - "target": "acme::care::Patient.consents" + "referrer": "PlayerContractSummary::contractCount", + "target": "acme::league::Player.contracts" } } ], diff --git a/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json b/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json similarity index 73% rename from fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json rename to fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json index aac28e4a2b..6a9baaf0c7 100644 --- a/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json +++ b/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::care", + "package": "acme::league", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -27,11 +27,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -41,7 +41,7 @@ }, { "field.long": { - "name": "patientId" + "name": "playerId" } }, { @@ -62,16 +62,16 @@ }, { "identity.reference": { - "name": "patient", - "@fields": "patientId", - "@references": "acme::care::Patient" + "name": "player", + "@fields": "playerId", + "@references": "acme::league::Player" } }, { "identity.reference": { "name": "witness", "@fields": "witnessId", - "@references": "acme::care::Patient" + "@references": "acme::league::Player" } } ] @@ -79,29 +79,29 @@ }, { "object.projection": { - "name": "PatientConsentSummary", + "name": "PlayerContractSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_patient_consent_summary" + "@view": "v_player_contract_summary" } }, { "field.long": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } }, { "field.int": { - "name": "consentCount", + "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", - "@of": "acme::care::Consent.id", - "@via": "acme::care::Patient.consents" + "@of": "acme::league::Contract.id", + "@via": "acme::league::Player.contracts" } } ] @@ -110,7 +110,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } } ] diff --git a/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json b/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json index dd80eac514..0c3a333306 100644 --- a/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json +++ b/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "count", - "@of": "acme::views::CaseHistory.id", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.id", + "@via": "acme::views::Consignment.consignmentHistory", "@segment": "dead" } } @@ -179,7 +179,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json index da10f876b2..f0a1bb8e4c 100644 --- a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json +++ b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json @@ -9,7 +9,7 @@ ], "jsonPath": "$['metadata.root'].children[1]['object.value'].children[0]['field.int'].children[0]['origin.passthrough']", "referrer": "Args::label", - "target": "demo::Case.label" + "target": "demo::Consignment.label" } } ], diff --git a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json index a476074970..1c635c075a 100644 --- a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json +++ b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -40,7 +40,7 @@ "children": [ { "origin.passthrough": { - "@from": "demo::Case.label" + "@from": "demo::Consignment.label" } } ] diff --git a/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json b/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json index 51720f937f..61655bf31b 100644 --- a/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json +++ b/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json @@ -2,7 +2,7 @@ "errors": [ { "code": "ERR_BAD_ATTR_VALUE", - "source": { "format": "json", "files": [ "meta.diagnosis.json" ], "jsonPath": "$['metadata.root'].children[0]['object.entity']" } + "source": { "format": "json", "files": [ "meta.analysis.json" ], "jsonPath": "$['metadata.root'].children[0]['object.entity']" } } ], "warnings": [] diff --git a/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json b/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json similarity index 53% rename from fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json rename to fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json index 22063012de..51a8959b8f 100644 --- a/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json +++ b/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json @@ -1,8 +1,8 @@ { "metadata.root": { - "package": "acme::clinical", + "package": "acme::lab", "children": [ - { "object.entity": { "name": "Diagnosis", "@objectAdapter": ["com.acme.clinical.DiagnosisAdapter"], "children": [ + { "object.entity": { "name": "Analysis", "@objectAdapter": ["com.acme.lab.AnalysisAdapter"], "children": [ { "field.long": { "name": "id" } }, { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } } diff --git a/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json b/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json index 673b59dbf9..f607bf0fec 100644 --- a/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json +++ b/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "plans" } }, { "field.long": { "name": "id" } }, - { "field.boolean": { "name": "consented" } }, + { "field.boolean": { "name": "contracted" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } @@ -17,7 +17,7 @@ "object.projection": { "name": "GatedPlans", "abstract": true, - "@filter": { "consented": true }, + "@filter": { "contracted": true }, "children": [ { "field.long": { "name": "planId", "extends": "Plan.id" } }, { "identity.primary": { "name": "id", "extends": "Plan.id" } } diff --git a/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json b/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json index 1d95da3239..7ccfebeb90 100644 --- a/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json +++ b/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json @@ -2,8 +2,8 @@ "metadata.root": { "package": "acme::tasks", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "status" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -13,11 +13,11 @@ { "source.rdb": { "@table": "tasks" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "consignmentId" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "acme::tasks::Case" } } + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "acme::tasks::Consignment" } } ] } }, - { "object.projection": { "name": "OpenTasks", "@filter": { "caseId.tasks.title": "x" }, "children": [ + { "object.projection": { "name": "OpenTasks", "@filter": { "consignmentId.tasks.title": "x" }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_open_tasks" } }, { "field.long": { "name": "id", "extends": "acme::tasks::Task.id" } }, { "field.string": { "name": "title", "extends": "acme::tasks::Task.title" } }, diff --git a/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json b/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json new file mode 100644 index 0000000000..c522a29b12 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json b/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json new file mode 100644 index 0000000000..d95ea15aa2 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json @@ -0,0 +1,12 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "tags", "isArray": true } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "G", "@grain": "tags", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, + { "field.long": { "name": "customerId", "extends": "Customer.id" } } + ] } } +] } } diff --git a/fixtures/conformance/error-projection-grain-not-object-array/providers.json b/fixtures/conformance/error-projection-grain-not-object-array/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-projection-union-shape/expected-errors.json b/fixtures/conformance/error-projection-union-shape/expected-errors.json new file mode 100644 index 0000000000..8f752c3ae4 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[3]['object.projection']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-projection-union-shape/input/meta.views.json b/fixtures/conformance/error-projection-union-shape/input/meta.views.json new file mode 100644 index 0000000000..89ec9dada7 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/input/meta.views.json @@ -0,0 +1,18 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "A", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } }, + { "field.string": { "name": "label", "extends": "Customer.zip" } } + ] } }, + { "object.projection": { "name": "B", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } } + ] } }, + { "object.projection": { "name": "U", "extends": "A", "@union": ["B"], "children": [ + { "source.rdb": { "@kind": "view", "@view": "u" } } + ] } } +] } } diff --git a/fixtures/conformance/error-projection-union-shape/providers.json b/fixtures/conformance/error-projection-union-shape/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json b/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json index 93a29fd765..0a2d464a88 100644 --- a/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json +++ b/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, diff --git a/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json b/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json index 65b4f1ed03..cf87e2a870 100644 --- a/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json +++ b/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, diff --git a/fixtures/conformance/field-object-storage-jsonb-array/expected.json b/fixtures/conformance/field-object-storage-jsonb-array/expected.json index 3b4489673e..e5d94bf969 100644 --- a/fixtures/conformance/field-object-storage-jsonb-array/expected.json +++ b/fixtures/conformance/field-object-storage-jsonb-array/expected.json @@ -26,11 +26,11 @@ }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { diff --git a/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json b/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json index d9c44f43e7..fcd8174c5d 100644 --- a/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json +++ b/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json @@ -26,11 +26,11 @@ }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { diff --git a/fixtures/conformance/object-collection-name-consignments/expected.json b/fixtures/conformance/object-collection-name-consignments/expected.json new file mode 100644 index 0000000000..1474a24dc3 --- /dev/null +++ b/fixtures/conformance/object-collection-name-consignments/expected.json @@ -0,0 +1,158 @@ +{ + "metadata.root": { + "package": "acme::consignments", + "children": [ + { + "object.entity": { + "name": "Consignment", + "children": [ + { + "source.rdb": { + "@table": "consignments" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", + "children": [ + { + "source.rdb": { + "@table": "consignment_history" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "consignmentId" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "field.timestamp": { + "name": "createdDate" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "consignmentId", + "@fields": [ + "consignmentId" + ], + "@references": "acme::consignments::Consignment" + } + }, + { + "dimension.attribute": { + "name": "status", + "@of": "acme::consignments::ConsignmentHistory.status" + } + }, + { + "measure.aggregate": { + "name": "entries", + "@agg": "count", + "@of": [ + "acme::consignments::ConsignmentHistory.id" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "ConsignmentActivity", + "@collectionName": "ConsignmentActivity", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_consignment_activity" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::consignments::Consignment.id" + } + }, + { + "field.int": { + "name": "historyCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@of": "acme::consignments::ConsignmentHistory.id", + "@via": "acme::consignments::Consignment.consignmentHistory" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::consignments::Consignment.id" + } + } + ] + } + }, + { + "object.report": { + "name": "HistoryCounts", + "@collectionName": "HistoryCounts", + "@dimensions": [ + "status" + ], + "@from": "acme::consignments::ConsignmentHistory", + "@measures": [ + "entries" + ], + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_history_counts" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/object-collection-name-consignments/input/meta.consignments.json b/fixtures/conformance/object-collection-name-consignments/input/meta.consignments.json new file mode 100644 index 0000000000..d1063f5c8b --- /dev/null +++ b/fixtures/conformance/object-collection-name-consignments/input/meta.consignments.json @@ -0,0 +1,150 @@ +{ + "metadata.root": { + "package": "acme::consignments", + "children": [ + { + "object.entity": { + "name": "Consignment", + "children": [ + { + "source.rdb": { + "@table": "consignments" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", + "children": [ + { + "source.rdb": { + "@table": "consignment_history" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "consignmentId" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "field.timestamp": { + "name": "createdDate" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::consignments::Consignment" + } + }, + { + "dimension.attribute": { + "name": "status", + "@of": "acme::consignments::ConsignmentHistory.status" + } + }, + { + "measure.aggregate": { + "name": "entries", + "@agg": "count", + "@of": "acme::consignments::ConsignmentHistory.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "ConsignmentActivity", + "@collectionName": "ConsignmentActivity", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_consignment_activity" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::consignments::Consignment.id" + } + }, + { + "field.int": { + "name": "historyCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@of": "acme::consignments::ConsignmentHistory.id", + "@via": "acme::consignments::Consignment.consignmentHistory" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::consignments::Consignment.id" + } + } + ] + } + }, + { + "object.report": { + "name": "HistoryCounts", + "@collectionName": "HistoryCounts", + "@from": "acme::consignments::ConsignmentHistory", + "@dimensions": [ + "status" + ], + "@measures": [ + "entries" + ], + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_history_counts" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/object-collection-name-consignments/providers.json b/fixtures/conformance/object-collection-name-consignments/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/object-collection-name-consignments/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/object-collection-name/expected.json b/fixtures/conformance/object-collection-name/expected.json index e4136d2a7b..761d627fbd 100644 --- a/fixtures/conformance/object-collection-name/expected.json +++ b/fixtures/conformance/object-collection-name/expected.json @@ -1,15 +1,15 @@ { "metadata.root": { - "package": "acme::clinical", + "package": "acme::lab", "children": [ { "object.entity": { - "name": "Diagnosis", - "@collectionName": "Diagnosis", + "name": "Analysis", + "@collectionName": "Analysis", "children": [ { "source.rdb": { - "@table": "diagnoses" + "@table": "analyses" } }, { @@ -33,15 +33,15 @@ { "dimension.attribute": { "name": "code", - "@of": "acme::clinical::Diagnosis.code" + "@of": "acme::lab::Analysis.code" } }, { "measure.aggregate": { - "name": "diagnoses", + "name": "analyses", "@agg": "count", "@of": [ - "acme::clinical::Diagnosis.id" + "acme::lab::Analysis.id" ] } } @@ -50,13 +50,13 @@ }, { "object.projection": { - "name": "DiagnosisSummary", - "@collectionName": "DiagnosisSummary", + "name": "AnalysisSummary", + "@collectionName": "AnalysisSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_diagnosis_summary" + "@view": "v_analysis_summary" } }, { @@ -69,20 +69,20 @@ }, { "object.report": { - "name": "DiagnosisCounts", - "@collectionName": "DiagnosisCounts", + "name": "AnalysisCounts", + "@collectionName": "AnalysisCounts", "@dimensions": [ "code" ], - "@from": "acme::clinical::Diagnosis", + "@from": "acme::lab::Analysis", "@measures": [ - "diagnoses" + "analyses" ], "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_diagnosis_counts" + "@view": "v_analysis_counts" } } ] diff --git a/fixtures/conformance/object-collection-name/input/meta.analysis.json b/fixtures/conformance/object-collection-name/input/meta.analysis.json new file mode 100644 index 0000000000..5473407ee4 --- /dev/null +++ b/fixtures/conformance/object-collection-name/input/meta.analysis.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme::lab", + "children": [ + { "object.entity": { "name": "Analysis", "@collectionName": "Analysis", "children": [ + { "source.rdb": { "@table": "analyses" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "code", "@of": "Analysis.code" } }, + { "measure.aggregate": { "name": "analyses", "@agg": "count", "@of": "Analysis.id" } } + ] } }, + { "object.projection": { "name": "AnalysisSummary", "@collectionName": "AnalysisSummary", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_analysis_summary" } }, + { "field.string": { "name": "code" } } + ] } }, + { "object.report": { "name": "AnalysisCounts", "@collectionName": "AnalysisCounts", "@from": "Analysis", + "@dimensions": ["code"], "@measures": ["analyses"], "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_analysis_counts" } } + ] } } + ] + } +} diff --git a/fixtures/conformance/object-collection-name/input/meta.diagnosis.json b/fixtures/conformance/object-collection-name/input/meta.diagnosis.json deleted file mode 100644 index 3fb6616ee3..0000000000 --- a/fixtures/conformance/object-collection-name/input/meta.diagnosis.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "metadata.root": { - "package": "acme::clinical", - "children": [ - { "object.entity": { "name": "Diagnosis", "@collectionName": "Diagnosis", "children": [ - { "source.rdb": { "@table": "diagnoses" } }, - { "field.long": { "name": "id" } }, - { "field.string": { "name": "code" } }, - { "identity.primary": { "name": "pk", "@fields": ["id"] } }, - { "dimension.attribute": { "name": "code", "@of": "Diagnosis.code" } }, - { "measure.aggregate": { "name": "diagnoses", "@agg": "count", "@of": "Diagnosis.id" } } - ] } }, - { "object.projection": { "name": "DiagnosisSummary", "@collectionName": "DiagnosisSummary", "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_diagnosis_summary" } }, - { "field.string": { "name": "code" } } - ] } }, - { "object.report": { "name": "DiagnosisCounts", "@collectionName": "DiagnosisCounts", "@from": "Diagnosis", - "@dimensions": ["code"], "@measures": ["diagnoses"], "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_diagnosis_counts" } } - ] } } - ] - } -} diff --git a/fixtures/conformance/origin-computed-case-over-joined/expected.json b/fixtures/conformance/origin-computed-case-over-joined/expected.json index a7a58af1fb..3afd146419 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/expected.json +++ b/fixtures/conformance/origin-computed-case-over-joined/expected.json @@ -39,11 +39,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -58,12 +58,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -107,18 +107,18 @@ }, { "object.projection": { - "name": "CaseLabels", + "name": "ConsignmentLabels", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_caselabels" + "@view": "v_consignmentlabels" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -128,7 +128,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.name", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -141,7 +141,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.displayName", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -181,7 +181,7 @@ "when": { "op": "eq", "left": { - "field": "cumulativeStatus" + "field": "rollupStatus" }, "right": { "value": 0 @@ -193,7 +193,7 @@ } ], "else": { - "field": "cumulativeStatus" + "field": "rollupStatus" } } } @@ -203,13 +203,13 @@ }, { "field.string": { - "name": "benefitTypeName", + "name": "serviceLevelName", "children": [ { "origin.computed": { "@expr": { "operand": { - "field": "priorType" + "field": "serviceLevel" }, "case": [ { @@ -217,7 +217,7 @@ "value": 1 }, "then": { - "value": "Medical" + "value": "Standard" } }, { @@ -225,7 +225,7 @@ "value": 2 }, "then": { - "value": "Pharmacy" + "value": "Express" } } ] @@ -316,7 +316,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json index 8839e5b8c2..6c8e5c6752 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json +++ b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json @@ -37,11 +37,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -56,12 +56,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -101,18 +101,18 @@ }, { "object.projection": { - "name": "CaseLabels", + "name": "ConsignmentLabels", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_caselabels" + "@view": "v_consignmentlabels" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -122,7 +122,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.name", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -135,7 +135,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.displayName", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -175,7 +175,7 @@ "when": { "op": "eq", "left": { - "field": "cumulativeStatus" + "field": "rollupStatus" }, "right": { "value": 0 @@ -187,7 +187,7 @@ } ], "else": { - "field": "cumulativeStatus" + "field": "rollupStatus" } } } @@ -197,13 +197,13 @@ }, { "field.string": { - "name": "benefitTypeName", + "name": "serviceLevelName", "children": [ { "origin.computed": { "@expr": { "operand": { - "field": "priorType" + "field": "serviceLevel" }, "case": [ { @@ -211,7 +211,7 @@ "value": 1 }, "then": { - "value": "Medical" + "value": "Standard" } }, { @@ -219,7 +219,7 @@ "value": 2 }, "then": { - "value": "Pharmacy" + "value": "Express" } } ] @@ -310,7 +310,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/expected.json b/fixtures/conformance/origin-correlated-filter-and-segment/expected.json index cb50ec0209..76e546a3c6 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/expected.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/expected.json @@ -34,11 +34,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -53,12 +53,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -93,12 +93,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -108,7 +108,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -137,11 +137,11 @@ }, { "identity.reference": { - "name": "caseId", + "name": "consignmentId", "@fields": [ - "caseId" + "consignmentId" ], - "@references": "acme::views::Case" + "@references": "acme::views::Consignment" } }, { @@ -170,7 +170,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -187,9 +187,9 @@ } } }, - "@of": "acme::views::CaseHistory.createdDate", + "@of": "acme::views::ConsignmentHistory.createdDate", "@segment": "live", - "@via": "acme::views::Case.caseHistory" + "@via": "acme::views::Consignment.consignmentHistory" } } ] @@ -208,12 +208,12 @@ } } }, - "@of": "acme::views::CaseHistory.statusId", + "@of": "acme::views::ConsignmentHistory.statusId", "@orderBy": [ "statusId" ], "@segment": "live", - "@via": "acme::views::Case.caseHistory" + "@via": "acme::views::Consignment.consignmentHistory" } } ] @@ -222,7 +222,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json b/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json index dfbf1198a4..1dc70e4857 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "min", - "@of": "acme::views::CaseHistory.createdDate", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.createdDate", + "@via": "acme::views::Consignment.consignmentHistory", "@segment": "live", "@filter": { "statusId": { @@ -189,8 +189,8 @@ "children": [ { "origin.first": { - "@of": "acme::views::CaseHistory.statusId", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.statusId", + "@via": "acme::views::Consignment.consignmentHistory", "@orderBy": [ "statusId" ], @@ -210,7 +210,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-reverse-reference-hop/expected.json b/fixtures/conformance/origin-reverse-reference-hop/expected.json index 41988191ee..48f18e3da0 100644 --- a/fixtures/conformance/origin-reverse-reference-hop/expected.json +++ b/fixtures/conformance/origin-reverse-reference-hop/expected.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::care", + "package": "acme::league", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -29,11 +29,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -43,7 +43,7 @@ }, { "field.long": { - "name": "patientId" + "name": "playerId" } }, { @@ -61,11 +61,11 @@ }, { "identity.reference": { - "name": "patient", + "name": "player", "@fields": [ - "patientId" + "playerId" ], - "@references": "acme::care::Patient" + "@references": "acme::league::Player" } } ] @@ -73,29 +73,29 @@ }, { "object.projection": { - "name": "PatientConsentSummary", + "name": "PlayerContractSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_patient_consent_summary" + "@view": "v_player_contract_summary" } }, { "field.long": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } }, { "field.int": { - "name": "consentCount", + "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", - "@of": "acme::care::Consent.id", - "@via": "acme::care::Patient.consents" + "@of": "acme::league::Contract.id", + "@via": "acme::league::Player.contracts" } } ] @@ -107,11 +107,11 @@ "children": [ { "origin.first": { - "@of": "acme::care::Consent.onFile", + "@of": "acme::league::Contract.onFile", "@orderBy": [ "id:desc" ], - "@via": "acme::care::Patient.consents" + "@via": "acme::league::Player.contracts" } } ] @@ -120,7 +120,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } } ] diff --git a/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json b/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json deleted file mode 100644 index a14ed58011..0000000000 --- a/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "metadata.root": { - "package": "acme::care", - "children": [ - { - "object.entity": { - "name": "Patient", - "children": [ - { "source.rdb": { "@table": "patients" } }, - { "field.long": { "name": "id" } }, - { "identity.primary": { "name": "id", "@fields": "id" } } - ] - } - }, - { - "object.entity": { - "name": "Consent", - "children": [ - { "source.rdb": { "@table": "consents" } }, - { "field.long": { "name": "id" } }, - { "field.long": { "name": "patientId" } }, - { "field.boolean": { "name": "onFile" } }, - { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "patient", "@fields": "patientId", "@references": "acme::care::Patient" } } - ] - } - }, - { - "object.projection": { - "name": "PatientConsentSummary", - "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_patient_consent_summary" } }, - { "field.long": { "name": "id", "extends": "acme::care::Patient.id" } }, - { "field.int": { "name": "consentCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::care::Consent.id", "@via": "acme::care::Patient.consents" } } ] } }, - { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::care::Consent.onFile", "@via": "acme::care::Patient.consents", "@orderBy": ["id:desc"] } } ] } }, - { "identity.primary": { "name": "id", "extends": "acme::care::Patient.id" } } - ] - } - } - ] - } -} diff --git a/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json b/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json new file mode 100644 index 0000000000..f3cb1f7b1f --- /dev/null +++ b/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json @@ -0,0 +1,42 @@ +{ + "metadata.root": { + "package": "acme::league", + "children": [ + { + "object.entity": { + "name": "Player", + "children": [ + { "source.rdb": { "@table": "players" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + }, + { + "object.entity": { + "name": "Contract", + "children": [ + { "source.rdb": { "@table": "contracts" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "playerId" } }, + { "field.boolean": { "name": "onFile" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "player", "@fields": "playerId", "@references": "acme::league::Player" } } + ] + } + }, + { + "object.projection": { + "name": "PlayerContractSummary", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_player_contract_summary" } }, + { "field.long": { "name": "id", "extends": "acme::league::Player.id" } }, + { "field.int": { "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::league::Contract.id", "@via": "acme::league::Player.contracts" } } ] } }, + { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::league::Contract.onFile", "@via": "acme::league::Player.contracts", "@orderBy": ["id:desc"] } } ] } }, + { "identity.primary": { "name": "id", "extends": "acme::league::Player.id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json index bd411f6965..109fcda9e5 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -22,13 +22,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@parameterRef": "demo::PhaseSummaryArgs", - "@proc": "fn_get_phase_summary" + "@parameterRef": "demo::StageSummaryArgs", + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json index faef10bce8..a9599a2bca 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -22,13 +22,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "demo::PhaseSummaryArgs" + "@proc": "fn_get_stage_summary", + "@parameterRef": "demo::StageSummaryArgs" } }, { diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json index dd527e5074..4ba87977d7 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -29,16 +29,16 @@ }, { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ { "origin.passthrough": { - "@from": "demo::Case.id" + "@from": "demo::Consignment.id" } } ] @@ -49,13 +49,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@parameterRef": "demo::PhaseSummaryArgs", - "@proc": "fn_get_phase_summary" + "@parameterRef": "demo::StageSummaryArgs", + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json index afaa447fd7..d747a0e2a8 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -27,16 +27,16 @@ }, { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ { "origin.passthrough": { - "@from": "demo::Case.id" + "@from": "demo::Consignment.id" } } ] @@ -47,13 +47,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "demo::PhaseSummaryArgs" + "@proc": "fn_get_stage_summary", + "@parameterRef": "demo::StageSummaryArgs" } }, { diff --git a/fixtures/conformance/projection-extends-filtered-projection/expected.json b/fixtures/conformance/projection-extends-filtered-projection/expected.json index 340e890c8f..dddb9c62ee 100644 --- a/fixtures/conformance/projection-extends-filtered-projection/expected.json +++ b/fixtures/conformance/projection-extends-filtered-projection/expected.json @@ -28,7 +28,7 @@ }, { "field.boolean": { - "name": "consented" + "name": "contracted" } }, { @@ -52,7 +52,7 @@ "name": "GatedPlans", "abstract": true, "@filter": { - "consented": { + "contracted": { "eq": true } }, diff --git a/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json b/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json index 3e2b1d8326..96652606f9 100644 --- a/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json +++ b/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json @@ -10,7 +10,7 @@ { "field.long": { "name": "id" } }, { "field.string": { "name": "name" } }, { "field.string": { "name": "code" } }, - { "field.boolean": { "name": "consented" } }, + { "field.boolean": { "name": "contracted" } }, { "field.boolean": { "name": "deleted" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] @@ -20,7 +20,7 @@ "object.projection": { "name": "GatedPlans", "abstract": true, - "@filter": { "consented": true }, + "@filter": { "contracted": true }, "children": [ { "field.long": { "name": "planId", "extends": "Plan.id" } }, { "field.string": { "name": "label", "children": [ { "origin.passthrough": { "@from": "Plan.name" } } ] } }, diff --git a/fixtures/conformance/projection-filter-joined-path/expected.json b/fixtures/conformance/projection-filter-joined-path/expected.json index 7122594bb5..6e7f65f1a1 100644 --- a/fixtures/conformance/projection-filter-joined-path/expected.json +++ b/fixtures/conformance/projection-filter-joined-path/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -60,7 +60,7 @@ }, { "field.long": { - "name": "caseId" + "name": "consignmentId" } }, { @@ -73,11 +73,11 @@ }, { "identity.reference": { - "name": "caseId", + "name": "consignmentId", "@fields": [ - "caseId" + "consignmentId" ], - "@references": "acme::tasks::Case" + "@references": "acme::tasks::Consignment" } } ] @@ -87,7 +87,7 @@ "object.projection": { "name": "OpenTasks", "@filter": { - "caseId.status": { + "consignmentId.status": { "eq": "open" } }, diff --git a/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json b/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json index e6bf337e67..9ac298a913 100644 --- a/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json +++ b/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json @@ -2,8 +2,8 @@ "metadata.root": { "package": "acme::tasks", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "status" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -13,11 +13,11 @@ { "source.rdb": { "@table": "tasks" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "consignmentId" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "acme::tasks::Case" } } + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "acme::tasks::Consignment" } } ] } }, - { "object.projection": { "name": "OpenTasks", "@filter": { "caseId.status": "open" }, "children": [ + { "object.projection": { "name": "OpenTasks", "@filter": { "consignmentId.status": "open" }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_open_tasks" } }, { "field.long": { "name": "id", "extends": "acme::tasks::Task.id" } }, { "field.string": { "name": "title", "extends": "acme::tasks::Task.title" } }, diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json new file mode 100644 index 0000000000..39387e08fc --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json @@ -0,0 +1,503 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.value": { + "name": "Contact", + "children": [ + { + "field.string": { + "name": "kind" + } + }, + { + "field.int": { + "name": "rank" + } + } + ] + } + }, + { + "object.entity": { + "name": "Customer", + "children": [ + { + "source.rdb": { + "@table": "customers" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "zip", + "@dbColumnType": "varchar(10)" + } + }, + { + "field.string": { + "name": "code", + "@dbColumnType": "character(3)" + } + }, + { + "field.string": { + "name": "note", + "@dbColumnType": "varchar" + } + }, + { + "field.object": { + "name": "contacts", + "isArray": true, + "@objectRef": "acme::views::Contact", + "@storage": "jsonb" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "tier", + "children": [ + { + "origin.function": { + "@args": [ + "id", + "zip" + ], + "@function": "tier_of", + "@params": [ + "long", + "string" + ], + "@returns": "string", + "@schema": "app" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.enum": { + "name": "status", + "@intValueMap": { + "Open": 0, + "Shipped": 1 + }, + "@values": [ + "Open", + "Shipped" + ] + } + }, + { + "field.int": { + "name": "stage" + } + }, + { + "field.timestamp": { + "name": "updatedAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "customerId", + "@fields": [ + "customerId" + ], + "@references": "acme::views::Customer" + } + } + ] + } + }, + { + "object.entity": { + "name": "OrderEvent", + "children": [ + { + "source.rdb": { + "@table": "order_events" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "orderId" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.timestamp": { + "name": "createdAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "orderId", + "@fields": [ + "orderId" + ], + "@references": "acme::views::Order" + } + } + ] + } + }, + { + "object.projection": { + "name": "OrderRow", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_order_row" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Order.id" + } + }, + { + "field.int": { + "name": "outcome", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "stage" + }, + "right": { + "value": 0 + } + }, + "then": { + "cast": { + "field": "status" + }, + "as": "int" + } + } + ], + "else": { + "field": "stage" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "zip5", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "splitPart", + "args": [ + { + "field": "customerId.zip" + }, + { + "value": "-" + }, + { + "value": 1 + } + ] + } + } + } + ] + } + }, + { + "field.string": { + "name": "nothing", + "children": [ + { + "origin.computed": { + "@expr": { + "cast": { + "value": null + }, + "as": "string", + "dbColumnType": "varchar" + } + } + } + ] + } + }, + { + "field.string": { + "name": "tier", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Customer.tier", + "@via": "acme::views::Order.customerId" + } + } + ] + } + }, + { + "field.timestamp": { + "name": "lastEvent", + "children": [ + { + "origin.aggregate": { + "@agg": "max", + "@of": "acme::views::OrderEvent.createdAt", + "@via": "acme::views::Order.orderEvents" + } + } + ] + } + }, + { + "field.timestamp": { + "name": "touched", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "greatest", + "args": [ + { + "field": "updatedAt" + }, + { + "field": "lastEvent" + } + ] + } + } + } + ] + } + }, + { + "field.long": { + "name": "eventOfCustomer", + "children": [ + { + "origin.first": { + "@filter": { + "customerId": { + "eq": { + "field": "customerId.id" + } + } + }, + "@of": "acme::views::OrderEvent.id", + "@orderBy": [ + "createdAt" + ], + "@via": "acme::views::Order.orderEvents" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Order.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "CustomerContact", + "@grain": "contacts", + "@grainOrdinal": "position", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_customer_contact" + } + }, + { + "field.long": { + "name": "customerId", + "extends": "acme::views::Customer.id" + } + }, + { + "field.int": { + "name": "position" + } + }, + { + "field.string": { + "name": "kind", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Contact.kind" + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "CustomerBranch", + "abstract": true, + "children": [ + { + "field.long": { + "name": "personId", + "extends": "acme::views::Customer.id" + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "lower", + "args": [ + { + "field": "zip" + } + ] + } + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "OrderBranch", + "abstract": true, + "children": [ + { + "field.long": { + "name": "personId", + "extends": "acme::views::Order.customerId" + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "cast": { + "field": "id" + }, + "as": "string" + } + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "People", + "extends": "acme::views::CustomerBranch", + "@union": [ + "OrderBranch" + ], + "@unionAll": true, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_people" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json new file mode 100644 index 0000000000..57c98b15a5 --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json @@ -0,0 +1,78 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "kind" } }, + { "field.int": { "name": "rank" } } + ] } }, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip", "@dbColumnType": "varchar(10)" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)" } }, + { "field.string": { "name": "note", "@dbColumnType": "varchar" } }, + { "field.object": { "name": "contacts", "@objectRef": "Contact", "isArray": true, "@storage": "jsonb" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ + { "origin.function": { "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } + ] } } + ] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "customerId" } }, + { "field.enum": { "name": "status", "@values": ["Open", "Shipped"], "@intValueMap": { "Open": 0, "Shipped": 1 } } }, + { "field.int": { "name": "stage" } }, + { "field.timestamp": { "name": "updatedAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "customerId", "@fields": "customerId", "@references": "Customer" } } + ] } }, + { "object.entity": { "name": "OrderEvent", "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "orderId" } }, + { "field.long": { "name": "customerId" } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } + ] } }, + { "object.projection": { "name": "OrderRow", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_order_row" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "outcome", "children": [ { "origin.computed": { "@expr": { + "case": [ { "when": { "op": "eq", "left": { "field": "stage" }, "right": { "value": 0 } }, + "then": { "cast": { "field": "status" }, "as": "int" } } ], + "else": { "field": "stage" } } } } ] } }, + { "field.string": { "name": "zip5", "children": [ { "origin.computed": { "@expr": { + "fn": "splitPart", "args": [ { "field": "customerId.zip" }, { "value": "-" }, { "value": 1 } ] } } } ] } }, + { "field.string": { "name": "nothing", "children": [ { "origin.computed": { "@expr": { + "cast": { "value": null }, "as": "string", "dbColumnType": "varchar" } } } ] } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "Customer.tier", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { "name": "lastEvent", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + { "field.timestamp": { "name": "touched", "children": [ { "origin.computed": { "@expr": { + "fn": "greatest", "args": [ { "field": "updatedAt" }, { "field": "lastEvent" } ] } } } ] } }, + { "field.long": { "name": "eventOfCustomer", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", + "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.id" } } } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Order.id" } } + ] } }, + { "object.projection": { "name": "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_customer_contact" } }, + { "field.long": { "name": "customerId", "extends": "Customer.id" } }, + { "field.int": { "name": "position" } }, + { "field.string": { "name": "kind", "children": [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } } + ] } }, + { "object.projection": { "name": "CustomerBranch", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } }, + { "field.string": { "name": "label", "children": [ { "origin.computed": { "@expr": { "fn": "lower", "args": [ { "field": "zip" } ] } } } ] } } + ] } }, + { "object.projection": { "name": "OrderBranch", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Order.customerId" } }, + { "field.string": { "name": "label", "children": [ { "origin.computed": { "@expr": { "cast": { "field": "id" }, "as": "string" } } } ] } } + ] } }, + { "object.projection": { "name": "People", "extends": "CustomerBranch", "@union": ["OrderBranch"], "@unionAll": true, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_people" } } + ] } } + ] + } +} diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/providers.json b/fixtures/conformance/projection-view-vocabulary-rc21/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/source-db-table-with-schema/expected.json b/fixtures/conformance/source-db-table-with-schema/expected.json index 229c73f7e6..94b0202d89 100644 --- a/fixtures/conformance/source-db-table-with-schema/expected.json +++ b/fixtures/conformance/source-db-table-with-schema/expected.json @@ -4,12 +4,12 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { "@schema": "public", - "@table": "Cases" + "@table": "Consignments" } }, { @@ -19,7 +19,7 @@ }, { "field.string": { - "name": "caseNumber" + "name": "consignmentNumber" } }, { diff --git a/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json b/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json index 002f40dea6..97cb736428 100644 --- a/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json +++ b/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "Cases", + "@table": "Consignments", "@schema": "public" } }, @@ -19,7 +19,7 @@ }, { "field.string": { - "name": "caseNumber" + "name": "consignmentNumber" } }, { diff --git a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json index 0bab414a97..9e5d141e5c 100644 --- a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json +++ b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json @@ -4,12 +4,12 @@ "children": [ { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary" + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json index 0bab414a97..9e5d141e5c 100644 --- a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json +++ b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json @@ -4,12 +4,12 @@ "children": [ { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary" + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json b/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json index e09204e4c1..775c7d6206 100644 --- a/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json +++ b/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json @@ -17,7 +17,7 @@ "name": "type", "@values": [ "Bridge", - "Copay" + "Coupon" ] } }, @@ -53,13 +53,13 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ { "field.decimal": { - "name": "copayAmount", + "name": "couponAmount", "@precision": 10, "@scale": 2 } diff --git a/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json b/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json index d1b9e53352..349eceffcf 100644 --- a/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json +++ b/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, @@ -31,11 +31,11 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } } diff --git a/fixtures/conformance/validator-db-check/expected.json b/fixtures/conformance/validator-db-check/expected.json new file mode 100644 index 0000000000..7abec7649e --- /dev/null +++ b/fixtures/conformance/validator-db-check/expected.json @@ -0,0 +1,151 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { + "source.rdb": { + "@table": "providers" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "state", + "@dbCheck": false, + "@values": [ + "OPEN", + "SHUT" + ] + } + }, + { + "field.string": { + "name": "npi", + "children": [ + { + "validator.regex": { + "name": "tenDigits", + "@dbCheck": false, + "@pattern": "^\\d{10}$" + } + }, + { + "validator.length": { + "name": "npiLength", + "@constraintName": "providers_npi_fits", + "@dbCheck": true, + "@max": 12 + } + } + ] + } + }, + { + "field.int": { + "name": "rank", + "children": [ + { + "validator.numeric": { + "name": "rankRange", + "@dbCheck": false, + "@max": 99, + "@min": 1 + } + } + ] + } + }, + { + "field.string": { + "name": "kind" + } + }, + { + "field.string": { + "name": "email" + } + }, + { + "field.string": { + "name": "phone" + } + }, + { + "field.timestamp": { + "name": "startsAt" + } + }, + { + "field.timestamp": { + "name": "endsAt" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "validator.comparison": { + "name": "window", + "@dbCheck": true, + "@left": "startsAt", + "@op": "lte", + "@right": "endsAt" + } + }, + { + "validator.requiredWhen": { + "name": "depotEmail", + "@dbCheck": true, + "@equals": "depot", + "@field": "email", + "@when": "kind" + } + }, + { + "validator.presentIff": { + "name": "depotStart", + "@dbCheck": true, + "@equals": "depot", + "@field": "startsAt", + "@when": "kind" + } + }, + { + "validator.atLeastOne": { + "name": "contact", + "@dbCheck": true, + "@fields": [ + "email", + "phone" + ] + } + }, + { + "validator.exactlyOne": { + "name": "oneOf", + "@dbCheck": true, + "@fields": [ + "email", + "phone" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-db-check/input/meta.checks.json b/fixtures/conformance/validator-db-check/input/meta.checks.json new file mode 100644 index 0000000000..1a3ee25e35 --- /dev/null +++ b/fixtures/conformance/validator-db-check/input/meta.checks.json @@ -0,0 +1,33 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { "source.rdb": { "@table": "providers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false } }, + { "validator.length": { "name": "npiLength", "@max": 12, "@dbCheck": true, "@constraintName": "providers_npi_fits" } } + ] } }, + { "field.int": { "name": "rank", "children": [ { "validator.numeric": { "name": "rankRange", "@min": 1, "@max": 99, "@dbCheck": false } } ] } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "field.timestamp": { "name": "startsAt" } }, + { "field.timestamp": { "name": "endsAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } }, + { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": true } }, + { "validator.requiredWhen": { "name": "depotEmail", "@field": "email", "@when": "kind", "@equals": "depot", "@dbCheck": true } }, + { "validator.presentIff": { "name": "depotStart", "@field": "startsAt", "@when": "kind", "@equals": "depot", "@dbCheck": true } }, + { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": true } }, + { "validator.exactlyOne": { "name": "oneOf", "@fields": ["email", "phone"], "@dbCheck": true } } + ] + } + } + ] + } +} diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json index f11226954f..0c7c63df7b 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json @@ -414,11 +414,11 @@ } } }, - "/api/auths/copay": { + "/api/auths/coupon": { "get": { - "operationId": "listCopayAuth", + "operationId": "listCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "parameters": [ { @@ -457,10 +457,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/CopayAuthList" + "$ref": "#/components/schemas/CouponAuthList" }, { - "$ref": "#/components/schemas/CopayAuthPage" + "$ref": "#/components/schemas/CouponAuthPage" } ] } @@ -480,16 +480,16 @@ } }, "post": { - "operationId": "createCopayAuth", + "operationId": "createCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthCreate" + "$ref": "#/components/schemas/CouponAuthCreate" } } } @@ -500,7 +500,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -528,7 +528,7 @@ } } }, - "/api/auths/copay/{id}": { + "/api/auths/coupon/{id}": { "parameters": [ { "name": "id", @@ -541,9 +541,9 @@ } ], "get": { - "operationId": "getCopayAuth", + "operationId": "getCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "200": { @@ -551,7 +551,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -569,16 +569,16 @@ } }, "patch": { - "operationId": "updateCopayAuth", + "operationId": "updateCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -589,7 +589,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -627,16 +627,16 @@ } }, "put": { - "operationId": "putCopayAuth", + "operationId": "putCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -647,7 +647,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -685,9 +685,9 @@ } }, "delete": { - "operationId": "deleteCopayAuth", + "operationId": "deleteCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "204": { @@ -746,14 +746,14 @@ "$ref": "#/components/schemas/BridgeAuth" }, { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } ], "discriminator": { "propertyName": "type", "mapping": { "Bridge": "#/components/schemas/BridgeAuth", - "Copay": "#/components/schemas/CopayAuth" + "Coupon": "#/components/schemas/CouponAuth" } } }, @@ -864,8 +864,8 @@ } } }, - "CopayAuth": { - "title": "CopayAuth", + "CouponAuth": { + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -873,7 +873,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -894,8 +894,8 @@ "auditRef" ] }, - "CopayAuthCreate": { - "title": "CopayAuthCreate", + "CouponAuthCreate": { + "title": "CouponAuthCreate", "type": "object", "properties": { "reference": { @@ -908,15 +908,15 @@ "reference" ] }, - "CopayAuthList": { - "title": "CopayAuthList", + "CouponAuthList": { + "title": "CouponAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, - "CopayAuthPage": { - "title": "CopayAuthPage", + "CouponAuthPage": { + "title": "CouponAuthPage", "type": "object", "required": [ "rows", @@ -926,7 +926,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, "total": { @@ -934,8 +934,8 @@ } } }, - "CopayAuthUpdate": { - "title": "CopayAuthUpdate", + "CouponAuthUpdate": { + "title": "CouponAuthUpdate", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json index 8b67c7624b..a3a91c6820 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json @@ -7,7 +7,7 @@ "$ref": "./BridgeAuth.schema.json" }, { - "$ref": "./CopayAuth.schema.json" + "$ref": "./CouponAuth.schema.json" } ] } diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json similarity index 72% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json index 664615d88d..c59f3bdf54 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.create.schema.json", - "title": "CopayAuth.create", + "$id": "schemas/acme/auth/CouponAuth.create.schema.json", + "title": "CouponAuth.create", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json similarity index 81% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json index c302a0d48b..9891bb8dab 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.schema.json", - "title": "CopayAuth", + "$id": "schemas/acme/auth/CouponAuth.schema.json", + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json similarity index 90% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json index 80c1ee1b79..2bfdc5fa2d 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "CopayAuth", + "title": "CouponAuth", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json similarity index 68% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json index 48d05089b8..6e7dfaee91 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.update.schema.json", - "title": "CopayAuth.update", + "$id": "schemas/acme/auth/CouponAuth.update.schema.json", + "title": "CouponAuth.update", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/meta.json b/fixtures/contract-conformance/tph-shared-marks/meta.json index c3cff88705..a9157a87db 100644 --- a/fixtures/contract-conformance/tph-shared-marks/meta.json +++ b/fixtures/contract-conformance/tph-shared-marks/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] @@ -23,9 +23,9 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ { "field.string": { "name": "token", "@maxLength": 100 } }, { "field.string": { "name": "auditRef", "@maxLength": 100 } } diff --git a/fixtures/contract-conformance/tph/expected/openapi.json b/fixtures/contract-conformance/tph/expected/openapi.json index 439dc9defb..f3f7c876ce 100644 --- a/fixtures/contract-conformance/tph/expected/openapi.json +++ b/fixtures/contract-conformance/tph/expected/openapi.json @@ -92,8 +92,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -104,8 +104,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -116,8 +116,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -813,11 +813,11 @@ } } }, - "/api/auths/copay": { + "/api/auths/coupon": { "get": { - "operationId": "listCopayAuth", + "operationId": "listCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "parameters": [ { @@ -937,7 +937,7 @@ } }, { - "name": "filter[copayAmount]", + "name": "filter[couponAmount]", "in": "query", "description": "Sugar for the eq operator.", "schema": { @@ -946,7 +946,7 @@ } }, { - "name": "filter[copayAmount][eq]", + "name": "filter[couponAmount][eq]", "in": "query", "schema": { "type": "string", @@ -954,7 +954,7 @@ } }, { - "name": "filter[copayAmount][ne]", + "name": "filter[couponAmount][ne]", "in": "query", "schema": { "type": "string", @@ -962,7 +962,7 @@ } }, { - "name": "filter[copayAmount][gt]", + "name": "filter[couponAmount][gt]", "in": "query", "schema": { "type": "string", @@ -970,7 +970,7 @@ } }, { - "name": "filter[copayAmount][gte]", + "name": "filter[couponAmount][gte]", "in": "query", "schema": { "type": "string", @@ -978,7 +978,7 @@ } }, { - "name": "filter[copayAmount][lt]", + "name": "filter[couponAmount][lt]", "in": "query", "schema": { "type": "string", @@ -986,7 +986,7 @@ } }, { - "name": "filter[copayAmount][lte]", + "name": "filter[couponAmount][lte]", "in": "query", "schema": { "type": "string", @@ -994,7 +994,7 @@ } }, { - "name": "filter[copayAmount][in]", + "name": "filter[couponAmount][in]", "in": "query", "schema": { "type": "string", @@ -1002,7 +1002,7 @@ } }, { - "name": "filter[copayAmount][isNull]", + "name": "filter[couponAmount][isNull]", "in": "query", "schema": { "type": "boolean" @@ -1020,9 +1020,9 @@ "reference", "reference:asc", "reference:desc", - "copayAmount", - "copayAmount:asc", - "copayAmount:desc" + "couponAmount", + "couponAmount:asc", + "couponAmount:desc" ] } }, @@ -1062,10 +1062,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/CopayAuthList" + "$ref": "#/components/schemas/CouponAuthList" }, { - "$ref": "#/components/schemas/CopayAuthPage" + "$ref": "#/components/schemas/CouponAuthPage" } ] } @@ -1085,16 +1085,16 @@ } }, "post": { - "operationId": "createCopayAuth", + "operationId": "createCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthCreate" + "$ref": "#/components/schemas/CouponAuthCreate" } } } @@ -1105,7 +1105,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1133,7 +1133,7 @@ } } }, - "/api/auths/copay/{id}": { + "/api/auths/coupon/{id}": { "parameters": [ { "name": "id", @@ -1146,9 +1146,9 @@ } ], "get": { - "operationId": "getCopayAuth", + "operationId": "getCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "200": { @@ -1156,7 +1156,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1174,16 +1174,16 @@ } }, "patch": { - "operationId": "updateCopayAuth", + "operationId": "updateCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -1194,7 +1194,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1232,16 +1232,16 @@ } }, "put": { - "operationId": "putCopayAuth", + "operationId": "putCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -1252,7 +1252,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1290,9 +1290,9 @@ } }, "delete": { - "operationId": "deleteCopayAuth", + "operationId": "deleteCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "204": { @@ -1321,11 +1321,11 @@ } } }, - "/api/auths/priorauth": { + "/api/auths/permit": { "get": { - "operationId": "listPriorAuthAuth", + "operationId": "listPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "parameters": [ { @@ -1542,10 +1542,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/PriorAuthAuthList" + "$ref": "#/components/schemas/PermitAuthList" }, { - "$ref": "#/components/schemas/PriorAuthAuthPage" + "$ref": "#/components/schemas/PermitAuthPage" } ] } @@ -1565,16 +1565,16 @@ } }, "post": { - "operationId": "createPriorAuthAuth", + "operationId": "createPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthCreate" + "$ref": "#/components/schemas/PermitAuthCreate" } } } @@ -1585,7 +1585,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1613,7 +1613,7 @@ } } }, - "/api/auths/priorauth/{id}": { + "/api/auths/permit/{id}": { "parameters": [ { "name": "id", @@ -1626,9 +1626,9 @@ } ], "get": { - "operationId": "getPriorAuthAuth", + "operationId": "getPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "responses": { "200": { @@ -1636,7 +1636,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1654,16 +1654,16 @@ } }, "patch": { - "operationId": "updatePriorAuthAuth", + "operationId": "updatePermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthUpdate" + "$ref": "#/components/schemas/PermitAuthUpdate" } } } @@ -1674,7 +1674,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1712,16 +1712,16 @@ } }, "put": { - "operationId": "putPriorAuthAuth", + "operationId": "putPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthUpdate" + "$ref": "#/components/schemas/PermitAuthUpdate" } } } @@ -1732,7 +1732,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1770,9 +1770,9 @@ } }, "delete": { - "operationId": "deletePriorAuthAuth", + "operationId": "deletePermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "responses": { "204": { @@ -1831,18 +1831,18 @@ "$ref": "#/components/schemas/BridgeAuth" }, { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" }, { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } ], "discriminator": { "propertyName": "type", "mapping": { "Bridge": "#/components/schemas/BridgeAuth", - "Copay": "#/components/schemas/CopayAuth", - "PriorAuth": "#/components/schemas/PriorAuthAuth" + "Coupon": "#/components/schemas/CouponAuth", + "Permit": "#/components/schemas/PermitAuth" } } }, @@ -1987,8 +1987,8 @@ } } }, - "CopayAuth": { - "title": "CopayAuth", + "CouponAuth": { + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -1996,7 +1996,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -2023,7 +2023,7 @@ ], "format": "date-time" }, - "copayAmount": { + "couponAmount": { "type": [ "string", "null" @@ -2038,11 +2038,11 @@ "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "copayAmount" + "couponAmount" ] }, - "CopayAuthCreate": { - "title": "CopayAuthCreate", + "CouponAuthCreate": { + "title": "CouponAuthCreate", "type": "object", "properties": { "reference": { @@ -2054,7 +2054,7 @@ "type": "string", "maxLength": 3 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number" @@ -2067,15 +2067,15 @@ "reference" ] }, - "CopayAuthList": { - "title": "CopayAuthList", + "CouponAuthList": { + "title": "CouponAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, - "CopayAuthPage": { - "title": "CopayAuthPage", + "CouponAuthPage": { + "title": "CouponAuthPage", "type": "object", "required": [ "rows", @@ -2085,7 +2085,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, "total": { @@ -2093,8 +2093,8 @@ } } }, - "CopayAuthUpdate": { - "title": "CopayAuthUpdate", + "CouponAuthUpdate": { + "title": "CouponAuthUpdate", "type": "object", "properties": { "reference": { @@ -2102,7 +2102,7 @@ "minLength": 1, "maxLength": 80 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number", @@ -2113,8 +2113,8 @@ } } }, - "PriorAuthAuth": { - "title": "PriorAuthAuth", + "PermitAuth": { + "title": "PermitAuth", "type": "object", "properties": { "id": { @@ -2122,7 +2122,7 @@ "format": "int64" }, "type": { - "const": "PriorAuth" + "const": "Permit" }, "reference": { "type": "string", @@ -2167,8 +2167,8 @@ "approver" ] }, - "PriorAuthAuthCreate": { - "title": "PriorAuthAuthCreate", + "PermitAuthCreate": { + "title": "PermitAuthCreate", "type": "object", "properties": { "reference": { @@ -2189,15 +2189,15 @@ "reference" ] }, - "PriorAuthAuthList": { - "title": "PriorAuthAuthList", + "PermitAuthList": { + "title": "PermitAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } }, - "PriorAuthAuthPage": { - "title": "PriorAuthAuthPage", + "PermitAuthPage": { + "title": "PermitAuthPage", "type": "object", "required": [ "rows", @@ -2207,7 +2207,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } }, "total": { @@ -2215,8 +2215,8 @@ } } }, - "PriorAuthAuthUpdate": { - "title": "PriorAuthAuthUpdate", + "PermitAuthUpdate": { + "title": "PermitAuthUpdate", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json index 2ee81ea91e..ed89793bee 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json @@ -7,10 +7,10 @@ "$ref": "./BridgeAuth.schema.json" }, { - "$ref": "./CopayAuth.schema.json" + "$ref": "./CouponAuth.schema.json" }, { - "$ref": "./PriorAuthAuth.schema.json" + "$ref": "./PermitAuth.schema.json" } ] } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json similarity index 83% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json index d669f9f28a..29c223ae05 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.create.schema.json", - "title": "CopayAuth.create", + "$id": "schemas/acme/auth/CouponAuth.create.schema.json", + "title": "CouponAuth.create", "type": "object", "properties": { "reference": { @@ -13,7 +13,7 @@ "type": "string", "maxLength": 3 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number" diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json similarity index 85% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json index a71e5f76bb..a4db653cc0 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.schema.json", - "title": "CopayAuth", + "$id": "schemas/acme/auth/CouponAuth.schema.json", + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -36,7 +36,7 @@ ], "format": "date-time" }, - "copayAmount": { + "couponAmount": { "type": [ "string", "null" @@ -51,6 +51,6 @@ "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "copayAmount" + "couponAmount" ] } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json similarity index 90% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json index 8aeeb3445b..45ce869ffd 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "CopayAuth", + "title": "CouponAuth", "type": "object", "properties": { "reference": { @@ -13,7 +13,7 @@ "null" ] }, - "copayAmount": { + "couponAmount": { "description": "A decimal, as a string in JSON-number grammar or a JSON number. Precision 10, scale 2. Pattern: ^-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?$.", "type": [ "string", @@ -24,7 +24,7 @@ "required": [ "reference", "issuedCurrency", - "copayAmount" + "couponAmount" ], "additionalProperties": false } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json similarity index 80% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json index 30d0ed1ddb..c45baa45df 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.update.schema.json", - "title": "CopayAuth.update", + "$id": "schemas/acme/auth/CouponAuth.update.schema.json", + "title": "CouponAuth.update", "type": "object", "properties": { "reference": { @@ -9,7 +9,7 @@ "minLength": 1, "maxLength": 80 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number", diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json similarity index 79% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json index c33766e807..98a7e41b78 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.create.schema.json", - "title": "PriorAuthAuth.create", + "$id": "schemas/acme/auth/PermitAuth.create.schema.json", + "title": "PermitAuth.create", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json similarity index 88% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json index d53d846f5d..f5dbff3c1e 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.schema.json", - "title": "PriorAuthAuth", + "$id": "schemas/acme/auth/PermitAuth.schema.json", + "title": "PermitAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "PriorAuth" + "const": "Permit" }, "reference": { "type": "string", diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json similarity index 94% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json index 96db0afeba..a37f33972c 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "PriorAuthAuth", + "title": "PermitAuth", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json similarity index 75% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json index 81d8db395c..3790b1b9eb 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.update.schema.json", - "title": "PriorAuthAuth.update", + "$id": "schemas/acme/auth/PermitAuth.update.schema.json", + "title": "PermitAuth.update", "type": "object", "properties": { "reference": { diff --git a/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml b/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml index f049a5524a..9e036b2355 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml @@ -19,7 +19,7 @@ cubes: type: count_distinct segments: - name: authsByKindScope - sql: '{CUBE}."type" <> ''PriorAuth''' + sql: '{CUBE}."type" <> ''Permit''' pre_aggregations: - name: AuthsByKind type: rollup diff --git a/fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml b/fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml similarity index 83% rename from fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml rename to fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml index 6ca62bd76e..fecda9a4e6 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml @@ -1,7 +1,7 @@ # @generated by @metaobjectsdev/codegen-ts — cube-model cubes: - - name: CopayAuth - sql: 'SELECT * FROM "auths" WHERE "type" = ''Copay''' + - name: CouponAuth + sql: 'SELECT * FROM "auths" WHERE "type" = ''Coupon''' dimensions: - name: id sql: '{CUBE}."id"' diff --git a/fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml b/fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml similarity index 82% rename from fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml rename to fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml index 057b00c807..f01b88f74d 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml @@ -1,7 +1,7 @@ # @generated by @metaobjectsdev/codegen-ts — cube-model cubes: - - name: PriorAuthAuth - sql: 'SELECT * FROM "auths" WHERE "type" = ''PriorAuth''' + - name: PermitAuth + sql: 'SELECT * FROM "auths" WHERE "type" = ''Permit''' dimensions: - name: id sql: '{CUBE}."id"' diff --git a/fixtures/cube-model/canonical/seed.mysql.sql b/fixtures/cube-model/canonical/seed.mysql.sql index 8bf766218b..56d6c8e852 100644 --- a/fixtures/cube-model/canonical/seed.mysql.sql +++ b/fixtures/cube-model/canonical/seed.mysql.sql @@ -46,8 +46,8 @@ INSERT INTO `nodes` (`id`,`label`,`parentId`) VALUES INSERT INTO `auths` (`id`,`type`,`reference`,`quantity`,`urgency`) VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); diff --git a/fixtures/cube-model/canonical/seed.sql b/fixtures/cube-model/canonical/seed.sql index 12bd66842d..1f60e3b4df 100644 --- a/fixtures/cube-model/canonical/seed.sql +++ b/fixtures/cube-model/canonical/seed.sql @@ -54,8 +54,8 @@ INSERT INTO "nodes" ("id","label","parentId") VALUES INSERT INTO "auths" ("id","type","reference","quantity","urgency") VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); diff --git a/fixtures/cube-model/entity-tph-subtype/meta.json b/fixtures/cube-model/entity-tph-subtype/meta.json index 75982300e4..514dee2877 100644 --- a/fixtures/cube-model/entity-tph-subtype/meta.json +++ b/fixtures/cube-model/entity-tph-subtype/meta.json @@ -22,7 +22,7 @@ "name": "type", "@values": [ "Bridge", - "Copay" + "Coupon" ] } }, @@ -53,9 +53,9 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [] } } diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index fa315e29c4..d2e2048b55 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -134,6 +134,13 @@ "eject": "full", "ports": ["csharp"] }, + "expression-indexes": { + "concept": "The expression (@expr) indexes the ORM model cannot carry, as one SQL file applied after the schema.", + "tier": "native", + "layer": "persistence", + "eject": "full", + "ports": ["csharp"] + }, "repository": { "concept": "Per-entity repository seam (Java: Spring Data interface; Kotlin: an open Exposed persistence base with CRUD + patch bodies).", "tier": "native", diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index f66e1327f1..94ab806838 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -19,7 +19,7 @@ children and the cardinality of that subtype. Documentation attributes | `attr.boolean` | A boolean-valued metadata attribute. Coerces to and validates as true/false. | [types/attr.md#attrboolean](types/attr.md#attrboolean) | | `attr.class` | A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets. | [types/attr.md#attrclass](types/attr.md#attrclass) | | `attr.double` | A double-precision floating-point-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrdouble](types/attr.md#attrdouble) | -| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | +| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | | `attr.filter` | A filter-expression-valued metadata attribute. Object-shaped value that desugars a preset filter to the canonical { field: { op: value } } form (scalar→eq, array→in, null→isNull; or/and recurse). | [types/attr.md#attrfilter](types/attr.md#attrfilter) | | `attr.int` | A 32-bit-integer-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrint](types/attr.md#attrint) | | `attr.intMap` | An object-shaped attribute whose values are all integers (e.g. field.enum's @intValueMap: {memberSymbol: int}). Generic shape check only; a consumer field type layers its own semantic rules (key-set membership, uniqueness) in its own content-rule validation. | [types/attr.md#attrintmap](types/attr.md#attrintmap) | @@ -35,7 +35,7 @@ children and the cardinality of that subtype. Documentation attributes | `field.decimal` | Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double. | [types/field.md#fielddecimal](types/field.md#fielddecimal) | | `field.double` | Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal. | [types/field.md#fielddouble](types/field.md#fielddouble) | | `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length. Justified in ADR-0023 Amendment 1. | [types/field.md#fieldduration](types/field.md#fieldduration) | -| `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. | [types/field.md#fieldenum](types/field.md#fieldenum) | +| `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). | [types/field.md#fieldenum](types/field.md#fieldenum) | | `field.float` | Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money. | [types/field.md#fieldfloat](types/field.md#fieldfloat) | | `field.inet` | An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4\|ipv6 value-constraint. | [types/field.md#fieldinet](types/field.md#fieldinet) | | `field.int` | 32-bit signed integer. Binds to the native int type; DB column is INTEGER. | [types/field.md#fieldint](types/field.md#fieldint) | @@ -66,6 +66,7 @@ children and the cardinality of that subtype. Documentation attributes | `origin.base` | Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/origin.md#originbase](types/origin.md#originbase) | | `origin.computed` | A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType. | [types/origin.md#origincomputed](types/origin.md#origincomputed) | | `origin.first` | The single related row selected by @orderBy along @via, projecting its @of column (argmax then project). Latest = @orderBy desc. Read-only; empty related set (after @filter) → null, so the field must not be @required. | [types/origin.md#originfirst](types/origin.md#originfirst) | +| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | | `origin.passthrough` | A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). | [types/origin.md#originpassthrough](types/origin.md#originpassthrough) | | `relationship.aggregation` | A shared/independent containment — the parent groups the target but does not own its lifecycle (default @onDelete set-null). | [types/relationship.md#relationshipaggregation](types/relationship.md#relationshipaggregation) | | `relationship.association` | A plain reference to another entity — no ownership; the target has an independent lifecycle (default @onDelete restrict). | [types/relationship.md#relationshipassociation](types/relationship.md#relationshipassociation) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 881fe9cce8..a8f406b9a9 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -13,14 +13,14 @@ provider owns. This is the ownership lens over the same vocabulary Core metaobjects metamodel types and subtypes. -**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` +**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.function`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.exactlyOne`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` **Contributes attributes:** - `field.base`: `@default`, `@mutability`, `@required`, `@unique` - `field.currency`: `@currency` - `field.decimal`: `@precision`, `@scale` -- `field.enum`: `@intValueMap`, `@maxLength`, `@provided`, `@values` +- `field.enum`: `@intValueMap`, `@maxLength`, `@provided`, `@stringValueMap`, `@values` - `field.inet`: `@lenient` - `field.map`: `@objectRef`, `@valueType` - `field.object`: `@objectRef` @@ -31,11 +31,12 @@ Core metaobjects metamodel types and subtypes. - `identity.secondary`: `@fields` - `object.base`: `@object`, `@objectAdapter` - `object.entity`: `@collectionName`, `@discriminator`, `@discriminatorValue` -- `object.projection`: `@collectionName`, `@filter` +- `object.projection`: `@collectionName`, `@filter`, `@grain`, `@grainOrdinal`, `@union`, `@unionAll` - `object.report`: `@collectionName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` - `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@segment`, `@via` - `origin.computed`: `@expr` - `origin.first`: `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.function`: `@args`, `@function`, `@params`, `@returns`, `@schema` - `origin.passthrough`: `@convert`, `@from`, `@via` - `relationship.aggregation`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` - `relationship.association`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` @@ -68,7 +69,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.decimal`: `@column`, `@db.indexed`, `@dbColumnType` - `field.double`: `@column`, `@db.indexed`, `@dbColumnType` - `field.duration`: `@column`, `@db.indexed`, `@dbColumnType` -- `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbColumnType` +- `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbCheck`, `@dbColumnType` - `field.float`: `@column`, `@db.indexed`, `@dbColumnType` - `field.inet`: `@column`, `@db.indexed`, `@dbColumnType` - `field.int`: `@column`, `@db.indexed`, `@dbColumnType` @@ -85,14 +86,14 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `identity.secondary`: `@expr`, `@orders`, `@using`, `@where` - `index.lookup`: `@expr`, `@orders`, `@using`, `@where` - `source.rdb`: `@function`, `@kind`, `@materializedView`, `@parameterRef`, `@proc`, `@role`, `@schema`, `@sql`, `@table`, `@unmanaged`, `@view` -- `validator.atLeastOne`: `@constraintName` -- `validator.comparison`: `@constraintName` -- `validator.exactlyOne`: `@constraintName` -- `validator.length`: `@constraintName` -- `validator.numeric`: `@constraintName` -- `validator.presentIff`: `@constraintName` -- `validator.regex`: `@constraintName` -- `validator.requiredWhen`: `@constraintName` +- `validator.atLeastOne`: `@constraintName`, `@dbCheck` +- `validator.comparison`: `@constraintName`, `@dbCheck` +- `validator.exactlyOne`: `@constraintName`, `@dbCheck` +- `validator.length`: `@constraintName`, `@dbCheck` +- `validator.numeric`: `@constraintName`, `@dbCheck` +- `validator.presentIff`: `@constraintName`, `@dbCheck` +- `validator.regex`: `@constraintName`, `@dbCheck` +- `validator.requiredWhen`: `@constraintName`, `@dbCheck` ## metaobjects-documentation diff --git a/fixtures/metamodel-docs/expected/types/attr.md b/fixtures/metamodel-docs/expected/types/attr.md index c59cccb5f1..b07e2267ee 100644 --- a/fixtures/metamodel-docs/expected/types/attr.md +++ b/fixtures/metamodel-docs/expected/types/attr.md @@ -68,7 +68,7 @@ _No structural children._ ### attr.expression -A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. +A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. **Owning provider:** metaobjects-core-types diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 1d03426759..c8074ef011 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -22,7 +22,7 @@ Abstract base field — the shared root subtype that concrete field subtypes spe | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -55,7 +55,7 @@ True/false flag. Binds to the native boolean type; DB column is BOOLEAN. | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -91,7 +91,7 @@ Stores money as integer minor units (cents). Binds to long; the client formats v | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@currency` | string | no | `USD` | | metaobjects-core-types | ISO 4217 currency code for a currency-subtype field. Storage is integer minor units; defaults to 'USD' when omitted. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -125,7 +125,7 @@ Calendar date (no time-of-day). Binds to the native date/temporal type; DB colum | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -160,7 +160,7 @@ Precision-exact decimal (use @precision/@scale). Native TS binding is string (lo | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -195,7 +195,7 @@ Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/nu | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -228,7 +228,7 @@ A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -249,11 +249,11 @@ A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — ### field.enum -String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. +String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). **Owning provider:** metaobjects-core-types -**Rules:** Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize). +**Rules:** Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize). **When to use:** A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks. @@ -265,7 +265,8 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@enumAlias` | properties | no | | | metaobjects-prompt | Map of alternate/off-vocabulary tokens to canonical enum members; feeds the FR-010 tolerant extract alias-fold. | | `@enumDoc` | properties | no | | | metaobjects-prompt | Map of enum member to a human-readable description; shown per-member in the FR-010 'guide'-style prompt fragment. | @@ -281,8 +282,9 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@required` | boolean | no | | | metaobjects-core-types | When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction. | | `@sortable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out. | | `@sortableDefaultOrder` | string | no | | `asc`, `desc` | metaobjects-ui | Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'. | +| `@stringValueMap` | properties | no | | | metaobjects-core-types | Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE). | | `@unique` | boolean | no | | | metaobjects-core-types | When true, the field gets a column-level UNIQUE constraint. | -| `@values` | string[] | yes | | | metaobjects-core-types | Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string. | +| `@values` | string[] | yes | | | metaobjects-core-types | Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it. | | `@xmlText` | boolean | no | | | metaobjects-prompt | When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json. | **Allowed children** @@ -303,7 +305,7 @@ Single-precision floating point. Binds to the native double/number type (TS has | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -336,7 +338,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -370,7 +372,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -403,7 +405,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -438,7 +440,7 @@ An open-keyed map (Record / dict[str,V]) stored in a single jsonb colu | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -475,7 +477,7 @@ A nested structured value (set @objectRef to the target object). Storage is gove | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -511,7 +513,7 @@ Variable-length text. Binds to the native string type; DB column is VARCHAR/TEXT | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -545,7 +547,7 @@ Time-of-day (no calendar date). Binds to the native date/temporal type; DB colum | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -579,7 +581,7 @@ Date + time-of-day instant (optionally with timezone). Binds to the native date/ | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -613,7 +615,7 @@ A URI/URL string (ADR-0036/0037 — a concept with a native type + behavior, so | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -647,7 +649,7 @@ Logical UUID identity scalar. A bare scalar (no required attrs, no loader value- | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | diff --git a/fixtures/metamodel-docs/expected/types/identity.md b/fixtures/metamodel-docs/expected/types/identity.md index 35dbe622dd..f99b4bf34d 100644 --- a/fixtures/metamodel-docs/expected/types/identity.md +++ b/fixtures/metamodel-docs/expected/types/identity.md @@ -43,7 +43,7 @@ A foreign-key reference to another entity (@references target; @enforce toggles | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@constraintName` | string | no | | | metaobjects-db | Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. | +| `@constraintName` | string | no | | | metaobjects-db | Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | | `@enforce` | boolean | no | | | metaobjects-core-types | When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level. | | `@fields` | string[] | yes | | | metaobjects-core-types | The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite. | | `@onDelete` | string | no | | `cascade`, `set-null`, `restrict`, `no-action` | metaobjects-db | Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider. | diff --git a/fixtures/metamodel-docs/expected/types/object.md b/fixtures/metamodel-docs/expected/types/object.md index 78000a784f..d18828a9f6 100644 --- a/fixtures/metamodel-docs/expected/types/object.md +++ b/fixtures/metamodel-docs/expected/types/object.md @@ -81,9 +81,13 @@ A derived read-only representation of entities. Its fields are extends-bound / o | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | -| `@filter` | filter | no | | | metaobjects-core-types | Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field. | +| `@filter` | filter | no | | | metaobjects-core-types | Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19). | +| `@grain` | string | no | | | metaobjects-core-types | rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection. | +| `@grainOrdinal` | string | no | | | metaobjects-core-types | rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array. | | `@object` | string | no | | | metaobjects-core-types | The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet. | | `@objectAdapter` | string | no | | | metaobjects-core-types | JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it. | +| `@union` | string[] | no | | | metaobjects-core-types | rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless. | +| `@unionAll` | boolean | no | | | metaobjects-core-types | rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index f2e4c364fc..04485083ae 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -26,10 +26,10 @@ A value reduced from the related row-set reached along a relationship path (@via | --- | --- | --- | --- | --- | --- | --- | | `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all`, `collect` | metaobjects-core-types | The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray). | | `@distinct` | boolean | no | | | metaobjects-core-types | Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal. | -| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or { field: "" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom. | +| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | no | | | metaobjects-core-types | Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column). | | `@orderBy` | string[] | no | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** @@ -82,16 +82,38 @@ The single related row selected by @orderBy along @via, projecting its @of colum | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or { field: "" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom. | +| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). | | `@of` | string | yes | | | metaobjects-core-types | Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine). | | `@orderBy` | string[] | yes | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax. | -| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | +| `@segment` | string | no | | | metaobjects-core-types | Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | **Allowed children** _No structural children._ +### origin.function + +A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. + +**Owning provider:** metaobjects-core-types + +**When to use:** A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@args` | string[] | no | | | metaobjects-core-types | The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments. | +| `@function` | string | yes | | | metaobjects-core-types | The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase. | +| `@params` | string[] | no | | | metaobjects-core-types | The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN). | +| `@returns` | string | yes | | | metaobjects-core-types | The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc). | +| `@schema` | string | no | | | metaobjects-core-types | The schema the function lives in, a plain identifier. Absent: public. | + +**Allowed children** + +_No structural children._ + ### origin.passthrough A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). diff --git a/fixtures/metamodel-docs/expected/types/validator.md b/fixtures/metamodel-docs/expected/types/validator.md index 5857bd44da..3568a4dfcf 100644 --- a/fixtures/metamodel-docs/expected/types/validator.md +++ b/fixtures/metamodel-docs/expected/types/validator.md @@ -45,6 +45,7 @@ Cardinality of presence: at least one of the named fields (@fields) must be pres | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced like the rule itself: by the database CHECK and, on create, by the generated record model in every port. Justified in ADR-0023 Amendment 1. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the candidate fields; at least one must be present. | **Allowed children** @@ -84,6 +85,7 @@ Cross-field ordering: requires two sibling fields of the owning entity stand in | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced like the rule itself: by the database CHECK and, on create, by the generated record model in every port. Justified in ADR-0023 Amendment 1. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@left` | string | yes | | | metaobjects-core-types | Name of the left-hand field of the owning entity. | | `@op` | string | yes | | `gt`, `gte`, `lt`, `lte`, `ne`, `eq` | metaobjects-core-types | Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=). | | `@right` | string | yes | | | metaobjects-core-types | Name of the right-hand field of the owning entity. | @@ -108,6 +110,7 @@ Cardinality of presence: exactly one of the named fields (@fields) is present (N | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced like the rule itself: by the database CHECK and, on create, by the generated record model in every port. Justified in ADR-0023 Amendment 1. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the alternative fields; exactly one must be present. | **Allowed children** @@ -127,6 +130,7 @@ Bounds string length / collection size via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -147,6 +151,7 @@ Bounds a numeric value's magnitude via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -170,6 +175,7 @@ Biconditional presence: the target field (@field) is present (NOT NULL) if and o | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced like the rule itself: by the database CHECK and, on create, by the generated record model in every port. Justified in ADR-0023 Amendment 1. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; @field is present exactly when @when equals this. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field whose presence is governed by the condition. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field. | @@ -191,6 +197,7 @@ Requires the value match a regular expression (@pattern). | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@pattern` | string | no | | | metaobjects-core-types | Regular expression the value must match. | @@ -231,6 +238,7 @@ One-directional conditional presence: when the gating field (@when) equals @equa | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced like the rule itself: by the database CHECK and, on create, by the generated record model in every port. Justified in ADR-0023 Amendment 1. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; when @when equals this, @field must be present. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field that becomes required when the condition holds. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field whose value triggers the requirement. | diff --git a/fixtures/naming-conformance/collection-segments.json b/fixtures/naming-conformance/collection-segments.json index f67d44cec7..e68da85e3c 100644 --- a/fixtures/naming-conformance/collection-segments.json +++ b/fixtures/naming-conformance/collection-segments.json @@ -12,7 +12,7 @@ { "name": "SSN", "segment": "ssns" }, { "name": "PA", "segment": "pas" }, { "name": "URLHost", "segment": "url_hosts" }, - { "name": "CaseHistory", "collectionName": "CaseHistory", "segment": "case_history" }, + { "name": "ConsignmentHistory", "collectionName": "ConsignmentHistory", "segment": "consignment_history" }, { "name": "Faq", "collectionName": "FAQs", "segment": "faqs" }, { "name": "TaxId", "collectionName": "TaxIDs", "segment": "tax_ids" }, { "name": "Box", "collectionName": "PDFBoxes", "segment": "pdf_boxes" }, diff --git a/fixtures/persistence-conformance/README.md b/fixtures/persistence-conformance/README.md index 724734bac9..6413db7da1 100644 --- a/fixtures/persistence-conformance/README.md +++ b/fixtures/persistence-conformance/README.md @@ -289,7 +289,7 @@ PK → update every subtype → read back → delete → get-returns-null). #### TPH (table-per-hierarchy) scenarios The `tph-*.yaml` scenarios exercise single-table inheritance through the runtime -(`Auth` base + `BridgeAuth` / `CopayAuth` / `PriorAuthAuth` subtypes over the one +(`Auth` base + `BridgeAuth` / `CouponAuth` / `PermitAuth` subtypes over the one `auths` table). They require the port's **runtime TPH support** (resolving a subtype's inherited fields/identity/table via `extends`, plus discriminator inject/scope/strip). **All five ports run the `tph-*` scenarios green** — TypeScript diff --git a/fixtures/persistence-conformance/canonical/meta.fitness.json b/fixtures/persistence-conformance/canonical/meta.fitness.json index 4dc7e65449..bed34278e7 100644 --- a/fixtures/persistence-conformance/canonical/meta.fitness.json +++ b/fixtures/persistence-conformance/canonical/meta.fitness.json @@ -256,7 +256,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth", "Referral"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit", "Referral"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { "dimension.attribute": { "name": "kind", "@of": "Auth.type" } }, @@ -273,17 +273,17 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80 } } ] @@ -468,7 +468,7 @@ "@dimensions": ["parentLabel"], "@measures": ["nodes"], "children": [ { "source.rdb": { "@kind": "view", "@view": "v_nodes_by_parent" } } ] } }, { "object.report": { "name": "AuthsByKind", "@from": "Auth", - "@dimensions": ["kind"], "@measures": ["auths", "distinctRefs"], "@filter": { "type": { "ne": "PriorAuth" } }, + "@dimensions": ["kind"], "@measures": ["auths", "distinctRefs"], "@filter": { "type": { "ne": "Permit" } }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_auths_by_kind" } } ] } }, { "object.entity": { diff --git a/fixtures/persistence-conformance/canonical/schema.mysql.sql b/fixtures/persistence-conformance/canonical/schema.mysql.sql index b0126bc272..bbcc0626e7 100644 --- a/fixtures/persistence-conformance/canonical/schema.mysql.sql +++ b/fixtures/persistence-conformance/canonical/schema.mysql.sql @@ -59,7 +59,7 @@ CREATE TABLE `auths` ( `type` VARCHAR(16), `reference` VARCHAR(80) NOT NULL, `quantity` INT, - `copayAmount` DECIMAL(10,2), + `couponAmount` DECIMAL(10,2), `approver` VARCHAR(80), `urgency` VARCHAR(16) ); @@ -346,7 +346,7 @@ CREATE VIEW `v_auths_by_kind` AS COUNT(a.`id`) AS `auths`, COUNT(DISTINCT a.`reference`) AS `distinctRefs` FROM `auths` a - WHERE a.`type` <> 'PriorAuth' + WHERE a.`type` <> 'Permit' GROUP BY a.`type`; CREATE VIEW `v_gadget_events_by_label` AS diff --git a/fixtures/persistence-conformance/canonical/schema.postgres.sql b/fixtures/persistence-conformance/canonical/schema.postgres.sql index 592c569126..c1a11b496e 100644 --- a/fixtures/persistence-conformance/canonical/schema.postgres.sql +++ b/fixtures/persistence-conformance/canonical/schema.postgres.sql @@ -101,11 +101,11 @@ CREATE TABLE "auths" ( "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), "urgency" VARCHAR(16), CONSTRAINT "auths_pkey" PRIMARY KEY ("id"), - CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Copay', 'PriorAuth', 'Referral')) + CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Coupon', 'Permit', 'Referral')) ); CREATE TABLE "post_referrals" ( @@ -486,9 +486,9 @@ CREATE VIEW "v_auths_by_kind" AS COUNT(a."id") AS "auths", COUNT(DISTINCT a."reference") AS "distinctRefs" FROM "auths" a - WHERE a."type" <> 'PriorAuth' + WHERE a."type" <> 'Permit' GROUP BY a."type"; -COMMENT ON VIEW "v_auths_by_kind" IS 'metaobjects:v1:sha256:600fcf3a54c8a8f51b2771850689073c7715193fe2528cd7af77bc2e97d22168'; +COMMENT ON VIEW "v_auths_by_kind" IS 'metaobjects:v1:sha256:175edfe5c4031c982d88596cab7a7168c7ae55c037cd6aff22279a52cebb49a1'; CREATE VIEW "v_gadget_events_by_label" AS SELECT diff --git a/fixtures/persistence-conformance/canonical/schema.sqlite.sql b/fixtures/persistence-conformance/canonical/schema.sqlite.sql index 8bf2efa396..8ca59f459c 100644 --- a/fixtures/persistence-conformance/canonical/schema.sqlite.sql +++ b/fixtures/persistence-conformance/canonical/schema.sqlite.sql @@ -99,10 +99,10 @@ CREATE TABLE "auths" ( "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), "urgency" VARCHAR(16), - CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Copay', 'PriorAuth', 'Referral')) + CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Coupon', 'Permit', 'Referral')) ); CREATE TABLE "post_referrals" ( @@ -426,7 +426,7 @@ CREATE VIEW "v_auths_by_kind" AS COUNT(a."id") AS "auths", COUNT(DISTINCT a."reference") AS "distinctRefs" FROM "auths" a - WHERE a."type" <> 'PriorAuth' + WHERE a."type" <> 'Permit' GROUP BY a."type"; CREATE VIEW "v_gadget_events_by_label" AS diff --git a/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml b/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml index 7085fd46c0..13008d9ca8 100644 --- a/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml +++ b/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml @@ -1,18 +1,18 @@ name: report-tph-base-filter description: | AuthsByKind is declared from the TPH base (Auth), the supported way to report on a - subset of subtypes: an @filter on the discriminator (`type <> 'PriorAuth'`). A row whose + subset of subtypes: an @filter on the discriminator (`type <> 'Permit'`). A row whose type is null is dropped by the comparison, as in any SQL. - 1 Bridge A-1 2 Bridge A-1 3 Copay C-1 - 4 PriorAuth P-1 5 Referral R-1 6 Referral R-2 7 (no type) N-1 - Bridge: 2 rows, 1 distinct reference. Copay: 1, 1. Referral: 2, 2. + 1 Bridge A-1 2 Bridge A-1 3 Coupon C-1 + 4 Permit P-1 5 Referral R-1 6 Referral R-2 7 (no type) N-1 + Bridge: 2 rows, 1 distinct reference. Coupon: 1, 1. Referral: 2, 2. seed-data: | INSERT INTO "auths" ("id","type","reference","quantity","urgency") VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); @@ -23,7 +23,7 @@ queries: sort: [{ field: kind, dir: asc }] expect: - { kind: "Bridge", auths: "2", distinctRefs: "1" } - - { kind: "Copay", auths: "1", distinctRefs: "1" } + - { kind: "Coupon", auths: "1", distinctRefs: "1" } - { kind: "Referral", auths: "2", distinctRefs: "2" } - name: filter-on-the-discriminator-dimension op: list diff --git a/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml b/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml index 235ccb53ce..cd34bfd639 100644 --- a/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml +++ b/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml @@ -1,6 +1,6 @@ name: tph-insert-then-find-by-id description: | - FR-017 TPH: insert a BridgeAuth and a CopayAuth into the single `auths` table + FR-017 TPH: insert a BridgeAuth and a CouponAuth into the single `auths` table via the runtime, then find by id. A subtype create injects its discriminator value (the caller omits `type`); a subtype find-by-id is SCOPED to that subtype, so a different-subtype row is invisible (null) — the runtime's @@ -16,11 +16,11 @@ queries: data: { reference: "REF-1", quantity: 5 } expect: { id: "1", type: "Bridge", reference: "REF-1", quantity: 5 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "REF-2", copayAmount: "12.50" } - expect: { id: "2", type: "Copay", reference: "REF-2", copayAmount: "12.5" } + entity: CouponAuth + data: { reference: "REF-2", couponAmount: "12.50" } + expect: { id: "2", type: "Coupon", reference: "REF-2", couponAmount: "12.5" } - name: find-bridge-by-id op: get diff --git a/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml b/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml index c4162328be..9c9e4d9690 100644 --- a/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml +++ b/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml @@ -14,17 +14,17 @@ queries: data: { reference: "B", quantity: 1 } expect: { id: "1", type: "Bridge", reference: "B", quantity: 1 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "C", copayAmount: "9.99" } - expect: { id: "2", type: "Copay", reference: "C", copayAmount: "9.99" } + entity: CouponAuth + data: { reference: "C", couponAmount: "9.99" } + expect: { id: "2", type: "Coupon", reference: "C", couponAmount: "9.99" } - - name: insert-priorauth + - name: insert-permit op: create - entity: PriorAuthAuth + entity: PermitAuth data: { reference: "P", approver: "Dr. X" } - expect: { id: "3", type: "PriorAuth", reference: "P", approver: "Dr. X" } + expect: { id: "3", type: "Permit", reference: "P", approver: "Dr. X" } - name: list-all-auths-polymorphic op: list @@ -32,5 +32,5 @@ queries: sort: [{ field: id, dir: asc }] expect: - { id: "1", type: "Bridge", reference: "B" } - - { id: "2", type: "Copay", reference: "C" } - - { id: "3", type: "PriorAuth", reference: "P" } + - { id: "2", type: "Coupon", reference: "C" } + - { id: "3", type: "Permit", reference: "P" } diff --git a/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml b/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml index da35b80487..608d3903f0 100644 --- a/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml +++ b/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml @@ -2,9 +2,9 @@ name: tph-no-cross-subtype-update description: | FR-017 TPH: a subtype's update surface is its OWN columns only, scoped to its own rows. Two cross-subtype writes must FAIL through the runtime: - (a) patching a BridgeAuth with a Copay-only column (copayAmount) — that + (a) patching a BridgeAuth with a Coupon-only column (couponAmount) — that column is not a field of BridgeAuth, so the write is rejected; - (b) patching id 2 (a Copay) through BridgeAuth — the row is invisible to the + (b) patching id 2 (a Coupon) through BridgeAuth — the row is invisible to the subtype scope, so it's not found. After both rejected writes the Bridge row is unchanged. @@ -16,17 +16,17 @@ queries: data: { reference: "REF-1", quantity: 5 } expect: { id: "1", type: "Bridge", reference: "REF-1", quantity: 5 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "REF-2", copayAmount: "1.00" } - expect: { id: "2", type: "Copay", reference: "REF-2", copayAmount: "1" } + entity: CouponAuth + data: { reference: "REF-2", couponAmount: "1.00" } + expect: { id: "2", type: "Coupon", reference: "REF-2", couponAmount: "1" } - name: cross-subtype-column-rejected op: update entity: BridgeAuth by: { id: 1 } - data: { copayAmount: "9.99" } + data: { couponAmount: "9.99" } expect-error: true - name: cross-subtype-id-not-found diff --git a/fixtures/registry-conformance/README.md b/fixtures/registry-conformance/README.md index e3bcb5ba6e..075b5c0af9 100644 --- a/fixtures/registry-conformance/README.md +++ b/fixtures/registry-conformance/README.md @@ -226,7 +226,7 @@ them as such with a declared reason. - Native type bindings (Node factory / `NodeConstructor` / Java `Class`, the Java `DataTypes` value-class, EF/CLR types, the coarse `DataType` classification) are not attrs and never reach the manifest. The `NATIVE_BINDING` attr category that used to - carve `@object` / `@objectAdapter` out is retired: both are in the + carve `@object` / `@objectAdapter` out is retired by ruling R40: both are in the contract now (see "Not carved out" below). Java's own registration and behaviour are unchanged. - **`STRUCTURAL_KEYWORD`** (`isArray`, `isAbstract`, `extends`, `implements`, @@ -244,7 +244,7 @@ them as such with a declared reason. only the concrete tree root (`metadata.root`). It is the not-universally-tracked `inheritsFrom` anchor this manifest already defers, so the `(metadata, base)` row is carved out. See SP-G analysis C-5. -### Not carved out: vocabulary only some ports act on +### Not carved out: vocabulary only some ports act on (ruling R40) Vocabulary that only some ports act on is still cross-port vocabulary. It is IN the manifest, marked rather than removed, and every port registers it and loads it @@ -257,8 +257,7 @@ still fails everywhere. generic `view.*` controls (`checkbox`, `date`, `dropdown`, `hidden`, `hotlink`, `image`, `month`, `number`, `password`, `radio`, `text`, `textarea`, `web`) and their attrs (`view.textarea @rows`, `view.image @accept/@aspectRatio/@maxBytes/@maxEdge/@store`) are - `["typescript"]`; `object.* @object` (ADR-0001) is `["java"]`; `object.* @collectionName` is - `["csharp"]`. They used to be carved out + `["typescript"]`; `object.* @object` (ADR-0001) is `["java"]`. They used to be carved out as `PRESENTATION_ONLY` / `NATIVE_BINDING`; both reasons are retired. The parity gaps are listed in `docs/CONFORMANCE.md`, "Split coverage". - **Kind 2 — language-specific by nature.** The attr carries `"ports": [...]`: diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index b1f7ab8ea0..1b4addf961 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -32,7 +32,7 @@ { "type": "attr", "subType": "expression", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.", + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.", "attrs": [], "children": [] }, @@ -163,11 +163,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -305,11 +301,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -455,11 +447,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -608,11 +596,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -751,11 +735,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -907,11 +887,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1049,11 +1025,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1169,8 +1141,8 @@ { "type": "field", "subType": "enum", - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "attrs": [ { @@ -1201,16 +1173,19 @@ "required": false, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "dbColumnType", "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1331,6 +1306,13 @@ ], "description": "Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'." }, + { + "name": "stringValueMap", + "valueType": "properties", + "isArray": false, + "required": false, + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." + }, { "name": "unique", "valueType": "boolean", @@ -1343,7 +1325,7 @@ "valueType": "string", "isArray": true, "required": true, - "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." + "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "name": "xmlText", @@ -1401,11 +1383,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1543,11 +1521,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1692,11 +1666,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1834,11 +1804,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1977,11 +1943,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2134,11 +2096,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2302,11 +2260,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2472,11 +2426,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2625,11 +2575,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2774,11 +2720,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2923,11 +2865,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -3093,7 +3031,7 @@ "valueType": "string", "isArray": false, "required": false, - "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider." + "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, { "name": "enforce", @@ -3662,7 +3600,21 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." + "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." + }, + { + "name": "grain", + "valueType": "string", + "isArray": false, + "required": false, + "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." + }, + { + "name": "grainOrdinal", + "valueType": "string", + "isArray": false, + "required": false, + "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "name": "object", @@ -3684,6 +3636,20 @@ "kotlin" ], "description": "JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it." + }, + { + "name": "union", + "valueType": "string", + "isArray": true, + "required": false, + "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." + }, + { + "name": "unionAll", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." } ], "children": [ @@ -3982,7 +3948,7 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." + "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, { "name": "of", @@ -4003,7 +3969,7 @@ "valueType": "string", "isArray": false, "required": false, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "name": "via", @@ -4050,7 +4016,7 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." + "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, { "name": "of", @@ -4071,7 +4037,7 @@ "valueType": "string", "isArray": false, "required": false, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "name": "via", @@ -4083,6 +4049,50 @@ ], "children": [] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "attrs": [ + { + "name": "args", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." + }, + { + "name": "function", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." + }, + { + "name": "params", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." + }, + { + "name": "returns", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." + }, + { + "name": "schema", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The schema the function lives in, a plain identifier. Absent: public." + } + ], + "children": [] + }, { "type": "origin", "subType": "passthrough", @@ -4998,6 +5008,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "fields", "valueType": "string", @@ -5051,6 +5068,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "left", "valueType": "string", @@ -5104,6 +5128,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "fields", "valueType": "string", @@ -5127,6 +5158,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5157,6 +5195,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5195,6 +5240,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", @@ -5232,6 +5284,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5285,6 +5344,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index 64d2858d5c..571f6fbb0e 100644 --- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs +++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (119 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into C#'s own suite and write the assertion the @@ -148,6 +148,10 @@ public void declare_derivation_originComputed() { /* metaobjects.declare.derivat [Fact(Skip = "unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.")] public void declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.")] + public void declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. [Fact(Skip = "unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.")] public void declare_derivation_originPassthrough() { /* metaobjects.declare.derivation.originPassthrough */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index bdcd3edcf6..c30bdd237f 100644 --- a/fixtures/requirement-harness/java/RequirementHarnessTest.java +++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (119 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Java's own suite and write the assertion the @@ -182,6 +182,11 @@ void declare_derivation_originComputed() { /* metaobjects.declare.derivation.ori @Disabled("unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.") void declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") + void declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @Test @Disabled("unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index 797f485c56..3df6053bf9 100644 --- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt +++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (119 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Kotlin's own suite and write the assertion the @@ -182,6 +182,11 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.") fun declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") + fun declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @Test @Disabled("unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index 69a1ede453..27077e27e3 100644 --- a/fixtures/requirement-harness/python/test_requirement_harness.py +++ b/fixtures/requirement-harness/python/test_requirement_harness.py @@ -1,6 +1,6 @@ # @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. # -# One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them). +# One slot per authored promise in metaobjects/meta.requirements.yaml (119 of them). # Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a # claim that nothing is verified — the conformance corpora already check many of # these. To FILL one, move it into Python's own suite and write the assertion the @@ -177,6 +177,11 @@ def test_declare_derivation_originComputed(): def test_declare_derivation_originFirst(): """metaobjects.declare.derivation.originFirst""" +# Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") +def test_declare_derivation_originFunction(): + """metaobjects.declare.derivation.originFunction""" + # Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") def test_declare_derivation_originPassthrough(): diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index 8720e5c83a..0c74868202 100644 --- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts +++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (119 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into TypeScript's own suite and write the assertion the @@ -177,6 +177,11 @@ test.skip("metaobjects.declare.derivation.originFirst", () => { // unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return. }); +// Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. +test.skip("metaobjects.declare.derivation.originFunction", () => { + // unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated. +}); + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. test.skip("metaobjects.declare.derivation.originPassthrough", () => { // unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so. diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index 93fe3b2627..ce93f87205 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1160,6 +1160,20 @@ metadata.root: counterexample: >- A latest value that is whichever row the database happened to return. + - requirement.functional: + name: originFunction + title: Owned database function + level: 4 + status: live + statement: >- + A value computed by a database function the + project owns is declared by the function's name, + schema and argument fields, so every call is + checked against the model, never written as SQL. + counterexample: >- + A view body that calls the function by hand and + keeps working after the argument column is renamed + only until the view is next recreated. - requirement.functional: name: reporting diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts index 838533a25e..3e2c7d1e03 100644 --- a/scripts/check-requirements-ledger.ts +++ b/scripts/check-requirements-ledger.ts @@ -48,7 +48,7 @@ const EXPECTED_WARNING = "WARN_REQUIREMENT_NOTHING_IMPLEMENTS"; * the neighbour — became `Number("metaobjects")`, i.e. NaN. Every comparison against * NaN is unequal, so the gate failed reporting "expected NaN" and a remedy paragraph * about updating the pin. */ -const DEFAULT_EXPECTED_WARNING_COUNT = 150; +const DEFAULT_EXPECTED_WARNING_COUNT = 151; function expectedWarnings(argv: readonly string[]): number { const flag = argv.find((a) => a.startsWith("--expect-warnings=")); diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index ded0dc449a..5fa6113bf3 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -766,11 +766,12 @@ gate_ts_unit() { done } gate_conf_csharp() { + # The minimal console logger prints a failing test's message; plain `--verbosity quiet` names the test and nothing else. ( cd server/csharp \ - && dotnet test MetaObjects.Conformance.Tests/MetaObjects.Conformance.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Render.Tests/MetaObjects.Render.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj --nologo --verbosity quiet ) + && dotnet test MetaObjects.Conformance.Tests/MetaObjects.Conformance.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Render.Tests/MetaObjects.Render.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" ) } # NOTE: these -Dtest= lists are a CHERRY-PICK, so a new test class that is not named here # runs in NO per-push lane and reports green. Adding a test to this module means adding its diff --git a/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs b/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs index da09117bac..d4e5af51f8 100644 --- a/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs @@ -60,7 +60,7 @@ public void A_config_namespace_is_used_by_gen_and_a_bare_verify_is_clean() Assert.True(gen.Exit == 0, gen.Output); Assert.Contains("namespace Acme.Blog;", EntityFile()); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -73,7 +73,7 @@ public void With_no_namespace_it_is_derived_from_the_metadata_package_and_a_bare Assert.True(gen.Exit == 0, gen.Output); Assert.Contains("namespace Acme.Shop;", EntityFile()); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -86,7 +86,7 @@ public void With_no_namespace_a_project_with_nothing_to_emit_generates_cleanly() var gen = Run("gen"); Assert.True(gen.Exit == 0, gen.Output); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -97,7 +97,7 @@ public void The_flag_wins_over_config_and_output_under_another_namespace_is_drif Assert.Equal(0, Run("gen", "--namespace", "Other.Ns").Exit); Assert.Contains("namespace Other.Ns;", EntityFile()); - Assert.Equal(1, Run("verify", "--codegen").Exit); + Assert.Equal(1, Run("verify", "--codegen", "--full").Exit); } [Theory] diff --git a/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs b/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs index 9328411512..ce4f67a205 100644 --- a/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs @@ -143,7 +143,7 @@ public void The_removed_flag_is_refused_on_verify_codegen() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); var (exit, stdout, stderr) = OwnedRunner.Run( - _tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--column-naming", "literal", "--namespace", "Acme.Generated"); + _tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--column-naming", "literal", "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(2, exit); Assert.Contains("--column-naming was removed in 1.1.0", output); @@ -162,7 +162,7 @@ public void Verify_with_the_wrong_naming_says_the_naming_differs_instead_of_rege Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); WriteConfig("\"columns\": \"literal\""); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -188,7 +188,7 @@ public void Verify_with_another_table_rule_says_the_naming_differs_instead_of_re Assert.Contains("\"OrderItems\"", File.ReadAllText(Path.Combine(outDir, "OrderItemNames.g.cs"))); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -212,7 +212,7 @@ public void Verify_finds_another_table_rule_when_only_the_entity_generator_runs( Assert.Contains("[Table(\"OrderItems\")]", File.ReadAllText(Path.Combine(outDir, "OrderItem.g.cs"))); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -231,7 +231,7 @@ public void Verify_finds_a_column_and_table_rule_that_differ_together() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -248,7 +248,7 @@ public void Real_drift_still_says_regenerate() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); File.AppendAllText(Path.Combine(outDir, "SubscriberNames.g.cs"), "// edited\n"); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains("Run 'dotnet meta gen' to regenerate", output); diff --git a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs index dae8de4d09..e3bd3effde 100644 --- a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs @@ -68,7 +68,7 @@ public void Verify_codegen_regenerates_what_gen_wrote_with_a_dependency() Assert.False(Directory.EnumerateFiles(Path.Combine(_root, "generated"), "*Customer*", SearchOption.AllDirectories).Any(), "an imported entity must not be generated"); - var verify = OwnedRunner.Run(_root, ["entity"], "verify", "--codegen", "--out", "generated", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_root, ["entity"], "verify", "--codegen", "--full", "--out", "generated", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, verify.Stdout + verify.Stderr); } diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs index 74c86d9121..b8e9e8bc82 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs @@ -192,7 +192,7 @@ public void Edited_ejected_copy_changes_gen_output_and_verify_codegen_passes() // 5. `dotnet run --project codegen -- verify --codegen ...` — the committed output // (produced by the SAME edited copy) must read as in sync with a fresh regen. var (verifyExit, verifyOutput) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", "entity,names"); Assert.True(verifyExit == 0, $"verify --codegen failed (exit {verifyExit}):\n{verifyOutput}"); Assert.Contains("OK", verifyOutput); @@ -326,7 +326,7 @@ public void Ejected_routes_run_on_the_owned_helper_runtime_with_no_MetaObjects_r // verify --codegen: the owned runtime lives outside --out and is never drift. var (verifyExit, verifyOutput) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); Assert.True(verifyExit == 0, $"verify --codegen failed (exit {verifyExit}):\n{verifyOutput}"); // The adopter's fix, made in their own copy. @@ -337,7 +337,7 @@ public void Ejected_routes_run_on_the_owned_helper_runtime_with_no_MetaObjects_r // The same verify stays clean after the edit: the runtime copy is owned code. var (verify2Exit, verify2Output) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); Assert.True(verify2Exit == 0, $"verify --codegen after a runtime edit failed (exit {verify2Exit}):\n{verify2Output}"); // A real web app: generated output + the owned runtime, EF Core + SQLite, and no diff --git a/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs new file mode 100644 index 0000000000..ef54d4d3aa --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs @@ -0,0 +1,53 @@ +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields +/// read a TPH subtype's columns returns every base row. The loader records that on its warning +/// channel, which `dotnet meta gen` does not print; gen now says it, and keeps its exit code. +/// +[Collection(OwnedRunnerCollection.Name)] +public sealed class GenExtenderScopeWarningTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-gen-extender-scope-" + Guid.NewGuid().ToString("N")); + private string MetaDir => Path.Combine(_tmp, "metaobjects"); + private string OutDir => Path.Combine(_tmp, "out"); + + private static string Model(string filter) => $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Truck", "extends": "Vehicle", "@discriminatorValue": "TRUCK", "children": [ { "field.string": { "name": "payloadClass" } } ] } }, + { "object.projection": { "name": "VehicleBase", "abstract": true, "children": [ + { "field.long": { "name": "vehicleId", "extends": "Vehicle.id" } }, { "identity.primary": { "name": "id", "extends": "Vehicle.primary" } } ] } }, + { "object.projection": { "name": "TruckRow", "extends": "VehicleBase", {{filter}} "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { "name": "payload", "extends": "Truck.payloadClass" } } ] } } ] } } + """; + + public GenExtenderScopeWarningTests() => Directory.CreateDirectory(MetaDir); + + public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } + + [Fact] + public void Gen_prints_the_widened_extender_warning_and_keeps_its_exit_code() + { + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Model("")); + var run = OwnedRunner.Run(_tmp, ["entity"], "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.Equal(0, run.ExitCode); + Assert.Contains("object.projection TruckRow", run.Stderr); + Assert.Contains("\"payload\" (Truck.payloadClass)", run.Stderr); + Assert.Contains("@filter { kind: }", run.Stderr); + } + + [Fact] + public void A_discriminator_filter_scopes_it_and_gen_says_nothing() + { + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Model("\"@filter\": { \"kind\": \"TRUCK\" },")); + var run = OwnedRunner.Run(_tmp, ["entity"], "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.Equal(0, run.ExitCode); + Assert.DoesNotContain("object.projection TruckRow", run.Stderr); + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index af5dbf87b3..3f8949d822 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(15, lines.Count); + Assert.Equal(16, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -61,6 +61,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() "report-export", // ADR-0025 — the api reference, an ordinary entry since ADR-0034 Amendment 9. "api-docs", + // The @expr indexes the EF model cannot carry, as SQL. + "expression-indexes", }) { Assert.Contains(lines, l => l.Contains($" {name} —")); diff --git a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs index e9cfadf747..ff667317f2 100644 --- a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs @@ -135,7 +135,7 @@ public void A_selection_writes_its_entries_as_the_whole_list_does() Assert.True(narrowed.ExitCode == 0, $"exit={narrowed.ExitCode}\nstdout={narrowed.Stdout}\nstderr={narrowed.Stderr}"); Assert.Equal(whole, File.ReadAllText(entity)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -229,7 +229,7 @@ public void Gen_in_a_project_with_no_generator_list_prints_the_amendment_line() [Fact] public void Verify_codegen_in_a_project_with_no_generator_list_prints_the_amendment_line() { - var (exit, _, stderr) = CliProcess.Run(_tmp, "verify", MetaDir, "--codegen", "--out", OutDir); + var (exit, _, stderr) = CliProcess.Run(_tmp, "verify", MetaDir, "--codegen", "--full", "--out", OutDir); Assert.Equal(2, exit); Assert.Contains(CodegenCli.NoGeneratorList("dotnet meta verify --codegen"), stderr); @@ -362,11 +362,11 @@ public void A_requirement_tests_entry_with_its_own_directory_is_written_and_chec Assert.Equal(["Subscriber.g.cs"], FilesUnder(OutDir)); Assert.Equal(["Requirements_acme_Tests.g.cs", "Requirements_acme_Witnesses.g.cs"], FilesUnder(testsDir)); - var clean = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var clean = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(clean.ExitCode == 0, $"exit={clean.ExitCode}\nstdout={clean.Stdout}\nstderr={clean.Stderr}"); File.AppendAllText(Path.Combine(testsDir, "Requirements_acme_Tests.g.cs"), "// edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("Requirements_acme_Tests.g.cs", drift.Stderr); } @@ -385,11 +385,11 @@ public void A_configured_out_dir_is_where_gen_writes_and_verify_checks_and_out_o Assert.True(gen.ExitCode == 0, $"exit={gen.ExitCode}\nstdout={gen.Stdout}\nstderr={gen.Stderr}"); Assert.Equal(["Subscriber.g.cs"], FilesUnder(OutDir)); - var clean = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--namespace", "Acme.Generated"); + var clean = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--namespace", "Acme.Generated"); Assert.True(clean.ExitCode == 0, $"exit={clean.ExitCode}\nstdout={clean.Stdout}\nstderr={clean.Stderr}"); File.AppendAllText(Path.Combine(OutDir, "Subscriber.g.cs"), "// edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("Subscriber.g.cs", drift.Stderr); @@ -398,7 +398,7 @@ public void A_configured_out_dir_is_where_gen_writes_and_verify_checks_and_out_o var genOther = OwnedRunner.Run(_tmp, declared, "gen", "--out", other, "--namespace", "Acme.Generated"); Assert.True(genOther.ExitCode == 0, $"exit={genOther.ExitCode}\n{genOther.Stdout}{genOther.Stderr}"); Assert.Equal(["Subscriber.g.cs"], FilesUnder(other)); - var cleanOther = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--out", other, "--namespace", "Acme.Generated"); + var cleanOther = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--out", other, "--namespace", "Acme.Generated"); Assert.True(cleanOther.ExitCode == 0, $"exit={cleanOther.ExitCode}\n{cleanOther.Stdout}{cleanOther.Stderr}"); } @@ -419,15 +419,15 @@ public void Verify_narrowed_to_an_entry_with_its_own_directory_does_not_convict_ IReadOnlyList declared = [new EntityGenerator(), new ApiDocsGenerator { OutDir = DocsDir }]; Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var docsOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); + var docsOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); Assert.True(docsOnly.ExitCode == 0, $"exit={docsOnly.ExitCode}\nstdout={docsOnly.Stdout}\nstderr={docsOnly.Stderr}"); - var codeOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); + var codeOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); Assert.True(codeOnly.ExitCode == 0, $"exit={codeOnly.ExitCode}\nstdout={codeOnly.Stdout}\nstderr={codeOnly.Stderr}"); // What the narrowed run does produce is still checked. File.AppendAllText(Path.Combine(DocsDir, "api", "csharp", "README.md"), "edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("api/csharp/README.md", drift.Stderr); } @@ -439,7 +439,7 @@ public void An_entry_directory_nested_in_out_is_compared_once_as_its_own() IReadOnlyList declared = [new EntityGenerator(), new ApiDocsGenerator { OutDir = nestedDocs }]; Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -471,7 +471,7 @@ public void A_conventional_template_spec_no_entry_declares_is_refused_and_nothin Assert.Equal(CodegenCli.LegacyTemplateSpec("dotnet meta gen", "template-spec.json"), stderr.Trim()); Assert.Equal(before, ProjectFiles()); - var (verifyExit, _, verifyErr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated"); + var (verifyExit, _, verifyErr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated"); Assert.Equal(2, verifyExit); Assert.Equal(CodegenCli.LegacyTemplateSpec("dotnet meta verify --codegen", "template-spec.json"), verifyErr.Trim()); } @@ -501,7 +501,7 @@ public void A_declared_template_spec_entry_renders_its_templates_and_verifies_cl Assert.Equal(["Subscriber.summary.txt"], FilesUnder(OutDir)); Assert.Equal("name=Subscriber\n", File.ReadAllText(Path.Combine(OutDir, "Subscriber.summary.txt"))); - var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", "--full"); + var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", "--full"); Assert.True(verifyExit == 0, $"exit={verifyExit}\nstdout={verifyOut}\nstderr={verifyErr}"); Assert.Contains("OK (generated output is in sync)", verifyOut); } @@ -533,9 +533,9 @@ public void The_runs_template_root_reaches_a_declared_spec_that_names_none() Assert.True(exit == 0, $"exit={exit}\nstdout={stdout}\nstderr={stderr}"); Assert.Equal("name=Subscriber\n", File.ReadAllText(Path.Combine(OutDir, "Subscriber.summary.txt"))); - var verify = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--template-root", "templates", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--template-root", "templates", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); - Assert.Equal(1, OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); + Assert.Equal(1, OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); } // ---- a directory gen never had to create is an empty tree, not a missing one --------------- @@ -550,7 +550,7 @@ public void An_entry_directory_that_got_no_files_verifies_clean() Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); Assert.False(Directory.Exists(testsDir)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -568,7 +568,7 @@ public void A_list_of_entries_with_their_own_directories_verifies_clean_in_a_fre Directory.Delete(OutDir); Assert.False(Directory.Exists(testsDir)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -578,7 +578,7 @@ public void Verify_codegen_of_a_list_that_declares_nothing_is_clean() { Assert.Equal(0, OwnedRunner.Run(_tmp, Array.Empty(), "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var verify = OwnedRunner.Run(_tmp, Array.Empty(), "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, Array.Empty(), "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); Assert.Contains("codegen/Generators.cs declares no generators; nothing to check", verify.Stdout); @@ -591,7 +591,7 @@ public void A_blank_generators_selection_is_refused(string command) { string[] args = command == "gen" ? ["gen", MetaDir, "--out", OutDir, "--generators", ""] - : ["verify", MetaDir, "--codegen", "--out", OutDir, "--generators", ""]; + : ["verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", ""]; var (exit, _, stderr) = OwnedRunner.Run(_tmp, ["entity"], args); diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs index eba808db7e..97587a3f9a 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs @@ -228,7 +228,7 @@ public void The_gate_runs_under_codegen_alone_and_its_errors_reach_the_exit_code // requirement gate still runs, as it does on every verify, and prints its findings. var args = Project(Requirement("Recorded", "live", "Refund")); var model = args[1]; - var codegenArgs = new[] { "verify", model, "--codegen", "--out", Path.Combine(_tmp, "out") }; + var codegenArgs = new[] { "verify", model, "--codegen", "--full", "--out", Path.Combine(_tmp, "out") }; var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, codegenArgs); @@ -354,7 +354,7 @@ public void Codegen_with_no_out_dir_never_loads_so_the_gate_reports_the_model_th { // In-process this time, through the built CLI: `--codegen` with no `--out` stops before it // loads anything, so here too the gate's load is the only one. - var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, "verify", UnloadableModel(), "--codegen"); + var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, "verify", UnloadableModel(), "--codegen", "--full"); Assert.True(exitCode != 0, $"exit={exitCode}\nstdout={stdout}\nstderr={stderr}"); Assert.Contains(" load error: ERR_BAD_ATTR_VALUE: ", stderr); @@ -376,7 +376,7 @@ public void A_load_failure_a_gate_already_reported_is_not_reported_again() // So did the codegen gate, in its own form: since ADR-0034 Amendment 9 it runs in the // project's codegen project (CodegenCli.Run, see OwnedRunner). var (codegenExit, _, codegenErr) = OwnedRunner.Run( - _tmp, Array.Empty(), "verify", "--codegen", model, "--out", Path.Combine(_tmp, "out")); + _tmp, Array.Empty(), "verify", "--codegen", "--full", model, "--out", Path.Combine(_tmp, "out")); Assert.NotEqual(0, codegenExit); Assert.Contains("verify --codegen: FAILED (metadata did not load cleanly)", codegenErr); Assert.Equal(1, CountOf(codegenErr, "ERR_BAD_ATTR_VALUE")); diff --git a/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs b/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs index c81a6212b0..45853427f6 100644 --- a/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs @@ -104,7 +104,7 @@ public void Verify_with_the_wrong_wire_setting_says_the_setting_differs_instead_ WriteConfig(null); var (exit, stdout, stderr) = OwnedRunner.Run( - _tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + _tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( diff --git a/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs index eba4a368ce..5e28985ed6 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs @@ -114,12 +114,13 @@ public void Pluralize_keeps_existing_behavior_for_s_u_i_a_plus_s_endings(string Assert.Equal(expected, CSharpNaming.Pluralize(input)); } - // A Greek "-sis" noun takes "-ses" (Diagnosis -> Diagnoses), not the sibilant "+es" that - // produced "Diagnosises" in every DbSet and finder name. The other common endings are pinned + // A Greek "-sis" noun takes "-ses" (Analysis -> Analyses), not the sibilant "+es" that + // produced "Analysises" in every DbSet and finder name. The other common endings are pinned // beside it so the new rule cannot widen past "-sis". [Theory] - [InlineData("Diagnosis", "Diagnoses")] [InlineData("Analysis", "Analyses")] + [InlineData("Thesis", "Theses")] + [InlineData("Diagnosis", "Diagnoses")] [InlineData("Basis", "Bases")] [InlineData("OrderAnalysis", "OrderAnalyses")] [InlineData("Notification", "Notifications")] @@ -137,6 +138,8 @@ public void Pluralize_handles_sis_tion_y_and_s_endings(string input, string expe [Fact] public void DbSetName_and_reverse_finder_name_use_the_sis_plural() { + Assert.Equal("Analyses", CSharpNaming.DbSetName(Entity("Analysis"))); + Assert.Equal("FindAnalysesByPlayer", CSharpNaming.ReverseFinderName(Entity("Analysis"), "playerId")); Assert.Equal("Diagnoses", CSharpNaming.DbSetName(Entity("Diagnosis"))); Assert.Equal("FindDiagnosesByPatient", CSharpNaming.ReverseFinderName(Entity("Diagnosis"), "patientId")); } @@ -147,9 +150,9 @@ public void RoutePath_keeps_the_cross_port_rule_for_a_sis_noun() // The REST collection segment is a wire contract every port spells the same way // (fixtures/naming-conformance); the "-sis" rule is a C# identifier fix only, so the // route does not move until every port moves with it. + Assert.Equal("analysises", CSharpNaming.RoutePath(Entity("Analysis"))); Assert.Equal("diagnosises", CSharpNaming.RoutePath(Entity("Diagnosis"))); } - [Fact] public void Pluralize_documented_known_miss_Lens_reads_as_already_plural() { @@ -413,7 +416,125 @@ public void DbSetName_names_the_property_and_resolves_a_same_context_collision() Assert.Contains("Payers { get; set; }", context); } - // A @collectionName that is no C# identifier, or names a DbContext member, would fail at compile + // ── rc.19 fix round (I3): fixtures/naming-conformance/collection-segments.json ────────────── + // The REST segment, shared with TypeScript: nothing configured is rc.18's rule byte for byte; + // a declared name or a configured pluralizer is snake_cased keeping an acronym's plural suffix. + + public sealed record SegmentCase(string Name, string? CollectionName, string? Pluralizer, string Segment) + { + public override string ToString() => $"{Name} (declared {CollectionName ?? "-"}, pluralizer {Pluralizer ?? "-"}) -> {Segment}"; + } + + public static TheoryData SegmentCases() + { + var path = Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "naming-conformance", "collection-segments.json"); + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + var data = new TheoryData(); + foreach (var c in doc.RootElement.GetProperty("cases").EnumerateArray()) + { + data.Add(new SegmentCase( + c.GetProperty("name").GetString()!, + c.TryGetProperty("collectionName", out var d) ? d.GetString() : null, + c.TryGetProperty("pluralizer", out var p) ? p.GetString() : null, + c.GetProperty("segment").GetString()!)); + } + return data; + } + + [Theory] + [MemberData(nameof(SegmentCases))] + public void The_REST_segment_is_the_cross_port_one(SegmentCase c) + { + var declared = c.CollectionName is null ? "" : $@"""@collectionName"": ""{c.CollectionName}"", "; + var json = $@"{{ ""metadata.root"": {{ ""package"": ""test"", ""children"": [ + {{ ""object.entity"": {{ ""name"": ""{c.Name}"", {declared}""children"": [ + {{ ""source.rdb"": {{ ""@table"": ""t"" }} }}, + {{ ""field.long"": {{ ""name"": ""id"" }} }}, + {{ ""identity.primary"": {{ ""name"": ""pk"", ""@fields"": ""id"" }} }} + ] }} }} ] }} }}"; + var r = new MetaDataLoader().Load([new InMemoryStringSource(json, id: "seg.json")]); + Assert.Empty(r.Errors); + if (c.Pluralizer is not null) r.Root.PhysicalNaming = r.Root.PhysicalNaming with { Collections = c.Pluralizer }; + Assert.Equal(c.Segment, CSharpNaming.RoutePath(r.Root.Objects().Single())); + } + + // ── rc.19 (R57): @collectionName, its deprecated alias, and the pluggable pluralizer ───────── + + private const string HistoryModel = """ + { "metadata.root": { "package": "core", "children": [ + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } + ] } }, + { "object.entity": { "name": "ConsignmentHistory", ATTRS "children": [ + { "source.rdb": { "@table": "consignment_history" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "consignmentId" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } } + ] } } + ] } } + """; + + private static MetaRoot History(string attrs, string? pluralizer = null) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(HistoryModel.Replace("ATTRS", attrs), id: "h.json")]); + Assert.Empty(r.Errors.Select(e => e.Code + ": " + e.Message)); + if (pluralizer is not null) r.Root.PhysicalNaming = r.Root.PhysicalNaming with { Collections = pluralizer }; + return r.Root; + } + + private static GenContext CtxWarn(MetaRoot root, List warnings) => new() + { + Entities = root.Objects(), Root = root, Warn = warnings.Add, + Config = new GenConfig { OutDir = "/unused", Namespace = "Acme.Generated" }, + }; + + private static MetaObject HistoryOf(MetaRoot root) => root.Objects().Single(o => o.Name == "ConsignmentHistory"); + + [Fact] + public void CollectionName_names_the_DbSet_the_route_the_finder_and_the_reverse_hop() + { + var root = History("\"@collectionName\": \"ConsignmentHistory\","); + var history = HistoryOf(root); + Assert.Equal("ConsignmentHistory", CSharpNaming.DbSetName(history)); + Assert.Equal("consignment_history", CSharpNaming.RoutePath(history)); + Assert.Equal("FindConsignmentHistoryByConsignment", CSharpNaming.ReverseFinderName(history, "consignmentId")); + Assert.Equal("consignmentHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(history)); + var warnings = new List(); + var context = Assert.Single(new DbContextGenerator().Generate(CtxWarn(root, warnings))).Content; + Assert.Contains("DbSet ConsignmentHistory { get; set; }", context); + Assert.DoesNotContain(warnings, w => w.Contains("deprecated")); + } + + [Fact] + public void Absent_the_configured_pluralizer_names_the_collection_and_unconfigured_output_is_unchanged() + { + var unconfigured = HistoryOf(History("")); + Assert.Equal("ConsignmentHistories", CSharpNaming.DbSetName(unconfigured)); + Assert.Equal("consignment_histories", CSharpNaming.RoutePath(unconfigured)); + + var none = HistoryOf(History("", pluralizer: "none")); + Assert.Equal("ConsignmentHistory", CSharpNaming.DbSetName(none)); + Assert.Equal("consignment_history", CSharpNaming.RoutePath(none)); + Assert.Equal("consignmentHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(none)); + } + + [Fact] + public void An_application_registers_its_own_pluralizer_and_an_unknown_name_fails_loudly() + { + // The registry is process-wide and other test classes register strategies in it, so this + // one is left registered (registering a name again replaces it) rather than reset. + MetaObjects.Meta.NamingStrategies.RegisterPluralizer("cs-test-latin", n => n.EndsWith("History") ? n[..^1] + "ies" : n + "s"); + Assert.Equal("ConsignmentHistories", CSharpNaming.DbSetName(HistoryOf(History("", pluralizer: "cs-test-latin")))); + Assert.Throws(() => MetaObjects.Meta.NamingStrategies.RegisterPluralizer("standard", n => n)); + var ex = Assert.Throws(() => MetaObjects.Meta.NamingStrategies.Pluralizer("klingon")); + Assert.Contains("\"naming.collections\" names \"klingon\"", ex.Message); + Assert.Contains("built in: standard, none", ex.Message); + } + + // A @dbSetName that is no C# identifier, or names a DbContext member, would fail at compile // time (or hide Database / Model); codegen refuses it by name. [Theory] [InlineData("Payer Rows")] @@ -472,6 +593,7 @@ public void Two_objects_mapping_one_routine_in_one_context_are_refused_naming_bo Assert.Contains("refresh_totals", ex.Message); } + [Fact] public void One_table_name_in_two_schemas_in_one_context_passes_schema_qualified() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs index 983e897ee0..e8b3fc8674 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs @@ -1,4 +1,4 @@ -// The generated EF model declares the CHECKs `meta migrate` derives — +// rc.19 item 13 (rulings R55): the generated EF model declares the CHECKs `meta migrate` derives — // every validator that can carry one, and every scalar field.enum — with migrate's names and // expression text, so one model builds one database through either delivery path (an EF // migration or `meta migrate`). The names and text are pinned by the shared corpus @@ -60,7 +60,8 @@ public void The_checks_are_meta_migrates_names_and_text(string file, string dial { var ctx = Ctx(Load(), dialect, skipRedundant); var actual = ctx.Root.Objects() - .Where(o => o.IsEntity() && o.DbTable is not null) + // A TPH subtype has no table of its own: its CHECKs are its base's (FR-017). + .Where(o => o.IsEntity() && o.DbTable is not null && !InstanceArtifacts.IsAbstract(o) && !TphPlanBuilder.IsTphSubtype(o, ctx.Root)) .Select(o => (Table: CSharpNaming.Table(o), Checks: CheckConstraints.For(o, ctx.Config))) .Where(t => t.Checks.Count > 0) .ToDictionary(t => t.Table, t => t.Checks.Select(c => (c.Name, c.Expression)).ToList()); @@ -78,6 +79,18 @@ public void The_context_declares_each_check_on_its_table() Assert.Contains("modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(\"gadgets_status_chk\", \"\\\"status\\\" IN ('DRAFT', 'LIVE')\"));", context); Assert.Contains("t.HasCheckConstraint(\"gadgets_sku_shape\", ", context); Assert.Contains("t.HasCheckConstraint(\"gadgets_email_exactlyone_chk\", \"num_nonnulls(\\\"email\\\", \\\"phone\\\") = 1\")", context); + // rc.20 @dbCheck: false — the opted-out validators and enum declare no CHECK; a sibling + // validator on the same field keeps its own. + Assert.DoesNotContain("gadgets_npi_", context); + Assert.DoesNotContain("gadgets_legacy_state_chk", context); + Assert.DoesNotContain("\\\"rank\\\" >= 1", context); + Assert.Contains("t.HasCheckConstraint(\"gadgets_rank_numeric_chk\", \"\\\"rank\\\" <= 99\")", context); + // FR-017 TPH: a subtype's columns are on its base's table, and so are their CHECKs. + Assert.Contains("modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(\"devices_mode_chk\", \"\\\"mode\\\" IN ('AUTO', 'MANUAL')\"));", context); + Assert.Contains("t.HasCheckConstraint(\"devices_sensor_unit_reqwhen_chk\", ", context); + // rc.21 fix round (I1): siblings that disagree on a shared column each guard their own CHECK. + Assert.Contains("t.HasCheckConstraint(\"devices_switch_grade_chk\", \"(\\\"kind\\\" <> 'SWITCH') OR (\\\"grade\\\" IN ('X', 'Y'))\")", context); + Assert.DoesNotContain("devices_legacy_position_chk", context); // A derived field is no column of the table: no CHECK names it, nor a cross-field CHECK over it. Assert.DoesNotContain("band", context); Assert.DoesNotContain("owner_name", context); @@ -108,4 +121,66 @@ public void The_context_with_its_checks_compiles_against_EF_Core_8() .Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); Assert.True(errors.Count == 0, string.Join("\n", errors)); } + + // rc.21 fix round (I2): two different CHECKs under one default name are refused, naming both. + [Fact] + public void Two_checks_under_one_name_are_refused() + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Window", "children": [ + { "source.rdb": { "@table": "windows" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "a" } }, { "field.int": { "name": "b" } }, { "field.int": { "name": "c" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "validator.comparison": { "name": "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { "name": "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } } + """, id: "w.json")]); + Assert.Empty(load.Errors); + var ex = Assert.Throws(() => CheckConstraints.For(load.Root.Objects().Single(), Ctx(load.Root, "postgres").Config)); + Assert.Contains("both named 'windows_a_cmp_chk'", ex.Message); + Assert.Contains("Postgres requires each constraint on a table to have its own name", ex.Message); + // rc.21 part B (N1): SQLite and D1 accept the pair (meta migrate keeps both), but EF's model + // keys a check constraint by name and would keep only the last, so C# still refuses it there. + foreach (var dialect in new[] { "sqlite", "d1" }) + { + var lite = Assert.Throws(() => CheckConstraints.For(load.Root.Objects().Single(), Ctx(load.Root, dialect).Config)); + Assert.Contains("EF Core keeps one check constraint per name", lite.Message); + } + } + + // rc.21 part B (N2): a generated name fitted to Postgres's 63-byte limit, spelled as meta migrate spells it. + [Fact] + public void FitPgIdentifier_matches_the_TypeScript_spelling() + { + Assert.Equal("devices_meter_serial_regex_chk", CheckConstraints.FitPgIdentifier("devices_meter_serial_regex_chk")); + Assert.Equal("measurement_devices_with_a_rather_long_table_name_mete_559a7830", + CheckConstraints.FitPgIdentifier("measurement_devices_with_a_rather_long_table_name_meterdevicekind_serial_chk")); + Assert.Equal(new string('é', 27) + "_84fe2e03", CheckConstraints.FitPgIdentifier(new string('é', 40))); + } + + [Fact] + public void A_qualified_TPH_check_name_over_63_bytes_is_fitted_on_Postgres_only() + { + const string table = "measurement_devices_with_a_rather_long_table_name"; + var load = new MetaDataLoader().Load([new InMemoryStringSource($$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Device", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "{{table}}" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "kind", "@maxLength": 20 } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.entity": { "name": "MeterDeviceKind", "extends": "Device", "@discriminatorValue": "METER", "children": [ + { "field.enum": { "name": "serial", "@values": ["M1", "M2"] } } ] } }, + { "object.entity": { "name": "SensorDeviceKind", "extends": "Device", "@discriminatorValue": "SENSOR", "children": [ + { "field.enum": { "name": "serial", "@values": ["S1", "S2"] } } ] } } ] } } + """, id: "d.json")]); + Assert.Empty(load.Errors); + var device = load.Root.Objects().Single(o => o.Name == "Device"); + IEnumerable Names(string dialect) => CheckConstraints.For(device, Ctx(load.Root, dialect).Config) + .Where(c => c.Expression.Contains("serial")).Select(c => c.Name); + Assert.Equal(new[] { "measurement_devices_with_a_rather_long_table_name_mete_559a7830", + CheckConstraints.FitPgIdentifier($"{table}_sensordevicekind_serial_chk") }, Names("postgres")); + Assert.Equal(new[] { $"{table}_meterdevicekind_serial_chk", $"{table}_sensordevicekind_serial_chk" }, Names("sqlite")); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossPackageBindingConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossPackageBindingConformanceTests.cs index b14c965475..319f39a429 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CrossPackageBindingConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CrossPackageBindingConformanceTests.cs @@ -122,7 +122,10 @@ private static Dictionary Generated(MetaRoot root) var files = new Dictionary(); foreach (var gen in new IGenerator[] { new EntityGenerator(), new DbContextGenerator(), new RoutesGenerator() }) foreach (var file in gen.Generate(ctx)) + { files.TryAdd(file.Path, file.Content); + files.TryAdd(System.IO.Path.GetFileName(file.Path), file.Content); + } return files; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DbContextCompileTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DbContextCompileTests.cs index de5e3f9867..ad7a0cf20a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DbContextCompileTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DbContextCompileTests.cs @@ -214,7 +214,7 @@ public void Generated_AppDbContext_and_entities_compile_against_EF_Core_8() // REFERENCES the names artifact, so this test proves what Ctx()'s // IncludeNames: true comment claims: entity + DbContext + names compile // together WITH a real cross-reference between them, not merely alongside. - var orderSrc = entityFiles.Single(f => f.Path == "Order.g.cs").Content; + var orderSrc = entityFiles.Single(f => System.IO.Path.GetFileName(f.Path) == "Order.g.cs").Content; Assert.Contains("[Table(OrderNames.SourcePrimaryTable)]", orderSrc); Assert.Contains("[Column(OrderNames.StatusColumn)]", orderSrc); } @@ -252,6 +252,39 @@ static List ConfigLines(string src) => src.Split('\n') Assert.True(errors.Count == 0, string.Join("\n", errors)); } + // Item 8: every model line is one complete statement, so a split at ANY boundary compiles. The + // @using index method used to be two entries — the provider guard and the statement it guards — + // and a chunk boundary between them left an `if (…)` closing its method. + [Fact] + public void A_guarded_index_method_survives_a_split_at_every_boundary() + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "email", "@maxLength": 80 } }, + { "identity.primary": { "@fields": "id" } }, + { "index.lookup": { "name": "ix_tickets_email", "@fields": "email", "@using": "gin" } } ] } } ] } } + """, id: "t.json")]); + Assert.Empty(load.Errors); + var ctx = new GenContext + { + Entities = load.Root.Objects(), Root = load.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", Dialect = "postgres" }, + }; + var split = Assert.Single(new DbContextGenerator { ModelConfigChunkSize = 1 }.Generate(ctx), f => f.Path == "AppDbContext.g.cs").Content; + Assert.Contains("\") modelBuilder.Entity().HasIndex(", split); + var comp = CSharpCompilation.Create( + "efcore_guard_" + Guid.NewGuid().ToString("N"), + new EntityGenerator().Generate(ctx).Select(f => f.Content).Append(split) + .Select(c => CSharpSyntaxTree.ParseText(c, new CSharpParseOptions(LanguageVersion.CSharp12))), + BuildReferences(), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); + Assert.True(errors.Count == 0, string.Join("\n", errors)); + } + // The map's value object is serialized by the MapJsonb helper's shared JsonSerializerOptions, // and System.Text.Json writes enums as NUMBERS by default — so a field.enum member of the // map's @objectRef value object persisted as its ORDINAL, while the same member of the same @@ -362,8 +395,8 @@ public void WriteThrough_read_model_carries_type_converter_and_jsonb_vo_columns( { var ctx = Ctx(Load()); var entityFiles = new EntityGenerator().Generate(ctx).ToList(); - var readModel = entityFiles.Single(f => f.Path == "InvoiceView.g.cs").Content; - var writeEntity = entityFiles.Single(f => f.Path == "Invoice.g.cs").Content; + var readModel = entityFiles.Single(f => System.IO.Path.GetFileName(f.Path) == "InvoiceView.g.cs").Content; + var writeEntity = entityFiles.Single(f => System.IO.Path.GetFileName(f.Path) == "Invoice.g.cs").Content; var dbctx = Assert.Single(new DbContextGenerator().Generate(ctx)).Content; // [0] — the read model class declares the field.uri column (a per-field TYPE binding). @@ -434,7 +467,7 @@ public void Sourceless_concrete_entity_loads_cleanly_and_compiles_under_the_defa // #248 -- no primary source, so no names artifact at all, regardless of the run. Assert.Empty(namesFiles); - var ledger = entityFiles.Single(f => f.Path == "Ledger.g.cs").Content; + var ledger = entityFiles.Single(f => System.IO.Path.GetFileName(f.Path) == "Ledger.g.cs").Content; Assert.DoesNotContain("LedgerNames", ledger); Assert.DoesNotContain("[Table(LedgerNames.SourcePrimaryTable)]", ledger); // #248 — a sourceless entity is not in the database, so it carries no [Table] at diff --git a/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs index 24cdbeace7..adb88d4220 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs @@ -109,10 +109,10 @@ private static List Generate(MetaRoot root, GenConfig config) private static IEnumerable Usings(string source) => CSharpSyntaxTree.ParseText(source).GetCompilationUnitRoot().Usings.Select(u => u.Name!.ToString()); - private static GenConfig Bare() => new() { OutDir = "/tmp" }; + private static GenConfig Bare() => new() { OutDir = "/tmp", OutputLayout = OutputLayout.Package }; private static string Content(List files, string name) => - files.Single(f => f.Path == name).Content; + files.Single(f => System.IO.Path.GetFileName(f.Path) == name).Content; [Fact] public void No_config_derives_each_namespace_from_its_package() @@ -137,12 +137,15 @@ public void A_single_package_is_its_own_home_namespace() Assert.Contains("namespace Acme.Billing;", Content(files, "AppDbContext.g.cs")); } + // rc.19 R65: a configured namespace is the home of the package-less artifacts only; a packaged + // type keeps its package's namespace. [Fact] - public void Configured_namespace_overrides_the_derived_default() + public void A_configured_namespace_places_only_the_artifacts_of_no_package() { - var files = Generate(Load(Billing(), Crm, Ops), Bare() with { Namespace = "My.App" }); - Assert.Contains("namespace My.App;", Content(files, "Invoice.g.cs")); - Assert.Contains("namespace My.App;", Content(files, "Order.g.cs")); + var files = Generate(Load(Billing(), Crm, Ops), Bare() with { PackageNamespacesFromMetadata = true, Namespace = "My.App" }); + Assert.Contains("namespace Acme.Billing;", Content(files, "Invoice.g.cs")); + Assert.Contains("namespace Acme.Crm;", Content(files, "Order.g.cs")); + Assert.Contains("namespace My.App;", Content(files, "AppDbContext.g.cs")); } [Fact] @@ -168,16 +171,16 @@ public void A_multi_package_model_compiles() var files = Generate(Load(Billing(), Crm, Ops), Bare()); foreach (var expected in new[] { - "Enums.g.cs", "TicketSummary.callable.g.cs", "triage.render.cs", "triage.response.cs", + "Grade.g.cs", "TicketSummary.callable.g.cs", "triage.render.cs", "triage.response.cs", "triage.responseFormat.cs", "TicketVerdictExtracted.g.cs", "InvoiceTotalsExport.g.cs", }) - Assert.Contains(files, f => f.Path == expected); + Assert.Contains(files, f => System.IO.Path.GetFileName(f.Path) == expected); // Routes import the ASP.NET Core shared framework, which an in-memory compilation does not // carry (CodegenCompileConformanceTests draws the same line); their package usings are // asserted by Routes_reach_the_package_namespaces_of_the_types_they_name. var comp = CSharpCompilation.Create( "derived_ns_" + Guid.NewGuid().ToString("N"), - files.Where(f => !f.Path.EndsWith("Routes.g.cs", StringComparison.Ordinal)).Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), + files.Where(f => !f.Path.EndsWith("Routes.g.cs", StringComparison.Ordinal)).Select(f => CSharpSyntaxTree.ParseText(MetaObjects.Codegen.FrameworkQualifier.Qualify(f.Content), new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) @@ -186,13 +189,14 @@ public void A_multi_package_model_compiles() } [Fact] - public void Routes_reach_the_package_namespaces_of_the_types_they_name() + public void Routes_and_exports_live_in_their_objects_package_namespace() { - var files = Generate(Load(Billing(), Crm, Ops), Bare()); - Assert.Contains("Acme.Billing", Usings(Content(files, "InvoiceRoutes.g.cs"))); - Assert.Contains("Acme.Crm", Usings(Content(files, "OrderRoutes.g.cs"))); - // Order navigates to an Invoice, and the home namespace is neither package's. - Assert.Contains("Acme", Content(files, "OrderRoutes.g.cs").Split('\n').Where(l => l.StartsWith("namespace ")).Select(l => l["namespace ".Length..].TrimEnd(';', '\r'))); - Assert.Contains("Acme.Billing", Usings(Content(files, "InvoiceTotalsExport.g.cs"))); + // rc.19 R65: a per-object class follows its object; what it names from elsewhere (the + // context, another package's types) is global::-qualified, so it needs no using. + var files = Generate(Load(Billing(), Crm, Ops), Bare() with { PackageNamespacesFromMetadata = true }); + Assert.Contains("namespace Acme.Billing;", Content(files, "InvoiceRoutes.g.cs")); + Assert.Contains("namespace Acme.Crm;", Content(files, "OrderRoutes.g.cs")); + Assert.Contains("global::Acme.AppDbContext db", Content(files, "OrderRoutes.g.cs")); + Assert.Empty(Usings(Content(files, "OrderRoutes.g.cs")).Where(u => u.StartsWith("Acme", StringComparison.Ordinal))); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs index fe49e53086..09ff7bbb7b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs @@ -221,6 +221,13 @@ public void Depth_every_engine_surface_entry_names_a_real_type() private sealed record Corpus(string Label, MetaRoot Root, string? TemplateRoot); /// Shared models that between them make every ejectable generator emit. + private static MetaRoot InlineModel(string json) + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(json, id: "inline.json")]); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + return load.Root; + } + private static List Corpora() { MetaRoot Directory(params string[] segments) @@ -234,6 +241,8 @@ MetaRoot Directory(params string[] segments) new("fitness", EjectedGeneratorCompileTests.LoadCorpus(), CorpusPaths.FitnessTemplateRoot), new("requirements", Directory("requirement-test-identity-conformance", "worked-example", "input"), null), new("stored-proc", Directory("conformance", "parameter-ref-on-stored-proc", "input"), null), + // An @expr index: expression-indexes emits only over one. + new("expression-indexes", InlineModel(ExpressionIndexesGeneratorTests.Model), null), // A reply with a nested object: the extractor emits only over one. new("nested-reply", Directory("template-output-render-conformance", "xpkg-collision-json"), Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "template-output-render-conformance", "templates")), @@ -283,7 +292,7 @@ List Run(IGenerator generator) => GeneratorRegistry.Get(stableName)!.Factory(new GeneratorBuildContext(corpus.TemplateRoot)))); var owned = Run(SharedModelTestSupport.Configure(Instantiate(copy.Assembly, corpus.TemplateRoot))); emitted += packaged.Count; - Assert.Equal(packaged.Select(f => f.Path), owned.Select(f => f.Path)); + Assert.Equal(packaged.Select(f => System.IO.Path.GetFileName(f.Path)), owned.Select(f => System.IO.Path.GetFileName(f.Path))); for (var i = 0; i < packaged.Count; i++) Assert.Equal(Expected(packaged[i].Content), owned[i].Content); diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs index 5bb22bf544..e73d486ce6 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs @@ -57,6 +57,7 @@ public class EjectedGeneratorsAloneTests ["MetaObjects.Codegen.CSharpNaming"] = "the naming and type-mapping tables", ["MetaObjects.Codegen.Generators.CheckConstraints"] = "the CHECKs meta migrate derives: a schema contract both delivery paths must agree on, not emitted code an owned copy should change", ["MetaObjects.Codegen.Generators.CheckConstraint"] = "one of those CHECKs, a name and an expression", + ["MetaObjects.Codegen.DesignTimeServicesReferences"] = "whether EF reads the generated design-time services reference: a question about the adopter's project layout, not emitted code", ["MetaObjects.Codegen.Generators.ForeignKeyIndexes"] = "the indexes and index names meta migrate creates (foreign-key indexes, and a declared name cut to what Postgres stores): a schema contract both delivery paths must agree on, held by fixtures/foreign-key-index-conformance", ["MetaObjects.Codegen.Generators.ForeignKeyIndex"] = "one of those indexes, a name and its columns", ["MetaObjects.Codegen.ValueObjectNames"] = "the one answer to what a value object's type is called and where it lives", @@ -273,6 +274,9 @@ private static MetaRoot LoadInline(string model, string id) // it also runs over the model its own codegen tests use. if (generator is "callable") yield return ("callable", LoadInline(Fr015CodegenTests.Model, "fr015.json")); + // `expression-indexes` emits only for an @expr index, which neither shared corpus has. + if (generator is "expression-indexes") + yield return ("expression-indexes", LoadInline(ExpressionIndexesGeneratorTests.Model, "expr.json")); yield return ("fitness", EjectedGeneratorCompileTests.LoadCorpus()); var worked = MetaDataLoader.FromDirectory( Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "requirement-test-identity-conformance", "worked-example", "input"), strict: true); diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs index e9e1353a1c..c522e3f977 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs @@ -31,7 +31,7 @@ private static MetaRoot Load(string model) }; private static string File(System.Collections.Generic.IEnumerable files, string path) => - files.Single(f => f.Path == path).Content; + files.Single(f => System.IO.Path.GetFileName(f.Path) == path).Content; // ----------------------------------------------------------------- items 2 + 3 diff --git a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs index 0c51bf6f7f..8ed7a12ce2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs @@ -53,7 +53,7 @@ public void Gen_reports_the_member_by_name_and_fails() [Fact] public void Verify_codegen_reports_the_member_by_name_and_fails() { - var (code, text) = Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + var (code, text) = Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); Assert.NotEqual(0, code); Assert.Contains("field.enum \"Ticket.status\" has the member \"CLOSED\"", text); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs new file mode 100644 index 0000000000..915be1f5ca --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs @@ -0,0 +1,89 @@ +// expression-indexes: the @expr indexes EF Core cannot model, as one SQL file. Qualified by the +// source's @schema, under the resolved index name, with @using and @where, unique for an +// identity.secondary. The model below is also the eject tests' corpus for this generator. + +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class ExpressionIndexesGeneratorTests +{ + internal const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets", "@schema": "support" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "email", "@maxLength": 80 } }, + { "field.string": { "name": "status", "@maxLength": 20 } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.secondary": { "name": "ux_tickets_lower_email", "@expr": "lower(email)", "@where": "status = 'open'" } }, + { "index.lookup": { "name": "ix_tickets_email_trgm", "@expr": "email gin_trgm_ops", "@using": "gin" } }, + { "index.lookup": { "name": "ix_tickets_status", "@fields": "status" } } + ] } } + ] } } + """; + + [Fact] + public void Each_expression_index_is_one_statement_and_a_column_index_is_none() + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "expr.json")]); + Assert.Empty(load.Errors); + var ctx = new GenContext { Entities = load.Root.Objects(), Root = load.Root, Config = new GenConfig { OutDir = "/unused", Namespace = "Acme" } }; + var sql = Assert.Single(new ExpressionIndexesGenerator().Generate(ctx)).Content; + Assert.Contains("CREATE INDEX IF NOT EXISTS \"ix_tickets_email_trgm\" ON \"support\".\"tickets\" USING gin (email gin_trgm_ops);", sql); + Assert.Contains("CREATE UNIQUE INDEX IF NOT EXISTS \"ux_tickets_lower_email\" ON \"support\".\"tickets\" (lower(email)) WHERE status = 'open';", sql); + Assert.DoesNotContain("ix_tickets_status", sql); + } + + private static string Sql(string model) + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "expr.json")]); + Assert.Empty(load.Errors); + var ctx = new GenContext { Entities = load.Root.Objects(), Root = load.Root, Config = new GenConfig { OutDir = "/unused", Namespace = "Acme" } }; + return Assert.Single(new ExpressionIndexesGenerator().Generate(ctx)).Content; + } + + [Fact] + public void An_expression_index_an_abstract_base_declares_is_written_on_the_concrete_table() + { + // The layered shape: the abstract base emits nothing, so the index is the child's, resolving. + var sql = Sql(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "BasePerson", "abstract": true, "children": [ + { "field.long": { "name": "id" } }, + { "field.string": { "name": "email", "@maxLength": 80 } }, + { "identity.primary": { "@fields": "id" } }, + { "index.lookup": { "name": "ix_people_lower_email", "@expr": "lower(email)" } } + ] } }, + { "object.entity": { "name": "Person", "extends": "BasePerson", "children": [ + { "source.rdb": { "@table": "people" } } + ] } } + ] } } + """); + Assert.Contains("CREATE INDEX IF NOT EXISTS \"ix_people_lower_email\" ON \"people\" (lower(email));", sql); + } + + [Fact] + public void A_tph_subtypes_expression_index_is_written_once_on_the_root_table() + { + var sql = Sql(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } }, + { "index.lookup": { "name": "ix_vehicles_lower_kind", "@expr": "lower(kind)" } } + ] } }, + { "object.entity": { "name": "Car", "extends": "Vehicle", "@discriminatorValue": "Car", "children": [ + { "field.string": { "name": "vin", "@maxLength": 17 } }, + { "index.lookup": { "name": "ix_vehicles_upper_vin", "@expr": "upper(vin)" } } + ] } } + ] } } + """); + Assert.Contains("CREATE INDEX IF NOT EXISTS \"ix_vehicles_upper_vin\" ON \"vehicles\" (upper(vin));", sql); + Assert.Single(System.Text.RegularExpressions.Regex.Matches(sql, "ix_vehicles_lower_kind")); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/ExtendsAbstractFieldInheritanceCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ExtendsAbstractFieldInheritanceCodegenTests.cs index e6439c4c73..37850794b3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ExtendsAbstractFieldInheritanceCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ExtendsAbstractFieldInheritanceCodegenTests.cs @@ -52,9 +52,9 @@ public void Generated_entity_honors_every_inherited_field_property() var files = new EntityGenerator().Generate(Context(root)).ToList(); // Abstract field bases + the abstract BaseEntity produce no entity file. - Assert.DoesNotContain(files, f => f.Path == "BaseEntity.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "BaseEntity.g.cs"); - var contact = Assert.Single(files, f => f.Path == "Contact.g.cs").Content; + var contact = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Contact.g.cs").Content; // BaseEntity PK (uuid id) inherited via extends -> [Key] on the Id property. Assert.Contains("[Key]", contact); diff --git a/server/csharp/MetaObjects.Codegen.Tests/FlattenedMemberReferenceCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/FlattenedMemberReferenceCodegenTests.cs index 811b95d6b8..241d0cc56d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/FlattenedMemberReferenceCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/FlattenedMemberReferenceCodegenTests.cs @@ -49,7 +49,9 @@ public void The_foreign_key_is_configured_on_the_owned_types_builder() { var (ctx, warnings) = Context(Model); var context = Assert.Single(new DbContextGenerator().Generate(ctx)).Content; - Assert.Contains("modelBuilder.Entity().OwnsOne(x => x.Address).HasOne().WithMany().HasForeignKey(e => e.CountryId)", context); + // rc.21 U6: the relationship is configured through the owned type's navigation to the target, when EF found one. + Assert.Contains("modelBuilder.Entity().OwnsOne(x => x.Address, b => b.HasOne(", context); + Assert.Contains(").WithMany().HasForeignKey(e => e.CountryId)", context); Assert.Contains("DeleteBehavior.Restrict", context); Assert.Empty(warnings); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Fr010CodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Fr010CodegenTests.cs index b45f7789bf..30b913309c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Fr010CodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Fr010CodegenTests.cs @@ -58,7 +58,7 @@ public void Parser_emits_extract_api_and_nullable_mirror_for_json() var files = new OutputParserGenerator().Generate(Ctx(Load(Model))).ToList(); var src = Assert.Single(files, f => f.Path.EndsWith(".response.cs")).Content; // ADR-0056 rule 3: the mirror is the value object's, in its own file. - var mirror = Assert.Single(files, f => f.Path == "AnswerPayloadExtracted.g.cs").Content; + var mirror = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "AnswerPayloadExtracted.g.cs").Content; Assert.Contains("using MetaObjects.Render.Extract;", src); // The single (loader-delegating) extract path — no baked snapshot. @@ -107,7 +107,7 @@ public void Parser_emits_extract_for_a_text_bodied_prompt_with_a_json_reply() public void Prompt_generator_emits_render_format_pair() { var file = Assert.Single(new OutputPromptGenerator().Generate(Ctx(Load(Model)))); - Assert.Equal("AnswerOutput.responseFormat.cs", file.Path); + Assert.Equal("AnswerOutput.responseFormat.cs", System.IO.Path.GetFileName(file.Path)); var src = file.Content; Assert.Contains("public static class AnswerOutputResponseFormat", src); Assert.Contains("private static readonly OutputFormatSpec Spec = new OutputFormatSpec(Format.Json, \"AnswerPayload\", PromptStyle.Guide,", src); @@ -131,7 +131,7 @@ public void Prompt_generator_serves_a_text_bodied_prompt() ]}} """; var file = Assert.Single(new OutputPromptGenerator().Generate(Ctx(Load(m)))); - Assert.Equal("TextOut.responseFormat.cs", file.Path); + Assert.Equal("TextOut.responseFormat.cs", System.IO.Path.GetFileName(file.Path)); Assert.Contains("Format.Json", file.Content); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs index 970da34395..4a4e30ebe8 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs @@ -2,7 +2,7 @@ // // Mirrors the TS reference (codegen-ts enum-shared / enum-import / enums-file): // • shared-materialized-once — a ROOT-level abstract field.enum extended by TWO -// entities is emitted ONCE (a shared Enums.g.cs, namespace-level `public enum E`), +// entities is emitted ONCE (its own /.g.cs, namespace-level `public enum E`), // and BOTH entity files REFERENCE it (no nested `public enum E`). // • @provided — `@provided: true` emits NOTHING for the type; consuming entities // reference `.E`; a missing namespace config is a clear @@ -47,11 +47,15 @@ private static GenContext Ctx( { OutDir = "/tmp", Namespace = "Acme.Generated", + OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, ProvidedEnumNamespace = providedNs, PackageNamespaces = packageNamespaces ?? new(), }, }; + /// The header line of a materialized shared enum's own file (item 12). + private const string SharedEnumFileMarker = "(FR-019 shared enum)"; + private const string SharedModel = """ { "metadata.root": { "package": "acme", "children": [ { "field.enum": { "name": "OrderStatus", "abstract": true, "@values": ["DRAFT", "PUBLISHED"] } }, @@ -75,8 +79,8 @@ public void Shared_enum_materialized_exactly_once_and_referenced_by_both_entitie { var files = new EntityGenerator().Generate(Ctx(Load(SharedModel))).ToList(); - // A dedicated shared-enums file is emitted, holding the single materialized enum. - var enumsFile = Assert.Single(files, f => f.Path == "Enums.g.cs"); + // The enum's own file is emitted, holding the single materialized enum. + var enumsFile = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "OrderStatus.g.cs"); Assert.Contains("public enum OrderStatus { DRAFT, PUBLISHED }", enumsFile.Content); // The enum is materialized EXACTLY ONCE across the whole emitted set. @@ -84,12 +88,12 @@ public void Shared_enum_materialized_exactly_once_and_referenced_by_both_entitie Assert.Equal(1, totalDecls); // BOTH entity files reference the shared type (no nested redeclaration). - var order = Assert.Single(files, f => f.Path == "Order.g.cs"); - var shipment = Assert.Single(files, f => f.Path == "Shipment.g.cs"); + var order = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Order.g.cs"); + var shipment = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Shipment.g.cs"); foreach (var ef in new[] { order, shipment }) { Assert.DoesNotContain("public enum OrderStatus", ef.Content); - Assert.Contains("public OrderStatus? Status { get; set; }", ef.Content); + Assert.Contains("public global::Acme.OrderStatus? Status { get; set; }", ef.Content); } } @@ -134,7 +138,7 @@ public void Shared_enum_set_compiles() // (ResolveSharedEnumDecl requires both). A field that extends another ENTITY's // concrete field — the ordinary way a projection restates a column it reads, e.g. // `ShipmentSummary.status extends "Shipment.status"` — resolves a super but shares - // nothing: no Enums.g.cs entry is emitted for it and no type of that name exists. + // nothing: no shared-enum file is emitted for it and no type of that name exists. // // EnumTypeName used to take the super's simple name unconditionally, so such a field // nested `public enum Status` inside a class that also declares `public Status Status @@ -162,7 +166,7 @@ public void Shared_enum_set_compiles() public void A_field_extending_another_entitys_enum_keeps_the_entity_qualified_type_name() { var files = new EntityGenerator().Generate(Ctx(Load(ProjectionModel))).ToList(); - var summary = Assert.Single(files, f => f.Path == "ShipmentSummary.g.cs"); + var summary = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "ShipmentSummary.g.cs"); // Entity-qualified, so it cannot collide with the property of the same name. Assert.Contains("public enum ShipmentSummaryStatus", summary.Content); @@ -171,7 +175,7 @@ public void A_field_extending_another_entitys_enum_keeps_the_entity_qualified_ty Assert.DoesNotContain("public enum Status ", summary.Content); // Nothing is shared, so nothing is materialized centrally either. - Assert.DoesNotContain(files, f => f.Path == "Enums.g.cs"); + Assert.DoesNotContain(files, f => f.Content.Contains(SharedEnumFileMarker)); } [Fact] @@ -201,11 +205,11 @@ public void Provided_enum_is_not_materialized_and_referenced_via_configured_name var files = new EntityGenerator().Generate(Ctx(Load(ProvidedModel), providedNs: "Acme.External.Enums")).ToList(); // NOTHING is emitted for the provided type: no shared file, no nested decl. - Assert.DoesNotContain(files, f => f.Path == "Enums.g.cs"); + Assert.DoesNotContain(files, f => f.Content.Contains(SharedEnumFileMarker)); Assert.All(files, f => Assert.DoesNotContain("public enum ContactMethod", f.Content)); // The consuming entity references the externally-provided type at the configured namespace. - var customer = Assert.Single(files, f => f.Path == "Customer.g.cs"); + var customer = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Customer.g.cs"); Assert.Contains("public Acme.External.Enums.ContactMethod? Preferred { get; set; }", customer.Content); } @@ -248,8 +252,8 @@ public void Provided_enum_namespace_resolves_from_its_declaring_package() var files = new EntityGenerator().Generate( Ctx(root, packageNamespaces: new() { ["acme::ext::auth"] = "Acme.External.Auth" })).ToList(); - Assert.DoesNotContain(files, f => f.Path == "Enums.g.cs"); - var customer = Assert.Single(files, f => f.Path == "Customer.g.cs"); + Assert.DoesNotContain(files, f => f.Content.Contains(SharedEnumFileMarker)); + var customer = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Customer.g.cs"); Assert.Contains("public Acme.External.Auth.ContactMethod? Preferred { get; set; }", customer.Content); } @@ -262,7 +266,7 @@ public void Package_namespace_map_takes_precedence_over_the_single_fallback() providedNs: "Acme.Fallback", packageNamespaces: new() { ["acme::ext::auth"] = "Acme.External.Auth" })).ToList(); - var customer = Assert.Single(files, f => f.Path == "Customer.g.cs"); + var customer = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Customer.g.cs"); Assert.Contains("public Acme.External.Auth.ContactMethod? Preferred { get; set; }", customer.Content); Assert.DoesNotContain("Acme.Fallback", customer.Content); } @@ -274,7 +278,7 @@ public void Single_namespace_fallback_applies_when_package_is_unmapped() var files = new EntityGenerator().Generate( Ctx(root, providedNs: "Acme.Fallback")).ToList(); // no PackageNamespaces entry - var customer = Assert.Single(files, f => f.Path == "Customer.g.cs"); + var customer = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Customer.g.cs"); Assert.Contains("public Acme.Fallback.ContactMethod? Preferred { get; set; }", customer.Content); } @@ -305,10 +309,65 @@ public void Inline_enum_still_emits_nested_declaration_unchanged() var files = new EntityGenerator().Generate(Ctx(Load(inlineModel))).ToList(); // No shared file for an inline enum. - Assert.DoesNotContain(files, f => f.Path == "Enums.g.cs"); - var order = Assert.Single(files, f => f.Path == "Order.g.cs"); + Assert.DoesNotContain(files, f => f.Content.Contains(SharedEnumFileMarker)); + var order = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Order.g.cs"); // Nested, per-entity enum type name () — exactly as before FR-019. Assert.Contains("public enum OrderStatus { DRAFT, PUBLISHED, ARCHIVED }", order.Content); Assert.Contains("public OrderStatus? Status { get; set; }", order.Content); } + + // ---- item 12: a shared enum is a type like any other ---- + // + // One /.g.cs per materialized enum (OutputPaths.Of, ruling R39), in the + // namespace shared enums already land in (Config.Namespace; Q6 leaves namespaces alone). + // Its members carry their @intValueMap integers, and @enumDoc / @description become XML docs. + + private const string DocumentedModel = """ + { "metadata.root": { "package": "acme::billing", "children": [ + { "field.enum": { "name": "Priority", "abstract": true, "@values": ["LOW", "HIGH"], + "@intValueMap": { "LOW": 10, "HIGH": 20 }, + "@description": "How urgent a ticket is.", + "@enumDoc": { "LOW": "Handle when convenient.", "HIGH": "Handle & first." } } }, + { "field.enum": { "name": "Channel", "abstract": true, "@values": ["EMAIL", "PHONE"] } }, + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "priority", "extends": "Priority" } }, + { "field.enum": { "name": "channel", "extends": "Channel" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void Each_shared_enum_is_its_own_file_under_its_package() + { + var files = new EntityGenerator().Generate(Ctx(Load(DocumentedModel))).ToList(); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "Enums.g.cs"); + var priority = Assert.Single(files, f => f.Path == "acme/billing/Priority.g.cs"); + var channel = Assert.Single(files, f => f.Path == "acme/billing/Channel.g.cs"); + Assert.Contains("namespace Acme.Billing;", priority.Content); + Assert.Contains("namespace Acme.Billing;", channel.Content); + Assert.Contains("public enum Channel { EMAIL, PHONE }", channel.Content); + } + + [Fact] + public void A_shared_enum_carries_its_int_values_and_its_docs() + { + var files = new EntityGenerator().Generate(Ctx(Load(DocumentedModel))).ToList(); + var priority = Assert.Single(files, f => f.Path == "acme/billing/Priority.g.cs").Content; + Assert.Contains("/// How urgent a ticket is.\npublic enum Priority", priority.Replace("\r\n", "\n")); + Assert.Contains(" /// Handle when convenient.\n LOW = 10,", priority.Replace("\r\n", "\n")); + Assert.Contains(" /// Handle <now> & first.\n HIGH = 20,", priority.Replace("\r\n", "\n")); + } + + [Fact] + public void The_documented_enum_set_compiles() + { + var ctx = Ctx(Load(DocumentedModel)); + var files = new EntityGenerator().Generate(ctx) + .Concat(new NamesGenerator().Generate(ctx)) + .Concat(new DbContextGenerator().Generate(ctx)).ToList(); + AssertCompiles(files, "documented"); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs new file mode 100644 index 0000000000..2c92e056e9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs @@ -0,0 +1,125 @@ +// ADR-0062: with no GenConfig.ContextAssemblyName, the DbContext generator names its design-time +// services reference after the .csproj in --out or above it. That file is an input of the run, so +// the key moves when it does, even though it lies outside codegen/ and .metaobjects/. + +#nullable enable + +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using Xunit; + +[Collection("Console")] +public sealed class GenFingerprintProjectFileTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "meta-projfile-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } + + private string Key() => GenFingerprint.Key(GenFingerprint.IdentityEntries( + _root, _root, new GenFingerprint.Options { OutDir = Path.Combine("app", "Generated") }, [])); + + private static string Csproj(string assembly) => + $"{assembly}\n"; + + [Fact] + public void Renaming_the_assembly_of_the_output_project_changes_the_key() + { + Directory.CreateDirectory(Path.Combine(_root, "app", "Generated")); + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("First")); + var first = Key(); + Assert.Equal(first, Key()); + + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("Second")); + + Assert.NotEqual(first, Key()); + } + + [Fact] + public void A_project_created_after_a_run_without_one_changes_the_key() + { + Directory.CreateDirectory(Path.Combine(_root, "app", "Generated")); + var without = Key(); + + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("App")); + + Assert.NotEqual(without, Key()); + } + + // ---- end to end: `dotnet meta gen` on a Postgres project whose .csproj sits above --out + + private string Meta => Path.Combine(_root, "metaobjects"); + private string Out => Path.Combine(_root, "gen"); + private string Services => Path.Combine(Out, "AppDbContextDesignTimeServices.g.cs"); + private string StateFile => Path.Combine(_root, ".metaobjects", ".gen-state", GenFingerprint.FileName); + + private void Project(string assembly) + { + Directory.CreateDirectory(Meta); + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), """{ "schema_version": 1, "migrate": { "dialect": "postgres" } }"""); + File.WriteAllText(Path.Combine(Meta, "meta.acme.json"), """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment", "@sequenceStart": 100 } } + ]}} + ]}} + """); + File.WriteAllText(Path.Combine(_root, "App.csproj"), Csproj(assembly)); + } + + private (int Code, string Text) Gen() + { + var (cwd, prevOut, prevErr) = (Directory.GetCurrentDirectory(), Console.Out, Console.Error); + var (o, e) = (new StringWriter(), new StringWriter()); + Directory.SetCurrentDirectory(_root); + Console.SetOut(o); + Console.SetError(e); + try { return (CodegenCli.Run(["gen", Meta, "--out", Out, "--namespace", "Acme.Generated"], [new DbContextGenerator()]), o + "\n" + e); } + finally { Console.SetOut(prevOut); Console.SetError(prevErr); Directory.SetCurrentDirectory(cwd); } + } + + private static string Reference(string assembly) => + $"DesignTimeServicesReference(\"Acme.Generated.AppDbContextDesignTimeServices, {assembly}\""; + + [Fact] + public void Renaming_the_assembly_renders_again_and_the_reference_names_the_new_one() + { + Project("First"); + var (first, firstText) = Gen(); + Assert.True(first == 0, firstText); + Assert.Contains(Reference("First"), File.ReadAllText(Services)); + var (again, againText) = Gen(); + Assert.True(again == 0, againText); + Assert.Contains("nothing changed since the last run; skipped", againText); + + File.WriteAllText(Path.Combine(_root, "App.csproj"), Csproj("Second")); + var (renamed, renamedText) = Gen(); + + Assert.True(renamed == 0, renamedText); + Assert.DoesNotContain("skipped", renamedText); + Assert.Contains(Reference("Second"), File.ReadAllText(Services)); + } + + [Fact] + public void A_state_file_of_the_previous_format_is_not_a_match_and_gen_renders() + { + Project("App"); + var (first, firstText) = Gen(); + Assert.True(first == 0, firstText); + Assert.True(File.Exists(StateFile), firstText); + var stored = File.ReadAllText(StateFile); + Assert.Contains($"\"format\": {GenFingerprint.FormatVersion}", stored); + File.WriteAllText(StateFile, stored.Replace($"\"format\": {GenFingerprint.FormatVersion}", "\"format\": 3")); + + Assert.Null(GenFingerprint.Read(_root)); + var (second, secondText) = Gen(); + Assert.True(second == 0, secondText); + Assert.DoesNotContain("skipped", secondText); + Assert.Contains($"\"format\": {GenFingerprint.FormatVersion}", File.ReadAllText(StateFile)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs index 5c14e509e9..428a5ffe0c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs @@ -1080,4 +1080,26 @@ public void Reference_on_abstract_tph_intermediate_is_configured() g.Generate(GeneratorGoldenTests.Round2Context(shapes: true)).ToList(); Assert.Single(g.Calls, c => c == "ReferenceConfig:CaseJob.refWorkflow"); } + + // rc.21 part B (U2): a text @dbColumnType spelling is the EF column type, as meta migrate creates it. + [Fact] + public void A_text_db_column_type_spelling_is_the_column_type() + { + var root = Load(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Region", "children": [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)" } }, + { "field.string": { "name": "label", "@dbColumnType": "varchar" } }, + { "field.string": { "name": "note", "@dbColumnType": "varchar(20)" } }, + { "field.string": { "name": "body", "@dbColumnType": "text" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } } ] } } + """); + var db = Db(new DbContextGenerator(), root); + Assert.Contains(".Property(x => x.Code).HasColumnType(\"character(3)\");", db); + Assert.Contains(".Property(x => x.Label).HasColumnType(\"character varying\");", db); + Assert.Contains(".Property(x => x.Note).HasColumnType(\"character varying(20)\");", db); + Assert.Contains(".Property(x => x.Body).HasColumnType(\"text\");", db); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs index e7d3471a19..f39524545a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs @@ -36,7 +36,7 @@ private static GenContext Ctx() return new GenContext { Entities = r.Root.Objects(), Root = r.Root, - Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, }; } @@ -76,8 +76,8 @@ public void A_scoped_closure_drops_the_value_objects_include_rejects() public void DbContext_include_maps_only_the_accepted_objects() { var src = Assert.Single(new DbContextGenerator { Include = o => o.Name is "Customer" }.Generate(Ctx())).Content; - Assert.Contains("DbSet", src); - Assert.DoesNotContain("DbSet", src); + Assert.Contains("DbSet", src); + Assert.DoesNotContain("DbSet", src); } [Fact] @@ -103,4 +103,106 @@ public void No_include_is_unchanged_and_narrow_keeps_the_root() Assert.Single(narrowed.Entities); Assert.Same(ctx.Root, narrowed.Root); } + + // G2, rc.20: a narrowed entry declares the shared enums of what it emits, not the whole model's, + // so two entries splitting the model do not both declare one enum. + private const string SharedEnums = """ + { "metadata.root": { "package": "acme", "children": [ + { "field.enum": { "name": "OrderStatus", "abstract": true, "@values": ["DRAFT", "PLACED"] } }, + { "field.enum": { "name": "Tier", "abstract": true, "@values": ["GOLD", "SILVER"] } }, + { "field.enum": { "name": "Mood", "abstract": true, "@values": ["CALM", "LOUD"] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "extends": "OrderStatus" } }, + { "field.object": { "name": "note", "@objectRef": "Note" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "tier", "extends": "Tier" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.value": { "name": "Note", "children": [ { "field.enum": { "name": "mood", "extends": "Mood" } } ]}} + ]}} + """; + + private static string SharedEnumPaths(EntityGenerator g) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(SharedEnums, id: "enums.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, + }; + return string.Join("|", g.Generate(ctx).Select(f => f.Path).OrderBy(p => p)); + } + + [Fact] + public void A_narrowed_entry_declares_only_the_shared_enums_it_uses() + { + var all = SharedEnumPaths(new EntityGenerator()); + Assert.Contains("OrderStatus.g.cs", all); + Assert.Contains("Tier.g.cs", all); + Assert.Contains("Mood.g.cs", all); + + var orders = SharedEnumPaths(new EntityGenerator { Include = o => o.Name is "Order" }); + Assert.Contains("OrderStatus.g.cs", orders); + // The value object Order reaches is emitted, so the enum it uses is too. + Assert.Contains("Note.g.cs", orders); + Assert.Contains("Mood.g.cs", orders); + Assert.DoesNotContain("Tier.g.cs", orders); + + var customers = SharedEnumPaths(new EntityGenerator { Include = o => o.Name is "Customer" }); + Assert.Contains("Tier.g.cs", customers); + Assert.DoesNotContain("OrderStatus.g.cs", customers); + Assert.DoesNotContain("Mood.g.cs", customers); + } + + // G2, rc.20 fix round 1: an enum both narrowed entries use is declared by exactly one of them, + // the one that emits its first consumer by resolution key, so their outputs build together. + private const string BothUse = """ + { "metadata.root": { "package": "acme", "children": [ + { "field.enum": { "name": "Level", "abstract": true, "@values": ["LOW", "HIGH"] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "level", "extends": "Level" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "level", "extends": "Level" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void An_enum_both_narrowed_entries_use_is_declared_once() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(BothUse, id: "both.json")]); + Assert.Empty(r.Errors); + // One run, one claim registry, as two entries of one generator list share. + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, + }; + var orders = new EntityGenerator { Include = o => o.Name is "Order" }.Generate(ctx).ToList(); + var customers = new EntityGenerator { Include = o => o.Name is "Customer" }.Generate(ctx).ToList(); + // Customer sorts first (acme::Customer < acme::Order), so its entry declares Level. + Assert.Contains(customers, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + Assert.DoesNotContain(orders, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + // Order still names it. + Assert.Contains("global::Acme.Level", Assert.Single(orders, f => f.Path.EndsWith("Order.g.cs", StringComparison.Ordinal)).Content); + var errors = PackageNamespaceTests.CompileErrors(orders.Concat(customers)); + Assert.True(errors.Count == 0, "the two entries' output should build together, but got:\n" + string.Join("\n", errors)); + // Un-narrowed, it is declared as before. + Assert.Single(new EntityGenerator().Generate(ctx), f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + } } + diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index ea333e5be1..c86309703f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -22,6 +22,8 @@ public sealed class GeneratorRegistryTests "callable", // Program A / §A5 — per-object physical database name constants. "names", + // The @expr indexes the EF model cannot carry, as SQL (C#-only). + "expression-indexes", // ADR-0057 — per-requirement xUnit tests calling a project-owned witness. "requirement-tests", // FR-023 — publishes a shared model: the artifact and the manifest a consumer syncs. diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs new file mode 100644 index 0000000000..c62f7d703e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs @@ -0,0 +1,127 @@ +// +// Generated by MetaObjects dbcontext-generator. Do not edit by hand. +#nullable enable +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace Acme.Generated; + +public class AppDbContext : DbContext +{ + public AppDbContext(DbContextOptions options) : base(options) { } + + public DbSet Gizmos { get; set; } = default!; + public DbSet Lines { get; set; } = default!; + public DbSet LineTotals { get; set; } = default!; + public DbSet Tags { get; set; } = default!; + public DbSet Vehicles { get; set; } = default!; + public DbSet VehicleTags { get; set; } = default!; + public DbSet WidgetSummaries { get; set; } = default!; + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasNoKey().ToView("v_line_totals"); + modelBuilder.Entity().HasNoKey().ToView("fn_widget_summary"); + modelBuilder.Entity().OwnsOne(x => x.Dims, b => b.ToJson("dims")); + modelBuilder.Entity().Property(x => x.Extras).HasColumnType("jsonb").HasConversion(MapJsonb.Converter(), MapJsonb.Comparer()); + modelBuilder.Entity().Property(x => x.CreatedAt).HasColumnType("timestamp with time zone"); + modelBuilder.Entity().Property(x => x.UpdatedAt).HasColumnType("timestamp with time zone"); + modelBuilder.Entity().Property(x => x.Stamp).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + modelBuilder.Entity().Property(x => x.Serial).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") modelBuilder.Entity().Property(x => x.Id).HasAnnotation("Npgsql:IdentitySequenceOptions", "'500', '1', '', '', 'False', '1'"); + modelBuilder.Entity().Property(x => x.Kind).HasConversion(); + modelBuilder.Entity().ToTable(t => t.HasCheckConstraint("vehicles_kind_chk", "\"kind\" IN ('Car', 'Van')")); + modelBuilder.Entity().HasMany(x => x.Tags).WithMany().UsingEntity(l => l.HasOne().WithMany().HasForeignKey(j => j.TagId), r => r.HasOne().WithMany().HasForeignKey(j => j.VehicleId)); + modelBuilder.Entity().HasDiscriminator(e => e.Kind).HasValue(global::Acme.Shop.Vehicle.VehicleKind.Car).HasValue(global::Acme.Shop.Vehicle.VehicleKind.Van); + modelBuilder.Entity().Property(x => x.RegNo).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + } + + /// + /// Shared jsonb (de)serialization for field.map columns. The comparer is required: + /// EF snapshots a value-converted property by reference, so without it an in-place + /// edit to the dictionary is never detected and the row is never updated. + /// + private static class MapJsonb + { + private static readonly System.Text.Json.JsonSerializerOptions Options = new() + { + Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } + }; + + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + System.Collections.Generic.Dictionary, string> RequiredConverter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>(v, Options)!); + + /// Same conversion as RequiredConverter, over the NULLABLE dictionary a + /// non-required map's property carries — keep the two bodies identical. EF Core's + /// nullability-aware HasConversion checks the converter's model type against the + /// property's own annotation, so one factory cannot serve both arms. + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + System.Collections.Generic.Dictionary?, string> Converter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>(v, Options)!); + + /// A whole value-object document (or collection of them) as one jsonb value, + /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON). + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize(v, Options)!); + + internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( + (a, b) => System.Text.Json.JsonSerializer.Serialize(a, Options) == System.Text.Json.JsonSerializer.Serialize(b, Options), + v => System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), + v => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); + + internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< + System.Collections.Generic.Dictionary?> Comparer() => new( + (a, b) => Eq(a, b), v => Hash(v), v => Snap(v)); + + /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key + /// order holds the same value, and comparing serialized JSON would call it changed + /// and issue an UPDATE for a row nothing touched. Scalars settle on the default + /// comparer (no serialization at all); a value-object value falls through to a JSON + /// compare, since the generated POCO is a class and compares by reference. + private static bool Eq( + System.Collections.Generic.Dictionary? a, + System.Collections.Generic.Dictionary? b) + { + if (a is null || b is null) return ReferenceEquals(a, b); + if (a.Count != b.Count) return false; + foreach (var kv in a) + { + if (!b.TryGetValue(kv.Key, out var other)) return false; + if (System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; + if (System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) + != System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; + } + return true; + } + + /// Keys and count only — order-independent (XOR), allocation-free, and + /// stable for a value-object value whose GetHashCode is reference-based. Equal + /// dictionaries always hash equal, which is all EF requires. + private static int Hash(System.Collections.Generic.Dictionary? v) + { + if (v is null) return 0; + var h = v.Count; + foreach (var k in v.Keys) h ^= k.GetHashCode(); + return h; + } + + /// The change-tracking snapshot. A value-object value needs a DEEP copy or + /// an in-place edit to a nested object mutates the snapshot too and goes undetected; + /// an immutable scalar only needs the dictionary copied. + private static System.Collections.Generic.Dictionary? Snap( + System.Collections.Generic.Dictionary? v) => + v is null + ? null + : typeof(TValue).IsValueType || typeof(TValue) == typeof(string) + ? new System.Collections.Generic.Dictionary(v) + : System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>( + System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs new file mode 100644 index 0000000000..41dc086cbd --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs @@ -0,0 +1,200 @@ +// +// Generated by MetaObjects db-context. Do not edit by hand. +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; + +namespace Acme.Generated; + +/// Design-time only: a start-only identity change scaffolds as SQL that records the +/// start and moves the counter forward to it, never back, instead of Npgsql's RESTART; and a +/// JSON column's comment, which EF 8 cannot carry, scaffolds as COMMENT ON COLUMN. EF runs +/// it for dotnet ef migrations add; nothing is registered at runtime. +public sealed class AppDbContextDesignTimeServices : IDesignTimeServices +{ + private const string Options = "Npgsql:IdentitySequenceOptions"; + private const string Strategy = "Npgsql:ValueGenerationStrategy"; + + /// Wraps the differ already registered (the context's own, by default), once. + public void ConfigureDesignTimeServices(IServiceCollection services) + { + // Found by the startup scan and by the reference both, or one such class per + // context in one assembly (EF applies every reference): wrap once. The marker is + // matched by name, so another context's services class counts too. + if (services.Any(d => d.ServiceType.Name == nameof(MetaObjectsDesignTimeApplied))) return; + services.AddSingleton(); + var inner = services.LastOrDefault(d => d.ServiceType == typeof(IMigrationsModelDiffer) && d.ServiceKey is null); + services.Add(new ServiceDescriptor(typeof(IMigrationsModelDiffer), + sp => new Differ(Resolve(inner, sp), sp.GetRequiredService().Context.GetService()), + inner?.Lifetime ?? ServiceLifetime.Transient)); + } + + private sealed class MetaObjectsDesignTimeApplied { } + + private static IMigrationsModelDiffer Resolve(ServiceDescriptor? inner, IServiceProvider sp) => inner switch + { + { ImplementationInstance: IMigrationsModelDiffer differ } => differ, + { ImplementationFactory: { } factory } => (IMigrationsModelDiffer)factory(sp), + { ImplementationType: { } type } => (IMigrationsModelDiffer)ActivatorUtilities.CreateInstance(sp, type), + _ => sp.GetRequiredService().Context.GetService(), + }; + + private sealed class Differ(IMigrationsModelDiffer inner, ISqlGenerationHelper sql) : IMigrationsModelDiffer + { + // A JSON column's comment is a difference the inner differ cannot see, so a change to it alone + // must still count: has-pending-model-changes and `migrations add` read this, not GetDifferences. + public bool HasDifferences(IRelationalModel? source, IRelationalModel? target) => + inner.HasDifferences(source, target) || JsonColumnComments(source, target, sql).Any(); + + public IReadOnlyList GetDifferences(IRelationalModel? source, IRelationalModel? target) + { + var result = new List(); + foreach (var operation in inner.GetDifferences(source, target)) + { + if (operation is not AlterColumnOperation alter || StartChange(alter, sql) is not { } change) + { + result.Add(operation); + continue; + } + result.AddRange(change.Statements.Select(s => new SqlOperation { Sql = s })); + if (OnlyTheStart(alter, change.OldOptions)) continue; + // The rest of the change, with the old start made the new one: no start change is left in it. + alter.OldColumn[Options] = change.OldOptions; + result.Add(alter); + } + result.AddRange(JsonColumnComments(source, target, sql).Select(s => new SqlOperation { Sql = s })); + return result; + } + } + + // Ruling R59: EF 8's JsonColumn carries no comment, so a JSON column's comment rides on + // its owned type as an annotation and is scaffolded here, after every other operation + // (a new table's column exists by then). Down is the same diff the other way. + private const string JsonComment = "MetaObjects:JsonColumnComment"; + + private static IEnumerable JsonColumnComments(IRelationalModel? source, IRelationalModel? target, ISqlGenerationHelper sql) + { + var from = JsonCommentsOf(source); + foreach (var (column, text) in JsonCommentsOf(target)) + if (!from.TryGetValue(column, out var old) || old != text) + yield return CommentOn(column, text, sql); + foreach (var (column, _) in from) + if (!JsonCommentsOf(target).ContainsKey(column) + && target?.FindTable(column.Table, column.Schema)?.FindColumn(column.Column) is not null) + yield return CommentOn(column, null, sql); + } + + private static Dictionary<(string? Schema, string Table, string Column), string> JsonCommentsOf(IRelationalModel? model) + { + var comments = new Dictionary<(string? Schema, string Table, string Column), string>(); + if (model is null) return comments; + foreach (var type in model.Model.GetEntityTypes()) + if (type.FindAnnotation(JsonComment)?.Value is string text + && type.GetContainerColumnName() is { } column && type.GetTableName() is { } table) + comments[(type.GetSchema(), table, column)] = text; + return comments; + } + + private static string CommentOn((string? Schema, string Table, string Column) c, string? text, ISqlGenerationHelper sql) => + "COMMENT ON COLUMN " + sql.DelimitIdentifier(c.Table, c.Schema) + "." + sql.DelimitIdentifier(c.Column) + + " IS " + (text is null ? "NULL" : Literal(text)) + sql.StatementTerminator; + + // The serialized options are "'start', 'increment', 'min', 'max', 'cyclic', 'cache'"; + // a missing annotation is Npgsql's defaults, and an empty start is no start. + private const string Defaults = "'', '1', '', '', 'False', '1'"; + private static string[] Parts(string? options) => (options ?? Defaults).Split(',').Select(p => p.Trim().Trim('\'')).ToArray(); + private static string? Start(string? options) => Parts(options)[0] is { Length: > 0 } start ? start : null; + + /// with the start replaced: what the old column + /// must say for Npgsql to see no start change. + private static string WithStart(string? options, string? start) => + "'" + (start ?? "") + "'" + (options ?? Defaults)[(options ?? Defaults).IndexOf(',')..]; + + private static bool Descending(string? options) => long.TryParse(Parts(options)[1], out var increment) && increment < 0; + + /// Where an identity without a start begins: its minimum ascending, its + /// maximum descending (PostgreSQL's default). + private static string DefaultStart(string? options) + { + var p = Parts(options); + return Descending(options) ? (p[3] is { Length: > 0 } max ? max : "-1") : (p[2] is { Length: > 0 } min ? min : "1"); + } + + private static bool IsIdentity(object? strategy) => strategy?.ToString()?.StartsWith("Identity", StringComparison.Ordinal) == true; + + private static string Literal(string text) => "'" + text.Replace("'", "''") + "'"; + + /// The SQL of the start-only change an alter carries, or null when it moves no start. + private static (IReadOnlyList Statements, string OldOptions)? StartChange(AlterColumnOperation operation, ISqlGenerationHelper sql) + { + if (!IsIdentity(operation[Strategy]) || !IsIdentity(operation.OldColumn[Strategy])) return null; + var to = operation[Options] as string; + var from = operation.OldColumn[Options] as string; + if (Start(to) == Start(from)) return null; + var table = sql.DelimitIdentifier(operation.Table, operation.Schema); + var column = sql.DelimitIdentifier(operation.Name); + var statements = new List + { + "ALTER TABLE " + table + " ALTER COLUMN " + column + " SET START WITH " + (Start(to) ?? DefaultStart(to)) + sql.StatementTerminator, + }; + // A declared start also moves the counter forward to it, or past the highest id, and + // never back. A removed start, or a descending identity, records the start only. + if (Start(to) is { } start && !Descending(to)) + statements.Add( + "DO $$\n" + + "DECLARE\n" + + " mo_seq regclass := pg_get_serial_sequence(" + Literal(table) + ", " + Literal(operation.Name) + ")::regclass;\n" + + " mo_target bigint;\n" + + " mo_next bigint;\n" + + "BEGIN\n" + + " SELECT GREATEST(" + start + ", COALESCE(MAX(" + column + "), 0) + 1) INTO mo_target FROM " + table + ";\n" + + " EXECUTE 'SELECT CASE WHEN is_called THEN last_value + ' || (SELECT seqincrement FROM pg_sequence WHERE seqrelid = mo_seq)\n" + + " || ' ELSE last_value END FROM ' || mo_seq INTO mo_next;\n" + + " IF mo_next < mo_target THEN PERFORM setval(mo_seq, mo_target, false); END IF;\n" + + "END $$;"); + return (statements, WithStart(from, Start(to))); + } + + /// Whether the alter changes nothing but its identity start. + private static bool OnlyTheStart(AlterColumnOperation operation, string oldOptions) + { + var o = operation.OldColumn; + if (operation.ClrType != o.ClrType || operation.ColumnType != o.ColumnType || operation.IsNullable != o.IsNullable + || operation.IsUnicode != o.IsUnicode || operation.IsFixedLength != o.IsFixedLength || operation.MaxLength != o.MaxLength + || operation.Precision != o.Precision || operation.Scale != o.Scale || operation.IsRowVersion != o.IsRowVersion + || !Equals(operation.DefaultValue, o.DefaultValue) || operation.DefaultValueSql != o.DefaultValueSql + || operation.ComputedColumnSql != o.ComputedColumnSql || operation.IsStored != o.IsStored + || operation.Comment != o.Comment || operation.Collation != o.Collation) + return false; + var names = operation.GetAnnotations().Select(a => a.Name).Union(o.GetAnnotations().Select(a => a.Name)); + return names.All(n => n == Options + ? Parts(operation[n] as string).SequenceEqual(Parts(oldOptions)) + : Equals(operation[n], o[n])); + } +} + +/// Kept for one release so code written against the earlier runtime registration still +/// compiles. It does nothing: the identity start is applied at design time. +public static class AppDbContextIdentityStartMigrations +{ + private const string Message = "UseIdentityStartMigrations() is no longer needed and does nothing: the identity start is " + + "applied at design time by AppDbContextDesignTimeServices, which dotnet ef migrations add finds on its own. Remove the call."; + + /// Does nothing. + [Obsolete(Message)] + public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) => options; + + /// Does nothing. + [Obsolete(Message)] + public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) + where TContext : DbContext => options; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs new file mode 100644 index 0000000000..bc27216e3c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Car. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class CarFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs new file mode 100644 index 0000000000..c4ab21e8d7 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs @@ -0,0 +1,54 @@ +// +// Generated by MetaObjects extractor-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using MetaObjects.Render.Extract; + +namespace Acme.Generated; + +/// The extract tier for the GadgetOut template.prompt — turns dirty LLM +/// text into a fully-typed graph (nested objects + arrays-of-objects +/// populated) in one call, by delegating to the nested-capable extract and mapping the all-nullable +/// GadgetExtracted mirror onto the value object. No registry / binding / factory. +public static class GadgetOutExtractor +{ + /// Extract a fully-typed from dirty using + /// the runtime (the loaded value object). Runs the tolerant extract, then maps + /// the extracted mirror onto the value object. + /// iff a @required field was lost or malformed (the strict opt-in gate). + public static global::Acme.Shop.Gadget Extract(global::MetaObjects.Meta.MetaObject mo, string text) + { + var r = GadgetOutParser.ExtractLenient(mo, text); + if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired()) + throw new ExtractException(r.Report); + return ToStrict_Gadget(r.Data!); + } + + /// Extract with explicit . + /// iff a @required field was lost or malformed. + public static global::Acme.Shop.Gadget Extract(global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions opts) + { + var r = GadgetOutParser.ExtractLenient(mo, text, opts); + if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired()) + throw new ExtractException(r.Report); + return ToStrict_Gadget(r.Data!); + } + + /// Re-exposes the nested-capable tolerant extract; never throws. Inspect Report for + /// lost/defaulted fields. Returns the all-nullable mirror (not the value object). + public static ExtractionResult ExtractLenient(global::MetaObjects.Meta.MetaObject mo, string text) => + GadgetOutParser.ExtractLenient(mo, text); + + /// Map the all-nullable GadgetExtracted mirror onto Gadget. Generated. + private static global::Acme.Shop.Gadget ToStrict_Gadget(global::Acme.Shop.GadgetExtracted m) => new global::Acme.Shop.Gadget + { + GadgetId = m.gadgetId!, + Part = m.part is null ? null : ToStrict_Part(m.part), + }; + + /// Map the all-nullable PartExtracted mirror onto Part. Generated. + private static global::Acme.Shop.Part ToStrict_Part(global::Acme.Shop.PartExtracted m) => new global::Acme.Shop.Part + { + PartName = m.partName!, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs new file mode 100644 index 0000000000..feb66b9426 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Gizmo. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class GizmoFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + "title", + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + ["title"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs new file mode 100644 index 0000000000..dc726e1a64 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -0,0 +1,312 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class GizmoRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Title", + "Stamp", + "Serial", + "PinHash", + "TokenHash", + "CreatedAt", + "UpdatedAt", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + ["Title"] = true, + }; + + // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. + private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + { + "createdAt", + "dims", + "extras", + "id", + "pinHash", + "serial", + "stamp", + "title", + "tokenHash", + "updatedAt", + }; + + /// Maps Gizmo REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapGizmoRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Gizmos.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, GizmoFilterAllowlist.Fields, GizmoFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortGizmo(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "PinHash" }); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Gizmos.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "PinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Gizmos.FindAsync(id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "PinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + System.Text.Json.JsonDocument __body; + try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + var __issues = new ValidationIssues(); + var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase); + foreach (var __p in __body.RootElement.EnumerateObject()) + if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name); + foreach (var __req in new[] { "title" }) + if (!__present.Contains(__req)) __issues.AddRequired(__req); + Gizmo? input = null; + try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Gizmo)); } + if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.PinHash = default!; + input.TokenHash = default!; + __issues.ValidateObjectExcept(input, jsonOpts, new[] { "Serial" }); + ValueObjectValidator.Collect(input.Dims, __issues, jsonOpts, "dims"); + ValueObjectValidator.Collect(input.Extras, __issues, jsonOpts, "extras"); + if (__issues.Any) return __issues.ToResult(); + input.CreatedAt = System.DateTimeOffset.UtcNow; + input.UpdatedAt = System.DateTimeOffset.UtcNow; + db.Gizmos.Add(input); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "PinHash" }, status: 201, location: prefix + "/gizmos"); + }); + + async System.Threading.Tasks.Task UpdateGizmo(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Gizmos.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + System.Text.Json.JsonDocument body; + try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var bodyScope = body; + if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + existing.UpdatedAt = System.DateTimeOffset.UtcNow; + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); + var __issues = new ValidationIssues(); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "PinHash" or "TokenHash") continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "pinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "tokenHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "dims", System.StringComparison.OrdinalIgnoreCase) || __clr == "Dims") + { + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + existing.Dims = null; + continue; + } + global::Acme.Shop.Dims __vo0; + try { __vo0 = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), jsonOpts); } + catch (System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "dims"); continue; } + if (!ValueObjectValidator.Collect(__vo0, __issues, jsonOpts, "dims")) continue; + existing.Dims = __vo0; + continue; + } + if (string.Equals(prop.Name, "extras", System.StringComparison.OrdinalIgnoreCase) || __clr == "Extras") + { + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { existing.Extras = null; continue; } + System.Collections.Generic.Dictionary? __map0; + try { __map0 = System.Text.Json.JsonSerializer.Deserialize>(prop.Value.GetRawText(), jsonOpts); } + catch (System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "extras"); continue; } + if (!ValueObjectValidator.Collect(__map0, __issues, jsonOpts, "extras")) continue; + existing.Extras = __map0; + continue; + } + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "CreatedAt", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "UpdatedAt", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "Stamp", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (string.Equals(target.Name, "Serial", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) { __issues.AddRequired(__wire); continue; } + entry.CurrentValues[target] = null; + continue; + } + var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + object? __val; + try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue; + entry.CurrentValues[target] = __val; + } + if (__issues.Any) return __issues.ToResult(); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "PinHash" }); + } + app.MapPatch(prefix + "/gizmos/{id}", UpdateGizmo); + app.MapPut(prefix + "/gizmos/{id}", UpdateGizmo); + + app.MapDelete(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Gizmos.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Gizmos.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortGizmo(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Title" => desc ? q.OrderByDescending(x => EF.Property(x!, "Title") == null).ThenByDescending(x => EF.Property(x!, "Title")) : q.OrderBy(x => EF.Property(x!, "Title") == null).ThenBy(x => EF.Property(x!, "Title")), + "Stamp" => desc ? q.OrderByDescending(x => EF.Property(x!, "Stamp") == null).ThenByDescending(x => EF.Property(x!, "Stamp")) : q.OrderBy(x => EF.Property(x!, "Stamp") == null).ThenBy(x => EF.Property(x!, "Stamp")), + "Serial" => desc ? q.OrderByDescending(x => EF.Property(x!, "Serial") == null).ThenByDescending(x => EF.Property(x!, "Serial")) : q.OrderBy(x => EF.Property(x!, "Serial") == null).ThenBy(x => EF.Property(x!, "Serial")), + "PinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "PinHash") == null).ThenByDescending(x => EF.Property(x!, "PinHash")) : q.OrderBy(x => EF.Property(x!, "PinHash") == null).ThenBy(x => EF.Property(x!, "PinHash")), + "TokenHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "TokenHash") == null).ThenByDescending(x => EF.Property(x!, "TokenHash")) : q.OrderBy(x => EF.Property(x!, "TokenHash") == null).ThenBy(x => EF.Property(x!, "TokenHash")), + "CreatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "CreatedAt") == null).ThenByDescending(x => EF.Property(x!, "CreatedAt")) : q.OrderBy(x => EF.Property(x!, "CreatedAt") == null).ThenBy(x => EF.Property(x!, "CreatedAt")), + "UpdatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "UpdatedAt") == null).ThenByDescending(x => EF.Property(x!, "UpdatedAt")) : q.OrderBy(x => EF.Property(x!, "UpdatedAt") == null).ThenBy(x => EF.Property(x!, "UpdatedAt")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } + + /// Escape hatch: insert without @autoSet stamping (created-at/updated-at + /// written verbatim from ) for import / restore / replication. + public static async System.Threading.Tasks.Task InsertPreserving(global::Acme.Generated.AppDbContext db, Gizmo input) + { + db.Gizmos.Add(input); + await db.SaveChangesAsync(); + return input; + } + + // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled. + // Serializes with the app's configured JSON options, then removes the named keys from each row. + private sealed class CredentialOmittingResult : IResult + { + private readonly object _value; + private readonly string[] _names; + private readonly bool _envelope; + private readonly int _status; + private readonly string? _location; + public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) + { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } + public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + { + var opts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. + SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + http.Response.StatusCode = _status; + if (_location is not null) http.Response.Headers.Location = _location; + await http.Response.WriteAsJsonAsync(node, opts); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs new file mode 100644 index 0000000000..948a184142 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Line. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class LineFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs new file mode 100644 index 0000000000..3b3d1aba9b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -0,0 +1,210 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class LineRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Label", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. + private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + { + "id", + "label", + }; + + /// Maps Line REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapLineRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/lines", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Lines.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineFilterAllowlist.Fields, LineFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortLine(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Lines.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapGet(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Lines.FindAsync(id) is { } found + ? Results.Ok(found) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/lines", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + System.Text.Json.JsonDocument __body; + try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + var __issues = new ValidationIssues(); + Line? input = null; + try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Line)); } + if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); + __issues.ValidateObject(input, jsonOpts); + if (__issues.Any) return __issues.ToResult(); + db.Lines.Add(input); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Created(prefix + "/lines", input); + }); + + async System.Threading.Tasks.Task UpdateLine(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Lines.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + System.Text.Json.JsonDocument body; + try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var bodyScope = body; + if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); + var __issues = new ValidationIssues(); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) { __issues.AddRequired(__wire); continue; } + entry.CurrentValues[target] = null; + continue; + } + var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + object? __val; + try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue; + entry.CurrentValues[target] = __val; + } + if (__issues.Any) return __issues.ToResult(); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Ok(existing); + } + app.MapPatch(prefix + "/lines/{id}", UpdateLine); + app.MapPut(prefix + "/lines/{id}", UpdateLine); + + app.MapDelete(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Lines.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Lines.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortLine(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Label" => desc ? q.OrderByDescending(x => EF.Property(x!, "Label") == null).ThenByDescending(x => EF.Property(x!, "Label")) : q.OrderBy(x => EF.Property(x!, "Label") == null).ThenBy(x => EF.Property(x!, "Label")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs new file mode 100644 index 0000000000..0f92d48114 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs @@ -0,0 +1,37 @@ +// +// Generated by MetaObjects report-export. Do not edit by hand. +#nullable enable +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Acme.Shop; + +/// The CSV and XML export of the LineTotals report: its columns, in derived-field order, over the generated row. +public static class LineTotalsExport +{ + /// The XML root element. + public const string Root = "LineTotals"; + + /// The derived field names, in derived-field order: the CSV header row and the XML element names. + public static readonly IReadOnlyList Columns = + [ + "label", + "lines", + ]; + + /// One row's cells in wire form, in order. + public static global::Acme.Generated.ReportExportCell[] Cells(LineTotals row) => + [ + global::Acme.Generated.ReportExportWriter.Cell(row.Label), + global::Acme.Generated.ReportExportWriter.Cell(row.Lines), + ]; + + /// Writes the rows as RFC 4180 CSV. + public static void WriteCsv(TextWriter writer, IEnumerable rows) => + global::Acme.Generated.ReportExportWriter.WriteCsv(writer, Columns, rows.Select(Cells)); + + /// Writes the rows as XML. + public static void WriteXml(TextWriter writer, IEnumerable rows) => + global::Acme.Generated.ReportExportWriter.WriteXml(writer, Root, Columns, rows.Select(Cells)); +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs new file mode 100644 index 0000000000..1bff83183d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs @@ -0,0 +1,26 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for LineTotals. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class LineTotalsFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + "label", + "lines", + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + ["label"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["lines"] = new(System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs new file mode 100644 index 0000000000..4e83b30597 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -0,0 +1,105 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class LineTotalsRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Label", + "Lines", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps LineTotals REST routes. Unauthenticated — see remarks. + /// + /// These read endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapLineTotalsRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those read endpoints. + /// + public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/line_totals", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.LineTotals.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineTotalsFilterAllowlist.Fields, LineTotalsFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortLineTotals(q, resolved, desc); + } + + // Pagination (report): every row up to the cap, refused above it. + const int maxRows = 10000; + long? limit = null; + long offset = 0; + if (qs.TryGetValue("limit", out var limitRaw)) + { + if (!long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRaw.ToString(), expected = $"an integer from 1 to {maxRows}" }); + if (parsedLimit > maxRows) + return Results.BadRequest(new { error = "report_too_large", maxRows }); + limit = parsedLimit; + } + if (qs.TryGetValue("offset", out var offsetRaw) + && (!long.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRaw.ToString(), expected = "a non-negative integer (0 or more)" }); + if (offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue)); + q = q.Take((int)(limit ?? maxRows + 1L)); + + var rows = await q.ToListAsync(); + if (limit is null && rows.Count > maxRows) + return Results.BadRequest(new { error = "report_too_large", maxRows }); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.LineTotals.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapPost(prefix + "/line_totals", () => + Results.Json(new { error = "method_not_allowed", message = "POST is not supported on a report (read-only)." }, statusCode: 405)); + + return mount; + } + + private static IOrderedQueryable ApplySortLineTotals(IQueryable q, string field, bool desc) + { + return field switch + { + "Label" => desc ? q.OrderByDescending(x => EF.Property(x!, "Label") == null).ThenByDescending(x => EF.Property(x!, "Label")) : q.OrderBy(x => EF.Property(x!, "Label") == null).ThenBy(x => EF.Property(x!, "Label")), + "Lines" => desc ? q.OrderByDescending(x => EF.Property(x!, "Lines") == null).ThenByDescending(x => EF.Property(x!, "Lines")) : q.OrderBy(x => EF.Property(x!, "Lines") == null).ThenBy(x => EF.Property(x!, "Lines")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs new file mode 100644 index 0000000000..2c516fe2c9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs @@ -0,0 +1,169 @@ +// +// Generated by MetaObjects report-export. Do not edit by hand. +// +// The shared writer of every report export: CSV and XML over cells already in wire form. +#nullable enable +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Net; +using System.Text; +using System.Xml; + +namespace Acme.Generated; + +/// One exported cell: its wire-form text (null for a null) and whether the CSV formula-injection guard applies to it. +public readonly record struct ReportExportCell(string? Value, bool IsText); + +/// CSV and XML writers for a report export, and the wire-form conversion of a cell. +public static class ReportExportWriter +{ + /// Start the CSV with a UTF-8 byte order mark. Flip it here, or regenerate with CsvBom = true. + public static readonly bool ExportCsvBom = false; + + /// The project's wire.decimals setting: write a decimal as its canonical string (12.5) rather than as System.Text.Json does (12.50). + public static readonly bool DecimalsAsString = false; + + /// Write a null field as an empty element carrying xsi:nil="true" (and declare xmlns:xsi on the root) instead of as a bare empty element. + public static readonly bool XmlNil = true; + + private const string XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"; + + /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, a boolean as true/false, a null as null. + public static ReportExportCell Cell(object? value) + { + switch (value) + { + case null: return new(null, false); + case string s: return new(s, true); + case bool b: return new(b ? "true" : "false", false); + case DateOnly d: return new(d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), false); + case TimeOnly t: return new(t.ToString("HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture), false); + case DateTimeOffset o: return new(Timestamp(o), false); + case DateTime dt: return new(dt.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture), false); + case Guid g: return new(g.ToString("D", CultureInfo.InvariantCulture), false); + case decimal m: return new(DecimalsAsString ? Canonical(m) : m.ToString(CultureInfo.InvariantCulture), false); + case Enum e: return new(e.ToString(), true); + case Uri u: return new(u.OriginalString, true); + case IPAddress ip: return new(ip.ToString(), false); + case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); + case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); + default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); + } + } + + // A timestamp as the list route writes it (Iso8601TimestampConverter): UTC with Z, and + // milliseconds only when the instant has a fraction. + private static string Timestamp(DateTimeOffset value) + { + var utc = value.UtcDateTime; + var format = utc.Ticks % TimeSpan.TicksPerSecond == 0 + ? "yyyy-MM-dd'T'HH:mm:ss'Z'" + : "yyyy-MM-dd'T'HH:mm:ss.fff'Z'"; + return utc.ToString(format, CultureInfo.InvariantCulture); + } + + // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". + private static string Canonical(decimal value) + { + var s = value.ToString(CultureInfo.InvariantCulture); + if (s.IndexOf('.') >= 0) + { + s = s.TrimEnd('0'); + if (s.EndsWith('.')) s = s.Substring(0, s.Length - 1); + } + return s == "-0" || s.Length == 0 ? "0" : s; + } + + /// + /// Writes RFC 4180 CSV: UTF-8 text, a header row of , CRLF after every record + /// including the last. A cell containing ", ,, CR or LF is quoted with embedded quotes doubled. + /// A string-valued cell starting with =, +, -, @, TAB or CR is prefixed with an + /// apostrophe first (the formula-injection guard); a number, date or boolean never is. A null is an empty cell. + /// + public static void WriteCsv(TextWriter writer, IReadOnlyList columns, IEnumerable rows) + { + if (ExportCsvBom) writer.Write(''); + for (var i = 0; i < columns.Count; i++) + { + if (i > 0) writer.Write(','); + writer.Write(CsvQuote(columns[i])); + } + writer.Write("\r\n"); + foreach (var row in rows) + { + for (var i = 0; i < row.Length; i++) + { + if (i > 0) writer.Write(','); + writer.Write(CsvField(row[i])); + } + writer.Write("\r\n"); + } + } + + /// One CSV field: the injection guard (text cells only), then the quoting. + public static string CsvField(ReportExportCell cell) + { + if (cell.Value is not { } value) return ""; + if (cell.IsText && value.Length > 0 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r') + value = "'" + value; + return CsvQuote(value); + } + + private static string CsvQuote(string value) => + value.AsSpan().IndexOfAny("\",\r\n") >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + + /// + /// Writes <root><row><field>value</field>...</row>...</root>: no XML declaration, no indentation, + /// text escaped by XmlWriter (& < >, and a CR as a character reference so a parse keeps it). + /// There is no injection guard in XML. A null follows . A character XML 1.0 cannot carry + /// is written as U+FFFD rather than failing the whole export. + /// + public static void WriteXml(TextWriter writer, string root, IReadOnlyList columns, IEnumerable rows) + { + var settings = new XmlWriterSettings + { + OmitXmlDeclaration = true, + Indent = false, + NewLineHandling = NewLineHandling.Entitize, + }; + using var xml = XmlWriter.Create(writer, settings); + xml.WriteStartElement(root); + if (XmlNil) xml.WriteAttributeString("xmlns", "xsi", null, XsiNamespace); + foreach (var row in rows) + { + xml.WriteStartElement("row"); + for (var i = 0; i < columns.Count; i++) + { + xml.WriteStartElement(columns[i]); + if (row[i].Value is { } text) xml.WriteString(XmlSafe(text)); + else if (XmlNil) xml.WriteAttributeString("xsi", "nil", XsiNamespace, "true"); + xml.WriteEndElement(); + } + xml.WriteEndElement(); + } + xml.WriteEndElement(); + } + + private static string XmlSafe(string text) + { + StringBuilder? fixedUp = null; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + var ok = XmlConvert.IsXmlChar(c); + if (!ok && i + 1 < text.Length && XmlConvert.IsXmlSurrogatePair(text[i + 1], c)) + { + fixedUp?.Append(c).Append(text[i + 1]); + i++; + continue; + } + if (ok) { fixedUp?.Append(c); continue; } + fixedUp ??= new StringBuilder(text.Length).Append(text, 0, i); + fixedUp.Append('�'); + } + return fixedUp?.ToString() ?? text; + } +} \ No newline at end of file diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs new file mode 100644 index 0000000000..60c41974b5 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Tag. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class TagFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs new file mode 100644 index 0000000000..852e0ed6dd --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -0,0 +1,212 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class TagRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Name", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. + private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + { + "id", + "name", + }; + + /// Maps Tag REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapTagRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Tags.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, TagFilterAllowlist.Fields, TagFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortTag(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Tags.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapGet(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Tags.FindAsync(id) is { } found + ? Results.Ok(found) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + System.Text.Json.JsonDocument __body; + try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + var __issues = new ValidationIssues(); + Tag? input = null; + try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Tag)); } + if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + __issues.ValidateObject(input, jsonOpts); + if (__issues.Any) return __issues.ToResult(); + db.Tags.Add(input); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Created(prefix + "/tags", input); + }); + + async System.Threading.Tasks.Task UpdateTag(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Tags.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + System.Text.Json.JsonDocument body; + try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var bodyScope = body; + if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); + var __issues = new ValidationIssues(); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) { __issues.AddRequired(__wire); continue; } + entry.CurrentValues[target] = null; + continue; + } + var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + object? __val; + try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue; + entry.CurrentValues[target] = __val; + } + if (__issues.Any) return __issues.ToResult(); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Ok(existing); + } + app.MapPatch(prefix + "/tags/{id}", UpdateTag); + app.MapPut(prefix + "/tags/{id}", UpdateTag); + + app.MapDelete(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Tags.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Tags.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortTag(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Name" => desc ? q.OrderByDescending(x => EF.Property(x!, "Name") == null).ThenByDescending(x => EF.Property(x!, "Name")) : q.OrderBy(x => EF.Property(x!, "Name") == null).ThenBy(x => EF.Property(x!, "Name")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs new file mode 100644 index 0000000000..0444514ca1 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Van. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VanFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs new file mode 100644 index 0000000000..345446a7f2 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Vehicle. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VehicleFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs new file mode 100644 index 0000000000..73941c624c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -0,0 +1,490 @@ +// +// Generated by MetaObjects routes-generator (TPH). Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class VehicleRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. + private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + { + "id", + "kind", + "payloadKg", + "plate", + "regNo", + "seatCount", + "vinHash", + }; + + private static readonly System.Collections.Generic.HashSet CarSortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + "SeatCount", + "RegNo", + }; + + private static readonly System.Collections.Generic.Dictionary CarSortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + private static readonly System.Collections.Generic.HashSet VanSortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + "PayloadKg", + }; + + private static readonly System.Collections.Generic.Dictionary VanSortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps Vehicle REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapVehicleRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleFilterAllowlist.Fields, VehicleFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySort(q, resolved, desc); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) + q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) + q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapGet(prefix + "/vehicles/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + app.MapGet(prefix + "/vehicles/car", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.OfType().AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, global::Acme.Shop.CarFilterAllowlist.Fields, global::Acme.Shop.CarFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!CarSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : CarSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) + q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) + q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/vehicles/car", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + System.Text.Json.JsonDocument __body; + try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + var __issues = new ValidationIssues(); + global::Acme.Shop.Car? input = null; + try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Car)); } + if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + input.Kind = default!; + input.Tags = new System.Collections.Generic.List(); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.VinHash = default!; + __issues.ValidateObject(input, jsonOpts); + if (__issues.Any) return __issues.ToResult(); + db.Vehicles.Add(input); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); + }); + + async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + System.Text.Json.JsonDocument body; + try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var bodyScope = body; + if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + // Configured JSON options (not defaults) so a custom converter — e.g. the + // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); + var __issues = new ValidationIssues(); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "VinHash") continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "vinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "Kind", System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (string.Equals(target.Name, "RegNo", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) { __issues.AddRequired(__wire); continue; } + entry.CurrentValues[target] = null; + continue; + } + var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + object? __val; + try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue; + entry.CurrentValues[target] = __val; + } + if (__issues.Any) return __issues.ToResult(); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "VinHash" }); + } + app.MapPatch(prefix + "/vehicles/car/{id}", UpdateCar); + app.MapPut(prefix + "/vehicles/car/{id}", UpdateCar); + + app.MapDelete(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Vehicles.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + app.MapGet(prefix + "/vehicles/car/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) + return Results.Ok(new System.Collections.Generic.List()); + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + app.MapGet(prefix + "/vehicles/van", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.OfType().AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, global::Acme.Shop.VanFilterAllowlist.Fields, global::Acme.Shop.VanFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!VanSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : VanSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) + q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) + q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/vehicles/van", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + System.Text.Json.JsonDocument __body; + try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + var __issues = new ValidationIssues(); + global::Acme.Shop.Van? input = null; + try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Van)); } + if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + input.Kind = default!; + input.Tags = new System.Collections.Generic.List(); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.VinHash = default!; + __issues.ValidateObject(input, jsonOpts); + if (__issues.Any) return __issues.ToResult(); + db.Vehicles.Add(input); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); + }); + + async System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + System.Text.Json.JsonDocument body; + try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + using var bodyScope = body; + if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; + // Configured JSON options (not defaults) so a custom converter — e.g. the + // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. + var jsonOpts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); + var __issues = new ValidationIssues(); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "VinHash") continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "vinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "Kind", System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) { __issues.AddRequired(__wire); continue; } + entry.CurrentValues[target] = null; + continue; + } + var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + object? __val; + try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue; + entry.CurrentValues[target] = __val; + } + if (__issues.Any) return __issues.ToResult(); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "VinHash" }); + } + app.MapPatch(prefix + "/vehicles/van/{id}", UpdateVan); + app.MapPut(prefix + "/vehicles/van/{id}", UpdateVan); + + app.MapDelete(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Vehicles.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + app.MapGet(prefix + "/vehicles/van/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) + return Results.Ok(new System.Collections.Generic.List()); + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + return mount; + } + + private static IOrderedQueryable ApplySort(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Plate" => desc ? q.OrderByDescending(x => EF.Property(x!, "Plate") == null).ThenByDescending(x => EF.Property(x!, "Plate")) : q.OrderBy(x => EF.Property(x!, "Plate") == null).ThenBy(x => EF.Property(x!, "Plate")), + "VinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "VinHash") == null).ThenByDescending(x => EF.Property(x!, "VinHash")) : q.OrderBy(x => EF.Property(x!, "VinHash") == null).ThenBy(x => EF.Property(x!, "VinHash")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } + + // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled. + // Serializes with the app's configured JSON options, then removes the named keys from each row. + private sealed class CredentialOmittingResult : IResult + { + private readonly object _value; + private readonly string[] _names; + private readonly bool _envelope; + private readonly int _status; + private readonly string? _location; + public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) + { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } + public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + { + var opts = ((Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. + SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + http.Response.StatusCode = _status; + if (_location is not null) http.Response.Headers.Location = _location; + await http.Response.WriteAsJsonAsync(node, opts); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs new file mode 100644 index 0000000000..6791ce02e7 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for VehicleTag. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VehicleTagFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs new file mode 100644 index 0000000000..e15592ead1 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -0,0 +1,88 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class VehicleTagRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "VehicleId", + "TagId", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps VehicleTag REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapVehicleTagRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/vehicle_tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.VehicleTags.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleTagFilterAllowlist.Fields, VehicleTagFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortVehicleTag(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.VehicleTags.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortVehicleTag(IQueryable q, string field, bool desc) + { + return field switch + { + "VehicleId" => desc ? q.OrderByDescending(x => EF.Property(x!, "VehicleId") == null).ThenByDescending(x => EF.Property(x!, "VehicleId")) : q.OrderBy(x => EF.Property(x!, "VehicleId") == null).ThenBy(x => EF.Property(x!, "VehicleId")), + "TagId" => desc ? q.OrderByDescending(x => EF.Property(x!, "TagId") == null).ThenByDescending(x => EF.Property(x!, "TagId")) : q.OrderBy(x => EF.Property(x!, "TagId") == null).ThenBy(x => EF.Property(x!, "TagId")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs new file mode 100644 index 0000000000..59cc33e859 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs @@ -0,0 +1,23 @@ +// +// Generated by MetaObjects callable-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace Acme.Generated; + +/// +/// FR-015: typed wrapper around the fn_widget_summary stored procedure. Arguments bind in +/// declaration order from the @parameterRef value-object (acme::shop::WidgetArgs). +/// +public static class WidgetSummaryCallable +{ + public static async Task> Call(global::Acme.Generated.AppDbContext db, global::Acme.Shop.WidgetArgs args) + { + return await db.Set() + .FromSqlInterpolated($"SELECT * FROM fn_widget_summary({args.WidgetId}, {args.MaxRows})") + .AsNoTracking() + .ToListAsync(); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs new file mode 100644 index 0000000000..69644c321b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for WidgetSummary. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class WidgetSummaryFilterAllowlist +{ + public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs new file mode 100644 index 0000000000..2bb6099be9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -0,0 +1,89 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class WidgetSummaryRoutes +{ + private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + { + "WidgetId", + }; + + private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps WidgetSummary REST routes. Unauthenticated — see remarks. + /// + /// These read endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapWidgetSummaryRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those read endpoints. + /// + public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/widget_summaries", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.WidgetSummaries.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, WidgetSummaryFilterAllowlist.Fields, WidgetSummaryFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortWidgetSummary(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.WidgetSummaries.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapPost(prefix + "/widget_summaries", () => + Results.Json(new { error = "method_not_allowed", message = "POST is not supported on a projection (read-only)." }, statusCode: 405)); + + return mount; + } + + private static IOrderedQueryable ApplySortWidgetSummary(IQueryable q, string field, bool desc) + { + return field switch + { + "WidgetId" => desc ? q.OrderByDescending(x => EF.Property(x!, "WidgetId") == null).ThenByDescending(x => EF.Property(x!, "WidgetId")) : q.OrderBy(x => EF.Property(x!, "WidgetId") == null).ThenBy(x => EF.Property(x!, "WidgetId")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs index 0990392368..e02e1ef87c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs @@ -286,4 +286,16 @@ public void Any_other_project_needs_no_Npgsql_and_cannot_restart(string? dialect Assert.DoesNotContain("Npgsql:IdentitySequenceOptions", context); Assert.Contains(warnings, w => w.Contains("@sequenceStart") && w.Contains("migrate.dialect") && w.Contains("GenConfig.Dialect")); } + + // Ruling R56 (item 3): @sequenceName is not refused — it describes an adopted database whose + // sequence kept its name, which EF cannot express — and it is said once, naming the objects. + [Fact] + public void A_sequence_name_warns_once_and_generates() + { + var model = Model.Replace("\"@sequenceStart\": 100", "\"@sequenceStart\": 100, \"@sequenceName\": \"tickets_seq\""); + var (files, warnings) = Run("postgres", model); + Assert.Contains(files, f => f.Path == "AppDbContext.g.cs"); + var warning = Assert.Single(Others(warnings)); + Assert.Contains("@sequenceName is not in the EF model (acme::Ticket)", warning); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs index 99205d8cad..0955df9a24 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs @@ -58,4 +58,29 @@ public void Verify_reads_the_dialect_gen_read() Directory.SetCurrentDirectory(cwd); } } + + // The assembly name gen reads from the .csproj above --out is the one the drift render uses: a + // render under a temporary directory with no project would leave the reference line out and + // report the design-time services file as drift on every CI run. + [Fact] + public void Verify_renders_the_design_time_reference_gen_read_from_the_project() + { + File.WriteAllText(Path.Combine(_root, "Acme.App.csproj"), + "Acme.App\n"); + var cwd = Directory.GetCurrentDirectory(); + Directory.SetCurrentDirectory(_root); + try + { + var (gen, genText) = Run("gen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.True(gen == 0, genText); + var services = File.ReadAllText(Path.Combine(Out, "AppDbContextDesignTimeServices.g.cs")); + Assert.Contains("DesignTimeServicesReference(\"Acme.Generated.AppDbContextDesignTimeServices, Acme.App\"", services); + var (verify, verifyText) = Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.True(verify == 0, verifyText); + } + finally + { + Directory.SetCurrentDirectory(cwd); + } + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/InheritanceConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/InheritanceConformanceTests.cs index 96d85de3c9..4304948be9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/InheritanceConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/InheritanceConformanceTests.cs @@ -50,10 +50,10 @@ public void Concrete_entity_flattens_the_full_multi_level_inherited_field_set() var files = new EntityGenerator().Generate(Context(LoadFixture())).ToList(); // Abstract bases produce no entity file (the abstract invariant). - Assert.DoesNotContain(files, f => f.Path == "Base.g.cs"); - Assert.DoesNotContain(files, f => f.Path == "Auditable.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "Base.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "Auditable.g.cs"); - var product = Assert.Single(files, f => f.Path == "Product.g.cs"); + var product = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "Product.g.cs"); Assert.Contains("[Table(ProductNames.SourcePrimaryTable)]", product.Content); // §A6 (task 4) // All five fields present — 2 levels of inherited + 2 own. diff --git a/server/csharp/MetaObjects.Codegen.Tests/Issue195NativeTypingCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Issue195NativeTypingCodegenTests.cs index 9eaac87994..c2047ab53b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Issue195NativeTypingCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Issue195NativeTypingCodegenTests.cs @@ -61,7 +61,7 @@ private static string ProjectionClass() Entities = r.Root.Objects(), Root = r.Root, Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, }; - return new EntityGenerator().Generate(ctx).Single(f => f.Path == "SessionSummary.g.cs").Content; + return new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "SessionSummary.g.cs").Content; } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/Issue205ValueObjectEnumTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Issue205ValueObjectEnumTests.cs index 97c1c44dd0..e876bd94e5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Issue205ValueObjectEnumTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Issue205ValueObjectEnumTests.cs @@ -64,7 +64,7 @@ private static MetaRoot Load() public void ValueObject_enum_field_emits_provided_enum_type_not_string() { var files = new EntityGenerator().Generate(Ctx(Load())).ToList(); - var vo = Assert.Single(files, f => f.Path == "ContactInfo.g.cs"); + var vo = Assert.Single(files, f => System.IO.Path.GetFileName(f.Path) == "ContactInfo.g.cs"); var src = vo.Content; // The property is typed by the provided enum (resolved via PackageNamespaces), diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs index cdc8435b58..1e65c43c8c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs @@ -38,12 +38,12 @@ public class NamesExtendsChainTests { "object.entity": { "name": "Auth", "@discriminator": "kind", "children": [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "zz_copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "zz_coupon_cents" } } ]}}, { "object.value": { "name": "Money", "children": [ { "field.long": { "name": "cents", "@column": "zz_cents" } } @@ -65,7 +65,7 @@ private static Dictionary Generate() ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase, IncludeNames = true, }, }; - return new NamesGenerator().Generate(ctx).ToDictionary(f => f.Path, f => f.Content); + return new NamesGenerator().Generate(ctx).ToDictionary(f => System.IO.Path.GetFileName(f.Path), f => f.Content); } [Fact] @@ -107,9 +107,9 @@ public void The_child_extends_the_base_and_declares_only_its_own_column() [Fact] public void A_tph_subtype_inherits_the_shared_table_name_rather_than_restating_it() { - var src = Generate()["CopayAuthNames.g.cs"]; - Assert.Contains("public abstract class CopayAuthNames : AuthNames", src); - Assert.Contains("public const string CopayAmountColumn = \"zz_copay_cents\";", src); + var src = Generate()["CouponAuthNames.g.cs"]; + Assert.Contains("public abstract class CouponAuthNames : AuthNames", src); + Assert.Contains("public const string CouponAmountColumn = \"zz_coupon_cents\";", src); // The whole point: the subtype used to restate the base's table name and every one // of its columns. Assert.DoesNotContain("zz_auths", src); @@ -155,7 +155,7 @@ public void A_key_only_abstract_is_a_link_in_the_chain_not_a_node_to_walk_past() ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase, IncludeNames = true, }, }; - var files = new NamesGenerator().Generate(ctx).ToDictionary(f => f.Path, f => f.Content); + var files = new NamesGenerator().Generate(ctx).ToDictionary(f => System.IO.Path.GetFileName(f.Path), f => f.Content); // The intermediate has something to contribute, so it gets a class of its own... Assert.True(files.ContainsKey("AuditedNames.g.cs"), string.Join(", ", files.Keys)); @@ -197,11 +197,11 @@ public static class Probe // An inherited const from a TPH base, including the shared table name. A TPH // subtype declares no own source, so `SourcePrimaryTable` is the base's, reached // through the base class — not restated here. - public const string B = CopayAuthNames.SourcePrimaryTable; - public const string C = CopayAuthNames.CopayAmountColumn; + public const string B = CouponAuthNames.SourcePrimaryTable; + public const string C = CouponAuthNames.CouponAmountColumn; // ColumnsByField stays COMPLETE on the subtype — it is the lookup surface, and a // miss on an inherited field is the fallback-to-literal this artifact removes. - public static readonly int Count = CopayAuthNames.ColumnsByField.Count; + public static readonly int Count = CouponAuthNames.ColumnsByField.Count; } """; var trees = files.Values.Append(probe) @@ -219,11 +219,11 @@ public static class Probe // A clean compile proves the members resolve; this proves the SUBTYPE's dictionary // is the complete one rather than the base's (a static field is hidden, not - // overridden, so `new` is what makes CopayAuthNames.ColumnsByField the 4-entry one). - var sub = files["CopayAuthNames.g.cs"]; + // overridden, so `new` is what makes CouponAuthNames.ColumnsByField the 4-entry one). + var sub = files["CouponAuthNames.g.cs"]; Assert.Contains("public static new readonly Dictionary ColumnsByField", sub); Assert.Contains("[\"id\"] = IdColumn,", sub); - Assert.Contains("[\"copayAmount\"] = CopayAmountColumn,", sub); + Assert.Contains("[\"couponAmount\"] = CouponAmountColumn,", sub); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs index 8af2743ba5..f5a06a6170 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs @@ -51,7 +51,7 @@ public class NamesGeneratorTests private static MetaRoot Load(string model) { var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "gen.json")]); - Assert.Empty(r.Errors); + Assert.Empty(r.Errors.Select(e => $"{e.Code}: {e.Message}")); return r.Root; } @@ -127,6 +127,64 @@ public void Emits_const_string_members_for_table_and_columns() Assert.Contains("public const string CreatedAtColumn = \"created_at\";", src); } + // rc.21 (U7): a derived field of a table-backed entity has no column, so the artifact names no + // column for it (no `…Field`/`…Column` pair, no ColumnsByField entry). A projection's derived + // field IS a column of its view and keeps its pair. + [Fact] + public void A_derived_field_of_a_table_entity_has_no_column_constant() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "score" } }, + { "field.boolean": { "name": "isHigh", "children": [ { "origin.computed": { "@expr": { + "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } } } } ] } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.projection": { "name": "AccountView", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "field.int": { "name": "doubled", "children": [ { "origin.computed": { "@expr": { + "fn": "coalesce", "args": [ { "field": "score" }, { "value": 0 } ] } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Account.id" } } ] } } ] } } + """; + var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); + var account = files.Single(f => f.Path.EndsWith("AccountNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string ScoreColumn = \"score\";", account); + Assert.DoesNotContain("IsHigh", account); + var view = files.Single(f => f.Path.EndsWith("AccountViewNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string DoubledColumn = \"doubled\";", view); + } + + // rc.21 fix round (M8): an abstract-entity fragment drops its derived field, so a write-through + // extender (whose read view HAS that column) declares the constant itself. + [Fact] + public void A_write_through_extender_declares_the_derived_column_its_fragment_drops() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Tracked", "abstract": true, "children": [ + { "field.int": { "name": "score" } }, + { "field.boolean": { "name": "isHigh", "children": [ { "origin.computed": { "@expr": { + "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } } } } ] } } ] } }, + { "object.entity": { "name": "Account", "extends": "Tracked", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "source.rdb": { "name": "read", "@kind": "view", "@view": "v_accounts", "@role": "replica" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.projection": { "name": "HighAccounts", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "identity.primary": { "name": "id", "extends": "Account.id" } } ] } } ] } } + """; + var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); + var tracked = files.Single(f => f.Path.EndsWith("TrackedNames.g.cs", StringComparison.Ordinal)).Content; + Assert.DoesNotContain("IsHigh", tracked); + var account = files.Single(f => f.Path.EndsWith("AccountNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string IsHighColumn = \"is_high\";", account); + } + [Fact] public void An_explicit_column_wins_over_the_naming_strategy() { @@ -207,7 +265,7 @@ public void An_object_with_no_primary_source_emits_nothing() // all and must not appear in the output. var files = new NamesGenerator().Generate(Ctx(Load(SubscriberModel))).ToList(); var file = Assert.Single(files); - Assert.Equal("SubscriberNames.g.cs", file.Path); + Assert.Equal("SubscriberNames.g.cs", System.IO.Path.GetFileName(file.Path)); } [Fact] @@ -476,7 +534,7 @@ public void Two_primaries_AGREEING_on_a_physical_name_are_not_refused() // artifact compares the resolved SourceNames instead — the same DISAGREEMENT rule // SourceResolution already enforces, not a stricter one invented here. var src = new NamesGenerator().Generate(Ctx(root)) - .Single(f => f.Path == "ChildSameNames.g.cs").Content; + .Single(f => System.IO.Path.GetFileName(f.Path) == "ChildSameNames.g.cs").Content; Assert.Contains("public new const string SourcePrimaryTable = \"same_table\";", src); } @@ -489,7 +547,7 @@ public void Two_primaries_AGREEING_on_a_physical_name_are_not_refused() public void Entity_Table_and_Column_attributes_reference_the_name_constants() { var ctx = Ctx(Load(SubscriberModel)); - var src = new EntityGenerator().Generate(ctx).Single(f => f.Path == "Subscriber.g.cs").Content; + var src = new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "Subscriber.g.cs").Content; Assert.Contains("[Table(SubscriberNames.SourcePrimaryTable)]", src); Assert.Contains("[Column(SubscriberNames.CreatedAtColumn)]", src); @@ -525,7 +583,7 @@ public void TPH_subtype_columns_reference_the_subtypes_own_name_constants_not_a_ ]}} """; var ctx = Ctx(Load(model), ColumnNamingStrategy.Literal); - var src = new EntityGenerator().Generate(ctx).Single(f => f.Path == "BridgeAuth.g.cs").Content; + var src = new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "BridgeAuth.g.cs").Content; Assert.Contains("[Column(BridgeAuthNames.QuantityColumn)]", src); Assert.DoesNotContain("[Column(\"quantity\")]", src); @@ -761,7 +819,7 @@ public void A_run_that_names_no_generator_is_a_usage_error_and_writes_nothing() public void C1_with_names_absent_Entity_Table_and_Column_fall_back_to_the_pre_ProgramA_literal() { var ctx = CtxWithoutNames(Load(SubscriberModel)); - var src = new EntityGenerator().Generate(ctx).Single(f => f.Path == "Subscriber.g.cs").Content; + var src = new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "Subscriber.g.cs").Content; // The exact literal spellings EntityGenerator emitted before Program A referenced // the constant (git 488143e21) -- present. @@ -796,7 +854,7 @@ public void C1_with_names_absent_TPH_subtype_columns_fall_back_to_the_pre_Progra ]}} """; var ctx = CtxWithoutNames(Load(model), ColumnNamingStrategy.Literal); - var src = new EntityGenerator().Generate(ctx).Single(f => f.Path == "BridgeAuth.g.cs").Content; + var src = new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "BridgeAuth.g.cs").Content; Assert.Contains("[Column(\"quantity\")]", src); Assert.DoesNotContain("BridgeAuthNames", src); @@ -878,7 +936,7 @@ public void GenConfig_IncludeNames_defaults_to_false_so_a_bare_config_falls_back Entities = root.Objects(), Root = root, Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, // IncludeNames unset }; - var src = new EntityGenerator().Generate(ctx).Single(f => f.Path == "Subscriber.g.cs").Content; + var src = new EntityGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "Subscriber.g.cs").Content; // Positive: the literal spelling is present. Assert.Contains("[Table(\"subscribers\")]", src); @@ -906,7 +964,7 @@ public void GenConfig_IncludeNames_defaults_to_false_so_a_bare_config_falls_back [Fact] public void A_flattened_member_gets_a_column_constant_beside_its_field_constants() { - var content = new NamesGenerator().Generate(Ctx(Load(FlattenedModel))).Single(f => f.Path == "ShipmentNames.g.cs").Content; + var content = new NamesGenerator().Generate(Ctx(Load(FlattenedModel))).Single(f => System.IO.Path.GetFileName(f.Path) == "ShipmentNames.g.cs").Content; Assert.Contains("public const string ShipToStreetColumn = \"ship_to_street\";", content); Assert.Contains("public const string ShipToPostalCodeColumn = \"ship_to_ZIP\";", content); @@ -933,7 +991,7 @@ public void A_flattened_member_constant_that_collides_with_a_field_constant_is_l Entities = root.Objects(), Root = root, Warn = warnings.Add, Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase, IncludeNames = true }, }; - var content = new NamesGenerator().Generate(ctx).Single(f => f.Path == "ShipmentNames.g.cs").Content; + var content = new NamesGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "ShipmentNames.g.cs").Content; // The field's constant wins; the model generates, as it did before member constants. Assert.Contains("public const string ShipToStreetColumn = \"ship_to_street\";", content); @@ -971,7 +1029,7 @@ public void A_child_that_redeclares_a_flattened_field_as_jsonb_does_not_inherit_ ]}} """; var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); - var order = files.Single(f => f.Path == "OrderNames.g.cs").Content; + var order = files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderNames.g.cs").Content; // Extending BaseNames would make BaseNames.ShipToStreetColumn a member of OrderNames, // naming a column `orders` does not have; the artifact is emitted complete instead. diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index 5b6c984290..e91f0ee7e9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -187,8 +187,8 @@ public void DbContext_configures_owned_types_flattened_and_json() // migration never created — measured against a real Postgres, not inferred. Assert.Contains("b.Property(p => p.Kind).HasColumnName(\"homeAddress_kind\").HasConversion();", dbContext); Assert.Contains( - "b.Property(p => p.Grade).HasColumnName(\"homeAddress_grade\").HasConversion(v => v == Address.AddressGrade.LO ? 1 : v == Address.AddressGrade.HI ? 2 : UnmappedEnumMember(v, \"grade\"), " + - "v => v == 1 ? Address.AddressGrade.LO : v == 2 ? Address.AddressGrade.HI : UnmappedEnumValue(v, \"grade\"));", + "b.Property(p => p.Grade).HasColumnName(\"homeAddress_grade\").HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == Address.AddressGrade.LO ? 1 : v == Address.AddressGrade.HI ? 2 : UnmappedEnumMember(v, \"grade\"), " + + "v => v == 1 ? Address.AddressGrade.LO : v == 2 ? Address.AddressGrade.HI : UnmappedEnumValue(v, \"grade\")));", dbContext); // ...and the fail-fast helper that converter names is declared, even though the ONLY // int-backed enum in this model lives on the value object, which is not an emitted diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs new file mode 100644 index 0000000000..d222e4fd1d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs @@ -0,0 +1,159 @@ +// G5, rc.20 (fix round 1): a self-hosted runner that makes one CodegenRunner.Run per target sweeps +// once, after all of them, through the hash manifest (OrphanSweep.Sweep with the union of every +// run's directories and EmittedPaths). Ownership is the manifest's recorded hash, never a header: +// `// ` is the .NET convention (Roslyn source generators write it, adopters put it +// on hand-written partials), so a file carrying it that MetaObjects did not record is never touched, +// and an edited orphan is refused by name, as `dotnet meta gen` refuses one. Paths compare +// case-insensitively: on macOS or Windows a case-only rename keeps the old spelling on disk. + +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class OrphanSweepRunnerTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-runner-sweep-" + Guid.NewGuid().ToString("N")); + private string Out => Path.Combine(_root, "gen"); + private string State => Path.Combine(_root, ".metaobjects", ".gen-state"); + + public OrphanSweepRunnerTests() => Directory.CreateDirectory(_root); + public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } + + /// One file per value object, under its package directory when . + private sealed class PerValue(bool byPackage, string dir = "acme/") : IGenerator + { + public string Name => "values"; + public IEnumerable Generate(GenContext ctx) => + ctx.Root.Objects().Select(o => new EmittedFile( + (byPackage ? dir : "") + $"{o.Name}.g.cs", + $"// \n// Generated by MetaObjects values.\npublic sealed class {o.Name} {{ }}\n")); + } + + private static MetaRoot Root(params string[] values) + { + var children = string.Join(",", values.Select(v => $$"""{ "object.value": { "name": "{{v}}", "children": [ { "field.string": { "name": "x" } } ] } }""")); + var r = new MetaDataLoader().Load([new InMemoryStringSource($$"""{ "metadata.root": { "package": "acme", "children": [ {{children}} ] } }""", id: "m.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + private CodegenRunner.RunResult Run(MetaRoot root, IGenerator generator, string? outDir = null) => + CodegenRunner.Run(new GenConfig { OutDir = outDir ?? Out, Namespace = "Acme", GenStateDir = State, ProjectRoot = _root }, + root, [generator]); + + private string At(string rel) => Path.Combine(Out, rel); + + private OrphanSweep.Result Sweep(IEnumerable runs, string[] dirs, bool reportUnrecorded = false, bool dryRun = false) => + OrphanSweep.Sweep(State, _root, dirs.Select(d => (d, "")).ToList(), + runs.SelectMany(r => r.EmittedPaths).ToHashSet(StringComparer.Ordinal), reportUnrecorded: reportUnrecorded, dryRun: dryRun); + + [Fact] + public void A_layout_change_is_swept_through_the_manifest() + { + Run(Root("Alpha", "Beta"), new PerValue(byPackage: false)); + var moved = Run(Root("Alpha", "Beta"), new PerValue(byPackage: true)); + Assert.True(File.Exists(At("Alpha.g.cs"))); + + var swept = Sweep([moved], [Out]); + Assert.Equal(["Alpha.g.cs", "Beta.g.cs"], swept.Removed); + Assert.False(File.Exists(At("Alpha.g.cs"))); + Assert.True(File.Exists(At("acme/Alpha.g.cs"))); + } + + [Fact] + public void A_dry_run_reports_and_removes_nothing() + { + Run(Root("Alpha"), new PerValue(byPackage: false)); + var moved = Run(Root("Alpha"), new PerValue(byPackage: true)); + Assert.Equal(["Alpha.g.cs"], Sweep([moved], [Out], dryRun: true).Removed); + Assert.True(File.Exists(At("Alpha.g.cs"))); + // The manifest still records it, so the real sweep removes it. + Assert.Equal(["Alpha.g.cs"], Sweep([moved], [Out]).Removed); + } + + [Fact] + public void A_foreign_auto_generated_file_is_never_touched() + { + // A Roslyn source generator's output, and a hand-written partial carrying the marker to quiet analyzers. + Directory.CreateDirectory(At("obj-gen")); + File.WriteAllText(At("obj-gen/Regex.g.cs"), "// \n#nullable enable\npartial class R { }\n"); + File.WriteAllText(At("Quiet.cs"), "// \npublic partial class Alpha { }\n"); + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([run], [Out], reportUnrecorded: true); + Assert.Empty(swept.Removed); + Assert.Empty(swept.Refused); + Assert.Empty(swept.Unrecorded); + Assert.True(File.Exists(At("obj-gen/Regex.g.cs"))); + Assert.True(File.Exists(At("Quiet.cs"))); + } + + [Fact] + public void An_edited_orphan_is_refused_by_name() + { + Run(Root("Alpha", "Beta"), new PerValue(byPackage: false)); + File.AppendAllText(At("Beta.g.cs"), "// my edit\n"); + var after = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([after], [Out]); + Assert.Empty(swept.Removed); + Assert.Equal(["gen/Beta.g.cs"], swept.Refused); + Assert.True(File.Exists(At("Beta.g.cs"))); + } + + [Fact] + public void A_case_only_rename_keeps_the_file_it_just_wrote() + { + // On macOS or Windows, overwriting Alpha.g.cs through the path ALPHA.g.cs keeps the old name, so + // the file on disk is spelled differently from the path the run emitted. Simulated here on any + // file system: the run emitted the upper-case spelling. + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + var emitted = run.EmittedPaths.Select(p => Path.Combine(Path.GetDirectoryName(p)!, Path.GetFileName(p).ToUpperInvariant())).ToHashSet(); + var swept = OrphanSweep.Sweep(State, _root, [(Out, "")], emitted); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(At("Alpha.g.cs"))); + } + + [Fact] + public void A_directory_whose_case_changed_keeps_its_files() + { + var run = Run(Root("Alpha"), new PerValue(byPackage: true, dir: "acme/")); + var emitted = run.EmittedPaths.Select(p => p.Replace(Path.DirectorySeparatorChar + "acme" + Path.DirectorySeparatorChar, + Path.DirectorySeparatorChar + "ACME" + Path.DirectorySeparatorChar, StringComparison.Ordinal)).ToHashSet(); + Assert.Contains(emitted, p => p.Contains("ACME", StringComparison.Ordinal)); + var swept = OrphanSweep.Sweep(State, _root, [(Out, "")], emitted); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(At("acme/Alpha.g.cs"))); + } + + [Fact] + public void Several_runs_sweep_their_union_and_nested_directories_survive() + { + var inner = Path.Combine(Out, "inner"); + var outer = Run(Root("Alpha"), new PerValue(byPackage: false)); + var nested = Run(Root("Beta"), new PerValue(byPackage: false), outDir: inner); + // Swept alone, the outer run's sweep would see the inner run's recorded files as orphans. + var swept = Sweep([outer, nested], [Out, inner]); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(Path.Combine(inner, "Beta.g.cs"))); + Assert.True(File.Exists(At("Alpha.g.cs"))); + } + + [Fact] + public void Output_written_before_the_manifest_is_reported_never_deleted() + { + // A file an earlier, manifest-less run wrote: MetaObjects' own header, but no recorded hash, so + // an edit to it cannot be told from an untouched copy. + Directory.CreateDirectory(Out); + File.WriteAllText(At("Legacy.g.cs"), "// \n// Generated by MetaObjects values.\npublic sealed class Legacy { }\n"); + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([run], [Out], reportUnrecorded: true); + Assert.Empty(swept.Removed); + Assert.Equal(["gen/Legacy.g.cs"], swept.Unrecorded); + Assert.True(File.Exists(At("Legacy.g.cs"))); + Assert.Empty(Sweep([run], [Out]).Unrecorded); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs index fe02ac0ef1..578a035734 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs @@ -77,7 +77,7 @@ private void Model(string package, params string[] values) => } private (int Code, string Out, string Err) Gen(params string[] extra) => Run(["gen", Meta, "--out", Out, "--namespace", "Acme.Generated", .. extra]); - private (int Code, string Out, string Err) Verify() => Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + private (int Code, string Out, string Err) Verify() => Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); private Dictionary Manifest() => JsonSerializer.Deserialize>(File.ReadAllText(ManifestPath))!; diff --git a/server/csharp/MetaObjects.Codegen.Tests/OutputPathsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OutputPathsTests.cs new file mode 100644 index 0000000000..7b4fb41261 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/OutputPathsTests.cs @@ -0,0 +1,265 @@ +// R39: generated output paths are keyed by metadata package. Every per-object generator writes +// `/`, so two same-named objects in two packages are two files. Since +// rc.19 R65 the C# namespace follows the package too, so a same-namespace clash takes an explicit +// mapping of both packages onto one namespace; the claim registry refuses it, naming both. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class OutputPathsTests +{ + private static string Note(string pkg, string field) => $$""" + { "metadata.root": { "package": "{{pkg}}", "children": [ + { "object.entity": { "name": "Note", "children": [ + { "source.rdb": { "@table": "{{pkg.Replace("::", "_")}}_notes" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "{{field}}" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } } + """; + + private static MetaRoot Load() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Note("acme::alpha", "alphaText"), id: "a.json"), + new InMemoryStringSource(Note("acme::beta", "betaText"), id: "b.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + private static GenContext Ctx(MetaRoot root, bool mapped) => new() + { + Entities = root.Objects(), Root = root, + Config = new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", Namespace = "Acme.Generated", + PackageNamespaces = mapped ? new() { ["acme::alpha"] = "Acme.Alpha", ["acme::beta"] = "Acme.Beta" } : new(), + }, + }; + + /// R65: a real same-namespace clash — both packages mapped, explicitly, onto one namespace. + private static GenContext OneNamespace(MetaRoot root) => new() + { + Entities = root.Objects(), Root = root, + Config = new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", Namespace = "Acme.Generated", + PackageNamespaces = new() { ["acme::alpha"] = "Acme.Shared", ["acme::beta"] = "Acme.Shared" }, + }, + }; + + [Fact] + public void A_file_is_written_under_its_objects_package() + { + var root = Load(); + Assert.Equal("acme/alpha/Note.g.cs", OutputPaths.Of(root.Objects().First(o => o.ResolutionKey() == "acme::alpha::Note"), + new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package }, "Note.g.cs")); + } + + [Fact] + public void Two_same_named_objects_in_two_packages_are_two_files_from_every_per_object_generator() + { + var ctx = Ctx(Load(), mapped: true); + foreach (var (gen, file) in new (IGenerator, string)[] + { + (new EntityGenerator(), "Note.g.cs"), (new NamesGenerator(), "NoteNames.g.cs"), + (new FilterAllowlistGenerator(), "NoteFilterAllowlist.g.cs"), + }) + { + var paths = gen.Generate(ctx).Select(f => f.Path).Where(p => p.EndsWith("/" + file)).Order().ToList(); + Assert.Equal([$"acme/alpha/{file}", $"acme/beta/{file}"], paths); + } + } + + [Fact] + public void One_namespace_still_refuses_the_pair_with_PackageNamespaces_as_the_remedy() + { + var ex = Assert.Throws(() => new EntityGenerator().Generate(OneNamespace(Load())).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("GenConfig.PackageNamespaces", ex.Message); + } + + // rc.19 fix round (I2): package-keyed paths mean two same-named objects no longer collide on one + // output file, so only a claim stops a duplicate type: every generator that emits a class claims + // its name where it emits it, and the filter allowlist lands in its entity's namespace. + + private static List CompileErrors(IEnumerable files) + { + var sources = files.ToList(); + var comp = CSharpCompilation.Create("paths_" + Guid.NewGuid().ToString("N"), + sources.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))), + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + return comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); + } + + [Fact] + public void Two_packages_mapped_apart_compile_entity_names_and_filter_allowlist_together() + { + var ctx = Ctx(Load(), mapped: true); + var files = new EntityGenerator().Generate(ctx).Concat(new NamesGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)).ToList(); + Assert.Contains("namespace Acme.Alpha;", Assert.Single(files, f => f.Path == "acme/alpha/NoteFilterAllowlist.g.cs").Content); + var errors = CompileErrors(files); + Assert.True(errors.Count == 0, "generated code should compile, but got:\n" + string.Join("\n", errors)); + } + + public static TheoryData ClassEmitters => new() { "names", "filter-allowlist" }; + + [Theory] + [MemberData(nameof(ClassEmitters))] + public void A_duplicate_in_one_namespace_is_a_named_refusal_not_CS0101(string generator) + { + IGenerator gen = generator == "names" ? new NamesGenerator() : new FilterAllowlistGenerator(); + var ex = Assert.Throws(() => gen.Generate(OneNamespace(Load())).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("acme::alpha::Note", ex.Message); + Assert.Contains("acme::beta::Note", ex.Message); + Assert.Contains("GenConfig.PackageNamespaces", ex.Message); + } + + private static string Prompt(string pkg) => $$""" + { "metadata.root": { "package": "{{pkg}}", "children": [ + { "object.value": { "name": "Ask{{pkg.Replace("::", "")}}", "children": [ { "field.string": { "name": "q" } } ] } }, + { "object.value": { "name": "Detail{{pkg.Replace("::", "")}}", "children": [ { "field.string": { "name": "d" } } ] } }, + { "object.value": { "name": "Answer{{pkg.Replace("::", "")}}", "children": [ { "field.string": { "name": "a" } }, + { "field.object": { "name": "detail", "@objectRef": "Detail{{pkg.Replace("::", "")}}" } } ] } }, + { "template.prompt": { "name": "Ask", "@payloadRef": "Ask{{pkg.Replace("::", "")}}", "@responseRef": "Answer{{pkg.Replace("::", "")}}", + "@textRef": "ask/x", "@format": "text", "@responseFormat": "json" } } ] } } + """; + + public static TheoryData TemplateEmitters => new() { "render-helper", "output-parser", "output-prompt", "extractor" }; + + [Theory] + [MemberData(nameof(TemplateEmitters))] + public void Two_same_named_templates_in_two_packages_are_a_named_refusal(string generator) + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Prompt("acme::alpha"), id: "a.json"), + new InMemoryStringSource(Prompt("acme::beta"), id: "b.json")]); + Assert.Empty(r.Errors); + var templates = Directory.CreateTempSubdirectory("mo-paths-tmpl-").FullName; + Directory.CreateDirectory(Path.Combine(templates, "ask")); + File.WriteAllText(Path.Combine(templates, "ask", "x.mustache"), "{{q}}"); + IGenerator gen = generator switch + { + "render-helper" => new RenderHelperGenerator(templates), + "output-parser" => new OutputParserGenerator(), + "output-prompt" => new OutputPromptGenerator(), + _ => new ExtractorGenerator(), + }; + // The template tier always emits into GenConfig.Namespace, so mapping the packages cannot help. + var ex = Assert.Throws(() => gen.Generate(Ctx(r.Root, mapped: true)).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("rename one", ex.Message); + // The refusal says why: the tier stays in the home namespace, whatever the package. + Assert.Contains("is declared in the configured namespace, GenConfig.Namespace, whatever its package", ex.Message); + Assert.DoesNotContain("PackageNamespaces", ex.Message); + } + + private static string Proc(string pkg) => $$""" + { "metadata.root": { "package": "{{pkg}}", "children": [ + { "object.projection": { "name": "Digest", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_{{pkg.Replace("::", "_")}}_digest" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "total" } } ] } } ] } } + """; + + [Fact] + public void Two_same_named_callables_in_two_packages_are_a_named_refusal_that_says_why() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Proc("acme::alpha"), id: "a.json"), + new InMemoryStringSource(Proc("acme::beta"), id: "b.json")]); + Assert.Empty(r.Errors); + // The wrapper class is declared in GenConfig.Namespace, so mapping the packages cannot help. + var ex = Assert.Throws(() => new CallableGenerator().Generate(Ctx(r.Root, mapped: true)).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("rename one (a callable wrapper is declared in the configured namespace, GenConfig.Namespace, whatever its package", ex.Message); + } + + private static string Report(string pkg) => $$""" + { "metadata.root": { "package": "{{pkg}}", "children": [ + { "object.entity": { "name": "Invoice", "children": [ + { "source.rdb": { "@table": "{{pkg.Replace("::", "_")}}_invoices" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id" } }, + { "dimension.attribute": { "name": "label", "@of": "Invoice.label" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Invoice.id" } } ] } }, + { "object.report": { "name": "InvoiceTotals", "@from": "Invoice", "@dimensions": ["label"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_{{pkg.Replace("::", "_")}}_invoice_totals" } } ] } } ] } } + """; + + [Fact] + public void Two_same_named_reports_in_two_packages_each_get_an_export_in_their_own_namespace() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Report("acme::alpha"), id: "a.json"), + new InMemoryStringSource(Report("acme::beta"), id: "b.json")]); + Assert.Empty(r.Errors); + var files = new ReportExportGenerator().Generate(Ctx(r.Root, mapped: false)).ToList(); + Assert.Contains("namespace Acme.Alpha;", Assert.Single(files, f => f.Path == "acme/alpha/InvoiceTotalsExport.g.cs").Content); + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path == "acme/beta/InvoiceTotalsExport.g.cs").Content); + } + + [Fact] + public void Two_same_named_reports_mapped_onto_one_namespace_are_a_named_refusal_from_the_export() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Report("acme::alpha"), id: "a.json"), + new InMemoryStringSource(Report("acme::beta"), id: "b.json")]); + Assert.Empty(r.Errors); + var ex = Assert.Throws(() => new ReportExportGenerator().Generate(OneNamespace(r.Root)).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("InvoiceTotalsExport", ex.Message); + } + + // rc.19 fix round (M1): the path half the GetFileName-based tests stopped pinning. Every + // per-object generator writes its object's file under the object's package directory. + public static TheoryData PerObjectFiles => new() + { + { "entity", "acme/alpha/Note.g.cs" }, + { "names", "acme/alpha/NoteNames.g.cs" }, + { "filter-allowlist", "acme/alpha/NoteFilterAllowlist.g.cs" }, + { "routes", "acme/alpha/NoteRoutes.g.cs" }, + { "output-parser", "acme/alpha/Ask.response.cs" }, + { "output-prompt", "acme/alpha/Ask.responseFormat.cs" }, + { "render-helper", "acme/alpha/Ask.render.cs" }, + { "extractor", "acme/alpha/AskExtractor.cs" }, + { "report-export", "acme/alpha/InvoiceTotalsExport.g.cs" }, + }; + + [Theory] + [MemberData(nameof(PerObjectFiles))] + public void Every_per_object_generator_writes_under_its_objects_package(string generator, string path) + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Note("acme::alpha", "alphaText"), id: "n.json"), + new InMemoryStringSource(Prompt("acme::alpha"), id: "p.json"), + new InMemoryStringSource(Report("acme::alpha"), id: "r.json")]); + Assert.Empty(r.Errors); + var templates = Directory.CreateTempSubdirectory("mo-paths-tmpl-").FullName; + Directory.CreateDirectory(Path.Combine(templates, "ask")); + File.WriteAllText(Path.Combine(templates, "ask", "x.mustache"), "{{q}}"); + IGenerator gen = generator switch + { + "entity" => new EntityGenerator(), + "names" => new NamesGenerator(), + "filter-allowlist" => new FilterAllowlistGenerator(), + "routes" => new RoutesGenerator(), + "output-parser" => new OutputParserGenerator(), + "output-prompt" => new OutputPromptGenerator(), + "render-helper" => new RenderHelperGenerator(templates), + "extractor" => new ExtractorGenerator(), + _ => new ReportExportGenerator(), + }; + var paths = gen.Generate(Ctx(r.Root, mapped: false)).Select(f => f.Path).ToList(); + Assert.Contains(path, paths); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs index 45e64cc9e5..d0c3ba5406 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs @@ -17,13 +17,17 @@ public class PackageBindingResolverTests { OutDir = "/tmp", Namespace = "Acme.Generated", + PackageNamespacesFromMetadata = true, }; + // rc.19 R65: with no binding, a package's namespace is the package itself, PascalCased per + // segment (as Java and Kotlin map packages); the configured namespace places package-less types. [Fact] - public void Default_config_falls_back_to_Namespace_byte_identical_to_pre_FR021() + public void Default_config_maps_a_package_to_its_own_namespace_and_no_package_to_Namespace() { var cfg = CfgWithDefaults(); - Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + Assert.Equal("Acme.Orders", PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); + Assert.Equal("Acme.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access", "User")); Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, null)); Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "")); } @@ -41,16 +45,16 @@ public void Type_override_wins_over_package_override_and_convention() }, PackageNamespaces = new Dictionary { - ["acme::cases"] = "Acme.Entities.CaseSpecialOverride", + ["acme::orders"] = "Acme.Entities.OrderSpecialOverride", }, TypeOverrides = new Dictionary { - ["acme::cases::Currency"] = "Acme.Shared.Money", + ["acme::orders::Currency"] = "Acme.Shared.Money", }, }; - Assert.Equal("Acme.Shared.Money", PackageBindingResolver.Resolve(cfg, "acme::cases", "Currency")); - Assert.Equal("Acme.Entities.CaseSpecialOverride", PackageBindingResolver.Resolve(cfg, "acme::cases", "OtherType")); + Assert.Equal("Acme.Shared.Money", PackageBindingResolver.Resolve(cfg, "acme::orders", "Currency")); + Assert.Equal("Acme.Entities.OrderSpecialOverride", PackageBindingResolver.Resolve(cfg, "acme::orders", "OtherType")); } [Fact] @@ -67,12 +71,12 @@ public void Convention_rule_strips_prefix_pascalcases_segments_joins_by_separato }, }; - Assert.Equal("Acme.Domain.Entities.Cases", - PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + Assert.Equal("Acme.Domain.Entities.Orders", + PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); Assert.Equal("Acme.Domain.Entities.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access", "User")); - Assert.Equal("Acme.Domain.Entities.Cases.CustomProperties", - PackageBindingResolver.Resolve(cfg, "acme::cases::custom-properties", "CustomProperty")); + Assert.Equal("Acme.Domain.Entities.Orders.CustomProperties", + PackageBindingResolver.Resolve(cfg, "acme::orders::custom-properties", "CustomProperty")); } [Fact] @@ -89,7 +93,7 @@ public void Convention_falls_through_when_package_does_not_start_with_strip() }; // Falls back to Flatten (Acme.Generated) since the package doesn't match strip. - Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "other::cases", "Case")); + Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "other::orders", "Order")); } [Fact] @@ -164,19 +168,19 @@ public void An_override_that_is_not_an_identifier_path_stops_generation(string t { var typeOverride = CfgWithDefaults() with { - TypeOverrides = new Dictionary { ["acme::cases::Case"] = target }, + TypeOverrides = new Dictionary { ["acme::orders::Order"] = target }, }; var packageOverride = CfgWithDefaults() with { - PackageNamespaces = new Dictionary { ["acme::cases"] = target }, + PackageNamespaces = new Dictionary { ["acme::orders"] = target }, }; foreach (var cfg in new[] { typeOverride, packageOverride }) { - var ex = Assert.Throws(() => PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + var ex = Assert.Throws(() => PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); Assert.Contains($"\"{badSegment}\" is not an identifier", ex.Message); - Assert.Contains("metadata package \"acme::cases\"", ex.Message); - Assert.Throws(() => PackageBindingResolver.TryResolve(cfg, "acme::cases", "Case")); + Assert.Contains("metadata package \"acme::orders\"", ex.Message); + Assert.Throws(() => PackageBindingResolver.TryResolve(cfg, "acme::orders", "Order")); } } @@ -254,7 +258,7 @@ public void TryResolve_returns_null_when_nothing_matches_for_provided_enum_use_c } [Fact] - public void Real_P3_config_resolves_all_18_domains_correctly() + public void Adopter_style_config_resolves_all_domains_correctly() { var cfg = CfgWithDefaults() with { @@ -271,20 +275,20 @@ public void Real_P3_config_resolves_all_18_domains_correctly() ["acme::reporting"] = "Acme.Domain.Entities.ReportEntities", ["acme::domain::dataEnums"] = "Acme.Domain.DataEnums", ["acme::domain::dataEnums::authorizations"] = "Acme.Domain.DataEnums.Authorizations", - ["acme::domain::dataEnums::copayCards"] = "Acme.Domain.DataEnums.CopayCards", - ["acme::domain::dataEnums::dataExportIntegration"] = "Acme.Domain.DataEnums.DataExportIntegration", - ["acme::domain::dataEnums::spIntegration"] = "Acme.Domain.DataEnums.SPIntegration", + ["acme::domain::dataEnums::couponCards"] = "Acme.Domain.DataEnums.CouponCards", + ["acme::domain::dataEnums::warehouseFeed"] = "Acme.Domain.DataEnums.WarehouseFeed", + ["acme::domain::dataEnums::ediIntegration"] = "Acme.Domain.DataEnums.EDIIntegration", }, }; - // Convention rule: 13 of the 19 P3 domains fall through here. - Assert.Equal("Acme.Domain.Entities.Cases", PackageBindingResolver.Resolve(cfg, "acme::cases")); + // Convention rule: most of the domains fall through here. + Assert.Equal("Acme.Domain.Entities.Orders", PackageBindingResolver.Resolve(cfg, "acme::orders")); Assert.Equal("Acme.Domain.Entities.Workflow", PackageBindingResolver.Resolve(cfg, "acme::workflow")); - Assert.Equal("Acme.Domain.Entities.Patients", PackageBindingResolver.Resolve(cfg, "acme::patients")); + Assert.Equal("Acme.Domain.Entities.Players", PackageBindingResolver.Resolve(cfg, "acme::players")); Assert.Equal("Acme.Domain.Entities.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access")); Assert.Equal("Acme.Domain.Entities.Authorizations", PackageBindingResolver.Resolve(cfg, "acme::authorizations")); - // Overrides win for the 6 P3-specific names. + // Overrides win for the adopter-specific names. Assert.Equal("Acme.Domain.Entities.ReportEntities", PackageBindingResolver.Resolve(cfg, "acme::reporting")); Assert.Equal("Acme.Domain.DataEnums", PackageBindingResolver.Resolve(cfg, "acme::domain::dataEnums")); Assert.Equal("Acme.Domain.DataEnums.Authorizations", PackageBindingResolver.Resolve(cfg, "acme::domain::dataEnums::authorizations")); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs new file mode 100644 index 0000000000..e3bb7b11c9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs @@ -0,0 +1,199 @@ +// rc.19 R65: a generated type's C# namespace is its metadata package, each `::` segment +// PascalCased (`acme::alpha` → `Acme.Alpha`), as the Java and Kotlin ports map packages. +// GenConfig.Namespace places only package-less objects and the artifacts of no single package +// (the context, the callable wrappers, the template tier). So two same-named entities in two +// packages are two types, and every generated file names each one `global::`-qualified: no +// namespace can capture another (CS0234), and no pair of `using`s can make a name ambiguous +// (CS0104). + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class PackageNamespaceTests +{ + // Each package holds a `Note` entity, a `Comment` entity that references it (reverse finders), + // a `Payload` value object and a prompt over it (the template tier). The beta pair declares + // collection names, since one routes app cannot serve `/notes` twice. `acme::app::acme::Tag` + // lands in `Acme.App.Acme`, a child of the configured home `Acme.App`: inside the home + // namespace, a partially-qualified `Acme.Alpha.Note` would resolve `Acme` to it (CS0234). + // `acme::alpha::system::Clock` lands in `Acme.Alpha.System`, so inside `Acme.Alpha` a + // `System.Text.Json…` written without `global::` would resolve to it (CS0234) too. + private static string Package(string pkg, string prefix, string prompt, bool collectionNames) => $$""" + { "metadata.root": { "package": "{{pkg}}", "children": [ + { "object.entity": { "name": "Note"{{(collectionNames ? ", \"@collectionName\": \"BetaNotes\"" : "")}}, "children": [ + { "source.rdb": { "@table": "{{prefix}}_notes" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "text" } }, + { "field.enum": { "name": "level", "@values": ["LOW", "HIGH"] } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, + { "object.entity": { "name": "Comment"{{(collectionNames ? ", \"@collectionName\": \"BetaComments\"" : "")}}, "children": [ + { "source.rdb": { "@table": "{{prefix}}_comments" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "noteId", "@required": true } }, + { "field.object": { "name": "payload", "@objectRef": "Payload", "@storage": "jsonb" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { "name": "refNote", "@fields": "noteId", "@references": "Note" } } ] } }, + { "object.value": { "name": "Payload", "children": [ { "field.string": { "name": "text" } } ] } }, + { "template.prompt": { "name": "{{prompt}}", "@payloadRef": "Payload", "@responseRef": "Payload", + "@textRef": "p/{{prefix}}", "@format": "text", "@responseFormat": "json" } } + ] } } + """; + + private const string App = """ + { "metadata.root": { "package": "acme::app", "children": [ + { "object.projection": { "name": "Digest", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_digest", "@parameterRef": "acme::beta::Payload" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "total" } } ] } } + ] } } + """; + + private const string Capturing = """ + { "metadata.root": { "package": "acme::app::acme", "children": [ + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } + ] } } + """; + + private static MetaRoot Load() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Package("acme::alpha", "alpha", "AlphaPrompt", collectionNames: false), id: "a.json"), + new InMemoryStringSource(Package("acme::beta", "beta", "BetaPrompt", collectionNames: true), id: "b.json"), + new InMemoryStringSource(App, id: "app.json"), + new InMemoryStringSource(Capturing, id: "tag.json"), + new InMemoryStringSource(Capturing.Replace("acme::app::acme", "acme::alpha::system").Replace("\"Tag\"", "\"Clock\"").Replace("tags", "clocks"), id: "sys.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + private static GenContext Ctx(MetaRoot root, GenConfig? config = null) => new() + { + Entities = root.Objects(), Root = root, + Config = config ?? new GenConfig { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, OutDir = "/tmp", Namespace = "Acme.App", Dialect = "postgres", IncludeNames = true }, + }; + + private static string TemplateRoot() + { + var root = Path.Combine(Path.GetTempPath(), "pkgns_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(root, "p")); + File.WriteAllText(Path.Combine(root, "p", "alpha.mustache"), "Alpha {{text}}"); + File.WriteAllText(Path.Combine(root, "p", "beta.mustache"), "Beta {{text}}"); + return root; + } + + private static List GenerateAll(GenContext ctx) + { + var templates = TemplateRoot(); + IGenerator[] generators = + [ + new EntityGenerator(), new NamesGenerator(), new DbContextGenerator(), new FilterAllowlistGenerator(), + new RoutesGenerator(), new CallableGenerator(), + new RenderHelperGenerator(templates), new OutputParserGenerator(), new OutputPromptGenerator(), new ExtractorGenerator(), + ]; + return generators.SelectMany(g => g.Generate(ctx)).ToList(); + } + + [Fact] + public void A_type_takes_its_packages_namespace() + { + var files = GenerateAll(Ctx(Load())); + Assert.Contains("namespace Acme.Alpha;", Assert.Single(files, f => f.Path == "acme/alpha/Note.g.cs").Content); + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path == "acme/beta/Note.g.cs").Content); + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path == "acme/beta/Payload.g.cs").Content); + Assert.Contains("namespace Acme.App.Acme;", Assert.Single(files, f => f.Path == "acme/app/acme/Tag.g.cs").Content); + // The per-entity companions follow their entity. + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path.EndsWith("beta/NoteRoutes.g.cs")).Content); + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path.EndsWith("beta/CommentQueries.g.cs")).Content); + // The artifacts of no single object stay in the configured namespace. + Assert.Contains("namespace Acme.App;", Assert.Single(files, f => f.Path.EndsWith("AppDbContext.g.cs")).Content); + Assert.Contains("namespace Acme.App;", Assert.Single(files, f => f.Path.EndsWith("Digest.callable.g.cs")).Content); + Assert.Contains("namespace Acme.App;", Assert.Single(files, f => f.Path.EndsWith("AlphaPrompt.response.cs")).Content); + } + + [Fact] + public void Two_same_named_entities_in_two_packages_build_together_with_every_tier() + { + var files = GenerateAll(Ctx(Load())); + var errors = CompileErrors(files); + Assert.True(errors.Count == 0, "generated code should compile, but got:\n" + string.Join("\n", errors)); + } + + [Fact] + public void A_package_less_object_takes_the_configured_namespace() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(""" + { "metadata.root": { "children": [ + { "object.value": { "name": "Loose", "children": [ { "field.string": { "name": "x" } } ] } } ] } } + """, id: "loose.json")]); + Assert.Empty(r.Errors); + var file = Assert.Single(new EntityGenerator().Generate(Ctx(r.Root)), f => f.Path == "Loose.g.cs"); + Assert.Contains("namespace Acme.App;", file.Content); + } + + [Fact] + public void PackageNamespaces_keeps_a_package_where_it_was() + { + var ctx = Ctx(Load(), new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", Namespace = "Acme.App", Dialect = "postgres", + PackageNamespaces = new() { ["acme::alpha"] = "Acme.App" }, + }); + var files = new EntityGenerator().Generate(ctx).ToList(); + Assert.Contains("namespace Acme.App;", Assert.Single(files, f => f.Path == "acme/alpha/Note.g.cs").Content); + Assert.Contains("namespace Acme.Beta;", Assert.Single(files, f => f.Path == "acme/beta/Note.g.cs").Content); + } + + [Fact] + public void Two_packages_mapped_onto_one_namespace_are_still_refused() + { + var ctx = Ctx(Load(), new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", Namespace = "Acme.App", + PackageNamespaces = new() { ["acme::alpha"] = "Acme.Shared", ["acme::beta"] = "Acme.Shared" }, + }); + var ex = Assert.Throws(() => new EntityGenerator().Generate(ctx).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("Acme.Shared", ex.Message); + Assert.Matches("\"acme::alpha::(Note|Comment|Payload)\" and \"acme::beta::(Note|Comment|Payload)\"", ex.Message); + } + + [Fact] + public void An_explicit_Error_strategy_under_a_namespace_keeps_its_meaning() + { + var ctx = Ctx(Load(), new GenConfig { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, OutDir = "/tmp", Namespace = "Acme.App", UnmappedStrategy = UnmappedPackageStrategy.Error }); + var ex = Assert.Throws(() => new EntityGenerator().Generate(ctx).ToList()); + Assert.Contains("has no namespace binding", ex.Message); + } + + internal static List CompileErrors(IEnumerable files) + { + var sources = files.Where(f => f.Path.EndsWith(".cs")).ToList(); + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var p in ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator)) + if (p.Length > 0) paths.Add(p); + paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); + paths.Add(typeof(Uri).Assembly.Location); + paths.Add(typeof(MetaObjects.Codegen.Runtime.FilterParser).Assembly.Location); + paths.Add(typeof(MetaObjects.Render.Extract.ExtractSchema).Assembly.Location); + paths.Add(typeof(MetaObject).Assembly.Location); + var comp = CSharpCompilation.Create("pkgns_" + Guid.NewGuid().ToString("N"), + sources.Select(f => CSharpSyntaxTree.ParseText(MetaObjects.Codegen.FrameworkQualifier.Qualify(f.Content), new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), + paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + return comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()} @ {d.Location.SourceTree?.FilePath}: " + + d.Location.SourceTree?.GetText().Lines[d.Location.GetLineSpan().StartLinePosition.Line].ToString().Trim()) + .ToList(); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs index 0f41436c75..029fd93b04 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs @@ -115,15 +115,15 @@ public void A_configured_resolver_names_every_property_the_entities_and_the_cont var files = Generate(ctx, new EntityGenerator(), new DbContextGenerator()); Assert.Empty(CompileErrors(files)); - var line = files.Single(f => f.Path == "OrderLine.g.cs").Content; + var line = files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderLine.g.cs").Content; Assert.Contains("[PrimaryKey(nameof(OrderNo), nameof(LineNO))]", line); Assert.Contains("public long CustomerID { get; set; }", line); - var context = files.Single(f => f.Path == "AppDbContext.g.cs").Content; + var context = files.Single(f => System.IO.Path.GetFileName(f.Path) == "AppDbContext.g.cs").Content; Assert.Contains("HasForeignKey(e => e.CustomerID)", context); Assert.Contains("Property(x => x.STATUS)", context); Assert.Contains("HasDiscriminator(e => e.KIND)", context); Assert.Contains("b.Property(p => p.ZIPCode)", context); - var finders = files.Single(f => f.Path == "OrderLineQueries.g.cs").Content; + var finders = files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderLineQueries.g.cs").Content; Assert.Contains("e.CustomerID ==", finders); } @@ -141,11 +141,40 @@ private sealed class AcronymContext : DbContextGenerator [Fact] public void The_overridable_hooks_agree_across_both_generators() { - var ctx = Ctx(Load()); + // The hooks agree with the resolver: the run is accepted and compiles. + var ctx = Ctx(Load(), Acronyms); var files = Generate(ctx, new AcronymEntities(), new AcronymContext()); Assert.Empty(CompileErrors(files)); - Assert.Contains("e.CustomerID ==", files.Single(f => f.Path == "OrderLineQueries.g.cs").Content); + Assert.Contains("e.CustomerID ==", files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderLineQueries.g.cs").Content); + } + + [Fact] + public void A_hook_override_that_differs_from_the_resolver_is_refused() + { + // No resolver set: the override alone would rename the entity's property and nothing else. + var ex = Assert.Throws(() => new AcronymEntities().Generate(Ctx(Load())).ToList()); + Assert.Contains("set GenConfig.PropertyNaming", ex.Message); + Assert.Contains("hook names field \"", ex.Message); + var ex2 = Assert.Throws(() => new AcronymContext().Generate(Ctx(Load())).ToList()); + Assert.Contains("set GenConfig.PropertyNaming", ex2.Message); + } + + // A context hook that differs from the resolver only on a value-object member, or only on a TPH + // subtype's own field, would reference a name the class does not declare: refused up front. + private sealed class DivergesOn(string field) : DbContextGenerator + { + protected override string PropertyName(MetaField f) => f.Name == field ? "Diverged" : base.PropertyName(f); + } + + [Theory] + [InlineData("zipCode")] // PostalAddress, a value object + [InlineData("seatCount")] // Car, a TPH subtype + public void The_context_hook_guard_covers_value_object_members_and_subtype_fields(string field) + { + var ex = Assert.Throws(() => new DivergesOn(field).Generate(Ctx(Load())).ToList()); + Assert.Contains($".{field}\"", ex.Message); + Assert.Contains("set GenConfig.PropertyNaming", ex.Message); } [Fact] @@ -161,7 +190,7 @@ public void Without_a_resolver_the_output_is_the_pascal_default() public void Reverse_finders_take_the_configured_context_type() { var files = new EntityGenerator().Generate(Ctx(Load(), contextType: "ShopContext")).ToList(); - var finders = files.Single(f => f.Path == "OrderLineQueries.g.cs").Content; + var finders = files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderLineQueries.g.cs").Content; Assert.Contains("(ShopContext db, long customerId)", finders); Assert.DoesNotContain("AppDbContext", finders); } @@ -171,7 +200,7 @@ public void Reverse_finders_can_be_turned_off() { var files = new EntityGenerator { EmitsReverseFinders = false }.Generate(Ctx(Load())).ToList(); Assert.DoesNotContain(files, f => f.Path.EndsWith("Queries.g.cs", StringComparison.Ordinal)); - Assert.Contains(files, f => f.Path == "OrderLine.g.cs"); + Assert.Contains(files, f => System.IO.Path.GetFileName(f.Path) == "OrderLine.g.cs"); } // E17: a class-level attribute added through the seam, without re-implementing the header. @@ -181,7 +210,7 @@ protected override void EmitClassAttributes( StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) { if (kind is ClassDeclarationKind.MappedEntity or ClassDeclarationKind.TphSubtype) - sb.AppendLine("[System.Serializable]"); + sb.AppendLine("[global::System.Serializable]"); } } @@ -189,13 +218,13 @@ protected override void EmitClassAttributes( public void A_subclass_adds_a_class_attribute_through_the_seam() { var files = new MarkedEntities().Generate(Ctx(Load())).ToList(); - var customer = files.Single(f => f.Path == "Customer.g.cs").Content.Replace("\r\n", "\n"); - Assert.Contains("[System.Serializable]\npublic class Customer", customer); - Assert.True(customer.IndexOf("[Table(", StringComparison.Ordinal) < customer.IndexOf("[System.Serializable]", StringComparison.Ordinal)); - var vehicle = files.Single(f => f.Path == "Vehicle.g.cs").Content.Replace("\r\n", "\n"); + var customer = files.Single(f => System.IO.Path.GetFileName(f.Path) == "Customer.g.cs").Content.Replace("\r\n", "\n"); + Assert.Contains("[global::System.Serializable]\npublic class Customer", customer); + Assert.True(customer.IndexOf("[Table(", StringComparison.Ordinal) < customer.IndexOf("[global::System.Serializable]", StringComparison.Ordinal)); + var vehicle = files.Single(f => System.IO.Path.GetFileName(f.Path) == "Vehicle.g.cs").Content.Replace("\r\n", "\n"); // After the framework's own class attributes, immediately before the declaration. - Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(Van))]\n[System.Serializable]\npublic abstract class Vehicle", vehicle); - Assert.Contains("[System.Serializable]\npublic class Car : Vehicle", files.Single(f => f.Path == "Car.g.cs").Content.Replace("\r\n", "\n")); - Assert.DoesNotContain("[System.Serializable]", files.Single(f => f.Path == "PostalAddress.g.cs").Content); + Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(Van))]\n[global::System.Serializable]\npublic abstract class Vehicle", vehicle); + Assert.Contains("[global::System.Serializable]\npublic class Car : Vehicle", files.Single(f => System.IO.Path.GetFileName(f.Path) == "Car.g.cs").Content.Replace("\r\n", "\n")); + Assert.DoesNotContain("[global::System.Serializable]", files.Single(f => System.IO.Path.GetFileName(f.Path) == "PostalAddress.g.cs").Content); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs new file mode 100644 index 0000000000..8463be2d5b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -0,0 +1,376 @@ +// Every emit site that spells a field's C# property goes through the one resolver +// (GenConfig.PropertyNaming / CSharpNaming.PropertyName), not CSharpNaming.Pascal on the field name. +// A key named `widgetId` that the resolver spells `WidgetID` is declared as `WidgetID` by the entity, +// so the identity-start line, a callable's argument, an extractor's mapper target, a report export +// cell and the routes must all say `WidgetID`; `WidgetId` would not compile. + +using System.IO; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class PropertyNamingEmitSitesTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "widgetId" } }, + { "field.string": { "name": "label", "@maxLength": 40, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "widgetId", "@generation": "increment", "@sequenceStart": 1000 } } + ]}}, + { "object.value": { "name": "WidgetArgs", "children": [ + { "field.long": { "name": "widgetId", "@required": true } }, + { "field.int": { "name": "maxRows" } } + ]}}, + { "object.projection": { "name": "WidgetSummary", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_widget_summary", "@parameterRef": "WidgetArgs" } }, + { "field.long": { "name": "widgetId" } } + ]}}, + { "object.value": { "name": "Part", "children": [ + { "field.string": { "name": "partName", "@required": true } } + ]}}, + { "object.value": { "name": "Gadget", "children": [ + { "field.string": { "name": "gadgetId", "@required": true } }, + { "field.object": { "name": "part", "@objectRef": "Part" } } + ]}}, + { "template.prompt": { "name": "GadgetOut", "@payloadRef": "Gadget", "@responseRef": "Gadget", + "@textRef": "ai/gadget", "@format": "text", "@responseFormat": "json", "@promptStyle": "guide" } } + ]}} + """; + + private static string Spelling(MetaField f) => f.Name switch + { + "widgetId" => "WidgetID", + "gadgetId" => "GadgetID", + "maxRows" => "MaxROWS", + "label" => "LABEL", + _ => CSharpNaming.Pascal(f.Name), + }; + + private static GenContext Ctx(string model = Model, string? dialect = null) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "sites.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, OutDir = "/tmp", Namespace = "Acme.Generated", PropertyNaming = Spelling, Dialect = dialect }, + }; + } + + private static string One(IEnumerable files, string fileName) => + files.Single(f => System.IO.Path.GetFileName(f.Path) == fileName).Content; + + [Fact] + public void The_identity_start_line_names_the_resolved_property() + { + var files = new DbContextGenerator().Generate(Ctx(dialect: "postgres")).ToList(); + var context = One(files, "AppDbContext.g.cs"); + Assert.Contains("Property(x => x.WidgetID).HasAnnotation(", context); + Assert.DoesNotContain("x.WidgetId", context); + + // The entity and the context agree: the pair compiles (the context's CS1061 was the symptom). + var all = new EntityGenerator().Generate(Ctx(dialect: "postgres")).Concat(files); + var trees = all.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))); + var comp = CSharpCompilation.Create("sites_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + Assert.Empty(comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")); + } + + [Fact] + public void A_callable_binds_its_arguments_by_the_resolved_property_names() + { + var src = One(new CallableGenerator().Generate(Ctx()), "WidgetSummary.callable.g.cs"); + Assert.Contains("args.WidgetID", src); + Assert.Contains("args.MaxROWS", src); + Assert.DoesNotContain("args.WidgetId", src); + Assert.DoesNotContain("args.MaxRows", src); + } + + [Fact] + public void An_extractor_maps_onto_the_resolved_property_names() + { + var src = Assert.Single(new ExtractorGenerator().Generate(Ctx())).Content; + Assert.Contains("GadgetID = ", src); + Assert.DoesNotContain("GadgetId = ", src); + } + + [Fact] + public void The_routes_name_the_resolved_property_for_the_key_sort_and_frozen_members() + { + var src = One(new RoutesGenerator().Generate(Ctx()), "WidgetRoutes.g.cs"); + Assert.Contains("\"WidgetID\"", src); + Assert.Contains("\"LABEL\"", src); + Assert.DoesNotContain("\"WidgetId\"", src); + Assert.DoesNotContain("\"Label\"", src); + Assert.DoesNotContain(".WidgetId", src); + } + + private const string ReportModel = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.entity": { "name": "Line", "children": [ + { "source.rdb": { "@table": "lines" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "label", "@of": "Line.label" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Line.id" } } + ] } }, + { "object.report": { "name": "LineTotals", "@from": "Line", "@dimensions": ["label"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_line_totals" } } ] } } + ] } } + """; + + [Fact] + public void A_report_export_reads_the_resolved_property_names_of_the_row() + { + var src = One(new ReportExportGenerator().Generate(Ctx(ReportModel)), "LineTotalsExport.g.cs"); + Assert.Contains("row.LABEL", src); + Assert.DoesNotContain("row.Label", src); + } + + // ---- every routes site, every field renamed beyond case ---- + + private const string AllSitesModel = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.value": { "name": "Dims", "children": [ + { "field.string": { "name": "unit", "@maxLength": 10 } }, + { "field.int": { "name": "size" } } + ]}}, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Gizmo", "children": [ + { "source.rdb": { "@table": "gizmos" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 60, "@filterable": true, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "serial", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } }, + { "field.timestamp": { "name": "createdAt", "@required": true, "@autoSet": "onCreate" } }, + { "field.timestamp": { "name": "updatedAt", "@required": true, "@autoSet": "onUpdate" } }, + { "field.object": { "name": "dims", "@objectRef": "Dims" } }, + { "field.map": { "name": "extras", "@objectRef": "Dims" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["Car", "Van"] } }, + { "field.string": { "name": "plate", "@maxLength": 20, "@filterable": true } }, + { "field.string": { "name": "vinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "VehicleTag" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "Car", "extends": "Vehicle", "@discriminatorValue": "Car", "children": [ + { "field.int": { "name": "seatCount" } }, + { "field.string": { "name": "regNo", "@maxLength": 20, "@mutability": "readOnly" } } + ]}}, + { "object.entity": { "name": "Van", "extends": "Vehicle", "@discriminatorValue": "Van", "children": [ + { "field.int": { "name": "payloadKg" } } + ]}}, + { "object.entity": { "name": "VehicleTag", "children": [ + { "source.rdb": { "@table": "vehicle_tags" } }, + { "field.long": { "name": "vehicleId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "@fields": ["vehicleId", "tagId"] } }, + { "identity.reference": { "name": "fkVehicle", "@fields": "vehicleId", "@references": "Vehicle" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ]}} + ]}} + """; + + // Every field spelled beyond case: nothing here is the PascalCase of its name. + private static string XSpelling(MetaField f) => "X" + CSharpNaming.Pascal(f.Name); + + private static GenContext AllSitesCtx() => AllSitesCtx(XSpelling); + + private static GenContext AllSitesCtx(Func? naming) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(AllSitesModel, id: "all-sites.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal, + PropertyNaming = naming, + }, + }; + } + + private static List AllSites(GenContext ctx) => + new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)) + .Concat(new RoutesGenerator().Generate(ctx)) + .ToList(); + + private static List CompileAll(IEnumerable files) + { + var trees = files.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)).ToList(); + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!; + foreach (var p in tpa.Split(Path.PathSeparator)) if (p.Length > 0) paths.Add(p); + paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location); + paths.Add(typeof(MetaObjects.Codegen.Runtime.FilterParser).Assembly.Location); + var refs = paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); + var comp = CSharpCompilation.Create("all_sites_" + Guid.NewGuid().ToString("N"), trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + return comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()} @ {d.Location}").ToList(); + } + + [Fact] + public void A_model_with_every_routes_site_compiles_with_every_field_renamed() + { + var errors = CompileAll(AllSites(AllSitesCtx())); + Assert.True(errors.Count == 0, "entity + context + filter allowlist + routes should compile:\n" + string.Join("\n", errors)); + } + + [Fact] + public void Without_a_resolver_the_same_model_compiles_and_names_the_pascal_properties() + { + var files = AllSites(AllSitesCtx(null)); + Assert.Empty(CompileAll(files)); + Assert.DoesNotContain("PropertyByField", One(files, "GizmoFilterAllowlist.g.cs")); + } + + [Fact] + public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_every_write() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + + // The credential is named by its CLR property; the JSON key is the serializer's, read at run time + // (SerializerKeys.KeysOf), never spelled here. + Assert.Contains("new string[] { \"XPinHash\", \"pinHash\" }", gizmo); + Assert.Contains("new string[] { \"XVinHash\", \"vinHash\" }", vehicle); + Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); + Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); + + // No response shape bypasses the stripping result: read, list, list-with-count, create, PATCH. + Assert.DoesNotContain("Results.Ok(rows", gizmo); + Assert.DoesNotContain("Results.Ok(found", gizmo); + Assert.DoesNotContain("Results.Ok(existing", gizmo); + Assert.DoesNotContain("Results.Ok(new { rows, total })", gizmo); + Assert.DoesNotContain("Results.Created(", gizmo); + Assert.Contains("new CredentialOmittingResult(", gizmo); + // The TPH routes' only plain Results.Ok(rows) are the M:N Tag lists (no credential on a Tag). + Assert.DoesNotContain("Results.Created(", vehicle); + Assert.DoesNotContain("Results.Ok(existing", vehicle); + Assert.Contains("new CredentialOmittingResult(", vehicle); + + // PATCH refuses to write it: the deny arm matches the serializer-resolved property, and both spellings. + Assert.Contains("if (__clr is \"XPinHash\" or \"XTokenHash\") continue;", gizmo); + Assert.Contains("SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts)", gizmo); + foreach (var k in new[] { "pinHash", "XPinHash", "tokenHash", "XTokenHash" }) + Assert.Contains($"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential", gizmo); + // Create resets the resolved property, so the two writes agree. + Assert.Contains("input.XPinHash = default!;", gizmo); + Assert.Contains("input.XTokenHash = default!;", gizmo); + // The TPH subtype PATCH matches the base's credential under both spellings too. + Assert.Contains("\"XVinHash\"", vehicle); + Assert.Contains("input.XVinHash = default!;", vehicle); + } + + [Fact] + public void A_renamed_value_object_and_map_patch_arm_matches_both_spellings() + { + var gizmo = One(AllSites(AllSitesCtx()), "GizmoRoutes.g.cs"); + Assert.Contains("string.Equals(prop.Name, \"dims\", System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XDims\", System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("string.Equals(prop.Name, \"extras\", System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XExtras\", System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("existing.XDims =", gizmo); + Assert.Contains("existing.XExtras =", gizmo); + } + + [Fact] + public void Sort_and_EF_property_names_are_the_resolved_names_at_every_site() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + Assert.Contains("\"XTitle\" =>", gizmo); + Assert.Contains("EF.Property(x!, \"XTitle\")", gizmo); + Assert.Contains("[\"XTitle\"] = true", gizmo); // @sortableDefaultOrder keys + Assert.DoesNotContain("\"Title\"", gizmo); + Assert.Contains("EF.Property(x!, \"XPlate\")", vehicle); // TPH base + Assert.Contains("\"XSeatCount\",", vehicle); // per-subtype sort allowlist + Assert.DoesNotContain("\"Plate\"", vehicle); + // M:N junction: the FK properties and the target key, by their resolved names. + Assert.Contains("EF.Property(j, \"XVehicleId\")", vehicle); + Assert.Contains("EF.Property(j, \"XTagId\")", vehicle); + Assert.Contains("EF.Property(t, \"XId\")", vehicle); + Assert.DoesNotContain("\"VehicleId\"", vehicle); + } + + [Fact] + public void Frozen_autoset_readonly_and_discriminator_members_use_the_resolved_names() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + // Frozen (readOnly) members are skipped in the PATCH merge by their property name. + Assert.Contains("\"XStamp\"", gizmo); + Assert.Contains("\"XSerial\"", gizmo); + Assert.DoesNotContain("\"Stamp\"", gizmo); + // @autoSet columns are stamped through the resolved properties. + Assert.Contains("XCreatedAt", gizmo); + Assert.Contains("XUpdatedAt", gizmo); + Assert.DoesNotContain(".CreatedAt", gizmo); + // The TPH discriminator is immutable under its resolved name, and is reset on create. + Assert.Contains("\"XKind\"", vehicle); + Assert.Contains("input.XKind = default!;", vehicle); + Assert.Contains("input.Tags = new", vehicle); // the M:N navigation reset: a navigation, not a field + } + + [Fact] + public void The_filter_dispatch_is_given_the_property_map_when_a_rename_goes_beyond_case() + { + var files = AllSites(AllSitesCtx()); + var allowlist = One(files, "GizmoFilterAllowlist.g.cs"); + Assert.Contains("[\"title\"] = \"XTitle\"", allowlist); + var gizmo = One(files, "GizmoRoutes.g.cs"); + Assert.Contains("GizmoFilterAllowlist.PropertyByField", gizmo); + Assert.Contains("EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates, GizmoFilterAllowlist.PropertyByField)", gizmo); + } + + private sealed class FilterRow + { + public long OwnerKey { get; set; } + } + + [Fact] + public void The_filter_dispatch_finds_a_property_the_resolver_renamed_beyond_case() + { + var predicates = new[] { new MetaObjects.Codegen.Runtime.FilterPredicate("ownerRef", "eq", "5") }; + var map = new Dictionary { ["ownerRef"] = "OwnerKey" }; + var rows = new[] { new FilterRow { OwnerKey = 5 }, new FilterRow { OwnerKey = 6 } }.AsQueryable(); + + // With the map the field resolves to its property; without it the lookup misses (the 500 this guards). + var filtered = MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.ApplyFilter(rows, predicates, map).ToList(); + Assert.Equal(5, Assert.Single(filtered).OwnerKey); + Assert.Throws(() => MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.ApplyFilter(rows, predicates)); + + var bad = MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.Validate( + MetaObjects.Codegen.Runtime.FilterParseResult.Ok([new MetaObjects.Codegen.Runtime.FilterPredicate("ownerRef", "eq", "not-a-number")]), map); + Assert.Equal("invalid_filter_value", bad.ErrorEnvelope); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs new file mode 100644 index 0000000000..0b86aace4d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -0,0 +1,160 @@ +// The default output (no property-naming resolver) of the generators the rc.22 property-naming fix +// touched, compared byte for byte against files in Golden/pre-rc22-propname. They were captured from the +// generators BEFORE the fix (de59161f5) and then re-captured ONLY where the credential-stripping security +// fix legitimately changed the output: the four routes files (GizmoRoutes, VehicleRoutes, TagRoutes, +// LineRoutes: the credential omit list, the strip helper call, the startup contract check and the PATCH key +// lookup). Callable, Extractor, ReportExport, FilterAllowlist and DbContext are still byte-identical to +// de59161f5. So with no resolver the output is unchanged except for that security change. +// +// Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test +// --filter PropertyNamingGoldenTests. Compare mode is the default. + +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class PropertyNamingGoldenTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.value": { "name": "Dims", "children": [ + { "field.string": { "name": "unit", "@maxLength": 10 } }, + { "field.int": { "name": "size" } } + ]}}, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id", "@generation": "increment", "@sequenceStart": 500 } } + ]}}, + { "object.entity": { "name": "Gizmo", "children": [ + { "source.rdb": { "@table": "gizmos" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 60, "@filterable": true, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "serial", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } }, + { "field.timestamp": { "name": "createdAt", "@required": true, "@autoSet": "onCreate" } }, + { "field.timestamp": { "name": "updatedAt", "@required": true, "@autoSet": "onUpdate" } }, + { "field.object": { "name": "dims", "@objectRef": "Dims" } }, + { "field.map": { "name": "extras", "@objectRef": "Dims" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["Car", "Van"] } }, + { "field.string": { "name": "plate", "@maxLength": 20, "@filterable": true } }, + { "field.string": { "name": "vinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "VehicleTag" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "Car", "extends": "Vehicle", "@discriminatorValue": "Car", "children": [ + { "field.int": { "name": "seatCount" } }, + { "field.string": { "name": "regNo", "@maxLength": 20, "@mutability": "readOnly" } } + ]}}, + { "object.entity": { "name": "Van", "extends": "Vehicle", "@discriminatorValue": "Van", "children": [ + { "field.int": { "name": "payloadKg" } } + ]}}, + { "object.entity": { "name": "VehicleTag", "children": [ + { "source.rdb": { "@table": "vehicle_tags" } }, + { "field.long": { "name": "vehicleId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "@fields": ["vehicleId", "tagId"] } }, + { "identity.reference": { "name": "fkVehicle", "@fields": "vehicleId", "@references": "Vehicle" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ]}} + ,{ "object.value": { "name": "WidgetArgs", "children": [ + { "field.long": { "name": "widgetId", "@required": true } }, + { "field.int": { "name": "maxRows" } } + ]}}, + { "object.projection": { "name": "WidgetSummary", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_widget_summary", "@parameterRef": "WidgetArgs" } }, + { "field.long": { "name": "widgetId" } } + ]}}, + { "object.value": { "name": "Part", "children": [ + { "field.string": { "name": "partName", "@required": true } } + ]}}, + { "object.value": { "name": "Gadget", "children": [ + { "field.string": { "name": "gadgetId", "@required": true } }, + { "field.object": { "name": "part", "@objectRef": "Part" } } + ]}}, + { "template.prompt": { "name": "GadgetOut", "@payloadRef": "Gadget", "@responseRef": "Gadget", + "@textRef": "ai/gadget", "@format": "text", "@responseFormat": "json", "@promptStyle": "guide" } }, + { "object.entity": { "name": "Line", "children": [ + { "source.rdb": { "@table": "lines" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "label", "@of": "Line.label" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Line.id" } } + ]}}, + { "object.report": { "name": "LineTotals", "@from": "Line", "@dimensions": ["label"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_line_totals" } } ] } } + ]}} + """; + + // Found from the repo root, not [CallerFilePath]: a CI build (CI=true turns on + // ContinuousIntegrationBuild) maps source paths to /_/, where no golden file exists. + private static string GoldenDir() => + Path.Combine(CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen.Tests", "Golden", "pre-rc22-propname"); + + [Fact] + public void Default_output_matches_the_output_captured_before_the_property_naming_fix() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "golden-rc22.json")]); + Assert.Empty(r.Errors); + GenContext Ctx(string? dialect = null) => new() + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal, Dialect = dialect }, + }; + var files = new RoutesGenerator().Generate(Ctx()) + .Concat(new CallableGenerator().Generate(Ctx())) + .Concat(new ExtractorGenerator().Generate(Ctx())) + .Concat(new ReportExportGenerator().Generate(Ctx())) + .Concat(new FilterAllowlistGenerator().Generate(Ctx())) + .Concat(new DbContextGenerator().Generate(Ctx("postgres"))) + .ToList(); + var names = files.Select(f => System.IO.Path.GetFileName(f.Path)).ToList(); + foreach (var name in new[] { "VehicleRoutes.g.cs", "GizmoRoutes.g.cs", "WidgetSummary.callable.g.cs", "LineTotalsExport.g.cs", "AppDbContext.g.cs", "GizmoFilterAllowlist.g.cs" }) + Assert.Contains(name, names); + Assert.True(names.Any(n => n.Contains("Extractor")), string.Join(",", names)); + + var dir = GoldenDir(); + if (Environment.GetEnvironmentVariable("GOLDEN_WRITE") == "1") + { + Directory.CreateDirectory(dir); + foreach (var f in files) File.WriteAllText(Path.Combine(dir, System.IO.Path.GetFileName(f.Path)), f.Content); + return; + } + var expected = Directory.GetFiles(dir).Select(p => Path.GetFileName(p)).Order(StringComparer.Ordinal).ToList(); + var actualNames = files.Select(f => System.IO.Path.GetFileName(f.Path)).Order(StringComparer.Ordinal).ToList(); + Assert.True(expected.SequenceEqual(actualNames), + $"golden file set differs. missing from output: [{string.Join(", ", expected.Except(actualNames))}]; not in golden: [{string.Join(", ", actualNames.Except(expected))}]"); + foreach (var f in files) + { + var name = System.IO.Path.GetFileName(f.Path); + var golden = File.ReadAllText(Path.Combine(dir, name)); + if (golden != f.Content) Assert.Fail(FirstDifference(name, golden, f.Content)); + } + } + + // A golden mismatch names the file, the first differing line and both spellings, so a failure that + // shows only on another machine can be read from its log instead of reproduced. + private static string FirstDifference(string name, string golden, string actual) + { + var g = golden.Split('\n'); + var a = actual.Split('\n'); + var i = 0; + while (i < g.Length && i < a.Length && g[i] == a[i]) i++; + string At(string[] lines, int n) => n < lines.Length ? lines[n].Replace("\r", "\\r") : ""; + return $"{name}: output differs from its golden at line {i + 1} (golden {g.Length} lines, output {a.Length} lines)\n" + + $" golden: {At(g, i)}\n output: {At(a, i)}\n culture: {System.Globalization.CultureInfo.CurrentCulture.Name}; cwd: {Directory.GetCurrentDirectory()}"; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs index 945bc07c86..abbdc187ed 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs @@ -66,12 +66,12 @@ public void The_recipe_generates_verifies_and_catches_drift() Assert.Equal("3.1.0", (string?)api["openapi"]); Assert.Equal(["/api/customers", "/api/customers/{id}"], api["paths"]!.AsObject().Select(p => p.Key)); - Assert.Equal(0, CodegenCli.Run(["verify", "--codegen", Meta, "--out", Out], Suite)); + Assert.Equal(0, CodegenCli.Run(["verify", "--codegen", "--full", Meta, "--out", Out], Suite)); File.WriteAllText(Path.Combine(Meta, "meta.shop.json"), Model.Replace("""{ "field.string": { "name": "email", "@required": true } },""", """{ "field.string": { "name": "email", "@required": true } }, { "field.string": { "name": "note" } },""")); - Assert.NotEqual(0, CodegenCli.Run(["verify", "--codegen", Meta, "--out", Out], Suite)); + Assert.NotEqual(0, CodegenCli.Run(["verify", "--codegen", "--full", Meta, "--out", Out], Suite)); } private sealed class Throws : IGenerator diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs index 6f23085912..39caf0d6d7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs @@ -54,10 +54,10 @@ private static MetaRoot Load() }; private static string Routes(GenContext ctx, string report) => - new RoutesGenerator().Generate(ctx).Single(f => f.Path == report + "Routes.g.cs").Content; + new RoutesGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == report + "Routes.g.cs").Content; private static string Export(GenContext ctx, string report) => - new ReportExportGenerator { MaxRows = 60 }.Generate(ctx).Single(f => f.Path == report + "Export.g.cs").Content; + new ReportExportGenerator { MaxRows = 60 }.Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == report + "Export.g.cs").Content; [Fact] public void The_row_model_marks_a_derived_credential() @@ -78,10 +78,10 @@ public void A_report_over_a_credential_omits_it_from_rows_and_export(string repo { var ctx = Ctx(Load()); var routes = Routes(ctx, report); - Assert.Contains($"new string[] {{ \"{column}\" }}", routes); + Assert.Contains($"new string[] {{ \"{char.ToUpperInvariant(column[0])}{column[1..]}\" }}", routes); Assert.DoesNotContain("Results.Ok(rows)", routes); // The JSON export strips it too; the CSV / XML column list names no credential. - Assert.Contains($"rows, new string[] {{ \"{column}\" }}", routes); + Assert.Contains($"rows, new string[] {{ \"{char.ToUpperInvariant(column[0])}{column[1..]}\" }}", routes); var export = Export(ctx, report); Assert.DoesNotContain($"\"{column}\"", export); Assert.DoesNotContain($"row.{char.ToUpperInvariant(column[0])}{column[1..]}", export); @@ -107,13 +107,15 @@ public void A_plain_report_is_unchanged() public void A_credential_column_is_neither_filterable_nor_sortable(string report, string column, string kept) { var ctx = Ctx(Load()); - var allowlist = new FilterAllowlistGenerator().Generate(ctx).Single(f => f.Path == report + "FilterAllowlist.g.cs").Content; + var allowlist = new FilterAllowlistGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == report + "FilterAllowlist.g.cs").Content; Assert.DoesNotContain($"\"{column}\"", allowlist); Assert.Contains($"\"{kept}\"", allowlist); var routes = Routes(ctx, report); var pascal = char.ToUpperInvariant(column[0]) + column[1..]; - Assert.DoesNotContain($"\"{pascal}\"", routes); + // The credential's CLR name appears once, in the omit list; never as a sort-allowlist entry or sort arm. + Assert.DoesNotContain($" \"{pascal}\",", routes); + Assert.DoesNotContain($"\"{pascal}\" =>", routes); Assert.Contains($"\"{char.ToUpperInvariant(kept[0])}{kept[1..]}\"", routes); } @@ -121,7 +123,7 @@ public void A_credential_column_is_neither_filterable_nor_sortable(string report public void A_plain_reports_allowlists_keep_every_column() { var ctx = Ctx(Load()); - var allowlist = new FilterAllowlistGenerator().Generate(ctx).Single(f => f.Path == "AccountsByNameFilterAllowlist.g.cs").Content; + var allowlist = new FilterAllowlistGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "AccountsByNameFilterAllowlist.g.cs").Content; Assert.Contains("\"name\"", allowlist); Assert.Contains("\"accounts\"", allowlist); var routes = Routes(ctx, "AccountsByName"); diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs index 66313734d7..c93614ea43 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs @@ -67,7 +67,7 @@ private static MetaRoot Load(string model = Model) }; private static string Routes(GenContext ctx) => - new RoutesGenerator().Generate(ctx).Single(f => f.Path == "LineTotalsRoutes.g.cs").Content; + new RoutesGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == "LineTotalsRoutes.g.cs").Content; [Fact] public void Routes_are_unchanged_when_no_export_generator_is_wired() @@ -99,7 +99,7 @@ public void A_hand_edits_wrapper_does_not_hide_the_wiring() [Fact] public void It_writes_one_shared_writer_and_one_module_per_served_report_only() { - var files = new ReportExportGenerator().Generate(Ctx(Load())).ToDictionary(f => f.Path, f => f.Content); + var files = new ReportExportGenerator().Generate(Ctx(Load())).ToDictionary(f => System.IO.Path.GetFileName(f.Path), f => f.Content); Assert.Equal(["LineTotalsExport.g.cs", "ReportExportWriter.g.cs"], files.Keys.OrderBy(k => k, StringComparer.Ordinal)); var module = files["LineTotalsExport.g.cs"]; Assert.Contains("Root = \"LineTotals\"", module); @@ -112,7 +112,7 @@ public void It_writes_one_shared_writer_and_one_module_per_served_report_only() public void Options_reach_the_shared_writer() { var writer = new ReportExportGenerator { CsvBom = true, XmlNulls = ReportExportXmlNulls.Empty } - .Generate(Ctx(Load())).Single(f => f.Path == "ReportExportWriter.g.cs").Content; + .Generate(Ctx(Load())).Single(f => System.IO.Path.GetFileName(f.Path) == "ReportExportWriter.g.cs").Content; Assert.Contains("ExportCsvBom = true;", writer); Assert.Contains("XmlNil = false;", writer); } @@ -150,7 +150,7 @@ private static MethodInfo[] Compile(ReportExportGenerator gen, string? decimals { var root = Load(model); if (decimals == "string") root.WireFormat = new WireFormat(DecimalWireForm.String, NullMemberForm.Native); - var writer = gen.Generate(Ctx(root)).Single(f => f.Path == "ReportExportWriter.g.cs").Content; + var writer = gen.Generate(Ctx(root)).Single(f => System.IO.Path.GetFileName(f.Path) == "ReportExportWriter.g.cs").Content; var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)); var comp = CSharpCompilation.Create("export_writer_" + Guid.NewGuid().ToString("N"), @@ -317,7 +317,7 @@ public sealed record PinRow(string Name, string PinHash, long Accounts); RequestServices = Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services), }; http.Response.Body = new MemoryStream(); - await ReportExportHttp.Json(http, "accounts-by-pin", body, ["pinHash"], envelope).ExecuteAsync(http); + await ReportExportHttp.Json(http, "accounts-by-pin", body, ["PinHash"], envelope).ExecuteAsync(http); Assert.Equal("attachment; filename=\"accounts-by-pin.json\"", http.Response.Headers.ContentDisposition.ToString()); http.Response.Body.Position = 0; return System.Text.Json.Nodes.JsonNode.Parse(http.Response.Body)!; diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs index 223a5dc25d..d8f5e79fc2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs @@ -844,4 +844,22 @@ public void An_abstract_report_is_refused_at_load() Assert.Equal(ErrorCode.ERR_INVALID_REPORT, error.Code); Assert.Contains("a report cannot be abstract", error.Message); } + + // rc.21 fix round (I3): a dimension over a @stringValueMap enum reads its stored strings — the + // row model carries the map from its type source, so the row gets the member <-> stored-string + // converter (which throws on an unknown stored value), not the name-based HasConversion(). + [Fact] + public void A_string_value_map_enum_dimension_reads_its_stored_strings() + { + var model = ModelTemplate.Replace( + "{ \"field.enum\": { \"name\": \"status\", \"@required\": true, \"@values\": [\"OPEN\", \"PAID\"] } }", + "{ \"field.enum\": { \"name\": \"status\", \"@required\": true, \"@values\": [\"OPEN\", \"PAID\"], \"@stringValueMap\": { \"OPEN\": \"open_v1\", \"PAID\": \"paid_v1\" } } }") + .Replace("<>", Report("SalesCube", "\"@kind\": \"view\", \"@view\": \"v_sales_cube\"", AllDimensions, AllMeasures)); + var load = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "shop.json")]); + Assert.Empty(load.Errors); + var context = EmitAll(RunnerContext(load.Root))["AppDbContext.g.cs"]; + var line = context.Split('\n').Single(l => l.Contains("Entity().Property(x => x.Status)")); + Assert.Contains("? \"open_v1\" :", line); + Assert.Contains("UnmappedEnumStoredValue<", line); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/RuntimeTemplateQualificationTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RuntimeTemplateQualificationTests.cs index 619d315fa0..bfabf06d8b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RuntimeTemplateQualificationTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RuntimeTemplateQualificationTests.cs @@ -1,10 +1,8 @@ -// The runtime text the DbContext generator writes verbatim after the context class (the -// DurationInterval mapping) names every framework type global::-qualified, so a package whose -// namespace derives `.System` (here `acme::system` -> `Acme.System`, beside a context in -// `Acme`) cannot capture a `System.` or `Microsoft.` reference written inside the home namespace -// (CS0234). The design-time services reach framework types only through top-level usings, which -// nothing captures; their compile is proved by the integration project, which references -// Microsoft.EntityFrameworkCore.Design. +// G8, rc.20: the runtime text the DbContext generator writes verbatim (the DurationInterval +// mapping after the context class, the design-time services) names every framework type +// global::-qualified or through a top-level using, so a package whose namespace derives +// `.System` (here `acme::system` -> `Acme.System`, beside a context in `Acme`) cannot +// capture a `System.` or `Microsoft.` reference written inside the home namespace (CS0234). using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -26,8 +24,9 @@ public sealed class RuntimeTemplateQualificationTests { "field.duration": { "name": "laps", "isArray": true } }, { "field.decimal": { "name": "cost", "@precision": 10, "@scale": 2 } }, { "field.map": { "name": "labels", "@valueType": "string" } }, - { "field.object": { "name": "meta", "@objectRef": "Meta", "@storage": "jsonb" } }, - { "identity.primary": { "@fields": "id", "@generation": "increment" } } + { "field.enum": { "name": "level", "@values": ["LOW", "HIGH"], "@intValueMap": { "LOW": 1, "HIGH": 2 } } }, + { "field.object": { "name": "meta", "@objectRef": "Meta", "@storage": "jsonb", "@description": "Tags." } }, + { "identity.primary": { "@fields": "id", "@generation": "increment", "@sequenceStart": 100 } } ] } } ] } } """; @@ -41,6 +40,27 @@ public sealed class RuntimeTemplateQualificationTests ] } } """; + [Fact] + public void The_runtime_templates_build_beside_a_home_System_namespace() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Home, id: "a.json"), new InMemoryStringSource(Capturing, id: "s.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", Dialect = "postgres", IncludeNames = true, OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, + }; + var files = new IGenerator[] { new EntityGenerator(), new NamesGenerator(), new DbContextGenerator() } + .SelectMany(g => g.Generate(ctx)).ToList(); + var context = Assert.Single(files, f => f.Path == "AppDbContext.g.cs").Content; + Assert.Contains("namespace Acme", context); + Assert.Contains("class DurationInterval", context); + Assert.Contains(files, f => f.Path.EndsWith("DesignTimeServices.g.cs", StringComparison.Ordinal)); + Assert.Contains(files, f => f.Content.Contains("namespace Acme.System;", StringComparison.Ordinal)); + var errors = PackageNamespaceTests.CompileErrors(files); + Assert.True(errors.Count == 0, "generated code should compile, but got:\n" + string.Join("\n", errors)); + } + [Fact] public void The_duration_interval_mapping_builds_beside_a_home_System_namespace() { @@ -50,7 +70,7 @@ public void The_duration_interval_mapping_builds_beside_a_home_System_namespace( { Entities = r.Root.Objects(), Root = r.Root, Config = PackageBindingResolver.WithDerivedHome( - new GenConfig { OutDir = "/tmp", Dialect = "postgres", IncludeNames = true }, r.Root), + new GenConfig { OutDir = "/tmp", Dialect = "postgres", IncludeNames = true, OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, r.Root), }; var files = new IGenerator[] { new EntityGenerator(), new NamesGenerator(), new DbContextGenerator() } .SelectMany(g => g.Generate(ctx)) diff --git a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs index e84bc9e601..7e48419a88 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -84,7 +84,7 @@ private static string Routes(string model, string file = "AccountRoutes.g.cs") Root = r.Root, Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal }, }; - return new RoutesGenerator().Generate(ctx).Single(f => f.Path == file).Content; + return new RoutesGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == file).Content; } [Fact] @@ -96,7 +96,7 @@ public void A_tph_column_marked_on_another_subtype_is_hidden_and_ignored_on_this Assert.True(start >= 0 && end > start, src); var aRoutes = src[start..end]; - Assert.Contains("new string[] { \"token\" }", aRoutes); + Assert.Contains("new string[] { \"Token\" }", aRoutes); Assert.Contains("input.Token = default!;", aRoutes); Assert.Contains("input.Memo = default!;", aRoutes); Assert.Contains("string.Equals(prop.Name, \"token\", System.StringComparison.OrdinalIgnoreCase)) continue;", aRoutes); @@ -118,7 +118,7 @@ public void Write_paths_name_both_denied_fields_and_read_hides_only_the_credenti Assert.Contains("string.Equals(prop.Name, \"pinHash\", System.StringComparison.OrdinalIgnoreCase)) continue;", src); // Only the credential is omitted on read (list, get, create echo, update echo). - Assert.Contains("new string[] { \"pinHash\" }", src); + Assert.Contains("new string[] { \"PinHash\" }", src); Assert.DoesNotContain("\"tokenHash\" }", src); Assert.DoesNotContain("new string[] { \"tokenHash\"", src); Assert.DoesNotContain("Results.Ok(rows)", src); diff --git a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs new file mode 100644 index 0000000000..124a8ecdfe --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs @@ -0,0 +1,97 @@ +// SerializerKeys fails closed: a credential that cannot be matched to the serializer's contract is a +// refusal, never a silently unstripped response. + +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using MetaObjects.Codegen.Runtime; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class SerializerKeysTests +{ + public sealed class Row + { + public long Id { get; set; } + public string? PinHash { get; set; } + } + + private static readonly string[] Names = ["PinHash", "pinHash"]; + + [Fact] + public void The_default_contract_gives_the_policys_key() + { + var opts = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + Assert.Equal(["pin_hash"], SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + } + + [Fact] + public void A_type_without_the_credential_contributes_nothing_and_never_throws() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + Assert.Empty(SerializerKeys.KeysOfType(typeof(string), opts, Names)); + } + + // A resolver whose properties carry no reflection member (what a custom resolver, a rebuilding + // modifier or a source-generated context can do). + private sealed class NoProviderResolver : IJsonTypeInfoResolver + { + public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options) + { + var info = JsonTypeInfo.CreateJsonTypeInfo(type, options); + if (type != typeof(Row)) return info; + var id = info.CreateJsonPropertyInfo(typeof(long), "id"); + id.Get = o => ((Row)o).Id; + id.Set = (o, v) => ((Row)o).Id = (long)v!; + var pin = info.CreateJsonPropertyInfo(typeof(string), "pinHash"); + pin.Get = o => ((Row)o).PinHash; + pin.Set = (o, v) => ((Row)o).PinHash = (string?)v; + info.Properties.Add(id); + info.Properties.Add(pin); + return info; + } + } + + [Fact] + public void A_contract_with_no_reflection_member_is_refused_naming_the_type_and_property_but_no_value() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + Assert.Contains("refused", ex.Message); + } + + private sealed class RowConverter : JsonConverter + { + public override Row? Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => throw new NotSupportedException(); + public override void Write(Utf8JsonWriter writer, Row value, JsonSerializerOptions o) => writer.WriteStringValue("x"); + } + + [Fact] + public void A_custom_converter_for_the_row_type_is_refused() + { + var opts = new JsonSerializerOptions { Converters = { new RowConverter() }, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void A_credential_the_contract_does_not_carry_is_refused() + { + // A modifier that drops the property from the contract while the type still declares it. + var resolver = new DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { if (ti.Type == typeof(Row)) ti.Properties.Remove(ti.Properties.Single(p => p.Name == "PinHash")); }); + var opts = new JsonSerializerOptions { TypeInfoResolver = resolver }; + var ex = Assert.Throws(() => SerializerKeys.KeysOf(new[] { new Row() }, false, opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void Strip_also_removes_a_key_that_spells_the_credential_ignoring_case_and_separators() + { + var node = System.Text.Json.Nodes.JsonNode.Parse("""{"id":1,"pin_hash":"v","PIN-HASH":"v","name":"n"}""")!; + SerializerKeys.Strip(node, [], Names); + Assert.Equal("""{"id":1,"name":"n"}""", node.ToJsonString()); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs index eb3efd9d23..19365e9468 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs @@ -26,23 +26,23 @@ namespace MetaObjects.Codegen.Tests; public class TphCodegenTests { // Mirrors fixtures/api-contract-conformance/tph/meta.json: Auth base - // (@discriminator "type", table "auths") + Bridge/Copay/PriorAuth subtypes. + // (@discriminator "type", table "auths") + Bridge/Coupon/Permit subtypes. private const string Model = """ { "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ]}}, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true, "@filterable": true, "@sortable": true } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ]}}, - { "object.entity": { "name": "PriorAuthAuth", "extends": "Auth", "@discriminatorValue": "PriorAuth", "children": [ + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true } } ]}} ]}} @@ -75,14 +75,14 @@ public void Plan_resolves_base_and_subtypes_in_stable_order() var plan = TphPlanBuilder.For(auth, root); Assert.NotNull(plan); Assert.Equal("type", plan!.DiscriminatorField); - // Name-sorted: BridgeAuth, CopayAuth, PriorAuthAuth. - Assert.Equal(["BridgeAuth", "CopayAuth", "PriorAuthAuth"], plan.Subtypes.Select(s => s.Entity.Name)); - Assert.Equal(["Bridge", "Copay", "PriorAuth"], plan.Subtypes.Select(s => s.Value)); - Assert.Equal(["bridge", "copay", "priorauth"], plan.Subtypes.Select(s => s.RouteSegment)); + // Name-sorted: BridgeAuth, CouponAuth, PermitAuth. + Assert.Equal(["BridgeAuth", "CouponAuth", "PermitAuth"], plan.Subtypes.Select(s => s.Entity.Name)); + Assert.Equal(["Bridge", "Coupon", "Permit"], plan.Subtypes.Select(s => s.Value)); + Assert.Equal(["bridge", "coupon", "permit"], plan.Subtypes.Select(s => s.RouteSegment)); // The subtypes are NOT TPH bases; they ARE TPH subtypes. Assert.True(TphPlanBuilder.IsTphDiscriminatorBase(auth, root)); - foreach (var name in new[] { "BridgeAuth", "CopayAuth", "PriorAuthAuth" }) + foreach (var name in new[] { "BridgeAuth", "CouponAuth", "PermitAuth" }) { var sub = root.FindObject(name)!; Assert.False(TphPlanBuilder.IsTphDiscriminatorBase(sub, root)); @@ -127,8 +127,8 @@ public void Entity_base_declares_its_subtypes_for_polymorphic_serialization() var auth = FileContent(new EntityGenerator().Generate(Ctx(Load())), "Auth.g.cs"); Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(BridgeAuth))]", auth); - Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(CopayAuth))]", auth); - Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(PriorAuthAuth))]", auth); + Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(CouponAuth))]", auth); + Assert.Contains("[System.Text.Json.Serialization.JsonDerivedType(typeof(PermitAuth))]", auth); Assert.DoesNotContain("typeDiscriminator", auth); } @@ -174,15 +174,15 @@ public void Entity_subtypes_extend_base_with_only_own_fields_and_no_table() Assert.DoesNotContain("public long Id", bridge); Assert.DoesNotContain("public string Reference", bridge); - var copay = FileContent(files, "CopayAuth.g.cs"); - Assert.Contains("public class CopayAuth : Auth", copay); - Assert.DoesNotContain("[Table", copay); - Assert.Contains("public decimal? CopayAmount { get; set; }", copay); + var coupon = FileContent(files, "CouponAuth.g.cs"); + Assert.Contains("public class CouponAuth : Auth", coupon); + Assert.DoesNotContain("[Table", coupon); + Assert.Contains("public decimal? CouponAmount { get; set; }", coupon); - var priorAuth = FileContent(files, "PriorAuthAuth.g.cs"); - Assert.Contains("public class PriorAuthAuth : Auth", priorAuth); - Assert.DoesNotContain("[Table", priorAuth); - Assert.Contains("public string? Approver { get; set; }", priorAuth); + var permit = FileContent(files, "PermitAuth.g.cs"); + Assert.Contains("public class PermitAuth : Auth", permit); + Assert.DoesNotContain("[Table", permit); + Assert.Contains("public string? Approver { get; set; }", permit); } [Fact] @@ -192,8 +192,8 @@ public void DbContext_emits_single_dbset_and_has_discriminator() // Exactly one DbSet for the hierarchy (the base); no per-subtype DbSet. Assert.Contains("public DbSet Auths { get; set; }", db); Assert.DoesNotContain("DbSet", db); - Assert.DoesNotContain("DbSet", db); - Assert.DoesNotContain("DbSet", db); + Assert.DoesNotContain("DbSet", db); + Assert.DoesNotContain("DbSet", db); // HasDiscriminator + HasValue per subtype (the discriminator maps to the enum prop; // the enum's HasConversion() stores the symbol, so the column is TEXT). // Bare "Auth." stays bare: the global::-qualification (CSharpNaming.QualifiedOwnerTypeRef) @@ -201,8 +201,8 @@ public void DbContext_emits_single_dbset_and_has_discriminator() // a base entity named like e.g. "AllTypes" would get the qualified form. Assert.Contains("HasDiscriminator(e => e.Type)", db); Assert.Contains("HasValue(Auth.AuthType.Bridge)", db); - Assert.Contains("HasValue(Auth.AuthType.Copay)", db); - Assert.Contains("HasValue(Auth.AuthType.PriorAuth)", db); + Assert.Contains("HasValue(Auth.AuthType.Coupon)", db); + Assert.Contains("HasValue(Auth.AuthType.Permit)", db); } [Fact] @@ -213,8 +213,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() // Subtypes emit NO routes file (they are folded into the base). Assert.DoesNotContain(files, f => f.Path == "BridgeAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => f.Path == "CopayAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => f.Path == "PriorAuthAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => f.Path == "CouponAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => f.Path == "PermitAuthRoutes.g.cs"); var auth = FileContent(files, "AuthRoutes.g.cs"); // Polymorphic list + get at the base path; NO base POST (can't create an abstract base). @@ -222,8 +222,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() Assert.Contains("prefix + \"/auths/{id}\"", auth); // Per-subtype segments are the @discriminatorValue lowercased. Assert.Contains("prefix + \"/auths/bridge\"", auth); - Assert.Contains("prefix + \"/auths/copay\"", auth); - Assert.Contains("prefix + \"/auths/priorauth\"", auth); + Assert.Contains("prefix + \"/auths/coupon\"", auth); + Assert.Contains("prefix + \"/auths/permit\"", auth); // Per-subtype CRUD: create scopes reads/mutations via OfType() and injects the // discriminator via the subtype CLR type on Add (the POST body omits it). FR-036 #4 — // because every subtype has a @required field (the base string `reference`, and @@ -236,8 +236,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() Assert.Matches(@"new\[\] \{[^}]*""reference""[^}]*\}", auth); // base @required string Assert.Matches(@"new\[\] \{[^}]*""quantity""[^}]*\}", auth); // own @required value-type Assert.Contains("OfType()", auth); - Assert.Contains("OfType()", auth); - Assert.Contains("OfType()", auth); + Assert.Contains("OfType()", auth); + Assert.Contains("OfType()", auth); // Polymorphic POST is NOT emitted on the base path itself. Assert.DoesNotContain("MapPost(prefix + \"/auths\",", auth); // Per-subtype list ?sort resolves the raw qs field through a per-subtype diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs index cd19cb6d7a..c8b2d1d8ad 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs @@ -25,8 +25,8 @@ // silent 404. // C. a THIRD, latent compile defect this model's abstract mid level (ScopedAuth) // surfaced under the DEFAULT config (EmitAbstractShapes: false — see Ctx() below): -// `class PriorAuthAuth : ScopedAuth` named a class that is never emitted, AND -// ScopedAuth's own field was silently excluded from PriorAuthAuth's member set as +// `class PermitAuth : ScopedAuth` named a class that is never emitted, AND +// ScopedAuth's own field was silently excluded from PermitAuth's member set as // "already inherited" by that never-emitted class — a dropped member, worse than // the compile error alone. Fixed by EntityGenerator.EmittedTphAncestor (walks past // any skipped abstract level to the nearest ancestor that IS emitted — ultimately @@ -42,9 +42,9 @@ // - BridgeAuth (subtype) declares "linkedAuths", a directed self-join onto // itself through AuthLink — subtype-declared AND a subtype-typed M:N target // in one relationship (rule b/c + defect B) -// - CopayAuth (subtype) declares nothing of its own; it still resolves "tags" +// - CouponAuth (subtype) declares nothing of its own; it still resolves "tags" // via extends (rule b, overlap with a) -// - ScopedAuth (ABSTRACT mid level between Auth and PriorAuthAuth) declares +// - ScopedAuth (ABSTRACT mid level between Auth and PermitAuth) declares // "auditors" -> Tag through AuthAudit — served nowhere but under the one // concrete subtype beneath it (rule d) // - Payer (non-TPH source) declares "bridgeAuths" -> BridgeAuth through @@ -73,7 +73,7 @@ public class TphM2mRoutesTests { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths2" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } @@ -83,14 +83,14 @@ public class TphM2mRoutesTests { "field.boolean": { "name": "verified", "@required": true, "@default": true } }, { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.int": { "name": "copayCents" } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.int": { "name": "couponCents" } } ]}}, { "object.entity": { "name": "ScopedAuth", "extends": "Auth", "abstract": true, "children": [ { "field.string": { "name": "auditNotes", "@maxLength": 200 } }, { "relationship.association": { "name": "auditors", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthAudit" } } ]}}, - { "object.entity": { "name": "PriorAuthAuth", "extends": "ScopedAuth", "@discriminatorValue": "PriorAuth", "children": [ + { "object.entity": { "name": "PermitAuth", "extends": "ScopedAuth", "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80 } } ]}}, { "object.entity": { "name": "AuthTag", "children": [ @@ -114,7 +114,7 @@ public class TphM2mRoutesTests { "field.long": { "name": "auditAuthId", "@required": true } }, { "field.long": { "name": "auditTagId", "@required": true } }, { "identity.primary": { "@fields": ["auditAuthId", "auditTagId"] } }, - { "identity.reference": { "name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth" } }, + { "identity.reference": { "name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth" } }, { "identity.reference": { "name": "fkAuditTag", "@fields": "auditTagId", "@references": "Tag" } } ]}}, { "object.entity": { "name": "Payer", "children": [ @@ -136,10 +136,10 @@ public class TphM2mRoutesTests """; // DEFAULT config deliberately — EmitAbstractShapes is false (the GenConfig default), - // so ScopedAuth (the abstract TPH mid level between Auth and PriorAuthAuth) emits NO - // class of its own. That used to leave `class PriorAuthAuth : ScopedAuth` referencing + // so ScopedAuth (the abstract TPH mid level between Auth and PermitAuth) emits NO + // class of its own. That used to leave `class PermitAuth : ScopedAuth` referencing // a type that does not exist, AND silently dropped ScopedAuth's own fields (excluded - // from PriorAuthAuth's member set as "already inherited" by a class that was never + // from PermitAuth's member set as "already inherited" by a class that was never // emitted). See EntityGenerator.EmittedTphAncestor + the tests below. private static GenContext Ctx(MetaRoot root) => new() { @@ -215,16 +215,16 @@ public void Subtype_declared_selfjoin_gates_the_source_and_binds_target_through_ public void Inherited_m2m_is_served_at_the_base_and_under_every_concrete_subtype() { var routes = FileContent(new RoutesGenerator().Generate(Ctx(Load())), "AuthRoutes.g.cs"); - // "tags" is declared on Auth, so BridgeAuth/CopayAuth/PriorAuthAuth all resolve it + // "tags" is declared on Auth, so BridgeAuth/CouponAuth/PermitAuth all resolve it // too (rule b) — the base mount plus one per subtype is FOUR mounts total. This is // the independent oracle's rule (expectedRoutes), which walks every SERVED // object's RESOLVED relationships, not an own-only read. var tagMounts = System.Text.RegularExpressions.Regex.Matches(routes, "\\{id\\}/tags\"").Count; - Assert.Equal(4, tagMounts); // /auths, /auths/bridge, /auths/copay, /auths/priorauth - var copayMount = ExtractMount(routes, "/auths/copay/{id}/tags"); - Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", copayMount); - var priorAuthMount = ExtractMount(routes, "/auths/priorauth/{id}/tags"); - Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", priorAuthMount); + Assert.Equal(4, tagMounts); // /auths, /auths/bridge, /auths/coupon, /auths/permit + var couponMount = ExtractMount(routes, "/auths/coupon/{id}/tags"); + Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", couponMount); + var permitMount = ExtractMount(routes, "/auths/permit/{id}/tags"); + Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", permitMount); } [Fact] @@ -233,26 +233,26 @@ public void Abstract_mid_level_m2m_is_served_only_under_the_one_concrete_subtype var routes = FileContent(new RoutesGenerator().Generate(Ctx(Load())), "AuthRoutes.g.cs"); // "auditors" lives on ScopedAuth — abstract, so it has no path and no rows of its // own, and it is not on the base either. The ONLY place it can be served is - // beneath PriorAuthAuth, the one concrete subtype beneath that level. - var mount = ExtractMount(routes, "/auths/priorauth/{id}/auditors"); + // beneath PermitAuth, the one concrete subtype beneath that level. + var mount = ExtractMount(routes, "/auths/permit/{id}/auditors"); Assert.Contains("db.AuthAudits", mount); Assert.Contains("db.Tags.AsNoTracking()", mount); Assert.DoesNotContain("/auths/{id}/auditors\"", routes); Assert.DoesNotContain("/auths/bridge/{id}/auditors\"", routes); - Assert.DoesNotContain("/auths/copay/{id}/auditors\"", routes); + Assert.DoesNotContain("/auths/coupon/{id}/auditors\"", routes); } [Fact] public void Abstract_mid_level_extends_and_field_fold_under_the_default_config() { // GenConfig.EmitAbstractShapes defaults to false, so ScopedAuth (abstract, between - // Auth and PriorAuthAuth) emits NO class of its own. Two things must still be true: - // 1. PriorAuthAuth's base-class clause resolves PAST ScopedAuth to the nearest + // Auth and PermitAuth) emits NO class of its own. Two things must still be true: + // 1. PermitAuth's base-class clause resolves PAST ScopedAuth to the nearest // ancestor that DOES get emitted — here, the TPH discriminator base itself // (always emitted; never metadata-abstract) — instead of naming a type that // does not exist. // 2. ScopedAuth's OWN field ("auditNotes") still lands SOMEWHERE — on - // PriorAuthAuth, the one concrete subtype beneath it — rather than being + // PermitAuth, the one concrete subtype beneath it — rather than being // silently dropped because it was excluded as "already inherited" by a class // that was never emitted. A dropped member is worse than the compile error // fixing only the base-class clause would have left behind: the compile error @@ -260,17 +260,17 @@ public void Abstract_mid_level_extends_and_field_fold_under_the_default_config() var files = new EntityGenerator().Generate(Ctx(Load())).ToList(); Assert.DoesNotContain(files, f => f.Path == "ScopedAuth.g.cs"); - var priorAuth = FileContent(files, "PriorAuthAuth.g.cs"); - Assert.Contains("public class PriorAuthAuth : Auth", priorAuth); - Assert.DoesNotContain("ScopedAuth", priorAuth); + var permit = FileContent(files, "PermitAuth.g.cs"); + Assert.Contains("public class PermitAuth : Auth", permit); + Assert.DoesNotContain("ScopedAuth", permit); // ScopedAuth's own field, folded onto the one concrete subtype beneath it. - Assert.Contains("public string? AuditNotes { get; set; }", priorAuth); + Assert.Contains("public string? AuditNotes { get; set; }", permit); // The sibling subtypes (which do NOT extend ScopedAuth) never see it. var bridge = FileContent(files, "BridgeAuth.g.cs"); Assert.DoesNotContain("AuditNotes", bridge); - var copay = FileContent(files, "CopayAuth.g.cs"); - Assert.DoesNotContain("AuditNotes", copay); + var coupon = FileContent(files, "CouponAuth.g.cs"); + Assert.DoesNotContain("AuditNotes", coupon); } [Fact] @@ -291,8 +291,8 @@ public void Subtypes_still_emit_no_standalone_routes_file() { var files = new RoutesGenerator().Generate(Ctx(Load())).ToList(); Assert.DoesNotContain(files, f => f.Path == "BridgeAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => f.Path == "CopayAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => f.Path == "PriorAuthAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => f.Path == "CouponAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => f.Path == "PermitAuthRoutes.g.cs"); Assert.DoesNotContain(files, f => f.Path == "ScopedAuthRoutes.g.cs"); } @@ -318,9 +318,9 @@ public void Full_model_compiles_against_ef_core_8_and_aspnetcore() // compiles clean everywhere else and only fails here, or in a live consumer's build. // // Also the regression guard for the abstract-TPH-mid-level defect (ScopedAuth, - // between Auth and PriorAuthAuth): Ctx() uses the DEFAULT config + // between Auth and PermitAuth): Ctx() uses the DEFAULT config // (EmitAbstractShapes: false), the shape a shared cross-port conformance fixture - // carries — a `class PriorAuthAuth : ScopedAuth` referencing a class that is never + // carries — a `class PermitAuth : ScopedAuth` referencing a class that is never // emitted is exactly what this compile assertion exists to catch. var ctx = Ctx(Load()); var sources = new EntityGenerator().Generate(ctx) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs new file mode 100644 index 0000000000..ab1fcb4679 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs @@ -0,0 +1,126 @@ +// A scalar value-mapped field.enum (@intValueMap or @stringValueMap) is converted by an explicit +// ValueConverter typed on the NON-nullable enum, whether the field is required or optional. +// +// The lambda pair used to be passed straight to HasConversion(...), so EF typed it on the +// property's CLR type — ValueConverter for an optional field. Npgsql EF 8 cannot build +// the JSON collection reader for a parameterised `Contains` over such a property, so +// `active.Contains(w.Status)` failed at runtime: an InvalidOperationException ("When building an +// array mapping over 'Nullable`1', the JsonValueReaderWriter for element mapping ... is incorrect") +// on the EF 8.0.10 this repository pins, and a MissingMethodException on +// JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E] on 8.0.11 and later. A converter on `E` is what EF's own built-in +// enum converters are, and what the array branch's element converter already was. The member +// chains themselves are unchanged. The live query is +// MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class ValueMappedEnumConverterTypeTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["DRAFT", "LIVE"], + "@intValueMap": { "DRAFT": 0, "LIVE": 5 } } }, + { "field.enum": { "name": "grade", "@required": true, "@values": ["LOW", "HIGH"], + "@intValueMap": { "LOW": 1, "HIGH": 9 } } }, + { "field.enum": { "name": "phase", "@maxLength": 12, "@values": ["OPEN", "SHUT"], + "@stringValueMap": { "OPEN": "open_v1", "SHUT": "shut_v1" } } }, + { "field.enum": { "name": "stage", "@required": true, "@maxLength": 10, "@values": ["NEW", "OLD"], + "@stringValueMap": { "NEW": "new", "OLD": "old" } } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + private const string Converter = "new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<"; + + private static GenContext Ctx() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "value-mapped-enum.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, OutDir = "/tmp", Namespace = "Acme.Generated", IncludeNames = true }, + }; + } + + private static string DbContext(GenContext ctx) => + Assert.Single(new DbContextGenerator().Generate(ctx)).Content; + + private const string Owner = "global::Acme.Widget"; + + [Fact] + public void An_optional_int_mapped_enum_is_converted_on_the_non_nullable_enum() + { + var e = $"{Owner}.WidgetStatus"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Status).HasConversion({Converter}{e}, int>(" + + $"v => v == {e}.DRAFT ? 0 : v == {e}.LIVE ? 5 : UnmappedEnumMember(v, \"status\"), " + + $"v => v == 0 ? {e}.DRAFT : v == 5 ? {e}.LIVE : UnmappedEnumValue<{e}>(v, \"status\")));", + DbContext(Ctx())); + } + + [Fact] + public void A_required_int_mapped_enum_is_converted_on_the_enum() + { + var e = $"{Owner}.WidgetGrade"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Grade).HasConversion({Converter}{e}, int>(" + + $"v => v == {e}.LOW ? 1 : v == {e}.HIGH ? 9 : UnmappedEnumMember(v, \"grade\"), " + + $"v => v == 1 ? {e}.LOW : v == 9 ? {e}.HIGH : UnmappedEnumValue<{e}>(v, \"grade\")));", + DbContext(Ctx())); + } + + [Fact] + public void An_optional_string_mapped_enum_is_converted_on_the_non_nullable_enum_and_keeps_its_length() + { + var e = $"{Owner}.WidgetPhase"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Phase).HasConversion({Converter}{e}, string>(" + + $"v => v == {e}.OPEN ? \"open_v1\" : v == {e}.SHUT ? \"shut_v1\" : UnmappedEnumStoredMember(v, \"phase\"), " + + $"v => v == \"open_v1\" ? {e}.OPEN : v == \"shut_v1\" ? {e}.SHUT : UnmappedEnumStoredValue<{e}>(v, \"phase\"))).HasMaxLength(12);", + DbContext(Ctx())); + } + + [Fact] + public void A_required_string_mapped_enum_is_converted_on_the_enum_and_keeps_its_length() + { + var e = $"{Owner}.WidgetStage"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Stage).HasConversion({Converter}{e}, string>(" + + $"v => v == {e}.NEW ? \"new\" : v == {e}.OLD ? \"old\" : UnmappedEnumStoredMember(v, \"stage\"), " + + $"v => v == \"new\" ? {e}.NEW : v == \"old\" ? {e}.OLD : UnmappedEnumStoredValue<{e}>(v, \"stage\"))).HasMaxLength(10);", + DbContext(Ctx())); + } + + // The typed converter compiles against EF Core 8 on a nullable property and a non-nullable + // one alike (PropertyBuilder.HasConversion(ValueConverter) takes a converter on E). + [Fact] + public void The_typed_converters_compile_against_EF_Core_8() + { + var ctx = Ctx(); + var sources = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new NamesGenerator().Generate(ctx)) + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))); + var comp = CSharpCompilation.Create( + "value_mapped_enum_" + Guid.NewGuid().ToString("N"), sources, DbContextCompileTests.BuildReferences(), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var errors = comp.GetDiagnostics() + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()}") + .ToList(); + Assert.True(errors.Count == 0, "generated code should compile:\n" + string.Join("\n", errors)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs index ce0065582d..1628cf86ff 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs @@ -70,6 +70,28 @@ public void Every_value_shape_gets_a_poco_whether_or_not_an_entity_reaches_it() Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, }; + private static GenContext Split(MetaRoot root) => new() + { + Entities = root.Objects(), Root = root, + Config = new GenConfig + { + OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + PackageNamespaces = new() { ["acme::alpha"] = "Acme.Alpha", ["acme::beta"] = "Acme.Beta" }, + }, + }; + + // rc.19 R65: each package has its own namespace by default, so "one namespace" is now an explicit + // mapping of both packages onto it. + private static GenContext OneNamespace(MetaRoot root) => new() + { + Entities = root.Objects(), Root = root, + Config = new GenConfig + { + OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + PackageNamespaces = new() { ["acme::alpha"] = "Acme.Generated", ["acme::beta"] = "Acme.Generated" }, + }, + }; + [Fact] public void Two_value_objects_sharing_a_short_name_keep_it_in_their_own_package_namespaces() { @@ -113,6 +135,77 @@ public void Two_value_objects_sharing_a_short_name_in_one_namespace_fail_loud_na Assert.Contains("acme::beta::Note", ex.Message); } + // Ruling R52 — a value object is never renamed. Two that share a short name in one namespace are + // a real collision, refused by the run's claim registry with the remedy; in two namespaces they + // are two types of the same name. + + [Fact] + public void Two_value_objects_sharing_a_short_name_in_one_namespace_are_refused_naming_both() + { + var root = Load(Alpha, Beta); + var ex = Assert.ThrowsAny(() => new EntityGenerator().Generate(OneNamespace(root)).ToList()); + Assert.Contains("ERR_NAME_COLLISION", ex.Message); + Assert.Contains("\"acme::alpha::Note\"", ex.Message); + Assert.Contains("\"acme::beta::Note\"", ex.Message); + Assert.Contains("the C# namespace Acme.Generated", ex.Message); + Assert.Contains("PackageNamespaces", ex.Message); + } + + [Fact] + public void Two_value_objects_sharing_a_short_name_in_two_namespaces_keep_their_name() + { + var root = Load(Alpha, Beta); + var files = new EntityGenerator().Generate(Split(root)).ToList(); + Assert.Equal(2, files.Count); + Assert.All(files, f => Assert.Contains("public class Note", f.Content)); + Assert.Contains(files, f => f.Content.Contains("namespace Acme.Alpha")); + Assert.Contains(files, f => f.Content.Contains("namespace Acme.Beta")); + Assert.Equal("Note", ValueObjectNames.TypeName(root.Objects().First(o => o.ResolutionKey() == "acme::alpha::Note"), root)); + } + + [Fact] + public void An_entity_and_a_value_object_of_one_name_in_one_namespace_are_refused() + { + // CS0101 otherwise: the type-per-namespace check every C# generator shares. + var root = Load(Alpha, """ + { "metadata.root": { "package": "acme::beta", "children": [ + { "object.entity": { "name": "Note", "children": [ + { "source.rdb": { "@table": "notes" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } ] } } ] } } + """); + var ex = Assert.ThrowsAny(() => new EntityGenerator().Generate(OneNamespace(root)).ToList()); + Assert.Contains("ERR_NAME_COLLISION", ex.Message); + Assert.Contains("\"Note\"", ex.Message); + } + + [Fact] + public void An_abstract_value_object_claims_no_name() + { + // It emits nothing, so a concrete object of its name elsewhere keeps the bare name. + var root = Load(Alpha, """ + { "metadata.root": { "package": "acme::beta", "children": [ + { "object.value": { "name": "Note", "abstract": true, "children": [ { "field.string": { "name": "x" } } ] } } ] } } + """); + var file = Assert.Single(new EntityGenerator().Generate(Ctx(root))); + Assert.Equal("Note.g.cs", System.IO.Path.GetFileName(file.Path)); + Assert.Contains("public class Note", file.Content); + } + + [Fact] + public void The_same_claimant_claiming_again_is_not_a_collision_and_a_second_is() + { + var root = Load(Alpha); + var ctx = Ctx(root); + ctx.Claim("scope", "Name", "a", "remedy"); + ctx.Claim("scope", "Name", "a", "remedy"); + ctx.Claim("another scope", "Name", "b", "remedy"); + var ex = Assert.Throws(() => ctx.Claim("scope", "Name", "b", "rename one")); + Assert.Equal("ERR_NAME_COLLISION: \"a\" and \"b\" both generate \"Name\" in scope — rename one.", ex.Message); + // A narrowed context shares the run's registry. + Assert.Throws(() => ctx.Narrow(_ => true).Claim("scope", "Name", "c", "remedy")); + } + // ---- the template tier references it ---- private const string SharedResponse = """ diff --git a/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs b/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs index 64f7d0bd22..7079b02dc7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs @@ -48,7 +48,7 @@ public void A_wrapped_declared_spec_is_not_legacy_and_an_invalid_one_is_validate public void A_wrapped_declared_spec_is_not_legacy_and_an_invalid_one_is_validated_by_verify() { File.WriteAllText(Spec, "{ not json"); - var verify = Run("verify", "--codegen", Meta, "--out", Out); + var verify = Run("verify", "--codegen", "--full", Meta, "--out", Out); Assert.DoesNotContain("1.0 template-spec configuration", verify.Err); Assert.Contains("template spec", verify.Err); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/XpkgValueObjectRefsConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/XpkgValueObjectRefsConformanceTests.cs new file mode 100644 index 0000000000..df1b76431b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/XpkgValueObjectRefsConformanceTests.cs @@ -0,0 +1,99 @@ +// fixtures/codegen-conformance/xpkg-value-object-refs/ (C# lane). One generated file meets two +// same-named types from two packages: the routes for `acme::app::Host` name `acme::alpha::Note` +// and `acme::beta::Note`, and the callable wrapper for `acme::app::Summary` names its arguments +// object `acme::alpha::Summary`. Nothing is renamed (ruling R52), so with the packages mapped to +// namespaces each file must name the pair unambiguously — a bare name under `using`s of both +// namespaces is CS0104. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class XpkgValueObjectRefsConformanceTests +{ + private static string FixtureDir() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "fixtures"))) + dir = dir.Parent; + Assert.NotNull(dir); + return Path.Combine(dir!.FullName, "fixtures", "codegen-conformance", "xpkg-value-object-refs"); + } + + private static MetaRoot Load() + { + var load = MetaDataLoader.FromDirectory(Path.Combine(FixtureDir(), "input")); + Assert.Empty(load.Errors); + return load.Root; + } + + private static GenContext Ctx(MetaRoot root, bool mapPackages = true) => new() + { + Entities = root.Objects().ToList(), + Root = root, + Config = new GenConfig + { OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true, + OutDir = "/tmp", + Namespace = "Acme.Generated", + Dialect = "postgres", + // rc.19 R65: each package has its own namespace by default; "flattened" is an explicit + // mapping of every package onto one. + PackageNamespaces = mapPackages + ? new() { ["acme::alpha"] = "Acme.Alpha", ["acme::beta"] = "Acme.Beta", ["acme::app"] = "Acme.App" } + : new() { ["acme::alpha"] = "Acme.Generated", ["acme::beta"] = "Acme.Generated", ["acme::app"] = "Acme.Generated" }, + }, + }; + + [Fact] + public void With_the_packages_flattened_into_one_namespace_the_two_Notes_are_refused() + { + var ex = Assert.Throws(() => new EntityGenerator().Generate(Ctx(Load(), mapPackages: false)).ToList()); + Assert.Contains(NameClaims.ERR_NAME_COLLISION, ex.Message); + Assert.Contains("\"Note\"", ex.Message); + } + + [Fact] + public void The_routes_name_each_Note_unambiguously() + { + var ctx = Ctx(Load()); + var routes = Assert.Single(new RoutesGenerator().Generate(ctx), f => f.Path.EndsWith("HostRoutes.g.cs")).Content; + // Every type the routes name from another namespace is global::-qualified (rc.19 R65), so + // no using is needed and no bare `Note` could be ambiguous (CS0104). + Assert.DoesNotContain("using Acme.Alpha;", routes); + Assert.Contains("global::Acme.Alpha.Note", routes); + Assert.Contains("System.Collections.Generic.List", routes); + Assert.Contains("System.Collections.Generic.Dictionary", routes); + Assert.DoesNotMatch(@"[<\s(]Note[>\s)]", routes); + } + + [Fact] + public void Every_file_but_the_routes_compiles() + { + var ctx = Ctx(Load()); + var sources = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new CallableGenerator().Generate(ctx)) + .ToList(); + var callable = Assert.Single(sources, f => f.Path.EndsWith("Summary.callable.g.cs")).Content; + // The result entity and its arguments object share the short name `Summary`. + Assert.Contains("global::Acme.Alpha.Summary args", callable); + Assert.Contains("IReadOnlyList", callable); + + var comp = CSharpCompilation.Create( + "xpkg_vo_refs_" + Guid.NewGuid().ToString("N"), + sources.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))), + DbContextCompileTests.BuildReferences(), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var errors = comp.GetDiagnostics() + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Location.SourceTree?.GetText().Lines[d.Location.GetLineSpan().StartLinePosition.Line].ToString().Trim()} | {d.Id}: {d.GetMessage()} [{sources.FirstOrDefault(f => f.Content == d.Location.SourceTree?.ToString())?.Path}]") + .ToList(); + Assert.True(errors.Count == 0, "generated code should compile, but got:\n" + string.Join("\n", errors)); + } +} diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index e79039103d..2c5d465ffc 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -335,6 +335,50 @@ public static string Pascal(string name) => public static string PropertyName(MetaField field, GenConfig? config) => config?.PropertyNaming?.Invoke(field) ?? Pascal(field.Name); + /// + /// The fields whose C# property (the run's resolver) + /// is not the field name in another case: the only ones the runtime's case-insensitive + /// property lookup cannot find on its own. Shared with the routes generator, which + /// passes the emitted map to the filter dispatch exactly when this is non-empty. + /// + public static IReadOnlyDictionary RenamedProperties(MetaObject entity, GenConfig config) + { + var map = new Dictionary(System.StringComparer.Ordinal); + foreach (var f in entity.Fields()) + { + var prop = CSharpNaming.PropertyName(f, config); + if (!string.Equals(prop, f.Name, StringComparison.OrdinalIgnoreCase)) map[f.Name] = prop; + } + return map; + } + + /// + /// Refuse a generator whose PropertyName hook is overridden to answer differently from + /// for any field. Only the resolver reaches every + /// generator (the entity, the context, the routes, the callable, the extractor, the report + /// export, the filter map), so a lone override would declare one name and reference another + /// in a different file: output that does not compile, or a sort that fails at run time. + /// + public static void RefuseDivergingPropertyHook( + string generatorName, IEnumerable objects, GenConfig config, Func hook) + { + foreach (var obj in objects) + { + foreach (var f in obj.Fields()) + { + var resolved = PropertyName(f, config); + var hooked = hook(f); + if (!string.Equals(hooked, resolved, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"{generatorName}: its PropertyName hook names field \"{obj.Name}.{f.Name}\" \"{hooked}\", but the run's " + + $"property-naming resolver names it \"{resolved}\"; every other generator uses the resolver, so the " + + "generated files would disagree: set GenConfig.PropertyNaming instead of overriding the hook."); + } + } + } + } + // ---------------------------------------------------------------------------- // Generated-SDK SYMBOL names — the single source of truth for the public C# // identifiers the generators emit. Each generator calls one of these instead of @@ -367,20 +411,24 @@ public static string PropertyName(MetaField field, GenConfig? config) => /// /// public static string RoutePath(MetaObject entity) => + // rc.19 (R57, fix round I3): a declared @collectionName, or a configured pluralizer, names + // the segment (snake_cased, acronym-aware); otherwise the historical rule, byte-identical. + // One rule with TypeScript: fixtures/naming-conformance/collection-segments.json. CollectionNames.Segment(entity, name => PluralizeCrossPort(ToSnakeCase(name))); /// - /// The DbSet property name for an object: its @collectionName when it declares one, else - /// the configured pluralizer (naming.collections) over Pascal(name), else - /// Pluralize(Pascal(name)) (which keeps C#'s -sis rule, so an unconfigured project's - /// DbSets are unchanged). Every site that names the property (the context, the - /// routes, the reverse finders, the api reference) reads it here, so they always agree. + /// The DbSet property name for an object: its collection name (rc.19, R57) — its own + /// @collectionName (or the deprecated @dbSetName alias), else the configured + /// pluralizer (naming.collections) over Pascal(name), else the historical + /// Pluralize(Pascal(name)) (which keeps C#'s -sis rule, so an unconfigured + /// project's DbSets are unchanged). Every site that names the property (the context, the routes, + /// the reverse finders, the api reference) reads it here, so they always agree. /// public static string DbSetName(MetaObject entity) { - // ADR-0039: own — @collectionName names THIS object's property; an abstract base's value - // inherited by every subtype would hand them all one name. - if (entity.OwnAttr(OBJECT_ATTR_COLLECTION_NAME) is not string { Length: > 0 } declared) + // ADR-0039: own — the name is THIS object's; an abstract base's value inherited by every + // subtype would hand them all one name. + if (CollectionNames.Declared(entity) is not { } declared) return CollectionNames.ConfiguredPluralizer(entity) is { } configured ? NamingStrategies.Pluralizer(configured)(Pascal(entity.Name)) : Pluralize(Pascal(entity.Name)); @@ -388,7 +436,7 @@ public static string DbSetName(MetaObject entity) // error in the generated context (or a property that hides DbContext.Database). if (!System.Text.RegularExpressions.Regex.IsMatch(declared, "^[A-Za-z_][A-Za-z0-9_]*$") || ReservedDbSetNames.Contains(declared)) throw new InvalidOperationException( - $"{entity.ResolutionKey()}: @collectionName \"{declared}\" cannot be the DbSet property name — it must be a C# identifier " + + $"{entity.ResolutionKey()}: the collection name \"{declared}\" (@collectionName, or its deprecated alias @dbSetName) cannot be the DbSet property name — it must be a C# identifier " + "(letters, digits and underscores, not starting with a digit) and not a DbContext member (Database, Model, ChangeTracker, ContextId)."); return declared; } @@ -562,16 +610,25 @@ public static bool HasPrimarySource(MetaObject obj) => if (source is null) return null; var fields = new Dictionary(StringComparer.Ordinal); + // rc.21 (U7): a derived field of an object read from its table has no column, so it has + // no names entry — no `…Column` constant naming a column that does not exist. + var noColumn = source.IsWritable() && !obj.IsWriteThrough(); // ADR-0039: Fields() is the RESOLVING accessor — an inherited @column must // resolve here, or the constant disagrees with the column EF actually binds. - foreach (var f in obj.Fields()) + foreach (var f in obj.Fields().Where(f => !(noColumn && f.IsDerived()))) fields[f.Name] = FieldNamesOf(f, strategy); // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. var ownFields = new Dictionary(StringComparer.Ordinal); - foreach (var f in obj.OwnFields()) + foreach (var f in obj.OwnFields().Where(f => !(noColumn && f.IsDerived()))) ownFields[f.Name] = FieldNamesOf(f, strategy); var superObj = NamesArtifactSuperOf(obj); + // rc.21 fix round (M8): an abstract-entity fragment leaves its derived fields out (they are + // no column of the tables extending it), so an object whose derived fields ARE columns (a + // write-through entity's read view) declares the ones it inherits itself, or it would lose them. + if (!noColumn && superObj is not null && superObj.IsEntity() && superObj.IsAbstract) + foreach (var f in obj.Fields().Where(f => f.IsDerived() && !ownFields.ContainsKey(f.Name))) + ownFields[f.Name] = FieldNamesOf(f, strategy); // Identity of the resolved source NODE, not equality of the resolved strings: a // divergence guard is exactly what this codebase forbids here, and the question // being asked is structural — did this object declare a source, or is it using its @@ -768,10 +825,11 @@ private static bool DeclaresNamesContent(MetaObject obj) => { strategy ??= ColumnNamingStrategy.SnakeCase; if (!DeclaresNamesContent(obj)) return null; - var own = obj.OwnFields(); + // rc.21 (U7): an abstract ENTITY's derived field is no column of the tables extending it. + var own = obj.OwnFields().Where(f => !(obj.IsEntity() && f.IsDerived())).ToList(); var fields = new Dictionary(StringComparer.Ordinal); - foreach (var f in obj.Fields()) + foreach (var f in obj.Fields().Where(f => !(obj.IsEntity() && f.IsDerived()))) fields[f.Name] = FieldNamesOf(f, strategy); var ownFields = new Dictionary(StringComparer.Ordinal); foreach (var f in own) @@ -1194,7 +1252,7 @@ public static bool IsRequired(MetaObject entity, MetaField field) /// /// When the field extends a SHARED declaration — a root-level abstract /// field.enum (FR-019) — use the PascalCased super name, the one type - /// materialized in Enums.g.cs (or provided externally) and shared by every + /// materialized in its own <package>/<Enum>.g.cs (or provided externally) and shared by every /// field that extends it. /// Otherwise use <EntityPascal><FieldPascal>. /// diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 7c93eee6bc..3d2049436d 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -809,6 +809,13 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, WarnUnknownAttrs(meta); genLoad = meta.Load(); } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. The + // loader records it on its warning channel, which gen does not print, so it is said here. + if (genLoad.Errors.Count == 0) + { + foreach (var w in ValidationPasses.ValidateExtenderSubtypeScope(genLoad.Root)) + Console.Error.WriteLine($" warning: {w}"); + } if (RefuseEntities(a, genLoad.Root, GenCommandName) is { } unknownEntity) { Console.Error.WriteLine(unknownEntity); diff --git a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs index ac2f053ad5..7553e37984 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs @@ -88,7 +88,14 @@ public static Result Compute(GenConfig config, MetaRoot root, IReadOnlyList Path.Combine(virtualRoot, i.ToString())).ToList(); // No manifest and no sweep for the throwaway regen: it records nothing and deletes nothing. - var tempConfig = config with { OutDir = temps[0], GenStateDir = null, ProjectRoot = null, InputRoot = config.InputRoot ?? config.ProjectRoot, SweepOrphans = false }; + // The context's assembly name is pinned before --out moves: unset, it is read from the + // .csproj in or above --out, and the virtual root has none, so the render would leave the + // DesignTimeServicesReference line gen wrote out and report the file as drift. + var tempConfig = config with + { + OutDir = temps[0], ContextAssemblyName = config.ContextAssemblyName, + GenStateDir = null, ProjectRoot = null, InputRoot = config.InputRoot ?? config.ProjectRoot, SweepOrphans = false, + }; var rendered = new Dictionary(StringComparer.Ordinal); CodegenRunner.RunResult regen; try diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index b1ed44a0eb..eb2fd8e5ac 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -29,6 +29,10 @@ public sealed record RunResult(IReadOnlyList Files, IReadOnlyListverify --codegen reads it to tell that gen replaces an edit to one of them. public IReadOnlySet OverwritePaths { get; init; } = new HashSet(); + /// Absolute paths every generator of the run emitted (refused ones included): what a + /// self-hosted runner that makes several runs passes the union of to (G5, rc.20). + public IReadOnlySet EmittedPaths { get; init; } = new HashSet(); + /// ADR-0064: false when a file was refused, adopted, or an edited orphan was kept. /// Only a complete run may store a key. public bool Complete { get; init; } = true; @@ -203,6 +207,7 @@ internal static RunResult Run( return new RunResult(results, warnings) { OverwritePaths = overwritePaths, + EmittedPaths = emitted.Keys.ToHashSet(StringComparer.Ordinal), Complete = refused.Count == 0 && adopted.Count == 0 && !sweepRefused, OutsidePaths = outsidePaths, }; diff --git a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs index b18a450cce..5f0a2f4a4b 100644 --- a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs +++ b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs @@ -18,6 +18,9 @@ // lock and snapshots), `.gen-state` aside // flag the output-changing flags: --out, --namespace, --generators, // --template-root, --template-spec, --emit-abstract-shapes, --strict, baseline +// project the one .csproj in --out or the nearest directory above it, which names +// the assembly of the generated context's design-time services reference +// when GenConfig.ContextAssemblyName is unset (or "missing" when there is none) // template every file under prompts/, templates/, --template-root, and the template spec // extra every path a generator declared in IGenerator.ExtraInputs // format this format's version @@ -37,7 +40,7 @@ namespace MetaObjects.Codegen; public static class GenFingerprint { /// Bumped when an entry kind is added or its meaning changes, so an old file never matches. - public const int FormatVersion = 3; + public const int FormatVersion = 4; /// The stored key's file name inside .metaobjects/.gen-state/. One per port. public const string FileName = ".fingerprint-csharp.json"; @@ -166,6 +169,18 @@ public static IReadOnlyList IdentityEntries( Flag("generators", o.Generators); // Present only for a narrowed run, so a whole run's identity is unchanged. if (o.Entities is not null) Flag("entities", string.Join(",", o.Entities.Order(StringComparer.Ordinal))); + + // The project the output is compiled into. With no GenConfig.ContextAssemblyName the DbContext + // generator reads its assembly name from this file (CSharpProjectAssembly), which may lie + // outside codegen/ and .metaobjects/: renaming the assembly must render again. + if (o.OutDir is not null) + { + var outFull = Path.GetFullPath(Path.Combine(cwd, o.OutDir)); + if (CSharpProjectAssembly.FindProject(outFull) is { } csproj) + entries.AddRange(FileEntries("project", projectRoot, [csproj])); + else + entries.Add(new Entry("project", Rel(projectRoot, outFull), "missing")); + } Flag("template-root", o.TemplateRoot is null ? null : Path.GetFullPath(Path.Combine(cwd, o.TemplateRoot))); Flag("template-spec", o.TemplateSpec is null ? null : Path.GetFullPath(Path.Combine(cwd, o.TemplateSpec))); Flag("emit-abstract-shapes", o.EmitAbstractShapes ? "true" : "false"); diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index c4bf41fbd0..5320424372 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -218,17 +218,18 @@ public string Namespace /// /// The project's SQL dialect (.metaobjects/config.json migrate.dialect: /// postgres, sqlite, mysql, d1), or null when it names none. - /// Read only where generated code is provider-specific: the @sequenceStart model - /// annotation and the context's design-time services are Npgsql's concern, so they are emitted - /// for postgres alone. + /// Read only where generated code must bind one provider at compile time: the + /// @sequenceStart migrations generator subclasses Npgsql's, so it is emitted for + /// postgres alone. /// public string? Dialect { get; init; } /// - /// Leave out a validator CHECK the column already guarantees (a length maximum a - /// VARCHAR(n) enforces, a length minimum of zero or less), as meta migrate does - /// under migrate.checks.skipRedundant. A declared @constraintName keeps its CHECK - /// regardless. Default false. + /// .metaobjects/config.json migrate.checks.skipRedundant: leave out a validator CHECK + /// the column already guarantees (a validator.length maximum its VARCHAR(n) enforces, + /// a length minimum of 0 or less), exactly as meta migrate does, so the generated model and + /// the migrated database declare the same CHECKs. A validator with @constraintName keeps its + /// CHECK regardless. Default false. /// public bool SkipRedundantChecks { get; init; } @@ -243,7 +244,7 @@ public string Namespace /// warns, and EF finds the services only when the context's project is the startup project. EF /// reads the reference only from the startup and migrations assemblies, so a context in a third /// assembly needs the line in its migrations project; the run warns, with the line, whenever it - /// cannot show the line is unnecessary (). + /// cannot show the line is unnecessary (rc.19 I4, ). /// public string? ContextAssemblyName { @@ -271,11 +272,14 @@ public string? ContextAssemblyName /// /// The C# property name of a field, for every generator that names one: the entity and /// value-object classes, the composite [PrimaryKey], the DbContext's model - /// configuration, the reverse finders and the routes. null, the default, is the - /// PascalCased field name (). Set it to rename a property - /// (an acronym, say) once, so the class that declares it and every line that references it - /// agree. EntityGenerator.PropertyName and DbContextGenerator.PropertyName read - /// it by default; a subclass that overrides one of those hooks must override both. + /// configuration, the reverse finders, the routes (members, sort and filter names, credential + /// and write-deny keys), the callable arguments, the extractor mapper, the report export and + /// the filter allowlist's property map. null, the default, is the PascalCased field name + /// (). Set it to rename a property (an acronym, say) once, so + /// the class that declares it and every line that references it agree. This is the only way + /// to rename consistently: EntityGenerator.PropertyName and + /// DbContextGenerator.PropertyName default to it, are obsolete, and a generator whose + /// override answers differently from this resolver for any field refuses to run. /// public Func? PropertyNaming { get; init; } diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 5d32717045..12124b5a1a 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -261,6 +261,17 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Factory = _ => new NamesGenerator(), SourceFileName = "NamesGenerator.cs", }, + // The indexes the EF model cannot carry (an @expr key), as one SQL file to apply after the + // schema EF builds. C#-only: meta migrate writes them into its own DDL. + ["expression-indexes"] = new() + { + Name = "expression-indexes", + Description = "The expression (@expr) indexes EF Core cannot model, as one SQL file applied after the schema.", + Tier = GeneratorTier.Native, + Layer = GeneratorLayer.Persistence, + Factory = _ => new ExpressionIndexesGenerator(), + SourceFileName = "ExpressionIndexesGenerator.cs", + }, // The api reference (ADR-0025's api/csharp surface): an ordinary entry in codegen/Generators.cs, // with its output directory and page options as init properties (ADR-0034 Amendment 9). ["api-docs"] = new() diff --git a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs index 58b2b01dcf..084d416391 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs @@ -49,7 +49,7 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) var cls = CSharpNaming.Pascal(entity.Name); - // Schema-qualified physical proc/function name (e.g. analytics.fn_phase_summary). + // Schema-qualified physical proc/function name (e.g. analytics.fn_stage_summary). var physical = source.PhysicalName; var schemaPrefix = string.IsNullOrEmpty(source.Schema) ? "" : $"{source.Schema}."; var procName = $"{schemaPrefix}{physical}"; @@ -98,7 +98,7 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) // placeholder under FromSqlRaw. var argProps = argsObject is null ? [] - : argsObject.OwnFields().Select(f => CSharpNaming.Pascal(f.Name)).ToList(); + : argsObject.OwnFields().Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); var sqlArgs = string.Join(", ", argProps.Select(p => $"{{args.{p}}}")); var hasArgs = argsObject is not null; diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index fc1c6c1ce9..11c63b407d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -1,4 +1,4 @@ -// The CHECK constraints `meta migrate` derives for a table, with +// rc.19 item 13 (rulings R55) — the CHECK constraints `meta migrate` derives for a table, with // its names and its expression text, so the generated EF model declares the same constraints the // Node migrate path creates: one model, one database, through either delivery path. Ported from // typescript/packages/migrate-ts/src/expected-schema.ts (buildChecks, validatorCheck, @@ -46,47 +46,229 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co var table = CSharpNaming.Table(entity); var checks = new List(); foreach (var field in entity.Fields()) + checks.AddRange(FieldChecks(field, table, strategy, dialect, config).Select(c => c.Check)); + var root = entity.Root() as MetaRoot; + var tph = root is null ? null : TphPlanBuilder.For(entity, root); + if (tph is not null) checks.AddRange(SubtypeFieldChecks(entity, tph, table, strategy, dialect, config)); + // A cross-field validator always keeps its CHECK: it is enforced nowhere else, and the loader + // refuses @dbCheck: false on one (ERR_CROSS_FIELD_WITHOUT_CHECK). + foreach (var v in entity.Validators()) { - // No field-level CHECK on an array column: every expression below is scalar-shaped. - if (field.ResolvedIsArray()) continue; - // A derived (origin-bearing) field is no column of the table: a CHECK on it fails the - // migration. Its validators apply where it is read. - if (field.IsDerived()) continue; - var col = CSharpNaming.Column(field, strategy); - var qcol = Quote(col); - if (field.SubType == FIELD_SUBTYPE_ENUM && field.EffectiveEnumValues is { Count: > 0 } values) + if (CrossFieldCheck(v, entity, table, strategy, dialect) is { } check) + checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); + } + if (tph is not null) checks.AddRange(SubtypeCrossFieldChecks(entity, tph, table, strategy, dialect)); + return Distinct(entity, checks, dialect); + } + + /// + /// One table's CHECKs, with an exact repeat (same name, same expression) kept once, and two + /// different CHECKs under one name refused on every dialect. On Postgres the database would + /// refuse the second at CREATE TABLE. SQLite and D1 accept both (rc.21, N1), but EF's model keys + /// a check constraint by name: a second HasCheckConstraint with the same name replaces the + /// first (verified on EF Core 8.0.18), so the model would silently hold one of them. That is an + /// EF limit, so the C# port keeps the refusal where meta migrate accepts the pair. + /// + private static IReadOnlyList Distinct(MetaObject entity, List checks, string? dialect) + { + var byName = new Dictionary(StringComparer.Ordinal); + var outList = new List(); + foreach (var c in checks) + { + if (byName.TryGetValue(c.Name, out var seen)) { - var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; - var members = ints is null - ? values.Select(Literal) - : values.Select(v => ints.TryGetValue(v, out var n) && n is not null - ? Number(n) - : throw new InvalidOperationException( - $"field.enum '{field.Name}' @intValueMap has no integer for member '{v}' — cannot build the CHECK constraint for column '{col}'.")); - checks.Add(Named(new CheckConstraint($"{table}_{col}_chk", $"{qcol} IN ({string.Join(", ", members)})"), field)); + if (seen.Expression == c.Expression) continue; + var why = IsSqlite(dialect) + ? "EF Core keeps one check constraint per name, so the model would hold only the last" + : "Postgres requires each constraint on a table to have its own name"; + throw new InvalidOperationException( + $"object.entity '{entity.Name}': two CHECK constraints are both named '{c.Name}' ({seen.Expression} | {c.Expression}); {why}. " + + "Give one of the validators (or enums) a @constraintName."); } - // The VARCHAR(n) the column already is, when the project skips what it enforces. Not on - // SQLite / D1: they accept a declared length and store longer values anyway. - var enforcedMax = config.SkipRedundantChecks && !IsSqlite(dialect) ? VarcharLength(field) : null; - foreach (var v in field.Validators()) + byName[c.Name] = c; + outList.Add(c); + } + return outList; + } + + /// One column's field-level CHECKs (its enum membership, then each validator's), each with whether its name was declared. + private static List<(CheckConstraint Check, bool Declared)> FieldChecks( + MetaField field, string table, ColumnNamingStrategy strategy, string? dialect, GenConfig config) + { + var checks = new List<(CheckConstraint, bool)>(); + // No field-level CHECK on an array column: every expression below is scalar-shaped. + if (field.ResolvedIsArray()) return checks; + // A derived (origin-bearing) field is no column of the table: a CHECK on it fails the + // migration. Its validators apply where it is read. + if (field.IsDerived()) return checks; + var col = CSharpNaming.Column(field, strategy); + var qcol = Quote(col); + // @dbCheck: false (resolving) asks for no CHECK: the rule is enforced app-side only. + if (field.SubType == FIELD_SUBTYPE_ENUM && !OptedOut(field) && field.EffectiveEnumValues is { Count: > 0 } values) + { + var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; + // rc.21: a string member is stored as its @stringValueMap string, else as itself. + var members = ints is null + ? values.Select(v => Literal(EnumStorage.StoredValue(field, v))) + : values.Select(v => ints.TryGetValue(v, out var n) && n is not null + ? Number(n) + : throw new InvalidOperationException( + $"field.enum '{field.Name}' @intValueMap has no integer for member '{v}' — cannot build the CHECK constraint for column '{col}'.")); + checks.Add((Named(new CheckConstraint($"{table}_{col}_chk", $"{qcol} IN ({string.Join(", ", members)})"), field), DeclaredName(field) is not null)); + } + // The VARCHAR(n) the column already is, when the project skips what it enforces. Not on + // SQLite / D1: they accept a declared length and store longer values anyway. + var enforcedMax = config.SkipRedundantChecks && !IsSqlite(dialect) ? VarcharLength(field) : null; + foreach (var v in field.Validators()) + { + if (OptedOut(v)) continue; + // A declared @constraintName asks for the CHECK by name, so it is kept even where + // skipRedundant would leave it out: a declaration beats a default. + var declared = DeclaredName(v) is not null; + var check = ValidatorCheck(v, qcol, table, col, dialect, + skipRedundant: !declared && config.SkipRedundantChecks, enforcedMax: declared ? null : enforcedMax); + if (check is not null) checks.Add((Named(check, v), declared)); + } + return checks; + } + + /// + /// FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded columns, + /// so it carries their field-level CHECKs too, the subtypes in name order. + /// A column ONE field node owns (declared once, on a subtype or on an abstract level its + /// subtypes share) gets the text a base column gets, with no guard: a CHECK refuses only FALSE, + /// and a sibling's row holds NULL there, for which every field-level expression is NULL. So does + /// a column several sibling nodes declare with identical CHECKs. Sibling nodes that disagree + /// (different @values, a different pattern) each get their own CHECKs, guarded by the + /// discriminator values of the subtypes that carry that node and named after the declaring + /// object (<table>_<declarer>_<col>_…), so neither refuses the other's rows. + /// + private static IEnumerable SubtypeFieldChecks( + MetaObject entity, TphPlan tph, string table, ColumnNamingStrategy strategy, string? dialect, GenConfig config) + { + var baseNames = new HashSet(entity.Fields().Select(f => f.Name), StringComparer.Ordinal); + var groups = new List<(string Name, List<(MetaField Node, List Values)> Owners)>(); + foreach (var st in tph.Subtypes) + { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + foreach (var f in st.Entity.Fields()) { - // A declared @constraintName asks for the CHECK by name, so it is kept even where - // skipRedundant would leave it out: a declaration beats a default. - var declared = DeclaredName(v) is not null; - var check = ValidatorCheck(v, qcol, table, col, dialect, - skipRedundant: !declared && config.SkipRedundantChecks, enforcedMax: declared ? null : enforcedMax); - if (check is not null) checks.Add(Named(check, v)); + if (baseNames.Contains(f.Name)) continue; + var g = groups.FindIndex(x => x.Name == f.Name); + if (g < 0) + { + groups.Add((f.Name, [(f, [st.Value])])); + continue; + } + var owners = groups[g].Owners; + var o = owners.FindIndex(x => ReferenceEquals(x.Node, f)); + if (o < 0) owners.Add((f, [st.Value])); + else owners[o].Values.Add(st.Value); } } - // A cross-field validator always keeps its CHECK: it is enforced nowhere else. - foreach (var v in entity.Validators()) + foreach (var (_, owners) in groups) { - if (CrossFieldCheck(v, entity, table, strategy, dialect) is { } check) - checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); + var per = owners.Select(o => (o.Node, o.Values, Checks: FieldChecks(o.Node, table, strategy, dialect, config))).ToList(); + var first = per[0].Checks.Select(c => c.Check).ToList(); + if (per.All(p => p.Checks.Select(c => c.Check).SequenceEqual(first))) + { + foreach (var c in first) yield return c; + continue; + } + foreach (var (node, values, nodeChecks) in per) + foreach (var (check, declared) in nodeChecks) + { + var guarded = Wrap(check, DiscriminatorIn(tph, values), entity, strategy, dialect); + yield return declared ? guarded : guarded with { Name = Qualified(check.Name, table, node.Parent, dialect) }; + } } - return checks; } + /// A default CHECK name made unique to the object that declares the rule: <table>_<declarer>_…. + private static string Qualified(string name, string table, MetaData? declarer, string? dialect) + { + var tag = (declarer?.Name ?? "subtype").ToLowerInvariant(); + var qualified = name.StartsWith(table + "_", StringComparison.Ordinal) + ? $"{table}_{tag}_{name[(table.Length + 1)..]}" + : $"{tag}_{name}"; + return IsSqlite(dialect) ? qualified : FitPgIdentifier(qualified); + } + + /// Postgres's identifier limit, in bytes (NAMEDATALEN - 1). A longer name is truncated. + private const int PgIdentifierMaxBytes = 63; + + /// + /// rc.21 (N2): a generated name fitted to Postgres's 63-byte identifier limit, spelled as + /// meta migrate spells it (fitPgIdentifier). A longer name keeps its first 54 + /// bytes (whole characters) and gains _ and the first 8 hex digits of the SHA-256 of the + /// whole name. A name that fits is unchanged. + /// + public static string FitPgIdentifier(string name) + { + var utf8 = System.Text.Encoding.UTF8; + if (utf8.GetByteCount(name) <= PgIdentifierMaxBytes) return name; + var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(utf8.GetBytes(name)))[..8].ToLowerInvariant(); + var head = new System.Text.StringBuilder(); + var bytes = 0; + foreach (var rune in name.EnumerateRunes()) + { + var n = rune.Utf8SequenceLength; + if (bytes + n > PgIdentifierMaxBytes - 9) break; + head.Append(rune.ToString()); + bytes += n; + } + return $"{head}_{hash}"; + } + + /// The condition "the discriminator is one of ". + private static IReadOnlyDictionary DiscriminatorIn(TphPlan tph, IReadOnlyList values) + { + IReadOnlyDictionary Eq(string value) => new Dictionary + { + [KeyOp] = FILTER_OP_EQ, + [KeyLeft] = new Dictionary { [KeyField] = tph.DiscriminatorField }, + [KeyRight] = new Dictionary { [KeyValue] = value }, + }; + return values.Count == 1 + ? Eq(values[0]) + : new Dictionary { [KeyOp] = FILTER_COMPOSE_OR, [KeyArgs] = values.Select(x => (object?)Eq(x)).ToList() }; + } + + /// + /// FR-017 TPH: a cross-field validator a subtype adds holds for that subtype's rows only, so the + /// discriminator guards it — unlike a field-level CHECK, most cross-field rules are FALSE (not + /// NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists every concrete + /// subtype the validator reaches (one on an abstract level, or on a parent subtype, reaches each + /// of its concrete descendants), as an @condition ANDed with the validator's own. Its + /// default name carries the declaring object (<table>_<declarer>_…), so the same + /// rule on two siblings, or on a sibling and the base, does not collide. + /// + private static IEnumerable SubtypeCrossFieldChecks( + MetaObject entity, TphPlan tph, string table, ColumnNamingStrategy strategy, string? dialect) + { + var baseValidators = new HashSet(entity.Validators(), ReferenceEqualityComparer.Instance); + var reached = new List<(MetaValidator Validator, MetaObject Holder, List Values)>(); + foreach (var st in tph.Subtypes) + // ADR-0039: resolving — a validator on an abstract level or a parent subtype applies here too. + foreach (var v in st.Entity.Validators()) + { + if (baseValidators.Contains(v)) continue; + var i = reached.FindIndex(r => ReferenceEquals(r.Validator, v)); + if (i < 0) reached.Add((v, st.Entity, [st.Value])); + else reached[i].Values.Add(st.Value); + } + foreach (var (v, holder, values) in reached) + { + if (CrossFieldCheck(v, holder, table, strategy, dialect) is not { } check) continue; + var guarded = WithCondition(check, v, holder, strategy, dialect, DiscriminatorIn(tph, values)); + yield return DeclaredName(v) is { } name ? guarded with { Name = name } : guarded with { Name = Qualified(check.Name, table, v.Parent, dialect) }; + } + } + + /// Whether a validator or field.enum opts out of its CHECK (@dbCheck: false, resolving). + /// SkipRedundantChecks is independent of it: it only ever leaves more out. + private static bool OptedOut(MetaData node) => node.Attr(VALIDATOR_ATTR_DB_CHECK) is false; + /// The length a string column's VARCHAR(n) enforces: a string's @maxLength, a string-stored enum's resolved length. private static long? VarcharLength(MetaField field) => field.SubType switch { @@ -145,20 +327,6 @@ private static (string Qcol, MetaField Field)? Ref(MetaObject entity, object? na return field is null || field.IsDerived() ? null : (Quote(CSharpNaming.Column(field, strategy)), field); } - /// The columns a validator's @fields name, or null when there are none or one is missing or derived. - private static List<(string Qcol, MetaField Field)>? FieldRefs(MetaValidator v, MetaObject entity, ColumnNamingStrategy strategy) - { - var raw = v.Attr(VALIDATOR_ATTR_FIELDS); - IReadOnlyList names = raw switch - { - string s => [s], - IEnumerable list => list.ToList(), - _ => [], - }; - var refs = names.Select(n => Ref(entity, n, strategy)).ToList(); - return refs.Count == 0 || refs.Any(r => r is null) ? null : refs.Select(r => r!.Value).ToList(); - } - private static CheckConstraint? CrossFieldCheck(MetaValidator v, MetaObject entity, string table, ColumnNamingStrategy strategy, string? dialect) { switch (v.SubType) @@ -190,21 +358,35 @@ private static (string Qcol, MetaField Field)? Ref(MetaObject entity, object? na } case VALIDATOR_SUBTYPE_AT_LEAST_ONE: { - var refs = FieldRefs(v, entity, strategy); - if (refs is null) return null; - return new CheckConstraint($"{table}_{CSharpNaming.Column(refs[0].Field, strategy)}_atleastone_chk", - string.Join(" OR ", refs.Select(r => $"{r.Qcol} IS NOT NULL"))); + var raw = v.Attr(VALIDATOR_ATTR_FIELDS); + IReadOnlyList names = raw switch + { + IEnumerable list when raw is not string => list.ToList(), + string s => [s], + _ => [], + }; + var refs = names.Select(n => Ref(entity, n, strategy)).ToList(); + if (refs.Count == 0 || refs.Any(r => r is null)) return null; + var name = $"{table}_{CSharpNaming.Column(refs[0]!.Value.Field, strategy)}_atleastone_chk"; + return new CheckConstraint(name, string.Join(" OR ", refs.Select(r => $"{r!.Value.Qcol} IS NOT NULL"))); } case VALIDATOR_SUBTYPE_EXACTLY_ONE: { - var refs = FieldRefs(v, entity, strategy); - if (refs is null) return null; + var raw = v.Attr(VALIDATOR_ATTR_FIELDS); + IReadOnlyList names = raw switch + { + IEnumerable list when raw is not string => list.ToList(), + string s => [s], + _ => [], + }; + var refs = names.Select(n => Ref(entity, n, strategy)).ToList(); + if (refs.Count == 0 || refs.Any(r => r is null)) return null; // Postgres counts the present fields with num_nonnulls; SQLite and D1 add the // presence tests, which they evaluate as 0 / 1. var count = IsSqlite(dialect) - ? $"({string.Join(" + ", refs.Select(r => $"({r.Qcol} IS NOT NULL)"))})" - : $"num_nonnulls({string.Join(", ", refs.Select(r => r.Qcol))})"; - return new CheckConstraint($"{table}_{CSharpNaming.Column(refs[0].Field, strategy)}_exactlyone_chk", $"{count} = 1"); + ? $"({string.Join(" + ", refs.Select(r => $"({r!.Value.Qcol} IS NOT NULL)"))})" + : $"num_nonnulls({string.Join(", ", refs.Select(r => r!.Value.Qcol))})"; + return new CheckConstraint($"{table}_{CSharpNaming.Column(refs[0]!.Value.Field, strategy)}_exactlyone_chk", $"{count} = 1"); } default: return null; @@ -215,9 +397,22 @@ private static (string Qcol, MetaField Field)? Ref(MetaObject entity, object? na /// A cross-field validator's @condition: the rule applies only when it holds, so the /// CHECK is the negated condition OR the rule. /// - private static CheckConstraint WithCondition(CheckConstraint check, MetaValidator v, MetaObject entity, ColumnNamingStrategy strategy, string? dialect) + private static CheckConstraint WithCondition( + CheckConstraint check, MetaValidator v, MetaObject entity, ColumnNamingStrategy strategy, string? dialect, + IReadOnlyDictionary? guard = null) + { + var own = v.Attr(VALIDATOR_ATTR_CONDITION) as IReadOnlyDictionary; + // A TPH subtype's validator holds only where its discriminator guard does (SubtypeCrossFieldChecks). + var condition = guard is null + ? own + : own is null ? guard : new Dictionary { [KeyOp] = FILTER_COMPOSE_AND, [KeyArgs] = new List { guard, own } }; + return condition is null ? check : Wrap(check, condition, entity, strategy, dialect); + } + + /// The CHECK holds only where does: the negated condition OR the rule. + private static CheckConstraint Wrap( + CheckConstraint check, IReadOnlyDictionary condition, MetaObject entity, ColumnNamingStrategy strategy, string? dialect) { - if (v.Attr(VALIDATOR_ATTR_CONDITION) is not IReadOnlyDictionary condition) return check; string? Column(string name) => entity.Fields().FirstOrDefault(f => f.Name == name) is { } f ? Quote(CSharpNaming.Column(f, strategy)) : null; // An int-backed enum stores a member as its integer; a duration in the form its column stores. @@ -225,9 +420,12 @@ private static CheckConstraint WithCondition(CheckConstraint check, MetaValidato { var field = entity.Fields().FirstOrDefault(f => f.Name == name); if (field?.SubType == FIELD_SUBTYPE_DURATION) return DurationLiteral(field, value, dialect, "@condition"); - return field?.Attr(FIELD_ATTR_INT_VALUE_MAP) is IReadOnlyDictionary ints - && value is string s && ints.TryGetValue(s, out var n) && n is not null && IsNumber(n) - ? Number(n) + if (field?.Attr(FIELD_ATTR_INT_VALUE_MAP) is IReadOnlyDictionary ints + && value is string s && ints.TryGetValue(s, out var n) && n is not null && IsNumber(n)) + return Number(n); + // rc.21: a member compared with a @stringValueMap enum is its stored string. + return field is not null && value is string member && EnumStorage.StringValueMapOf(field) is not null + ? Literal(EnumStorage.StoredValue(field, member)) : null; } var unless = Render(Negate(condition), Column, dialect, Stored); @@ -262,7 +460,8 @@ private static string EqualsLiteral(object? raw, MetaField when, string? dialect var numeric = when.SubType is FIELD_SUBTYPE_INT or FIELD_SUBTYPE_LONG or FIELD_SUBTYPE_DOUBLE or FIELD_SUBTYPE_FLOAT or FIELD_SUBTYPE_DECIMAL or FIELD_SUBTYPE_CURRENCY; if (numeric && Regex.IsMatch(s, @"^-?\d+(\.\d+)?$")) return s; - return Literal(s); + // rc.21: a member of a @stringValueMap enum is compared as its stored string. + return Literal(when.SubType == FIELD_SUBTYPE_ENUM ? EnumStorage.StoredValue(when, s) : s); } // ---- field.duration literals (typescript metadata duration-wire.ts) ---- diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 0e86d0e0bc..fbe963095a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -5,6 +5,8 @@ // jsonb / subdocument / absent → a single json column via .ToJson), and uses // .PrimitiveCollection() for scalar/enum array fields (EF Core 8 API). +// The PropertyName hook is obsolete for adopters (set GenConfig.PropertyNaming); this generator still calls it. +#pragma warning disable CS0618 using System.Text; using MetaObjects.Codegen.Docs; using MetaObjects.Meta; @@ -63,7 +65,10 @@ public class DbContextGenerator : IGenerator /// names one. Default: the run's resolver, else /// PascalCase of the field name — the same answer EntityGenerator.PropertyName gives /// by default, so the two agree. A subclass that overrides the entity generator's hook - /// overrides this one the same way (or sets the resolver on the config instead). + /// overrides this one the same way (or sets the resolver on the config instead). + /// An override that answers differently from the resolver for any field is refused when the + /// generator runs (set GenConfig.PropertyNaming instead). + [Obsolete("set GenConfig.PropertyNaming: it is the one resolver every generator consults. An override that names a field differently from the resolver is refused when the generator runs.")] protected virtual string PropertyName(MetaField field) => CSharpNaming.PropertyName(field, _config); // The run's config, for the PropertyName default. Set when Generate starts. @@ -100,8 +105,12 @@ public virtual IEnumerable Generate(GenContext ctx) .OrderBy(o => o.Name, StringComparer.Ordinal) .ToList(); if (objects.Count == 0) return []; + // Every object the context names a property of: the DbSet entities and views, but also the value-object + // members its owned and flattened configuration reaches and a TPH subtype's own fields. + CSharpNaming.RefuseDivergingPropertyHook(Name, ReportRows.WithReportRows(ctx), ctx.Config, PropertyName); // One context, one property per name (CS0102 otherwise), claimed as emitted: an object - // that gets no DbSet here never takes part. + // that gets no DbSet here never takes part. Two objects on one table are EF's to refuse + // (it does, at model build), not this generator's. var dbSets = $"the DbSet properties of the context of {Name} entry {ctx.EntryLabel(this)}"; foreach (var o in objects) { @@ -111,7 +120,9 @@ public virtual IEnumerable Generate(GenContext ctx) } ClaimPhysicalAddresses(objects, ctx); - // OnModelCreating body lines (8-space indented), in a stable order. + // OnModelCreating body lines (8-space indented), in a stable order. INVARIANT: each entry is + // one complete C# statement — a guard and the statement it guards are ONE entry — because a + // large model is split into ConfigureModelNN methods at any entry boundary. var modelLines = new List(); // The M:N navigations, derived ONCE. M2MNavigationBuilder.For re-walks the @@ -194,12 +205,14 @@ public virtual IEnumerable Generate(GenContext ctx) foreach (var e in objects.Where(o => o.IsEntity() && !o.IsReadOnlyProjection())) { var owner = ValueObjectNames.Ref(e, ctx.Config); - // #214 — these config lines target the table-mapped class, which omits the derived - // (origin.*) fields; so must the config, or it would reference properties the class - // does not declare (a compile error). A write-through entity's derived fields are - // mapped on its read model (registered below). An entity's primary source is always - // writable (the loader refuses a read-only primary), so this class always maps a table. - IEnumerable configFields = e.Fields().Where(f => !f.IsDerived()); + // #214 — for a write-through entity these config lines target the WRITE (table) + // class, which omits the derived (origin.*) fields; so must the config, or it + // would reference properties the write class does not declare (a compile error). + // The derived fields' EF mapping lives on the read model (registered below). + // rc.19 entity-derived: an entity's derived field is never a column of its table. + IEnumerable configFields = e.IsWriteThrough() || e.IsEntity() + ? e.Fields().Where(f => !f.IsDerived()) + : e.Fields(); // #214 [0] — the per-field EF TYPE converters (owned-VO / enum / primitive // collection / decimal precision / timestamp column type / field.uri / field.inet / // @dbColumnType) over the write entity's derived-EXCLUDED field set. The SAME helper @@ -324,9 +337,9 @@ public virtual IEnumerable Generate(GenContext ctx) // A TPH subtype's own read-only field is configured too (EmitTphSubtypeFieldConfig). || modelLines.Any(l => l.Contains("PropertySaveBehavior.", StringComparison.Ordinal)); - // The identity start. A Postgres context with an increment key gets the generated - // design-time services whether or not a start is declared today, so removing the last - // @sequenceStart still scaffolds through them. Nothing is registered at runtime: the + // R36, R50 — the identity start. A Postgres context with an increment key gets the + // generated design-time services whether or not a start is declared today, so removing the + // last @sequenceStart still scaffolds through them. Nothing is registered at runtime: the // rewrite matters only when a migration is scaffolded, and Migrate() runs what it says. var written = objects.Where(o => o.IsEntity() && !o.IsReadOnlyProjection()).ToList(); var declaresStart = written.Any(o => IdentityStartOf(o) is not null); @@ -335,6 +348,16 @@ public virtual IEnumerable Generate(GenContext ctx) ctx.Warn($"{Name}: @sequenceStart is not in the EF model: the project names no Postgres " + "dialect (.metaobjects/config.json migrate.dialect: \"postgres\"; a self-hosted runner sets GenConfig.Dialect), " + "and the design-time services that keep a changed start from restarting the sequence are Npgsql's concern. meta migrate still creates the start."); + // Ruling R56 (item 3): @sequenceName describes an adopted database whose sequence kept its name. + // EF never names an identity's sequence and Npgsql cannot express it, so it is not in the model; + // that is not an error. Said once per run, naming every object that declares it. + var namedSequences = written + .Where(o => o.PrimaryIdentity()?.Attr(DbConstants.IDENTITY_ATTR_SEQUENCE_NAME) is string { Length: > 0 }) + .Select(o => o.ResolutionKey()) + .ToList(); + if (namedSequences.Count > 0) + ctx.Warn($"{Name}: @sequenceName is not in the EF model ({string.Join(", ", namedSequences)}): EF never names an " + + "identity's sequence and Npgsql cannot express it. The database keeps the name it has, and meta migrate uses it."); var sb = new StringBuilder(); EmitUsings(sb, needsMetadataUsing, ctx); @@ -345,6 +368,8 @@ public virtual IEnumerable Generate(GenContext ctx) if (NeedsUnmappedEnumHelper(objects, ctx.Root) || modelLines.Any(l => l.Contains(UnmappedEnumMemberHelperName + "(", StringComparison.Ordinal))) EmitUnmappedEnumHelper(sb); + if (modelLines.Any(l => l.Contains(UnmappedEnumStoredMemberHelperName + "(", StringComparison.Ordinal))) + EmitUnmappedStoredEnumHelper(sb); // Gated on the EMITTED text, not on a second derivation of it. Every site that uses the // helper appends to modelLines (entity, read-only projection, and the flattened-VO member // block, which lands here as one OwnedTypeConfig string), and modelLines is complete by @@ -354,7 +379,7 @@ public virtual IEnumerable Generate(GenContext ctx) if (modelLines.Any(l => l.Contains(MapJsonbHelperName))) EmitMapJsonbHelper(sb); sb.AppendLine("}"); if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(sb); - // The design-time services also scaffold a JSON column's comment (the design-time services scaffold it). + // The design-time services also scaffold a JSON column's comment (ruling R59). identityStart |= IdentityStartOn(ctx) && modelLines.Any(l => l.Contains(JsonColumnCommentAnnotation, StringComparison.Ordinal)); if (!identityStart) return [new EmittedFile("AppDbContext.g.cs", sb.ToString())]; var contextName = ContextClassName(ctx); @@ -662,10 +687,21 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) lhs + ".HasColumnType(\"uuid\").HasConversion(v => System.Guid.Parse(v!), g => g.ToString(\"D\"));", DbConstants.DB_COLUMN_TYPE_JSONB => lhs + ".HasColumnType(\"jsonb\");", + // rc.21 part B (U2): a text spelling is the column type, as `meta migrate` creates it. + { } spelling when DbConstants.ParseDbColumnType(spelling) is { Kind: "text" or "varchar" or "char" } p => + lhs + $".HasColumnType(\"{TextColumnType(p)}\");", _ => null, }; } + /// rc.21 part B (U2): the Postgres column type a text @dbColumnType spelling names. + private static string TextColumnType(DbConstants.ParsedDbColumnType p) => p.Kind switch + { + "char" => $"character({p.Length})", + "varchar" => p.Length is { } n ? $"character varying({n})" : "character varying", + _ => "text", + }; + // FR-017 — EF TPH single-table inheritance config for a discriminator base. The // discriminator property is the base's @discriminator field (PascalCased); the // HasValue clauses bind each concrete subtype to its @discriminatorValue. When the @@ -924,14 +960,29 @@ static bool Extends(MetaObject sub, MetaObject super) /// out ids live rows hold, so the generated design-time services /// () scaffold it as SQL instead. /// - private static void EmitIdentityStartConfig(string owner, MetaObject entity, List modelLines) + private void EmitIdentityStartConfig(string owner, MetaObject entity, List modelLines) { if (IdentityStartOf(entity) is not { } start) return; // One entry, one statement: the guard and its body never split across a chunk boundary. - modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().Property(x => x.{CSharpNaming.Pascal(start.Field.Name)}).HasAnnotation(" + + modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().Property(x => x.{PropertyName(start.Field)}).HasAnnotation(" + $"\"{NpgsqlIdentityOptionsAnnotation}\", \"'{start.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)}', '1', '', '', 'False', '1'\");"); } + /// + /// The table's CHECK constraints (item 13, rulings R55): every validator that can carry one and + /// every scalar field.enum, with meta migrate's names and expression text + /// (), so an EF migration and meta migrate build the same + /// table. Declared only on a dialect migrate builds (postgres, sqlite, d1): + /// the text is dialect-specific and EF hands it to the provider verbatim. One statement per entry. + /// + protected virtual void EmitCheckConfig(string owner, MetaObject entity, GenContext ctx, List modelLines) + { + if (entity.DbTable is null) return; + foreach (var check in CheckConstraints.For(entity, ctx.Config)) + modelLines.Add($" modelBuilder.Entity<{owner}>().ToTable(t => t.HasCheckConstraint(\"{CSharpNaming.CSharpStringLiteral(check.Name)}\", " + + $"\"{CSharpNaming.CSharpStringLiteral(check.Expression)}\"));"); + } + private const string NpgsqlIdentityOptionsAnnotation = "Npgsql:IdentitySequenceOptions"; private const string DesignTimeServicesSuffix = "DesignTimeServices"; @@ -957,8 +1008,8 @@ private static (MetaField Field, long Value)? IdentityStartOf(MetaObject entity) } /// - /// The design-time services of a Postgres context, <Context>DesignTimeServices (one class for - /// every design-time concern): an + /// The design-time services of a Postgres context, <Context>DesignTimeServices (rulings R50, + /// R51, R59, R60; one class for every design-time concern): an /// IDesignTimeServices that wraps the model differ the context already has, so /// dotnet ef migrations add scaffolds every start-only identity change — a start added, /// changed or removed — as SQL, Up and Down, and never as the AlterColumn Npgsql would @@ -968,7 +1019,7 @@ private static (MetaField Field, long Value)? IdentityStartOf(MetaObject entity) /// GREATEST(n, max(id) + 1) when it is below that, and never back. That makes a database /// rebuilt by replaying migrations begin at n as a fresh one does, and never hands out an /// id a live row holds. - /// Design time only. The rewrite matters only when a migration is scaffolded; + /// Ruling: design time only. The rewrite matters only when a migration is scaffolded; /// Migrate() executes the operations a migration already holds. Nothing is registered at /// runtime, and the file uses public EF types only (no Npgsql reference, no EF-internal type). /// The accepted residual risk: a migrations or startup project that neither is the context's @@ -997,7 +1048,7 @@ private string DesignTimeServicesFile(GenContext ctx, string contextName, string } else if (DesignTimeServicesReferences.Warning(ctx.Config, Name, contextName, $"{ns}.{className}", line, consequence) is { } warning) { - // EF reads the reference only from the startup and migrations + // rc.19 fix round (I4): EF reads the reference only from the startup and migrations // assemblies, so the one generated here is read only when this project holds the // migrations. The run warns whenever that cannot be proved, with the line to add. ctx.Warn(warning); @@ -1081,7 +1132,7 @@ public IReadOnlyList GetDifferences(IRelationalModel? source } } - // EF 8's JsonColumn carries no comment, so a JSON column's comment rides on + // Ruling R59: EF 8's JsonColumn carries no comment, so a JSON column's comment rides on // its owned type as an annotation and is scaffolded here, after every other operation // (a new table's column exists by then). Down is the same diff the other way. private const string JsonComment = "{{JsonColumnCommentAnnotation}}"; @@ -1220,7 +1271,7 @@ private void EmitCommentConfig(string owner, MetaObject entity, IEnumerable())) { // An OwnedTypeConfig override decides the mapping, so the lines already emitted - // say which it is (an override of the mapping decides it): only an owned JSON navigation takes the annotation. + // say which it is (G1, rc.20): only an owned JSON navigation takes the annotation. var mapping = MappedAs(owner, PropertyName(f), modelLines); if (mapping == ObjectFieldMapping.Property) { @@ -1270,7 +1321,7 @@ private enum ObjectFieldMapping { OwnedJson, Property, Unknown } /// /// How the model lines emitted so far map a non-flattened object field of - /// (an override of the mapping decides it). The field-type lines, 's among them, are emitted before + /// (G1, rc.20). The field-type lines, 's among them, are emitted before /// the comments, and each line is one statement, so the emitted text is exact: a /// OwnsOne/OwnsMany of the navigation with a ToJson is an owned JSON column /// (the stock mapping), a Property(x => x.Nav) is a column an override mapped as a property @@ -1293,7 +1344,7 @@ private static ObjectFieldMapping MappedAs(string owner, string nav, ListThe owned-type annotation carrying a JSON column's comment (the design-time services scaffold it). + /// The owned-type annotation carrying a JSON column's comment (ruling R59). internal const string JsonColumnCommentAnnotation = "MetaObjects:JsonColumnComment"; /// @@ -1303,22 +1354,8 @@ private static ObjectFieldMapping MappedAs(string owner, string nav, Listidentity.secondary (unique) and an index.lookup, each with @where /// (HasFilter), @using (HasMethod) and @orders /// (IsDescending), under its resolved name. An @expr index is not one EF can - /// model; meta migrate creates it. - /// - /// - /// Declares the CHECK constraints meta migrate creates for the table (enum membership, - /// validators, cross-field validators), with the same names and expression text, so an EF - /// migration and meta migrate build the same database. Declared only for a dialect - /// meta migrate builds (see ). + /// model; writes it as SQL. /// - protected virtual void EmitCheckConfig(string owner, MetaObject entity, GenContext ctx, List modelLines) - { - if (entity.DbTable is null) return; - foreach (var check in CheckConstraints.For(entity, ctx.Config)) - modelLines.Add($" modelBuilder.Entity<{owner}>().ToTable(t => t.HasCheckConstraint(\"{CSharpNaming.CSharpStringLiteral(check.Name)}\", " + - $"\"{CSharpNaming.CSharpStringLiteral(check.Expression)}\"));"); - } - private void EmitIndexConfig(string owner, MetaObject entity, GenContext ctx, List modelLines, IEnumerable? ownFields = null, Func? declares = null) { @@ -1370,8 +1407,8 @@ private void EmitIndexConfig(string owner, MetaObject entity, GenContext ctx, Li // @using: the access method, an Npgsql annotation (btree is the default and is left out). if (node.Attr(DbConstants.IDENTITY_ATTR_USING) is string method && method.Trim().Length > 0 && method.Trim() != "btree") { - modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\")"); - modelLines.Add($" modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})" + + // One entry per statement (the modelLines invariant): the guard and its statement are one line. + modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})" + $".HasAnnotation(\"Npgsql:IndexMethod\", \"{CSharpNaming.CSharpStringLiteral(method.Trim())}\");"); } } @@ -1389,7 +1426,7 @@ private void EmitForeignKeyIndexConfig(MetaObject entity, TphPlan? tph, GenConte var name = $"\"{CSharpNaming.CSharpStringLiteral(index.Name)}\""; var props = index.Fields.Select(PropertyName).ToList(); var selector = props.Count == 1 ? $"x => x.{props[0]}" : $"x => new {{ {string.Join(", ", props.Select(p => "x." + p))} }}"; - modelLines.Add($" modelBuilder.Entity<{CSharpNaming.Pascal(index.Owner.Name)}>().HasIndex({selector}, {name}).HasDatabaseName({name});"); + modelLines.Add($" modelBuilder.Entity<{ValueObjectNames.Ref(index.Owner, ctx.Config)}>().HasIndex({selector}, {name}).HasDatabaseName({name});"); } } @@ -1601,7 +1638,7 @@ protected virtual IEnumerable ReferenceConfig( return []; } - // A reference whose fields are members of ONE flattened value object + // G6: a reference whose fields are members of ONE flattened value object // (`address.countryId`) is a foreign key of that owned type, configured on its builder. if (fkFields.Any(f => f.Contains('.'))) return FlattenedMemberReferenceConfig(entity, reference, target, fkFields, ctx); @@ -1609,10 +1646,9 @@ protected virtual IEnumerable ReferenceConfig( var props = new List(fkFields.Count); foreach (var name in fkFields) { - // #214 — an entity's table-mapped class omits the derived (origin.*) fields, so - // naming one here would reference a property the class does not declare (a - // compile error in the generated file). An entity's primary source is always - // writable (the loader refuses a read-only primary), so its class maps a table. + // #214 — a write-through entity's WRITE class omits the derived (origin.*) + // fields, so naming one here would reference a property the class does not + // declare (a compile error in the generated file). if (entity.FindField(name) is not { } field) { return []; @@ -1633,10 +1669,11 @@ protected virtual IEnumerable ReferenceConfig( } /// - /// The relationship for a reference whose @fields are members of one flattened value - /// object. The member properties live on the owned type, so the foreign key is configured on - /// its builder, one statement: - /// modelBuilder.Entity<Plan>().OwnsOne(x => x.Address).HasOne<Country>().WithMany().HasForeignKey(e => e.CountryId). + /// G6 (reference half): the relationship for a reference whose @fields are members of + /// one flattened value object. The member properties live on the owned type, so the foreign + /// key is configured on its builder, one statement: + /// modelBuilder.Entity<Plan>().OwnsOne(x => x.Address, b => b.HasOne<Country>(<nav>).WithMany().HasForeignKey(e => e.CountryId)), + /// where <nav> is the owned type's navigation to the target over those properties, if it has one. /// Fields spread over the entity and a value object, or over two value objects, have no EF /// mapping: the run warns and configures none. /// @@ -1653,11 +1690,41 @@ private IEnumerable FlattenedMemberReferenceConfig( var nav = PropertyName((MetaField)members[0]!.Embedding); var props = members.Select(m => PropertyName((MetaField)m!.Member)).ToList(); var actions = ReferentialActions.Resolve(entity, reference); - return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}).HasOne<{ValueObjectNames.Ref(target, ctx.Config)}>()" + var targetRef = ValueObjectNames.Ref(target, ctx.Config); + // rc.21 (U6): the owned type is the adopter's to extend (a partial with a navigation to the + // target is the usual shape), and EF's convention builds a relationship from such a navigation + // the moment the owned type joins the model. A second, navigation-less HasOne over the same + // columns would then be a second relationship, with a shadow FK beside it (`_1`). + // So the relationship is configured THROUGH the navigation EF found over these FK properties, + // when there is one, and navigation-less otherwise. Read from the model, not reflected. + // Which navigation: none to the target, none; exactly one, that one (whatever its name, so + // `HomeCountry` over `CountryId` matches too); several, the one whose convention FK is these + // properties — and with no such one the model build THROWS, naming the owner, rather than + // configure a second relationship beside them (rc.21 fix round, M6). + var linq = "System.Linq.Enumerable"; + var fkNames = string.Join(", ", props.Select(p => $"\"{p}\"")); + var toTarget = $"{linq}.Where(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}))"; + var byFk = $"{linq}.FirstOrDefault({toTarget}, n => {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))"; + var ambiguous = $"new System.InvalidOperationException(\"{CSharpNaming.CSharpStringLiteral($"{entity.Name}.{nav} has several navigations to {target.Name} and none over {string.Join(", ", props)}: name the one this reference uses with that foreign key, or remove the others.")}\")"; + // rc.21 part B (N3): what codegen can know, it decides here. When this entity declares + // another reference from the same owned member to the same target, a sole navigation may be + // THAT reference's, so only the navigation over these exact properties is this one's; with + // none, the relationship is navigation-less (the other reference keeps its navigation). With + // one reference, a sole navigation can only be this one's, and only "several, none over + // these properties" is left to the model build (the owned CLR type is invisible to codegen). + var siblings = entity.ReferenceIdentities().Count(r => + !ReferenceEquals(r, reference) + && ReferenceEquals(NamingRefs.RefTarget(r, IDENTITY_REFERENCE_ATTR_REFERENCES), target) + && ReferentialActions.ReadIdentityFields(r) is { Count: > 0 } other + && other.All(f => FlattenedMembers.Resolve(entity, f) is { } m && ReferenceEquals(m.Embedding, members[0]!.Embedding))); + var navigation = siblings > 0 + ? $"{byFk}?.Name" + : $"({linq}.Count({toTarget}) == 0 ? null : {linq}.Count({toTarget}) == 1 ? {linq}.First({toTarget}) : ({byFk} ?? throw {ambiguous}))?.Name"; + return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) + $"{OnDeleteCall(entity, fkFields, actions.OnDelete, ctx)}" - + ConstraintNameCall(reference) + ";"]; + + ConstraintNameCall(reference) + ");"]; } /// @@ -1846,6 +1913,36 @@ private string UsingEntityConfig(M2MNavigation nav, GenContext ctx) /// Name of the generated fail-fast helper the write converters end in. private const string UnmappedEnumMemberHelperName = "UnmappedEnumMember"; + /// rc.21 — the read/write helpers a @stringValueMap enum's converters end in. + private const string UnmappedEnumStoredValueHelperName = "UnmappedEnumStoredValue"; + private const string UnmappedEnumStoredMemberHelperName = "UnmappedEnumStoredMember"; + + /// + /// rc.21 — the fail-fast helpers a @stringValueMap enum's converters end in, emitted only + /// when a converter references them (so a model with none is byte-identical). + /// + private static void EmitUnmappedStoredEnumHelper(StringBuilder sb) + { + sb.AppendLine(); + sb.AppendLine(" /// "); + sb.AppendLine(" /// A field.enum column with @stringValueMap held a string that maps to no member: the"); + sb.AppendLine(" /// database holds data the model says is impossible."); + sb.AppendLine(" /// "); + sb.AppendLine($" private static T {UnmappedEnumStoredValueHelperName}(string stored, string field) =>"); + sb.AppendLine(" throw new System.InvalidOperationException("); + sb.AppendLine(" $\"field.enum '{field}' read stored value '{stored}' with no member in \" +"); + sb.AppendLine(" \"@stringValueMap — the database holds a value the model does not describe.\");"); + sb.AppendLine(); + sb.AppendLine(" /// "); + sb.AppendLine(" /// A field.enum property with @stringValueMap held a value outside @values: it has no"); + sb.AppendLine(" /// declared stored string, and writing another member's would corrupt the row silently."); + sb.AppendLine(" /// "); + sb.AppendLine($" private static string {UnmappedEnumStoredMemberHelperName}(object? value, string field) =>"); + sb.AppendLine(" throw new System.InvalidOperationException("); + sb.AppendLine(" $\"field.enum '{field}' cannot write {value}: it has no stored string in \" +"); + sb.AppendLine(" \"@stringValueMap — the value is not one of the members the model declares.\");"); + } + /// /// Emits the fail-fast helper every int-backed enum's provider→model converter ends /// in. Emitted only when at least one such converter was generated, so a model with @@ -2090,8 +2187,8 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met /// /// The complete HasConversion call for an enum property: the generic /// HasConversion<string>() for a string-backed enum, or - /// HasConversion(model→provider, provider→model) built from - /// @intValueMap for an int-backed one. + /// HasConversion(new ValueConverter<E, int|string>(model→provider, provider→model)) + /// built from @intValueMap / @stringValueMap for a value-mapped one. /// /// /// The mapping is emitted as a TERNARY CHAIN rather than a switch @@ -2112,16 +2209,18 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met { var config = ctx.Config; var intMap = IntValueMapOf(f); + var stringMap = f.ResolvedIsArray() ? null : EnumStorage.StringValueMapOf(f); // A string-backed enum's column length (EnumLength.ResolveMaxLength: its @maxLength, else // the project's enums.maxLength) is the VARCHAR(n) `meta migrate` creates. An array enum // is a text[] column, whose elements carry no length. - if (intMap is null) - return !f.ResolvedIsArray() && EnumLength.ResolveMaxLength(f) is { } length - ? $"HasConversion().HasMaxLength({length})" - : "HasConversion()"; + var maxLength = !f.ResolvedIsArray() && intMap is null && EnumLength.ResolveMaxLength(f) is { } length + ? $".HasMaxLength({length})" + : ""; + if (intMap is null && stringMap is null) + return $"HasConversion(){maxLength}"; var members = f.EffectiveEnumValues ?? new List(); - if (members.Count == 0) return "HasConversion()"; + if (members.Count == 0) return $"HasConversion(){maxLength}"; // FR-019: a SHARED (root-level abstract) or @provided enum is NOT nested inside the // entity class — EntityGenerator references it instead (see its EnumPropertyTypeName) @@ -2139,12 +2238,27 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met var type = Fr019SharedEnum.SharedEnumForField(f) is { } shared ? Fr019SharedEnum.SharedEnumTypeReference(shared, config) : $"{CSharpNaming.QualifiedOwnerTypeRef(owner, entity, config)}.{CSharpNaming.EnumTypeName(entity, f)}"; + // rc.21: a @stringValueMap enum stores each member's string. The same per-member chains as + // the int-backed pair below, over string literals, each ending in its throwing helper. + if (stringMap is not null) + { + var toStored = new System.Text.StringBuilder("v => "); + var fromStored = new System.Text.StringBuilder("v => "); + foreach (var m in members) + toStored.Append($"v == {type}.{m} ? \"{CSharpNaming.CSharpStringLiteral(EnumStorage.StoredValue(f, m))}\" : "); + toStored.Append($"{UnmappedEnumStoredMemberHelperName}(v, \"{f.Name}\")"); + foreach (var m in members) + fromStored.Append($"v == \"{CSharpNaming.CSharpStringLiteral(EnumStorage.StoredValue(f, m))}\" ? {type}.{m} : "); + fromStored.Append($"{UnmappedEnumStoredValueHelperName}<{type}>(v, \"{f.Name}\")"); + return $"HasConversion({TypedEnumConverter(type, "string")}({toStored}, {fromStored})){maxLength}"; + } + // Read the ints THROUGH the map, keyed by member, so @values stays the SSOT and a // member with no mapping cannot silently vanish from the conversion. var ints = new List(members.Count); foreach (var m in members) { - if (!intMap.TryGetValue(m, out var raw) || raw is null) + if (!intMap!.TryGetValue(m, out var raw) || raw is null) throw new InvalidOperationException( $"field.enum '{f.Name}' @{FIELD_ATTR_INT_VALUE_MAP} has no integer for member '{m}' — " + "cannot build the EF value conversion."); @@ -2159,7 +2273,7 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met // as the LAST member's int, silently. for (var i = 0; i < members.Count; i++) toProvider.Append($"v == {type}.{members[i]} ? {ints[i]} : "); - // Typed object: the lambda's parameter is the property's type, nullable or not. + // Typed object: the helper takes the enum boxed, so it serves any converter's model type. toProvider.Append($"{UnmappedEnumMemberHelperName}(v, \"{f.Name}\")"); // Every member gets its own branch here (no last-member fallthrough) so the // final else can reject an int the model does not describe. @@ -2172,12 +2286,28 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met // lambdas against (CS1660), so the pair is wrapped in an explicit ValueConverter. // The element converter is the scalar pair unchanged, so each element is stored as // its declared int and an unmapped stored element throws exactly as a scalar does. - if (f.ResolvedIsArray()) - return "HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<" - + $"{type}, int>({toProvider}, {fromProvider}))"; - return $"HasConversion({toProvider}, {fromProvider})"; + // A scalar takes the same explicitly typed converter (see TypedEnumConverter). + return $"HasConversion({TypedEnumConverter(type, "int")}({toProvider}, {fromProvider}))"; } + /// + /// new ValueConverter<E, provider> — a value-mapped enum's converter, typed on the + /// NON-nullable enum whatever the property's nullability. + /// + /// + /// Handing the lambda pair straight to a scalar property's HasConversion(...) types it + /// on the property's CLR type, so an OPTIONAL field got a ValueConverter<E?, int>. + /// EF Core 8 cannot build the JSON collection reader/writer for a parameterised collection + /// over that converter, and a query such as active.Contains(w.Status) fails at runtime + /// (Npgsql: an InvalidOperationException or a MissingMethodException on + /// JsonNullableStructCollectionReaderWriter, by patch version). A converter on E is + /// what EF's own enum converters are and what an array's element converter already was; EF + /// passes null around it and never invokes the expressions on null, so the member chains + /// stay as they are. + /// + private static string TypedEnumConverter(string enumType, string provider) => + $"new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<{enumType}, {provider}>"; + // #214 [0] — the per-field EF TYPE-converter emission, factored out so the SAME set of // converters configures BOTH the write entity (its derived-EXCLUDED field set) AND a // write-through entity's View read model (ALL fields, incl. the derived origin.* diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 56c7fb3545..5b5b68fa06 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -12,6 +12,8 @@ // Object-typed fields on read-only projections are not mapped here — that is a // separate projection-materialization concern. +// The PropertyName hook is obsolete for adopters (set GenConfig.PropertyNaming); this generator still calls it. +#pragma warning disable CS0618 using System.Text; using MetaObjects.Codegen.Docs; using MetaObjects.Meta; @@ -44,8 +46,10 @@ public class EntityGenerator : IGenerator /// subclass can override to honor an explicit casing source (an all-caps acronym a plain /// PascalCase of the field name would mangle). Every name this generator emits for a field — /// the property, the composite [PrimaryKey], the reverse finders — goes through here. - /// The DbContext generator names the same properties: set the resolver on the config, or - /// override DbContextGenerator.PropertyName to match. + /// Every other generator that names a property reads + /// only, so an override that answers differently from the resolver for any field is refused + /// when the generator runs (set GenConfig.PropertyNaming instead). + [Obsolete("set GenConfig.PropertyNaming: it is the one resolver every generator consults. An override that names a field differently from the resolver is refused when the generator runs.")] protected virtual string PropertyName(MetaField field) => CSharpNaming.PropertyName(field, _config); // The run's config, for the PropertyName default. Set when Generate starts. @@ -115,6 +119,7 @@ public virtual IEnumerable Generate(GenContext ctx) _wire = ctx.Root.WireFormat; _config = ctx.Config; _ctx = ctx; + CSharpNaming.RefuseDivergingPropertyHook(Name, ReportRows.WithReportRows(ctx), ctx.Config, PropertyName); // FR-044 — a view-backed report joins the set as its ROW MODEL (a keyless, // projection-shaped object carrying its derived fields); every other report node // is dropped. See ReportRows. @@ -159,10 +164,10 @@ public virtual IEnumerable Generate(GenContext ctx) var files = new List(); // FR-019 — materialized shared enums (root-level abstract field.enum, non-@provided, - // consumed by ≥1 field) are emitted ONCE in a dedicated Enums.g.cs at the entity-module - // namespace; consuming entity fields REFERENCE them (no nested redeclaration). @provided - // shared enums emit nothing here (referenced from configured external namespace). With no - // shared enums in the model (the common inline case) no file is emitted — byte-identical. + // consumed by ≥1 field) are emitted ONCE each, as /.g.cs in the entity-module + // namespace (item 12); consuming entity fields REFERENCE them (no nested redeclaration). + // @provided shared enums emit nothing here (referenced from configured external namespace). + // With no shared enums in the model (the common inline case) no file is emitted. files.AddRange(EmitSharedEnumFiles(ctx, valueObjects)); foreach (var e in mapped) @@ -291,10 +296,10 @@ protected virtual EmittedFile EmitMappedClass(MetaObject entity, GenContext ctx) // Read-only projections map to a view (no [Table]); tables / a write-through // WRITE entity carry [Table]. isView: entity.IsReadOnlyProjection(), - // #214 — an entity's table-mapped class omits the derived fields: its table has no column for them. - // An entity's primary source is always writable (the loader refuses a read-only primary), - // so every entity class here maps a table. - excludeDerived: entity.IsEntity(), + // #214 — the write entity of a write-through omits the derived (view-only) fields; and + // (rc.19 entity-derived) so does any entity: a derived field on an entity with no read + // source is no column, only a definition projections inline where they reach it. + excludeDerived: entity.IsWriteThrough() || entity.IsEntity(), // A plain read-only projection keeps its warn-and-skip on object-typed columns // (collection materialization is a separate concern); the write entity is not a // view so this flag is inert there. @@ -1073,7 +1078,7 @@ protected virtual IEnumerable ValueObjectMemberAttributes(MetaObject vo, // only one declaration (prevents CS0102 "already contains a definition for ''"). // // FR-019: a field resolving to a SHARED (root-level abstract field.enum) enum is - // SKIPPED here — that type is materialized once in Enums.g.cs (or, when @provided, + // SKIPPED here — that type is materialized once in its own .g.cs (or, when @provided, // not at all) and merely REFERENCED. Inline enums (no root-abstract super) keep their // per-object nested declaration exactly as before (byte-identical default). protected static List CollectEnumDecls(MetaObject owner) @@ -1095,8 +1100,8 @@ protected static List CollectEnumDecls(MetaObject owner) } // FR-019 — the C# enum type a property of is typed by: - // • shared (root-level abstract, non-@provided) → the bare materialized type name - // (same generated namespace as the entity). + // • shared (root-level abstract, non-@provided) → the materialized type, global::-qualified + // in its package's namespace (rc.19 R65). // • @provided → . (codegen error if unset). // • inline (the common case) → the per-object nested type name. private static string EnumPropertyTypeName(MetaObject owner, MetaField field, GenConfig config) @@ -1106,9 +1111,9 @@ private static string EnumPropertyTypeName(MetaObject owner, MetaField field, Ge return CSharpNaming.EnumTypeName(owner, field); } - // FR-019 — the materialized shared-enums file (Enums.g.cs), emitted ONCE per run when - // the model has ≥1 consumed, non-@provided root-level abstract field.enum. Returns null - // (no file) otherwise — so a model with only inline enums is byte-identical to pre-FR-019. + // FR-019 — the materialized shared enums, one file each (item 12): /.g.cs + // (OutputPaths.Of, ruling R39), emitted when the model has a consumed, non-@provided root-level + // abstract field.enum; none otherwise, so a model with only inline enums emits nothing here. // Referencing a @provided enum with no ProvidedEnumNamespace configured throws here too // (the collect walk constructs each consuming reference's type), surfacing the config gap // as a codegen-time error before any file is written. @@ -2601,7 +2606,7 @@ protected virtual string PropertyClrType(MetaObject owner, MetaField field, GenC } if (field.SubType == FIELD_SUBTYPE_MAP) { - return $"Dictionary" + (required ? string.Empty : "?"); + return $"Dictionary" + (required ? string.Empty : "?"); } return CSharpNaming.ScalarForField(field) ?? "object"; } @@ -3289,4 +3294,10 @@ protected static List ValueShapes(IReadOnlyList referenc .OrderBy(o => ValueObjectNames.TypeName(o, ctx.Root), StringComparer.Ordinal) .ToList(); } + // A map's value object is named as the owner's file sees it: global::-qualified when another + // object shares its short name (both namespaces' `using`s are in scope; CS0104 otherwise). + private static string MapValueTypeRef(MetaField field, MetaData owner, GenContext ctx) => + field.ObjectRef is { Length: > 0 } && ValueObjectNames.ResolveFieldRef(field, ctx.Root) is { } vo + ? ValueObjectNames.ShortRef(vo, ctx.Root, ctx.Config, ValueObjectNames.Namespace(owner, ctx.Config)) + : CSharpNaming.MapValueType(field, ctx.Root); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs new file mode 100644 index 0000000000..5c47fa9b86 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs @@ -0,0 +1,87 @@ +// expression-indexes — the indexes the EF model cannot carry: every identity.secondary or +// index.lookup whose key is an expression (core @expr), with its @using and @where. EF Core's +// HasIndex takes properties only, so DbContextGenerator skips these nodes and this generator +// writes them as one SQL file (`expression-indexes.g.sql`) to apply after the schema EF builds. +// +// It is the database-built-from-the-model half of what `meta migrate` creates from the same +// metadata (migrate-ts emits each as a CREATE INDEX on the table, in its @schema, under the +// resolved index name), so the two databases agree. EF migrations never see these indexes: a +// changed one needs its own migration statement beside the metadata change. IF NOT EXISTS, so +// the file re-applies. + +using System.Text; +using MetaObjects.Meta; +using static MetaObjects.Persistence.Db.DbConstants; +using static MetaObjects.Persistence.Source.SourceConstants; + +namespace MetaObjects.Codegen.Generators; + +public class ExpressionIndexesGenerator : IGenerator +{ + public string Name => "expression-indexes"; + + /// The file the statements are written to, under the run's output directory. + public string FileName { get; init; } = "expression-indexes.g.sql"; + + public IEnumerable Generate(GenContext ctx) + { + var statements = new SortedDictionary(StringComparer.Ordinal); + foreach (var o in ctx.Entities.Where(o => o.IsEntity() && InstanceArtifacts.EmitsInstanceArtifacts(o))) + { + // ADR-0039: resolving — an index an abstract base declares is each concrete child's, on + // its own table (the layered enterprise → core shape). A TPH subtype's lands on its + // root's table, and only what it adds beyond the nearest ancestor in the model. + var owner = TphPlanBuilder.IsTphSubtype(o, ctx.Root) ? TphPlanBuilder.DiscriminatorRoot(o) ?? o : o; + var inModel = ReferenceEquals(owner, o) ? null : NearestConcreteAncestor(o); + var inherited = inModel is null ? new HashSet(StringComparer.Ordinal) + : new HashSet(IndexNodes(inModel).Select(n => n.Name), StringComparer.Ordinal); + foreach (var node in IndexNodes(o).Where(n => !inherited.Contains(n.Name))) + { + bool? unique = node switch + { + MetaSecondaryIdentity => true, + MetaIndex mi when mi.IsLookup() => false, + _ => null, + }; + if (unique is null || node.Attr(IDENTITY_ATTR_EXPR) is not string { Length: > 0 } expr) continue; + var table = CSharpNaming.Table(owner); + var schema = owner.Sources().FirstOrDefault(s => s.SubType == SOURCE_SUBTYPE_RDB)?.Schema; + var relation = string.IsNullOrEmpty(schema) ? Quote(table) : Quote(schema) + "." + Quote(table); + var name = IndexNaming.ResolveIndexName(node); + var sql = new StringBuilder() + .Append(unique.Value ? "CREATE UNIQUE INDEX IF NOT EXISTS " : "CREATE INDEX IF NOT EXISTS ") + .Append(Quote(name)).Append(" ON ").Append(relation); + if (node.Attr(IDENTITY_ATTR_USING) is string method && method.Trim().Length > 0 && method.Trim() != "btree") + sql.Append(" USING ").Append(method.Trim()); + sql.Append(" (").Append(expr.Trim()).Append(')'); + if (node.Attr(IDENTITY_ATTR_WHERE) is string where && where.Trim().Length > 0) + sql.Append(" WHERE ").Append(where.Trim()); + // An index name is unique per schema, tables included (migrate's ERR_DUPLICATE_SQL_NAME): + // two tables claiming one would leave the second unbuilt under IF NOT EXISTS. + ctx.Claim($"the indexes of schema \"{(string.IsNullOrEmpty(schema) ? "(default)" : schema)}\"", name, owner.ResolutionKey(), + "an index's name is used verbatim, so give each table its own (declare it on each concrete entity)"); + statements[$"{schema}/{name}"] = sql.Append(';').ToString(); + } + } + if (statements.Count == 0) yield break; + + var file = new StringBuilder() + .Append("-- MetaObjects expression-indexes. Do not edit by hand.\n") + .Append("-- The expression indexes (@expr) the EF model cannot carry; apply after the schema EF builds.\n\n"); + foreach (var statement in statements.Values) file.Append(statement).Append('\n'); + yield return new EmittedFile(FileName, file.ToString()); + } + + private static IEnumerable IndexNodes(MetaObject o) => + o.SecondaryIdentities().Cast().Concat(o.LookupIndexes()); + + /// The nearest ancestor that is in the EF model itself (a concrete TPH level or the root). + private static MetaObject? NearestConcreteAncestor(MetaObject o) + { + for (var s = o.SuperData as MetaObject; s is not null; s = s.SuperData as MetaObject) + if (InstanceArtifacts.EmitsInstanceArtifacts(s)) return s; + return null; + } + + private static string Quote(string name) => "\"" + name.Replace("\"", "\"\"") + "\""; +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index 7fe3fd691b..54495d13ba 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -148,7 +148,7 @@ private static void EmitMapper(StringBuilder sb, MetaData vo, GenContext ctx) { // A readOnly member has a private setter on the POCO: an initializer cannot set it. if (f.IsReadOnlyMutability) continue; - sb.AppendLine($" {CSharpNaming.Pascal(f.Name)} = {StrictArg((MetaObject)vo, f, ctx)},"); + sb.AppendLine($" {CSharpNaming.PropertyName(f, ctx.Config)} = {StrictArg((MetaObject)vo, f, ctx)},"); } sb.AppendLine(" };"); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 4bbb74b254..edac5b1a99 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -118,6 +118,19 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) sb.AppendLine(" },"); } sb.AppendLine(" };"); + // The field -> CLR property map, only when a property-naming resolver renamed a property + // beyond case (the runtime matches a field to its property case-insensitively, which + // covers every other spelling). Nothing is emitted otherwise, so default output is unchanged. + var renamed = CSharpNaming.RenamedProperties(entity, ctx.Config); + if (renamed.Count > 0) + { + sb.AppendLine(); + sb.AppendLine(" /// The CLR property of each field whose property name is not the field name in another case."); + sb.AppendLine(" public static readonly IReadOnlyDictionary PropertyByField = new Dictionary(System.StringComparer.Ordinal)"); + sb.AppendLine(" {"); + foreach (var kvp in renamed) sb.AppendLine($" [\"{kvp.Key}\"] = \"{kvp.Value}\","); + sb.AppendLine(" };"); + } sb.AppendLine("}"); return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}FilterAllowlist.g.cs"), sb.ToString()); diff --git a/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs b/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs index 8188c0136a..e46036d864 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs @@ -9,7 +9,7 @@ // // Two cases on the abstract declaration: // • non-@provided → metaobjects MATERIALIZES the type once (a shared file, -// Enums.g.cs, a namespace-level `public enum E { A, B }`), and consuming +// /.g.cs, a namespace-level `public enum E { A, B }`), and consuming // fields reference it (same namespace ⇒ a bare `E`). // • @provided: true → metaobjects emits NOTHING for the type; consuming fields // reference an existing hand-written/third-party type, resolved via per-port diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index e5af4bfde2..25c5ecdbb1 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -94,7 +94,14 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) => /// One emitted constant: its member name, its declaration body, and the metadata /// node it came from (named in the collision refusal, so a failure points at the model). - private readonly record struct Member(string Name, string Decl, string NodePath); + private readonly record struct Member(string Name, string Decl, string NodePath, string? Attribute = null); + + // A @storage: flattened field's own column constant names no column of the table: its members + // are the columns. It is still emitted (owned copies and existing code that read it must keep + // compiling) but deprecated. [Obsolete] on a declaration warns nothing; only a use does, so a + // project that never reads it gets no new warning. + private const string FlattenedColumnObsolete = + "[System.Obsolete(\"A flattened field has no column of its own; use the member constants.\")]"; /// /// One string constant. The VALUE is author-controlled — an object name, a key name, a @@ -374,7 +381,7 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra // `abstract class`, not `static class`: a static class can neither inherit nor be // inherited, and this artifact now extends its parent's rather than restating it. // Abstract keeps the "never instantiate this" guarantee a static class gave, and a - // `const` is inherited — `CopayAuthNames.IdColumn` resolves through the base — so + // `const` is inherited — `CouponAuthNames.IdColumn` resolves through the base — so // every consumption site is unchanged. var extends = superCls is null ? "" : $" : {superCls}"; sb.AppendLine($"public abstract class {cls}{extends}"); @@ -383,6 +390,7 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra { foreach (var m in group) { + if (m.Attribute is { } attribute) sb.AppendLine($" {attribute}"); sb.AppendLine($" public {(inherited.Contains(m.Name) ? "new " : "")}{m.Decl}"); } sb.AppendLine(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index 25f12d8dbc..17fab9d940 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -127,7 +127,7 @@ private string ReportModule(MetaObject report, GenContext ctx) sb.AppendLine($" public static {cell}[] Cells({cls} row) =>"); sb.AppendLine(" ["); foreach (var f in fields) - sb.AppendLine($" {writer}.Cell(row.{CSharpNaming.Pascal(f.Name)}),"); + sb.AppendLine($" {writer}.Cell(row.{CSharpNaming.PropertyName(f, ctx.Config)}),"); sb.AppendLine(" ];"); sb.AppendLine(); sb.AppendLine(" /// Writes the rows as RFC 4180 CSV."); diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index ec25a5f72c..7ffffa0cc6 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -103,7 +103,7 @@ public override IEnumerable Generate(GenContext ctx) ctx.Config.PackageNamespacesFromMetadata ? "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one" : "rename one"); - return served.Select(e => FixupContext(GenerateOne(e, ctx), ctx)); + return served.Select(e => GenerateOne(e, ctx)); } protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) @@ -209,16 +209,6 @@ private static void AppendReportExportBranch(StringBuilder sb, string cls, strin // Every type the route file names bare — the entity itself, its value objects (owned and map // values) and the targets and junctions of its M:N traversals — so a split-namespace model gets // a `using` for each package namespace the home-namespace file reaches into. - // With package namespaces on, the routes file names the context global::-qualified: the context - // lives in GenConfig.Namespace and the file in its entity's package namespace. The handler - // bodies spell the context type as `AppDbContext db`; this swaps that for the configured type. - private static EmittedFile FixupContext(EmittedFile file, GenContext ctx) - { - if (!ctx.Config.PackageNamespacesFromMetadata) return file; - var context = ValueObjectNames.Global(ctx.Config.Namespace, "AppDbContext"); - return file with { Content = System.Text.RegularExpressions.Regex.Replace(file.Content, @"(? ReferencedTypes(IEnumerable entities, MetaRoot root) { foreach (var entity in entities) @@ -251,7 +241,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte if (pkField is not null) { pkType = CSharpNaming.ScalarFor(pkField.SubType); - pkProp = CSharpNaming.Pascal(pkField.Name); + pkProp = CSharpNaming.PropertyName(pkField, ctx.Config); } } bool isProjection = entity.IsReadOnlyProjection(); @@ -278,13 +268,13 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // Issue #203 — @autoSet timestamp columns the generated CRUD stamps with now() // (insert stamps all; update stamps onUpdate; the merge loop skips them; an // InsertPreserving escape hatch is emitted when any exist). - var autoSetFields = AutoSetFields(entity); + var autoSetFields = AutoSetFields(entity, ctx.Config); var autoSetNavs = autoSetFields.Select(a => a.Nav).ToList(); // FR-037 R1 — readOnly / writeOnce are excluded from the PATCH merge. - var frozenNavs = FrozenNavs(entity); + var frozenNavs = FrozenNavs(entity, ctx.Config); // #484 — write-denied (@formExclude or credential) keys are ignored on every write; credentials never leave. var deniedFields = WriteDeniedFields(entity); - var credentials = CredentialNames(entity); + var credentials = CredentialNames(entity, ctx.Config); // Physical table + PK column for the post-save array-null clear (EF OwnsMany ToJson // writes [] for a null nav, so a nullable array column is NULLed via raw SQL). Both // are C# EXPRESSIONS — the Names constant when the names artifact is in this @@ -316,7 +306,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte || (isReport && f.SubType == FIELD_SUBTYPE_ENUM)) && !f.ResolvedIsArray() && !(isReport && IsCredentialField(f))) // a credential column would be a sort oracle - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); // ADR-0019 Amendment 1 (W4): SQLite refuses `ORDER BY` over a decimal expression, and its @@ -325,7 +315,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte var decimalSortFields = entity.Fields() .Where(f => f.SubType == FIELD_SUBTYPE_DECIMAL && !f.ResolvedIsArray() && CSharpNaming.DbColumnTypeClrOverride(f) is null) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToHashSet(StringComparer.Ordinal); bool sqliteSort = sortFields.Any(decimalSortFields.Contains); @@ -354,15 +344,18 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, entity, "SortDefaultDesc"); + AppendSortDefaultOrder(sb, entity, "SortDefaultDesc", ctx.Config); if (writable) AppendKnownFields(sb, [entity], ctx.Root); AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + // Refuse to start when the host's serializer contract cannot be read to strip a credential. + if (credentials.Count > 0) + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); AppendDecimalRangeGroup(sb); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. - sb.AppendLine(" app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); sb.AppendLine(" {"); sb.AppendLine(" var qs = http.Request.Query;"); if (export is not null) @@ -374,12 +367,13 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine($" IQueryable<{readCls}> q = db." + readDbSet + ".AsNoTracking();"); sb.AppendLine(); sb.AppendLine(" // Filter: ?filter[][]= against the per-entity allowlist."); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField));"); + var fm = FilterMapArg($"{cls}FilterAllowlist", entity, ctx.Config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField){fm});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null)"); // `field` names the rejected filter field — required cross-port on every // filter envelope, so a caller with several filters knows which one failed. sb.AppendLine(" return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fm});"); sb.AppendLine(); sb.AppendLine(" // Sort: ?sort=field:asc|desc against the static allowlist."); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); @@ -419,7 +413,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); else sb.AppendLine($" if (!withCount) return format is null ? {OkResult("rows", credentials)} : ReportExportHttp.Json(http, \"{route}\", rows{ExportOmit(credentials, false)});"); - sb.AppendLine($" var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates);"); + sb.AppendLine($" var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates{fm});"); sb.AppendLine(" var total = await totalQ.CountAsync();"); if (export is null) sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); @@ -430,7 +424,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte if (hasItem) { sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); sb.AppendLine(" await db." + readDbSet + ".FindAsync(id) is { } found"); sb.AppendLine(" ? " + OkResult("found", credentials)); sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); @@ -447,11 +441,11 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // #214 — a write-through create binds the derived-FREE WRITE entity, persists to // the table, then RE-READS the row through the replica view by PK so the returned // body carries the derived (view-computed) fields (read-your-writes). - AppendCreateHandler(sb, "/" + route, cls, dbSet, requiredKeys, + AppendCreateHandler(sb, "/" + route, cls, ValueObjectNames.ContextTypeRef(ctx.Config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields, writeThrough ? (readDbSet, pkProp!, route) : null, - deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials, - ServerOwnedCreateResets(entity, ctx.Root, _ => { }), ctx.Root, RequiredReadOnlyProps(entity)); + deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), credentials, + ServerOwnedCreateResets(entity, ctx.Root, ctx.Config), ctx.Root, RequiredReadOnlyProps(entity, ctx.Config)); // PATCH + PUT share the same handler — TS reference exposes both verbs, and both // return the updated row (HTTP 200), matching the cross-port api-contract. @@ -470,7 +464,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // is a 400. The per-key merge (shared with the TPH per-subtype handler) is // emitted by AppendPartialMergeLoop. sb.AppendLine(); - sb.AppendLine(" async System.Threading.Tasks.Task Update" + cls + "(" + pkType + " id, HttpContext http, AppDbContext db)"); + sb.AppendLine(" async System.Threading.Tasks.Task Update" + cls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db)"); sb.AppendLine(" {"); sb.AppendLine(" var existing = await db." + dbSet + ".FindAsync(id);"); sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); @@ -489,7 +483,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine(" var entry = db.Entry(existing);"); AppendUpdateAutoSet(sb, autoSetFields); AppendPartialMergeLoop(sb, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), - deniedFields.Select(f => f.Name).ToList(), HasIsoDurationField(entity, ctx.Root)); + deniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), HasIsoDurationField(entity, ctx.Root)); AppendSaveChanges(sb); AppendArrayNullClears(sb, voFields, tableRef, pkColumnRef); // #214 — writes target the table; for a write-through entity re-read the row @@ -510,7 +504,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine(" app.MapPatch(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); sb.AppendLine(" app.MapPut(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); sb.AppendLine(); - sb.AppendLine(" app.MapDelete(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapDelete(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); sb.AppendLine(" {"); sb.AppendLine(" var existing = await db." + dbSet + ".FindAsync(id);"); sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); @@ -530,7 +524,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // segment = relationship name. if (hasItem) foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) - AppendM2mRoute(sb, nav, route, pkType!, ctx.Root, config: ctx.Config); + AppendM2mRoute(sb, nav, route, pkType!, ctx.Root, ctx.Config); sb.AppendLine(); sb.AppendLine(" return mount;"); @@ -556,7 +550,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // Issue #203 — the verbatim-insert escape hatch, only for an entity with @autoSet // fields (writable entities only; a read-only projection has no insert path). if (writable && autoSetFields.Count > 0) - AppendInsertPreserving(sb, cls, dbSet); + AppendInsertPreserving(sb, cls, dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); AppendOmitResultClass(sb); sb.AppendLine("}"); @@ -626,21 +620,21 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t } var pkField = pkFields.Count == 1 ? baseEntity.Fields().FirstOrDefault(f => f.Name == pkFields[0]) : null; var pkType = pkField is not null ? CSharpNaming.ScalarFor(pkField.SubType) : null; - var pkProp = pkField is not null ? CSharpNaming.Pascal(pkField.Name) : null; + var pkProp = pkField is not null ? CSharpNaming.PropertyName(pkField, ctx.Config) : null; bool hasItem = pkType is not null; - var discProp = CSharpNaming.Pascal(tph.DiscriminatorField); + var discProp = baseEntity.FindField(tph.DiscriminatorField) is { } dField ? CSharpNaming.PropertyName(dField, ctx.Config) : CSharpNaming.Pascal(tph.DiscriminatorField); var discField = baseEntity.FindField(tph.DiscriminatorField); // #484 — the polymorphic base rows carry every subtype's columns, so a credential declared // on the base OR on any subtype is omitted from them. - var baseCredentials = CredentialNames(baseEntity) - .Concat(tph.Subtypes.SelectMany(st => CredentialNames(st.Entity))) + var baseCredentials = CredentialNames(baseEntity, ctx.Config) + .Concat(tph.Subtypes.SelectMany(st => CredentialNames(st.Entity, ctx.Config))) .Distinct(StringComparer.Ordinal).ToList(); // Sortable base scalar fields (the polymorphic list sorts on base columns). var sortFields = baseEntity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); var sb = new StringBuilder(); @@ -668,7 +662,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc"); + AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc", ctx.Config); // One known set for the whole hierarchy: a sibling subtype's column is declared, so it is not unknown. AppendKnownFields(sb, tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root); @@ -682,7 +676,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var subClsName = CSharpNaming.Pascal(st.Entity.Name); var subSortFields = st.Entity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); sb.Append($" private static readonly System.Collections.Generic.HashSet {subClsName}SortAllowlist ="); sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); @@ -690,22 +684,28 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t foreach (var name in subSortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc"); + AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); } AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); sb.AppendLine($" public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + if (baseCredentials.Count > 0) + { + var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); + } AppendDecimalRangeGroup(sb); // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- - sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "\", async (HttpContext http, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); sb.AppendLine(" {"); sb.AppendLine(" var qs = http.Request.Query;"); sb.AppendLine($" IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField));"); + var fmB = FilterMapArg($"{baseCls}FilterAllowlist", baseEntity, ctx.Config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField){fmB});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine(" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmB});"); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); sb.AppendLine(" {"); sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); @@ -719,7 +719,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t sb.AppendLine(" var rows = await q.ToListAsync();"); sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine($" if (!withCount) return {OkResult("rows", baseCredentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates).CountAsync();"); + sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); sb.AppendLine($" return {OkResult("new { rows, total }", baseCredentials, envelope: true)};"); sb.AppendLine(" });"); @@ -727,7 +727,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t { // --- Polymorphic get: GET //{id} (one row of whatever subtype) --- sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "/{id}\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); sb.AppendLine($" await db.{dbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); sb.AppendLine(" ? " + OkResult("found", baseCredentials)); sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); @@ -739,12 +739,12 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // a vanilla entity's traversal at the base route. Mirrors TS // renderTphRoutesFile's baseM2mMounts. foreach (var nav in M2MNavigationBuilder.For(baseEntity, ctx.Root, ctx.Warn)) - AppendM2mRoute(sb, nav, baseRoute, pkType!, ctx.Root, config: ctx.Config); + AppendM2mRoute(sb, nav, baseRoute, pkType!, ctx.Root, ctx.Config); // --- Per-subtype CRUD sets --- var hierarchy = tph.Subtypes.Select(s => s.Entity).Prepend(baseEntity).ToList(); foreach (var st in tph.Subtypes) - AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn, ctx.Config); + AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, ctx.Config, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn); } sb.AppendLine(); @@ -767,8 +767,8 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // EF via the subtype CLR type on Add). Only when the subtype has @autoSet columns. if (hasItem) foreach (var st in tph.Subtypes) - if (AutoSetFields(st.Entity).Count > 0) - AppendInsertPreserving(sb, CSharpNaming.Pascal(st.Entity.Name), dbSet); + if (AutoSetFields(st.Entity, ctx.Config).Count > 0) + AppendInsertPreserving(sb, ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)), dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); AppendOmitResultClass(sb); sb.AppendLine("}"); @@ -805,10 +805,10 @@ private static List RequiredCreateKeys(MetaObject obj, Func RequiredReadOnlyProps(MetaObject obj) => + private static List RequiredReadOnlyProps(MetaObject obj, GenConfig config) => obj.Fields() .Where(f => f.IsRequired && f.IsReadOnlyMutability && !f.IsDerived()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, config)) .ToList(); // Issue #203 — one @autoSet timestamp column the generated CRUD stamps with now(). @@ -832,10 +832,10 @@ private sealed record AutoSetField(string Nav, string NowExpr, bool OnUpdate); /// echoed in the RESPONSE even where EF omitted the column from the UPDATE. Skipping /// the key here is what makes the response and the row agree. /// - private static List FrozenNavs(MetaObject entity) => + private static List FrozenNavs(MetaObject entity, GenConfig config) => entity.Fields() .Where(f => f.Mutability != MetaObjects.Core.Field.FieldConstants.MUTABILITY_READ_WRITE) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, config)) .ToList(); // #484 — a credential is a field that declares (or inherits, ADR-0039) a view.password child. @@ -855,10 +855,10 @@ private static List WriteDeniedFields(MetaObject entity) => /// An entity's credential names plus, for a TPH base, those of every subtype: its rows are /// shared-table rows of every subtype (#484). /// - private static List TphUnionCredentialNames(MetaObject entity, MetaRoot root) => - CredentialNames(entity) + private static List TphUnionCredentialNames(MetaObject entity, MetaRoot root, GenConfig config) => + CredentialNames(entity, config) .Concat(TphPlanBuilder.For(entity, root) is { } tph - ? tph.Subtypes.SelectMany(st => CredentialNames(st.Entity)) + ? tph.Subtypes.SelectMany(st => CredentialNames(st.Entity, config)) : Enumerable.Empty()) .Distinct(StringComparer.Ordinal).ToList(); @@ -875,8 +875,34 @@ private static List HierarchyMarkedFields( return subtype.Fields().Where(f => marked.Contains(f.Name)).ToList(); } - private static List CredentialNames(MetaObject entity) => - entity.Fields().Where(IsCredentialField).Select(f => f.Name).ToList(); + // The keys a body can carry a field under: its metadata name and, when a resolver renames the + // property beyond case, the resolved property name (an entity property serializes under the + // host's naming policy applied to the resolved name). Credential stripping and the PATCH + // deny and value-object arms match on both, so a renamed property cannot escape them. Without + // a rename the two differ at most by case and the list is the field name alone. + private static List WireKeys(MetaField f, GenConfig config) => + new[] { f.Name, CSharpNaming.PropertyName(f, config) } + .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + + // The CLR property names of an entity's credentials. The JSON key each is written under is not + // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). + private static List CredentialNames(MetaObject entity, GenConfig config) => + entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); + + // The CLR property first (what the serializer's contract is matched on), then the field name: the + // normalized-spelling backstop in SerializerKeys.Strip also removes a key that spells it. Equal + // ignoring case when no resolver renames, so the list is then the one CLR name. + private static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => + new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); + + // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. + private static string KeyMatch(IEnumerable keys) => + string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)")); + + // The extra argument that hands the filter dispatch the allowlist's field-to-property map: only + // when a resolver renamed a property beyond case (the allowlist emits the map on the same test). + private static string FilterMapArg(string allowlistRef, MetaObject entity, GenConfig config) => + CSharpNaming.RenamedProperties(entity, config).Count > 0 ? $", {allowlistRef}.PropertyByField" : ""; // A C# string[] expression of the names, spliced into the credential-omitting result. private static string NamesLiteral(IEnumerable names) => @@ -920,22 +946,17 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); sb.AppendLine(" .Value.SerializerOptions;"); sb.AppendLine(" var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); - sb.AppendLine(" Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node);"); + sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); + sb.AppendLine($" SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); + sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names);"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); sb.AppendLine(" }"); - sb.AppendLine(" private void Strip(System.Text.Json.Nodes.JsonNode? n)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (n is System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; }"); - sb.AppendLine(" if (n is not System.Text.Json.Nodes.JsonObject o) return;"); - sb.AppendLine(" foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, System.StringComparison.OrdinalIgnoreCase))).ToList())"); - sb.AppendLine(" o.Remove(key);"); - sb.AppendLine(" }"); sb.AppendLine(" }"); } - private static List AutoSetFields(MetaObject entity) + private static List AutoSetFields(MetaObject entity, GenConfig config) { var list = new List(); foreach (var f in entity.Fields()) @@ -943,7 +964,7 @@ private static List AutoSetFields(MetaObject entity) if (f.AutoSet is not (AUTO_SET_ON_CREATE or AUTO_SET_ON_UPDATE)) continue; if (NowExprFor(f) is not { } now) continue; // non-temporal @autoSet — skip list.Add(new AutoSetField( - Nav: CSharpNaming.Pascal(f.Name), + Nav: CSharpNaming.PropertyName(f, config), NowExpr: now, OnUpdate: f.AutoSet == AUTO_SET_ON_UPDATE)); } @@ -966,7 +987,7 @@ private static List AutoSetFields(MetaObject entity) // Program D — a value-object column the entity carries: a field.object whose @objectRef // resolves to an object.value (single or @isArray). The generated create + PATCH handlers - // deserialize, validate, and assign these as CLR owned-nav properties. WireName is the + // deserialize, validate, and assign these as CLR owned-nav properties. WireKeys are the // metadata (camelCase) field name; Nav is the PascalCase property; DeserType is the VO // POCO type (or List for an array); JsonColumnRef is the physical jsonb column (the // .ToJson name) as a C# EXPRESSION — `Names.Column` when the names artifact @@ -974,7 +995,7 @@ private static List AutoSetFields(MetaObject entity) // splicing into the post-save null-clear SQL; IsArray / Required drive the merge semantics // (present-null: a nullable single/array clears, a @required column 400s). private sealed record VoField( - string WireName, string Nav, string DeserType, string JsonColumnRef, bool IsArray, bool Required); + IReadOnlyList WireKeys, string WireName, string Nav, string DeserType, string JsonColumnRef, bool IsArray, bool Required); // #362 — the `field.map @objectRef` columns, deliberately NOT folded into VoField. // A VoField drives the owned-nav machinery (EF OwnsMany/.ToJson, deserialization as an @@ -982,10 +1003,10 @@ private sealed record VoField( // with a jsonb converter and none of that applies. What it DOES share is the nested // value-object graph, which the create and PATCH paths must validate — before this the // map reached neither, so its values were written unchecked on every write path. - private sealed record MapVoField(string WireName, string Nav, string DeserType); + private sealed record MapVoField(IReadOnlyList WireKeys, string WireName, string Nav, string DeserType); - // A value object named from the routes file: bare in the earlier layout (the file has a using for - // each namespace it reaches), global::-qualified when package namespaces are on. + // A value object named from the routes file: bare in the earlier layout, global::-qualified + // when package namespaces are on. private static string VoTypeRef(MetaData target, MetaRoot root, GenConfig config) => config.PackageNamespacesFromMetadata ? ValueObjectNames.GlobalRef(target, config) : ValueObjectNames.TypeName(target, root); @@ -999,8 +1020,8 @@ private static List MapValueObjectFields(MetaObject entity, MetaRoot var target = ValueObjectNames.ResolveFieldRef(f, root); if (target is null || !target.IsValue()) continue; // scalar-valued maps have no bean list.Add(new MapVoField( - WireName: f.Name, - Nav: CSharpNaming.Pascal(f.Name), + WireKeys: WireKeys(f, config), WireName: f.Name, + Nav: CSharpNaming.PropertyName(f, config), DeserType: $"System.Collections.Generic.Dictionary")); } return list; @@ -1018,8 +1039,8 @@ private static List ValueObjectFields(MetaObject entity, MetaRoot root, var voType = VoTypeRef(target, root, config); var isArray = f.ResolvedIsArray(); // ADR-0039: resolving array-ness list.Add(new VoField( - WireName: f.Name, - Nav: CSharpNaming.Pascal(f.Name), + WireKeys: WireKeys(f, config), WireName: f.Name, + Nav: CSharpNaming.PropertyName(f, config), DeserType: isArray ? $"System.Collections.Generic.List<{voType}>" : voType, JsonColumnRef: CSharpNaming.ColumnRef(entity, f, strategy, includeNames, config), IsArray: isArray, @@ -1095,7 +1116,7 @@ private static void AppendOffsetLimit(StringBuilder sb, ApiPagination? page, str } private static void AppendCreateHandler( - StringBuilder sb, string mapPath, string cls, string dbSet, + StringBuilder sb, string mapPath, string cls, string ctxType, string dbSet, IReadOnlyList requiredKeys, string createdExpr, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetFields, @@ -1109,7 +1130,7 @@ private static void AppendCreateHandler( // The body is always read here, not model-bound: the framework answers a body it cannot bind with a // bare 400 and no body, while every validation failure must list its issues (the cross-port // {error:"validation", issues:[...]} envelope), so the handler reads the body itself and collects them. - sb.AppendLine($" app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, AppDbContext db) =>"); + sb.AppendLine($" app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, {ctxType} db) =>"); sb.AppendLine(" {"); AppendJsonOptsLocal(sb); sb.AppendLine(" System.Text.Json.JsonDocument __body;"); @@ -1175,15 +1196,15 @@ private static void AppendCreatePersist( } } - // Input hardening — a generated create hands storage ONLY what the client may set. The body is - // bound straight onto the EF entity, so every member the server owns is reset to its CLR default - // before validation and `Add`, and the request answers as if the key were absent (never a 400): + // SECURITY (1.2.x) — a generated create hands storage ONLY what the client may set. The body is + // bound straight onto the EF entity, so every member the server owns is reset before validation + // and `Add`, and the request answers as if the key were absent (never a 400): // - a server-generated primary key (@generation increment|uuid): default, so EF generates it; - // - the TPH discriminator on a per-subtype route: default, so EF's discriminator generator - // stamps the subtype's own @discriminatorValue (the route's subtype is its only source); + // - the TPH discriminator on a per-subtype route: default, so EF's discriminator value + // generator stamps the route subtype's own @discriminatorValue (the route is its only source); // - M:N navigation collections: emptied, else `Add` would insert a client-sent related graph. - // @readOnly fields need no line here: the entity declares them with a private setter, which - // System.Text.Json never binds (see EntityGenerator.SetterFor). Each statement is a complete line. + // A readOnly field needs no line here: the entity declares it with a private setter, which + // System.Text.Json never binds (EntityGenerator.SetterFor). private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList? statements) { if (statements is null || statements.Count == 0) return; @@ -1191,28 +1212,32 @@ private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList ServerOwnedCreateResets(MetaObject entity, MetaRoot root, Action onWarn, MetaField? discField = null, MetaObject? navOwner = null) + // The reset statements AppendCreateServerOwned emits for one entity (empty when it has none, so an + // entity with an assigned key, no navigation and no discriminator keeps its output byte-identical). + // A TPH subtype class declares no M:N property of its own — the navigations it carries are its + // discriminator base class's — so a subtype route passes that base as navOwner. The key and + // discriminator resets are SKIPPED when that field is itself @mutability: readOnly: the entity + // declares it with a private setter (EntityGenerator.SetterFor), so the assignment would be + // CS0122 — and it is redundant, because System.Text.Json never binds a private setter. + // The M:N element type is spelled through ValueObjectNames.TypeRef from the routes file's own + // namespace (a generated type's namespace is its metadata package), and the List is + // global::-qualified, as every other emitted System reference here is. + private static List ServerOwnedCreateResets( + MetaObject entity, MetaRoot root, GenConfig config, MetaField? discField = null, MetaObject? navOwner = null) { var list = new List(); - if (entity.PrimaryIdentity() is MetaPrimaryIdentity - { - Generation: MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT - or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID, - Fields: [var keyName], - } && entity.Fields().FirstOrDefault(f => f.Name == keyName) is { IsReadOnlyMutability: false } keyField) - list.Add($"input.{CSharpNaming.Pascal(keyField.Name)} = default!;"); - if (discField is { IsReadOnlyMutability: false }) - list.Add($"input.{CSharpNaming.Pascal(discField.Name)} = default!;"); - // A TPH subtype class declares no M:N property of its own: the navigations that exist are those of the - // discriminator base class (navOwner), so a subtype route resets exactly those. - foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, onWarn)) + if (entity.PrimaryIdentity() is MetaPrimaryIdentity pk + && pk.Generation is MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT + or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID + && pk.Fields is [var keyName] + && entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField + && !keyField.IsReadOnlyMutability) + list.Add($"input.{CSharpNaming.PropertyName(keyField, config)} = default!;"); + if (discField is not null && !discField.IsReadOnlyMutability) + list.Add($"input.{CSharpNaming.PropertyName(discField, config)} = default!;"); + foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, _ => { })) { - var target = CSharpNaming.Pascal(nav.Target.Name); + var target = ValueObjectNames.Ref(nav.Target, config); list.Add($"input.{CSharpNaming.Pascal(nav.Name)} = new System.Collections.Generic.List<{target}>();"); } return list; @@ -1255,12 +1280,12 @@ private static void AppendUpdateAutoSet(StringBuilder sb, IReadOnlyListEscape hatch: insert without @autoSet stamping (created-at/updated-at"); sb.AppendLine(" /// written verbatim from ) for import / restore / replication."); - sb.AppendLine($" public static async System.Threading.Tasks.Task<{cls}> InsertPreserving(AppDbContext db, {cls} input)"); + sb.AppendLine($" public static async System.Threading.Tasks.Task<{cls}> InsertPreserving({ctxType} db, {cls} input)"); sb.AppendLine(" {"); sb.AppendLine($" db.{dbSet}.Add(input);"); sb.AppendLine(" await db.SaveChangesAsync();"); @@ -1398,7 +1423,7 @@ private static void AppendPartialMergeLoop( StringBuilder sb, string? discProp, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetNavs, IReadOnlyList frozenNavs, bool hasDecimal, - IReadOnlyList deniedKeys, bool hasDuration = false) + IReadOnlyList deniedKeys, IReadOnlyList deniedClr, bool hasDuration = false) { // A nullable array-of-VO column that a request clears to null (present-null) can NOT be // NULLed by an owned-nav assignment — EF OwnsMany(...).ToJson writes `[]` for a null @@ -1408,12 +1433,19 @@ private static void AppendPartialMergeLoop( if (voFields[i].IsArray && !voFields[i].Required) sb.AppendLine($" var __clearVo{i} = false;"); + // The body key -> CLR property map comes from the host serializer's own contract (a naming policy + // such as SnakeCaseLower, a rename, an attribute), never from a guess at the name: the keys a + // client echoes from a response are the keys this resolves. + sb.AppendLine($" var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts);"); // Every violation is collected (never the first alone) and answered together after the loop. sb.AppendLine(" var __issues = new ValidationIssues();"); sb.AppendLine(" foreach (var prop in body.RootElement.EnumerateObject())"); sb.AppendLine(" {"); + sb.AppendLine(" var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null;"); // #484 — @formExclude / credential keys are IGNORED (never a 400), ahead of every arm below - // (a present null is a write too). + // (a present null is a write too). Denied by the serializer-resolved property AND by the field-name spellings. + if (deniedClr.Count > 0) + sb.AppendLine($" if (__clr is {string.Join(" or ", deniedClr.Select(n => "\"" + n + "\""))}) continue; // @formExclude / credential: not writable"); foreach (var key in deniedKeys) sb.AppendLine($" if (string.Equals(prop.Name, \"{key}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); // Program D — typed value-object arms FIRST (owned-nav columns are invisible to @@ -1426,7 +1458,7 @@ private static void AppendPartialMergeLoop( { var vf = voFields[i]; var v = "__vo" + i; - sb.AppendLine($" if (string.Equals(prop.Name, \"{vf.WireName}\", System.StringComparison.OrdinalIgnoreCase))"); + sb.AppendLine($" if ({KeyMatch(vf.WireKeys)} || __clr == \"{vf.Nav}\")"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); sb.AppendLine(" {"); @@ -1463,7 +1495,7 @@ private static void AppendPartialMergeLoop( { var mf = mapVoFields[i]; var mv = "__map" + i; - sb.AppendLine($" if (string.Equals(prop.Name, \"{mf.WireName}\", System.StringComparison.OrdinalIgnoreCase))"); + sb.AppendLine($" if ({KeyMatch(mf.WireKeys)} || __clr == \"{mf.Nav}\")"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); sb.AppendLine($" {{ existing.{mf.Nav} = null; continue; }}"); @@ -1475,7 +1507,8 @@ private static void AppendPartialMergeLoop( sb.AppendLine(" continue;"); sb.AppendLine(" }"); } - sb.AppendLine(" var target = entry.Metadata.FindProperty(prop.Name)"); + sb.AppendLine(" var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))"); + sb.AppendLine(" ?? entry.Metadata.FindProperty(prop.Name)"); sb.AppendLine(" ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine(" if (target is null) continue;"); sb.AppendLine(" var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);"); @@ -1588,8 +1621,8 @@ private static void AppendPartialMergeLoop( // subtype CLR type (discriminator injected by EF on Add); update is a partial merge // that never touches the PK or the discriminator. private static void AppendTphSubtypeRoutes( - StringBuilder sb, TphSubtypePlan st, IReadOnlyList hierarchy, MetaRoot root, string baseRoute, string baseCls, string dbSet, - string pkType, string pkProp, string discProp, MetaField? discField, Action onWarn, GenConfig config) + StringBuilder sb, TphSubtypePlan st, IReadOnlyList hierarchy, MetaRoot root, GenConfig config, string baseRoute, string baseCls, string dbSet, + string pkType, string pkProp, string discProp, MetaField? discField, Action onWarn) { // #362 — field.object columns on a TPH subtype stay out of scope (Program D §6), but a // field.map @objectRef is NOT: it reaches the settable set, so its value objects reach @@ -1597,32 +1630,33 @@ private static void AppendTphSubtypeRoutes( var mapVoFields = MapValueObjectFields(st.Entity, root, config); var subCls = CSharpNaming.Pascal(st.Entity.Name); var subType = ValueObjectNames.Ref(st.Entity, config); - var subAllow = ValueObjectNames.CompanionRef(st.Entity, config, subCls + "FilterAllowlist"); + var subAllowlist = ValueObjectNames.CompanionRef(st.Entity, config, subCls + "FilterAllowlist"); var seg = st.RouteSegment; var subRoute = baseRoute + "/" + seg; // Issue #203 — @autoSet columns on the subtype's EFFECTIVE fields (a shared // BaseEntity.createdAt/updatedAt is inherited by every subtype). Stamped on // create/update and skipped in the merge, exactly like a vanilla entity. - var autoSetFields = AutoSetFields(st.Entity); + var autoSetFields = AutoSetFields(st.Entity, config); var autoSetNavs = autoSetFields.Select(a => a.Nav).ToList(); // FR-037 R1 — readOnly / writeOnce on the SUBTYPE's effective fields (a shared // base's mode is inherited by every subtype), excluded from the PATCH merge. - var frozenNavs = FrozenNavs(st.Entity); + var frozenNavs = FrozenNavs(st.Entity, config); // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => f.Name).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "\", async (HttpContext http, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); sb.AppendLine(" {"); sb.AppendLine(" var qs = http.Request.Query;"); sb.AppendLine($" IQueryable<{subType}> q = db.{dbSet}.OfType<{subType}>().AsNoTracking();"); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllow}.Fields, {subAllow}.OpsByField));"); + var fmS = FilterMapArg(subAllowlist, st.Entity, config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField){fmS});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine(" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmS});"); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); sb.AppendLine(" {"); sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); @@ -1636,13 +1670,13 @@ private static void AppendTphSubtypeRoutes( sb.AppendLine(" var rows = await q.ToListAsync();"); sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates).CountAsync();"); + sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates{fmS}).CountAsync();"); sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); sb.AppendLine(" });"); // Per-subtype get: GET ///{id} — scoped (cross-subtype → 404). sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); sb.AppendLine($" await db.{dbSet}.OfType<{subType}>().AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); sb.AppendLine(" ? " + OkResult("found", credentials)); sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); @@ -1653,22 +1687,22 @@ private static void AppendTphSubtypeRoutes( // (EF-injected) discriminator, so an omitted @required value-type field → 400. var requiredKeys = RequiredCreateKeys(st.Entity, f => { - var p = CSharpNaming.Pascal(f.Name); + var p = CSharpNaming.PropertyName(f, config); return string.Equals(p, pkProp, System.StringComparison.Ordinal) || string.Equals(p, discProp, System.StringComparison.Ordinal); }); sb.AppendLine(); // VO columns on a TPH subtype are out of scope (Program D §6) — no typed arms. - AppendCreateHandler(sb, "/" + subRoute, subType, dbSet, requiredKeys, + AppendCreateHandler(sb, "/" + subRoute, subType, ValueObjectNames.ContextTypeRef(config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields, - deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials, - serverOwned: ServerOwnedCreateResets(st.Entity, root, _ => { }, discField, hierarchy[0]), root: root, - readOnlyRequired: RequiredReadOnlyProps(st.Entity)); + deniedNavs: deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), credentials: credentials, + serverOwned: ServerOwnedCreateResets(st.Entity, root, config, discField, hierarchy[0]), root: root, + readOnlyRequired: RequiredReadOnlyProps(st.Entity, config)); // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. sb.AppendLine(); - sb.AppendLine(" async System.Threading.Tasks.Task Update" + subCls + "(" + pkType + " id, HttpContext http, AppDbContext db)"); + sb.AppendLine(" async System.Threading.Tasks.Task Update" + subCls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); sb.AppendLine(" {"); sb.AppendLine($" var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); @@ -1688,7 +1722,7 @@ private static void AppendTphSubtypeRoutes( // ADR-0045 + the 0.19.4 lesson: TPH is a SEPARATE code path per port, so the // per-subtype merge states the same exclusion rather than inheriting it. AppendPartialMergeLoop(sb, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), - deniedFields.Select(f => f.Name).ToList(), HasIsoDurationField(st.Entity, root)); + deniedFields.SelectMany(f => WireKeys(f, config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), HasIsoDurationField(st.Entity, root)); AppendSaveChanges(sb); sb.AppendLine($" return {OkResult("existing", credentials)};"); sb.AppendLine(" }"); @@ -1697,7 +1731,7 @@ private static void AppendTphSubtypeRoutes( // Per-subtype delete: DELETE ///{id} — scoped (cross-subtype → 404). sb.AppendLine(); - sb.AppendLine(" app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); sb.AppendLine(" {"); sb.AppendLine($" var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); @@ -1716,7 +1750,7 @@ private static void AppendTphSubtypeRoutes( // segment in the URL would be decorative (rule c). var sourceScope = new TphM2mSourceScope(dbSet, subType, pkProp); foreach (var nav in M2MNavigationBuilder.For(st.Entity, root, onWarn)) - AppendM2mRoute(sb, nav, subRoute, pkType, root, sourceScope, config); + AppendM2mRoute(sb, nav, subRoute, pkType, root, config, sourceScope); } /// @@ -1750,6 +1784,10 @@ private static void AppendSaveChanges(StringBuilder sb, string indent = " sb.AppendLine(indent + "}"); } + // A junction/target column's CLR property, through the same resolver its entity class used. + private static string JunctionProperty(MetaObject owner, string fieldName, GenConfig config) => + owner.FindField(fieldName) is { } f ? CSharpNaming.PropertyName(f, config) : CSharpNaming.Pascal(fieldName); + // Emit the M:N traversal handler for one navigation. The junction + target are // mapped DbSets; the handler does the same two-stage join M2MResolver performs at // runtime, but over the generated DbSets via EF.Property (no metadata at runtime). @@ -1772,29 +1810,29 @@ private static void AppendSaveChanges(StringBuilder sb, string indent = " // cross-port contract; mirrors TS mount-m2m.ts's `sourceDiscriminator` Stage 0). private static void AppendM2mRoute( System.Text.StringBuilder sb, M2MNavigation nav, string sourceRoute, string pkType, MetaRoot root, - TphM2mSourceScope? sourceScope = null, GenConfig? config = null) + GenConfig config, TphM2mSourceScope? sourceScope = null) { var relSeg = nav.Name; // relationship name segment - var targetCls = CSharpNaming.Pascal(nav.Target.Name); - var targetType = config is { PackageNamespacesFromMetadata: true } ? ValueObjectNames.GlobalRef(nav.Target, config) : targetCls; + var targetCls = ValueObjectNames.Ref(nav.Target, config); // Defect B — a TPH subtype target is folded into its discriminator base's single // table (no DbSet of its own). Bind to the BASE's DbSet and narrow with // OfType() so the emitted db. always names a real property; every // other target keeps binding to its own pluralized DbSet, byte-identical to before. var targetFrom = TphPlanBuilder.IsTphSubtype(nav.Target, root) - ? $"db.{CSharpNaming.DbSetName(TphPlanBuilder.DiscriminatorRoot(nav.Target)!)}.OfType<{targetType}>()" - : $"db.{CSharpNaming.Pluralize(targetCls)}"; - var junctionDbSet = CSharpNaming.Pluralize(CSharpNaming.Pascal(nav.Junction.Name)); - var srcFkProp = CSharpNaming.Pascal(nav.SourceField); - var tgtFkProp = CSharpNaming.Pascal(nav.TargetField); + ? $"db.{CSharpNaming.DbSetName(TphPlanBuilder.DiscriminatorRoot(nav.Target)!)}.OfType<{targetCls}>()" + : $"db.{CSharpNaming.DbSetName(nav.Target)}"; + // The DbSet the context declares for the junction, @collectionName included (item 17). + var junctionDbSet = CSharpNaming.DbSetName(nav.Junction); + var srcFkProp = JunctionProperty(nav.Junction, nav.SourceField, config); + var tgtFkProp = JunctionProperty(nav.Junction, nav.TargetField, config); // The junction FK CLR type (the related-id key type) + the target PK property. var fkType = JunctionFkType(nav); var targetPk = nav.Target.PrimaryIdentity()?.Fields is { Count: 1 } tf - ? CSharpNaming.Pascal(tf[0]) : "Id"; + ? JunctionProperty(nav.Target, tf[0], config) : "Id"; sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, AppDbContext db) =>"); + sb.AppendLine(" app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); sb.AppendLine(" {"); if (sourceScope is not null) { @@ -1803,7 +1841,7 @@ private static void AppendM2mRoute( // (it just has no relations under this segment): 200 with an empty list, // never 404 and never the sibling's rows. sb.AppendLine($" if (!await db.{sourceScope.DbSet}.OfType<{sourceScope.SubtypeClass}>().AnyAsync(x => x.{sourceScope.PkProp} == id))"); - sb.AppendLine($" return Results.Ok(new System.Collections.Generic.List<{targetType}>());"); + sb.AppendLine($" return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); } if (nav.Symmetric) { @@ -1823,11 +1861,11 @@ private static void AppendM2mRoute( sb.AppendLine($" .Select(j => EF.Property<{fkType}>(j, \"{tgtFkProp}\"))"); sb.AppendLine(" .ToListAsync()).ToHashSet();"); } - sb.AppendLine($" if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List<{targetType}>());"); + sb.AppendLine($" if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); sb.AppendLine($" var rows = await {targetFrom}.AsNoTracking()"); sb.AppendLine($" .Where(t => relatedIds.Contains(EF.Property<{fkType}>(t, \"{targetPk}\")))"); sb.AppendLine(" .ToListAsync();"); - sb.AppendLine($" return {OkResult("rows", TphUnionCredentialNames(nav.Target, root))};"); + sb.AppendLine($" return {OkResult("rows", TphUnionCredentialNames(nav.Target, root, config))};"); sb.AppendLine(" });"); } @@ -1861,7 +1899,7 @@ private static string JunctionFkType(M2MNavigation nav) /// default into its map. Attr() is the RESOLVING accessor (ADR-0039), so an /// order inherited via extends is honoured. /// - private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, string constName) + private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, string constName, GenConfig config) { sb.Append($" private static readonly System.Collections.Generic.Dictionary {constName} ="); sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); @@ -1871,7 +1909,7 @@ private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, s if (CSharpNaming.ScalarFor(f.SubType) is null || f.ResolvedIsArray()) continue; if (f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) is not string v) continue; if (v != "asc" && v != "desc") continue; - sb.AppendLine($" [\"{CSharpNaming.Pascal(f.Name)}\"] = {(v == "desc" ? "true" : "false")},"); + sb.AppendLine($" [\"{CSharpNaming.PropertyName(f, config)}\"] = {(v == "desc" ? "true" : "false")},"); } sb.AppendLine(" };"); sb.AppendLine(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs index 17c70322a1..01b7d4203a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs @@ -40,7 +40,7 @@ public static class TphPlanBuilder /// /// The per-subtype REST route segment for a discriminator value — the ONE place /// this rule lives (mirrors TS tphRouteSegment): the value lowercased - /// ("Bridge" → bridge, "PriorAuth" → priorauth). + /// ("Bridge" → bridge, "Permit" → permit). /// public static string RouteSegment(string discriminatorValue) => discriminatorValue.ToLowerInvariant(); diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs index c177184f0c..4245979de1 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs @@ -60,6 +60,8 @@ public static class HelperRuntime /// DurationWire.cs is the field.duration wire form it parses duration operands with. /// ReportExportHttp.cs is the HTTP side of report export: a report list route that /// is built with a report-export generator wired calls it. + /// SerializerKeys.cs reads the host serializer's own JSON key for a property, so credential + /// stripping and the PATCH key lookup agree with it under any naming policy. /// public static readonly IReadOnlyList Files = [ @@ -76,6 +78,7 @@ public static class HelperRuntime "DurationWire.cs", "DecimalRangeEndpointFilter.cs", "ReportExportHttp.cs", + "SerializerKeys.cs", ]; /// Runtime/ files that are CORE and never copied (see the header). diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index d1de31cf5c..bf9cdad1ce 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -47,6 +47,7 @@ + @@ -93,5 +94,6 @@ + diff --git a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs index 737b0617e2..af3ab1565f 100644 --- a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs +++ b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs @@ -39,7 +39,39 @@ public enum Verdict /// Project-relative paths of edited orphans, left in place. /// Edited orphans deleted anyway, because every generator writing into /// their directory declares (also in ). - public sealed record Result(IReadOnlyList Removed, IReadOnlyList Refused, IReadOnlyList Discarded); + public sealed record Result(IReadOnlyList Removed, IReadOnlyList Refused, IReadOnlyList Discarded) + { + /// + /// With reportUnrecorded: project-relative paths of files no generator emitted that the + /// manifest does not record but whose leading lines carry MetaObjects' own header + /// () — output written before the runner kept a manifest. Never deleted: + /// with no recorded hash there is no telling an edited file from an untouched one. Empty otherwise. + /// + public IReadOnlyList Unrecorded { get; init; } = []; + } + + /// The header every C# MetaObjects generator writes on a file's second line + /// (// Generated by MetaObjects <generator>); <auto-generated/> alone is the + /// .NET convention and is not ours. + public const string Signature = "Generated by MetaObjects "; + + /// How many leading lines are read for . + private const int SignatureLines = 5; + + private static bool CarriesSignature(string path) + { + try + { + using var reader = new StreamReader(path); + for (var i = 0; i < SignatureLines && reader.ReadLine() is { } line; i++) + if (line.Contains(Signature, StringComparison.Ordinal)) return true; + return false; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + return false; + } + } /// /// Classify one committed file no generator emitted. is its absolute @@ -71,10 +103,13 @@ public static Verdict Classify( return key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key) ? null : key; } + // Case-insensitive, as every path comparison of the sweep (I3, rc.20): on a case-insensitive file + // system (macOS, Windows) an overwrite keeps the old spelling, so a case-only rename leaves the + // emitted file under its old name. Keeping too much is the safe failure for a sweep. private static bool IsUnder(string path, string dir) => Path.GetFullPath(path).StartsWith( Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)) + Path.DirectorySeparatorChar, - StringComparison.Ordinal); + StringComparison.OrdinalIgnoreCase); /// /// Delete the untouched files under that the manifest records and @@ -82,16 +117,29 @@ private static bool IsUnder(string path, string dir) => /// not hold, and forget every recorded path under those directories whose file is gone. /// Each directory comes with the label the run reports its files under. In a directory of /// (absolute paths) an edited orphan is deleted too. + /// + /// A self-hosted runner that makes several + /// calls (one per target) gives each the same and + /// , leaves off, and calls this + /// once afterwards with every run's directories and the union of their + /// : one run's files look orphaned to another (G5, + /// rc.20). lists, never deletes, the files MetaObjects wrote before + /// the runner kept a manifest (); reports what + /// would be removed and changes nothing. + /// /// public static Result Sweep( string genStateDir, string projectRoot, IReadOnlyList<(string Dir, string Label)> dirs, IReadOnlySet emitted, - IReadOnlySet? overwriteDirs = null) + IReadOnlySet? overwriteDirs = null, bool reportUnrecorded = false, bool dryRun = false) { var removed = new List(); var refused = new List(); var discarded = new List(); + var unrecorded = new List(); if (!HashManifest.Exists(genStateDir)) return new Result(removed, refused, discarded); + // The emitted paths compared case-insensitively (see IsUnder), whatever set the caller passed. + emitted = emitted.Select(Path.GetFullPath).ToHashSet(StringComparer.OrdinalIgnoreCase); var hashes = HashManifest.Load(genStateDir); var forget = new HashSet(StringComparer.Ordinal); var root = Path.GetFullPath(projectRoot); @@ -117,15 +165,18 @@ public static Result Sweep( var key = KeyFor(root, path)!; switch (Classify(hashes, root, path, dirRel)) { + case Verdict.Stranger when reportUnrecorded && CarriesSignature(path): + unrecorded.Add(key.Replace(Path.DirectorySeparatorChar, '/')); + break; case Verdict.Pristine: - File.Delete(path); + if (!dryRun) File.Delete(path); // Only the spelling it was recorded under: a legacy dir-relative key // is otherwise someone else's record in another directory. forget.Add(hashes.ContainsKey(key) ? key : dirRel); removed.Add(label + dirRel.Replace(Path.DirectorySeparatorChar, '/')); break; case Verdict.Edited when overwrite: - File.Delete(path); + if (!dryRun) File.Delete(path); forget.Add(hashes.ContainsKey(key) ? key : dirRel); removed.Add(label + dirRel.Replace(Path.DirectorySeparatorChar, '/')); discarded.Add(key.Replace(Path.DirectorySeparatorChar, '/')); @@ -149,13 +200,16 @@ public static Result Sweep( } } - if (forget.Count > 0) + if (forget.Count > 0 && !dryRun) { foreach (var key in forget) hashes.Remove(key); HashManifest.Save(genStateDir, hashes); } return new Result(removed, refused.Distinct().Order(StringComparer.Ordinal).ToList(), - discarded.Distinct().Order(StringComparer.Ordinal).ToList()); + discarded.Distinct().Order(StringComparer.Ordinal).ToList()) + { + Unrecorded = unrecorded.Distinct().Order(StringComparer.Ordinal).ToList(), + }; } /// The warning for edited orphans. The same wording as codegen-ts's diff --git a/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs b/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs index b060c8103c..bbcaba25e7 100644 --- a/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs +++ b/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs @@ -4,7 +4,8 @@ // 1. Type-level override — config.TypeOverrides["::"] // 2. Package-level override — config.PackageNamespaces[] // 3. Convention rule — config.Convention (strip + prepend + case + separator); when -// none is set and no flat namespace is either, DefaultConvention +// none is set, DefaultConvention (the package itself, PascalCased), +// unless a configured namespace asks for Error/Derive (rc.19 R65) // 4. Unmapped strategy fallback — config.UnmappedStrategy (Flatten | Error | Derive) // // All resolution happens via this single helper so the @provided enum resolver @@ -62,6 +63,12 @@ public static IEnumerable HomeUsings(GenConfig config, IEnumerable ns, StringComparer.Ordinal) .Select(ns => $"using {ns};"); + // rc.19 R65: with no Convention, a package's namespace IS the package, each `::` segment + // PascalCased (`acme::alpha` → `Acme.Alpha`), as Java and Kotlin map packages — whether or not + // a namespace is configured; GenConfig.Namespace then serves only package-less objects and the + // artifacts of no single package. PackageNamespaces and TypeOverrides still win. A project that + // asks for UnmappedPackageStrategy.Error or Derive under a configured namespace keeps that + // meaning: it chose to map its packages itself. private static PackageBindingConvention? EffectiveConvention(GenConfig config) => // The 1.2.0 rule: a configured namespace turns the convention off. With package namespaces // on, a packaged type takes its package's namespace even when a namespace is configured @@ -128,7 +135,7 @@ void Consider(MetaObjects.Meta.MetaObject? target) /// . /// /// The codegen config holding the convention + overrides. - /// Metadata package (e.g. acme::cases). Empty/null → fall through + /// Metadata package (e.g. acme::orders). Empty/null → fall through /// to the unmapped strategy (no overrides/convention apply to no-package). /// Optional named type within the package. When provided, enables the /// type-level override layer (typeOverrides["::"]). When null, only diff --git a/server/csharp/MetaObjects.Codegen/ReportRows.cs b/server/csharp/MetaObjects.Codegen/ReportRows.cs index 71dc443208..5212c8730a 100644 --- a/server/csharp/MetaObjects.Codegen/ReportRows.cs +++ b/server/csharp/MetaObjects.Codegen/ReportRows.cs @@ -62,6 +62,8 @@ public static class ReportRows FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + // rc.21: a @stringValueMap enum is read through its stored strings, here as everywhere. + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs index b319691b2a..9e0b11e998 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs @@ -38,12 +38,13 @@ public static class EfCoreFilterDispatch { public static IQueryable ApplyFilter( IQueryable source, - IReadOnlyList predicates) where T : class + IReadOnlyList predicates, + IReadOnlyDictionary? propertyByField = null) where T : class { if (predicates is null || predicates.Count == 0) return source; foreach (var p in predicates) { - var lambda = BuildLambda(p); + var lambda = BuildLambda(p, propertyByField); source = source.Where(lambda); } return source; @@ -59,13 +60,13 @@ public static IQueryable ApplyFilter( /// duration operand with the duration wire grammar (). /// A failed parse result is returned unchanged. /// - public static FilterParseResult Validate(FilterParseResult parsed) + public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyDictionary? propertyByField = null) { if (parsed.ErrorEnvelope is not null) return parsed; foreach (var p in parsed.Predicates) { if (p.Op is "isNull" or "like") continue; - var prop = ResolveProperty(typeof(T), p.Field); + var prop = ResolveProperty(typeof(T), p.Field, propertyByField); if (prop is null) continue; // the allowlist gate upstream guarantees a match; BuildLambda reports a miss var memberType = prop.PropertyType; var underlying = Nullable.GetUnderlyingType(memberType) ?? memberType; @@ -88,10 +89,10 @@ public static FilterParseResult Validate(FilterParseResult parsed) /// Build an Expression<Func<T, bool>> for a single predicate /// against the resolved CLR property of . /// - private static Expression> BuildLambda(FilterPredicate p) + private static Expression> BuildLambda(FilterPredicate p, IReadOnlyDictionary? propertyByField) { var x = Expression.Parameter(typeof(T), "x"); - var prop = ResolveProperty(typeof(T), p.Field); + var prop = ResolveProperty(typeof(T), p.Field, propertyByField); // The metadata field name must map to a CLR property — the allowlist gate // upstream guarantees the field exists on the entity, so a miss here is a // generator/runtime contract violation, not user input. @@ -175,10 +176,12 @@ private static Expression> BuildLambda(FilterPredicate p) /// /// Resolve the CLR property on matching the /// metadata field name. The metadata name is camelCase (e.g. "createdAt") and - /// the property is PascalCase ("CreatedAt"); match case-insensitively. + /// the property is PascalCase ("CreatedAt"); match case-insensitively. When the generated + /// allowlist carries a field-to-property map (a property-naming resolver renamed a property + /// beyond case), the mapped property name is the one looked up. /// - private static PropertyInfo? ResolveProperty(Type entityType, string fieldName) => - entityType.GetProperty(fieldName, + private static PropertyInfo? ResolveProperty(Type entityType, string fieldName, IReadOnlyDictionary? propertyByField = null) => + entityType.GetProperty(propertyByField is not null && propertyByField.TryGetValue(fieldName, out var mapped) ? mapped : fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); /// diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 4c655bce8d..954d5b6312 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -66,7 +66,7 @@ public static IResult TooLarge(int maxRows) => /// /// The JSON export with credential columns (a derived field over a view.password field) OMITTED from - /// every row; says the body is { rows, total } rather than the rows. + /// every row ( names their CLR properties); says the body is { rows, total } rather than the rows. /// public static IResult Json(HttpContext http, string segment, T body, string[] omit, bool envelope = false) { @@ -78,18 +78,12 @@ is Microsoft.Extensions.Options.IOptions p.Key).Where(k => omit.Any(x => string.Equals(x, k, StringComparison.OrdinalIgnoreCase))).ToList()) - o.Remove(key); - } - /// The CSV export: fills a UTF-8 (no BOM of the encoder's own) body. public static IResult Csv(HttpContext http, string segment, Action write) => Body(http, segment, "csv", "text/csv; charset=utf-8", write); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs b/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs new file mode 100644 index 0000000000..b080c5a08c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs @@ -0,0 +1,143 @@ +// SerializerKeys — the JSON key the host's serializer gives a CLR property, read from the +// serializer's own contract (JsonSerializerOptions.GetTypeInfo) and never re-derived from names. +// +// A generated entity property carries no [JsonPropertyName]; its key is whatever the host's +// JsonSerializerOptions make of it: a naming policy (CamelCase, SnakeCaseLower, KebabCaseLower, a +// custom one), a property-naming resolver's rename, an attribute an adopter's emit hook added, or a +// JsonTypeInfo modifier. The generated routes need that key in two places: to omit a credential from +// a response, and to find which property a PATCH or PUT body key names. Both ask here, so they +// agree with the serializer by construction under every policy. +// +// Part of the codegen runtime surface, referenced by the generated routes. + +using System.Collections; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace MetaObjects.Codegen.Runtime; + +public static class SerializerKeys +{ + /// + /// The JSON keys under which writes the CLR properties named + /// on every runtime type found in (a row, a list of + /// rows, or, with , the rows of a { rows, total } envelope). A + /// polymorphic list contributes each element's own type, so a subtype-declared property is found. + /// Fails closed: see . + /// + public static HashSet KeysOf(object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = new HashSet(StringComparer.Ordinal); + foreach (var type in RowTypes(body, envelope)) + keys.UnionWith(KeysOfType(type, options, clrNames)); + return keys; + } + + /// + /// The JSON keys writes the credential properties of under, + /// read from the serializer's contract. A type that declares none of contributes + /// nothing. For a type that does, this THROWS rather than guess when the contract cannot be read: + /// its kind is not an object (a custom converter), any property has no reflection member behind it + /// (a custom type-info resolver, a modifier that rebuilds properties, a source-generated context that does + /// not carry it), or a credential has no matching property in the contract. A response that cannot be + /// stripped is refused, never sent. The message names the type and the credential property, never a value. + /// + public static HashSet KeysOfType(Type type, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = new HashSet(StringComparer.Ordinal); + var declared = clrNames + .Where(n => type.GetProperty(n, BindingFlags.Public | BindingFlags.Instance) is { } prop && !IsIgnored(prop)) + .Distinct(StringComparer.Ordinal).ToList(); + if (declared.Count == 0) return keys; + + JsonTypeInfo info; + try { info = options.GetTypeInfo(type); } + catch (NotSupportedException e) { throw Unreadable(type, declared, "the serializer has no contract for it (" + e.GetType().Name + ")"); } + if (info.Kind != JsonTypeInfoKind.Object) + throw Unreadable(type, declared, $"its JSON contract is a {info.Kind}, not an object (a custom converter?)"); + if (info.Properties.Any(p => p.AttributeProvider is not MemberInfo)) + throw Unreadable(type, declared, "a property has no reflection member behind it (a custom type-info resolver, a modifier that rebuilds properties, or a source-generated context?)"); + foreach (var name in declared) + { + var matched = info.Properties.Where(p => ((MemberInfo)p.AttributeProvider!).Name == name).Select(p => p.Name).ToList(); + if (matched.Count == 0) throw Unreadable(type, [name], "the credential has no property in the serializer's contract"); + keys.UnionWith(matched); + } + return keys; + } + + /// + /// Check, at startup (the generated route mapping calls it), that the credential properties of + /// can be stripped under the host's configured JsonOptions. Throws as + /// does, so a host whose serializer contract cannot be read fails to start + /// instead of failing on the first response. + /// + public static void EnsureContract(IServiceProvider services, IReadOnlyCollection types, IReadOnlyCollection clrNames) + { + var options = (services.GetService(typeof(Microsoft.Extensions.Options.IOptions)) + as Microsoft.Extensions.Options.IOptions)?.Value.SerializerOptions + ?? JsonSerializerOptions.Default; + foreach (var type in types) KeysOfType(type, options, clrNames); + } + + private static bool IsIgnored(PropertyInfo prop) => + prop.GetCustomAttribute() is { Condition: System.Text.Json.Serialization.JsonIgnoreCondition.Always }; + + private static InvalidOperationException Unreadable(Type type, IEnumerable credentials, string why) => + new($"cannot strip the credential {string.Join(", ", credentials.Select(c => type.Name + "." + c))} from a response: {why}. " + + "Credential stripping reads the serializer's reflection-visible contract; the response is refused rather than sent unstripped."); + + /// + /// Remove every key in from the object, or from each object of the array, and, as a + /// second line of defence, every key that spells one of ignoring case, _ and + /// -. + /// + public static void Strip(JsonNode? node, HashSet keys, IReadOnlyCollection? names = null) + { + if (keys.Count == 0 && (names is null || names.Count == 0)) return; + var normalized = names is null ? [] : names.Select(Normalize).ToHashSet(StringComparer.Ordinal); + StripCore(node, keys, normalized); + } + + private static void StripCore(JsonNode? node, HashSet keys, HashSet normalized) + { + if (node is JsonArray a) { foreach (var e in a) StripCore(e, keys, normalized); return; } + if (node is not JsonObject o) return; + foreach (var key in o.Select(p => p.Key).Where(k => keys.Contains(k) || normalized.Contains(Normalize(k))).ToList()) o.Remove(key); + } + + private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); + + /// + /// The map from a body's JSON key (compared ignoring case, as the PATCH merge always has) to the CLR + /// property name gives that key on . + /// + public static Dictionary PropertyByKey(Type type, JsonSerializerOptions options) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + var info = options.GetTypeInfo(type); + if (info.Kind != JsonTypeInfoKind.Object) return map; + foreach (var p in info.Properties) + if (p.AttributeProvider is MemberInfo member) + map.TryAdd(p.Name, member.Name); + return map; + } + + private static IEnumerable RowTypes(object? body, bool envelope) + { + if (body is null) yield break; + object? rows = body; + if (envelope && body.GetType().GetProperty("rows") is { } rowsProp) rows = rowsProp.GetValue(body); + if (rows is null) yield break; + if (rows is IEnumerable list and not string) + { + var seen = new HashSet(); + foreach (var e in list) + if (e is not null && seen.Add(e.GetType())) yield return e.GetType(); + yield break; + } + yield return rows.GetType(); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs new file mode 100644 index 0000000000..715ef8108b --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs @@ -0,0 +1,49 @@ +// rc.21 (U9): the first @via hop from a projection's base entity already walks an +// identity.reference backwards, under the holder's collection name. An author who guesses the +// name (the reference's own name, a plural a @collectionName overrides) is now told the name the +// rule gives: the refusal lists the reverse hops onto the entity. + +using MetaObjects; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ReverseHopHintTests +{ + private static LoadResult Load(string via, string? collectionName = null) => + new MetaDataLoader(FullCoreRegistry.Compose(), strict: true).Load([new InMemoryStringSource($$""" + { "metadata.root": { "package": "acme::orders", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.int": { "name": "id" } }, { "field.int": { "name": "statusId" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } }, + { "object.entity": { "name": "OrderEvent", {{(collectionName is null ? "" : $"\"@collectionName\": \"{collectionName}\",")}} "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.int": { "name": "id" } }, { "field.int": { "name": "orderId" } }, { "field.int": { "name": "statusId" } }, + { "field.timestamp": { "name": "createdDate" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { "name": "OrderView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_case" } }, + { "field.int": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "statusId", "extends": "Order.statusId" } }, + { "field.timestamp": { "name": "statusDate", "children": [ { "origin.aggregate": { "@via": "{{via}}", "@of": "OrderEvent.createdDate", + "@agg": "min", "@filter": { "statusId": { "eq": { "field": "statusId" } } } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Order.id" } } ] } } ] } } + """, id: "cases.json")]); + + [Fact] + public void The_first_hop_walks_the_reference_backwards_under_the_collection_name() + { + Assert.Empty(Load("Order.orderEvent", collectionName: "OrderEvent").Errors); + } + + [Fact] + public void A_guessed_hop_name_is_refused_naming_the_reverse_hops() + { + var error = Assert.Single(Load("Order.histories", collectionName: "OrderEvent").Errors); + Assert.Equal(ErrorCode.ERR_INVALID_ORIGIN, error.Code); + Assert.Contains("The reverse hops from Order are: \"orderEvent\" (walks OrderEvent.orderId backwards)", error.Message); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs index 682fa9bc49..d0cf28a7b1 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs @@ -24,4 +24,50 @@ public void Nonexistent_extends_collects_ERR_UNRESOLVED_SUPER() System.IO.Path.Combine(CorpusRoot.Path, "error-extends-nonexistent", "input")); Assert.Contains(result.Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); } + + // rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the + // root inherits from an abstract base in another package. The identity is unnamed, so it is + // named "primary": `Shipment.primary` resolves through the inherited member, and + // `Shipment.id` (the identity spelled by its field) names the members it could have meant. + private static string U1Model(string target) => """ + { "metadata.root": { "package": "acme::common", "children": [ + { "object.entity": { "name": "BaseEntity", "abstract": true, "children": [ + { "field.int": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } } + """ + "\u0000" + """ + { "metadata.root": { "package": "acme::shipping", "children": [ + { "object.entity": { "name": "Shipment", "extends": "acme::common::BaseEntity", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "shipments" } }, + { "field.string": { "name": "kind" } } ] } }, + { "object.entity": { "name": "AirShipment", "extends": "Shipment", "@discriminatorValue": "Air", "children": [ + { "field.string": { "name": "key" } } ] } }, + { "object.projection": { "name": "ShipmentView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_shipments" } }, + { "field.int": { "name": "id", "extends": "Shipment.id" } }, + { "field.string": { "name": "key", "extends": "AirShipment.key" } }, + { "identity.primary": { "extends": "TARGET" } } ] } } ] } } + """.Replace("TARGET", target); + + private static LoadResult LoadU1(string target) + { + var parts = U1Model(target).Split('\u0000'); + return new MetaDataLoader(FullCoreRegistry.Compose(), strict: true).Load([new InMemoryStringSource(parts[0], id: "common.json"), new InMemoryStringSource(parts[1], id: "auth.json")]); + } + + [Fact] + public void A_dotted_extends_resolves_an_identity_the_owner_inherits() + { + var result = LoadU1("Shipment.primary"); + Assert.Empty(result.Errors); + } + + [Fact] + public void A_dotted_extends_naming_a_missing_member_lists_the_owners_members() + { + var error = Assert.Single(LoadU1("Shipment.id").Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); + Assert.Contains("'acme::shipping::Shipment' has no identity named \"id\"; its identity children are: \"primary\" (identity.primary).", error.Message); + Assert.Contains("An identity.primary declared without a name is named \"primary\".", error.Message); + // The owner was found, so the same-named-object FQN advice would be wrong. + Assert.DoesNotContain("Qualify it with its package", error.Message); + } } diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs new file mode 100644 index 0000000000..6987db82bd --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -0,0 +1,301 @@ +// rc.21 part B — the view vocabulary at load, the C# twin of the TypeScript +// rc21b-view-vocabulary.test.ts: each construct accepted where it means something and refused, +// with its code and message, where it does not. The shared conformance fixtures +// (projection-view-vocabulary-rc21 and its error-* siblings) pin the cross-port envelopes. + +using System.Text.Json; +using MetaObjects.Loader; +using MetaObjects.Source; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ViewVocabularyRc21LoaderTests +{ + private const string Entities = """ + { "object.value": { "name": "Contact", "children": [ { "field.string": { "name": "kind" } } ] } }, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, { "field.string": { "name": "zip" } }, + { "field.object": { "name": "contacts", "@objectRef": "Contact", "isArray": true, "@storage": "jsonb" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, { "field.long": { "name": "customerId" } }, + { "field.enum": { "name": "status", "@values": ["Open", "Shipped"], "@intValueMap": { "Open": 0, "Shipped": 1 } } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "field.int": { "name": "n" } }, { "field.string": { "name": "ref" } }, { "field.timestamp": { "name": "at" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { "name": "OrderEvent", "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { "name": "id" } }, { "field.long": { "name": "orderId" } }, { "field.long": { "name": "customerId" } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } } + """; + + private static string View(params string[] fields) => $$""" + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + {{string.Join(",\n", fields)}} ] } } + """; + + private static string Computed(string name, string subType, object expr) => + $$"""{ "field.{{subType}}": { "name": "{{name}}", "children": [ { "origin.computed": { "@expr": {{JsonSerializer.Serialize(expr)}} } } ] } }"""; + + private static IReadOnlyList Load(params string[] extra) + { + var json = $$"""{ "metadata.root": { "package": "acme", "children": [ {{Entities}}{{string.Concat(extra.Select(e => ",\n" + e))}} ] } }"""; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + return new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "v.json")]).Errors; + } + + private static void Refused(string code, string fragment, params string[] extra) + { + var errors = Load(extra); + Assert.True(errors.Any(e => e.Code.ToString() == code && e.Message.Contains(fragment, StringComparison.Ordinal)), + $"expected {code} containing '{fragment}', got: {string.Join(" | ", errors.Select(e => $"{e.Code}: {e.Message}"))}"); + } + + private static object F(string name) => new Dictionary { ["field"] = name }; + private static object V(object? value) => new Dictionary { ["value"] = value }; + private static object Fn(string fn, params object[] args) => new Dictionary { ["fn"] = fn, ["args"] = args }; + private static object Cast(object arg, string to) => new Dictionary { ["cast"] = arg, ["as"] = to }; + + [Fact] + public void Typed_functions_casts_paths_and_aggregate_reads_load() + { + var errors = Load(View( + Computed("a", "string", Fn("splitPart", F("customerId.zip"), V("-"), V(1))), + Computed("b", "string", Fn("concatWs", V(" "), F("ref"), F("n"))), + Computed("c", "int", Fn("length", Fn("btrim", F("ref")))), + Computed("d", "string", Cast(F("id"), "string")), + Computed("e", "int", Cast(F("status"), "int")), + """{ "field.timestamp": { "name": "last", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }""", + Computed("touched", "timestamp", Fn("greatest", F("at"), F("last"))), + """{ "field.long": { "name": "ev", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.id" } } } } } ] } }""")); + Assert.Empty(errors); + } + + [Fact] + public void An_unknown_function_a_bad_arity_and_a_wrong_argument_are_refused() + { + Refused("ERR_UNKNOWN_EXPR_NODE", "unknown expression fn 'initcap'", View(Computed("a", "string", Fn("initcap", F("ref"))))); + Refused("ERR_UNKNOWN_EXPR_NODE", "'splitPart' requires at least 3 args", View(Computed("a", "string", Fn("splitPart", F("ref"))))); + Refused("ERR_INVALID_ORIGIN", "'lower' argument 1 must be a string, got int", View(Computed("a", "string", Fn("lower", F("n"))))); + Refused("ERR_INVALID_ORIGIN", "'greatest' arguments have differing types", View(Computed("a", "int", Fn("greatest", F("n"), F("id"))))); + } + + [Fact] + public void A_cast_the_source_cannot_hold_is_refused() + { + Refused("ERR_INVALID_ORIGIN", "only an enum stored as an integer", View(Computed("a", "int", Cast(F("kind"), "int")))); + Refused("ERR_INVALID_ORIGIN", "a timestamp cannot be cast to int", View(Computed("a", "int", Cast(F("at"), "int")))); + Refused("ERR_UNKNOWN_EXPR_NODE", "requires 'as': one of", View(Computed("a", "string", Cast(F("id"), "enum")))); + } + + [Fact] + public void An_expression_over_an_aggregate_is_not_filterable() + { + Refused("ERR_BAD_ATTR_FILTER", "touched", $$""" + { "object.projection": { "name": "V", "@filter": { "touched": { "isNull": false } }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.timestamp": { "name": "last", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + {{Computed("touched", "timestamp", Fn("greatest", F("at"), F("last")))}} ] } } + """); + } + + [Fact] + public void A_path_operand_that_does_not_resolve_is_refused() + { + Refused("ERR_BAD_ATTR_FILTER", "base-row path \"customerId.nope\"", View( + """{ "field.long": { "name": "ev", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.nope" } } } } } ] } }""")); + } + + [Fact] + public void A_check_condition_refuses_the_view_only_nodes() + { + Refused("ERR_BAD_ATTR_VALUE", "uses lower, which a CHECK condition cannot hold", """ + { "object.entity": { "name": "W", "children": [ + { "source.rdb": { "@table": "w" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "a" } }, { "field.string": { "name": "b" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "validator.requiredWhen": { "name": "r", "@field": "b", "@condition": { "op": "eq", "left": { "fn": "lower", "args": [ { "field": "a" } ] }, "right": { "value": "x" } } } } ] } } + """); + } + + [Fact] + public void A_grain_needs_an_object_array_and_a_union_needs_one_shape() + { + Refused("ERR_BAD_ATTR_VALUE", "@grain \"zip\" must name a field.object array", """ + { "object.projection": { "name": "G", "@grain": "zip", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, { "field.long": { "name": "customerId", "extends": "Customer.id" } } ] } } + """); + Assert.Empty(Load(""" + { "object.projection": { "name": "G", "@grain": "contacts", "@grainOrdinal": "pos", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, { "field.long": { "name": "customerId", "extends": "Customer.id" } }, + { "field.int": { "name": "pos" } }, + { "field.string": { "name": "kind", "children": [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } } ] } } + """)); + Refused("ERR_BAD_ATTR_VALUE", "@unionAll needs @union", """ + { "object.projection": { "name": "A", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Customer.id" } } ] } }, + { "object.projection": { "name": "U", "extends": "A", "@unionAll": true, "children": [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } } + """); + } + + [Fact] + public void The_db_column_type_text_spellings_load_and_an_oversize_max_length_is_refused() + { + foreach (var t in new[] { "text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)" }) + Assert.Empty(Load($$""" + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "{{t}}" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """)); + Refused("ERR_BAD_ATTR_VALUE", "@maxLength: 10 over '@dbColumnType: character(3)'", """ + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "character(3)", "@maxLength": 10 } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """); + Refused("ERR_BAD_ATTR_VALUE", "'VARCHAR' is not a valid value", """ + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "VARCHAR" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """); + } + + // rc.21 part B: a passthrough walks a reference backwards when its holder declares a unique identity over its fields. + [Theory] + [InlineData(true, false)] + [InlineData(false, false)] + [InlineData(true, true)] + public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique, bool partial) + { + // A partial (@where) unique index is unique only over its subset: the hop stays to-many. + var where = partial ? """, "@where": "\"note\" IS NOT NULL" """ : ""; + var secondary = unique ? $$"""{ "identity.secondary": { "name": "events_order_uq", "@fields": "orderId"{{where}} } },""" : ""; + unique = unique && !partial; + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Order", "children": [ { "source.rdb": { "@table": "orders" } }, { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Receipt", "children": [ { "source.rdb": { "@table": "receipts" } }, { "field.long": { "name": "id" } }, + { "field.long": { "name": "orderId" } }, { "field.string": { "name": "note" } }, { "identity.primary": { "@fields": "id" } }, {{secondary}} + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { "name": "V", "children": [ { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.string": { "name": "note", "children": [ { "origin.passthrough": { "@from": "Receipt.note", "@via": "Order.receipts" } } ] } }, + { "identity.primary": { "name": "id", "extends": "Order.primary" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var errors = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "r.json")]).Errors; + if (unique) Assert.Empty(errors); + else Assert.Contains(errors, e => e.Code.ToString() == "ERR_ORIGIN_CARDINALITY"); + } + + // rc.21 part B fix round (I2): an extender whose view widened over a TPH base warns, unless scoped. + [Theory] + [InlineData("", true)] + [InlineData("\"@filter\": { \"kind\": \"TRUCK\" },", false)] + [InlineData("\"abstract\": true,", false)] + public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, bool warns) + { + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Truck", "extends": "Vehicle", "@discriminatorValue": "TRUCK", "children": [ { "field.string": { "name": "payloadClass" } } ] } }, + { "object.projection": { "name": "VehicleBase", "abstract": true, "children": [ + { "field.long": { "name": "vehicleId", "extends": "Vehicle.id" } }, { "identity.primary": { "name": "id", "extends": "Vehicle.primary" } } ] } }, + { "object.projection": { "name": "TruckRow", "extends": "VehicleBase", {{filter}} "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { "name": "payload", "extends": "Truck.payloadClass" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var result = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "t.json")]); + Assert.Empty(result.Errors); + var hit = result.Warnings.Where(w => w.Contains("TruckRow", StringComparison.Ordinal)).ToList(); + if (warns) + { + var w = Assert.Single(hit); + Assert.Contains("\"payload\" (Truck.payloadClass) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator \"kind\"", w); + } + else Assert.Empty(hit); + } + + // rc.21 part B fix round (I4): origin.function's declared signature is checked. + [Theory] + [InlineData("[\"id\"]", "[\"int\"]", "string", "argument 1 \"id\" is a field.long, but parameter 1 is declared int")] + [InlineData("[\"id\"]", "[\"long\"]", "int", "@returns int, but the field is field.string")] + [InlineData("[\"id\", \"zip\"]", "[\"long\"]", "string", "@params declares 1 parameter type(s) for 2 argument(s)")] + [InlineData("[\"id\", \"zip\"]", "[\"long\", \"string\"]", "string", null)] + public void Origin_function_checks_its_declared_signature(string args, string parameters, string returns, string? fragment) + { + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "C2", "children": [ { "source.rdb": { "@table": "c2" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of", "@args": {{args}}, "@params": {{parameters}}, "@returns": "{{returns}}" } } ] } } ] } }, + { "object.projection": { "name": "P2", "children": [ { "source.rdb": { "@kind": "view", "@view": "p2" } }, + { "field.long": { "name": "id", "extends": "C2.id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "C2.tier" } } ] } }, + { "identity.primary": { "name": "id", "extends": "C2.id" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var errors = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "f.json")]).Errors; + if (fragment is null) Assert.Empty(errors); + else Assert.Contains(errors, e => e.Code.ToString() == "ERR_INVALID_ORIGIN" && e.Message.Contains(fragment, StringComparison.Ordinal)); + } + + // rc.21 part B fix round (M1, M4): casts Postgres has; a union member's own @union is refused. + [Fact] + public void A_boolean_casts_only_with_int_and_a_count_parameter_takes_only_an_int() + { + Refused("ERR_INVALID_ORIGIN", "a long cannot be cast to boolean; only an int can", View(Computed("a", "boolean", Cast(F("id"), "boolean")))); + Refused("ERR_INVALID_ORIGIN", "'left' argument 2 must be an int, got long", View(Computed("a", "string", Fn("left", F("ref"), F("id"))))); + Assert.Empty(Load(View(Computed("a", "boolean", Cast(F("n"), "boolean"))))); + } + + [Fact] + public void A_union_member_with_its_own_union_is_refused() + { + Refused("ERR_BAD_ATTR_VALUE", "member \"B\" declares its own @union", """ + { "object.projection": { "name": "A", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Customer.id" } } ] } }, + { "object.projection": { "name": "B", "abstract": true, "@union": ["C"], "children": [ { "field.long": { "name": "personId", "extends": "Order.customerId" } } ] } }, + { "object.projection": { "name": "C", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Order.id" } } ] } }, + { "object.projection": { "name": "U", "extends": "A", "@union": ["B"], "children": [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } } + """); + } + // Fix round 2 (N3): a view inlines a derived field's dependencies on the same row; a cycle has no SQL. + private static string Meter(params string[] fields) => $$""" + { "object.entity": { "name": "Meter", "children": [ + { "source.rdb": { "@table": "meters" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "name": "id", "@fields": "id" } }{{string.Concat(fields.Select(f => ",\n" + f))}} ] } }, + { "object.projection": { "name": "MeterRow", "children": [ { "source.rdb": { "@kind": "view", "@view": "v_meter" } }, + { "field.long": { "name": "id", "extends": "Meter.id" } }, + { "field.long": { "name": "a", "children": [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { "name": "id", "extends": "Meter.id" } } ] } } + """; + + private static string FnField(string name, string arg) => + $$"""{ "field.long": { "name": "{{name}}", "children": [ { "origin.function": { "@function": "f_{{name}}", "@args": ["{{arg}}"], "@params": ["long"], "@returns": "long" } } ] } }"""; + + [Fact] + public void A_cycle_through_derived_function_arguments_is_refused_naming_the_path() + { + Refused("ERR_INVALID_ORIGIN", "Meter.a: a derived field depends on itself through a → b → a", Meter(FnField("a", "b"), FnField("b", "a"))); + Refused("ERR_INVALID_ORIGIN", "depends on itself through a → c → a", Meter(FnField("a", "c"), + """{ "field.long": { "name": "c", "children": [ { "origin.computed": { "@expr": { "fn": "coalesce", "args": [ { "field": "a" }, { "field": "id" } ] } } } ] } }""")); + Assert.Empty(Load(Meter(FnField("a", "b"), FnField("b", "id")))); + } + + // Fix round 3 (M3): on an entity, a computed field that reads its own name reads itself; on a + // projection that name is the base entity's field, so it is no cycle. + [Fact] + public void An_entity_computed_field_that_reads_itself_is_a_one_node_cycle() + { + Refused("ERR_INVALID_ORIGIN", "Meter.a: a derived field depends on itself through a → a", + Meter("""{ "field.long": { "name": "a", "children": [ { "origin.computed": { "@expr": { "fn": "coalesce", "args": [ { "field": "a" }, { "field": "id" } ] } } } ] } }""")); + Assert.DoesNotContain(Load(View(Computed("customerId", "long", Fn("coalesce", F("customerId"), F("id"))))), + e => e.Message.Contains("depends on itself", StringComparison.Ordinal)); + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs index ebc6f44dc9..53cedeefb9 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs @@ -47,7 +47,7 @@ internal static class ApiContractCorpusPaths public static readonly string M2mMetaJson = Path.Combine(M2mDir, "meta.json"); // FR-017 TPH polymorphic-CRUD corpus — a discriminator base (Auth) + concrete - // subtypes (Bridge/Copay/PriorAuth) sharing one `auths` table, under tph/. + // subtypes (Bridge/Coupon/Permit) sharing one `auths` table, under tph/. public static readonly string TphDir = Path.Combine(Corpus, "tph"); public static readonly string TphScenariosDir = Path.Combine(TphDir, "scenarios"); public static readonly string TphSeedFile = Path.Combine(TphDir, "seed.json"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs new file mode 100644 index 0000000000..b6e40cc3dd --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs @@ -0,0 +1,307 @@ +// ApiContractCredentialHostVariantsTest — the live proof that a credential never leaves, and a +// write-denied field is never written, whatever the host does to a property's JSON key. +// +// The generated routes serialize an entity with the host's JsonOptions. A property's key is the host's +// naming policy applied to the property name, and the property name is whatever GenConfig.PropertyNaming +// made of the field. The credential omit list and the PATCH/PUT key lookup read the serializer's own key +// (SerializerKeys), so these variants must all hold: +// 1. a property renamed beyond case, default (camelCase) host; +// 2. the same rename under JsonNamingPolicy.SnakeCaseLower; +// 3. no rename under SnakeCaseLower (the leak that predates the resolver: pinHash -> pin_hash). +// Plus a credential declared on a TPH SUBTYPE, through the polymorphic list and the per-subtype routes. +// +// A response may not carry the credential under any key; a PATCH or PUT body naming it under any +// spelling is ignored (200) and the stored column stays; a POST stores null; and a multi-word ordinary +// field IS applied by PATCH under a snake policy (the key lookup is the serializer's). + +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Codegen; +using MetaObjects.IntegrationTests.Runner; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class ApiContractCredentialHostVariantsTest +{ + // pinHash is the credential (view.password); tokenHash is @formExclude (write-denied, still returned). + // displayName is an ordinary multi-word field that PATCH must apply under every policy. + private static string AccountMeta() => File.ReadAllText(ApiContractCorpusPaths.SecretFieldsMetaJson).Replace( + "{ \"field.string\": { \"name\": \"role\"", + "{ \"field.string\": { \"name\": \"displayName\", \"@maxLength\": 100 } },\n { \"field.string\": { \"name\": \"role\""); + + private const string AccountDdl = "ALTER TABLE \"accounts\" ADD COLUMN \"displayName\" VARCHAR(100) NULL;"; + + private static string AccountSpelling(MetaField f) => f.Name switch + { + "pinHash" => "PinSecret", + "tokenHash" => "ApiToken", + "displayName" => "ShownAs", + _ => CSharpNaming.Pascal(f.Name), + }; + + public static IEnumerable Hosts() => + [ + ["rename", "camel"], + ["rename", "snake"], + ["plain", "snake"], + ]; + + private static SecretFieldsHost AccountHost(string naming, string policy) => new( + PropertyNaming: naming == "rename" ? AccountSpelling : null, + JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, + MetaJson: AccountMeta(), ExtraDdl: AccountDdl); + + // A key is a credential key iff it spells the credential (or its resolved name) ignoring case and `_`/`-`. + private static readonly string[] CredentialKeys = ["pinhash", "pinsecret", "permitsecret"]; + + // The credential VALUES seeded by the corpus and the TPH test: they may appear in no response body, under any key. + private static readonly string[] CredentialValues = ["pin-hash-1", "pin-hash-2", "permit-secret"]; + + private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); + + private static void AssertNoCredential(JsonNode? node, string where) + { + switch (node) + { + case JsonObject o: + foreach (var kv in o) + { + Assert.False(CredentialKeys.Contains(Normalize(kv.Key)), $"{where}: credential key \"{kv.Key}\" in {o.ToJsonString()}"); + AssertNoCredential(kv.Value, where); + } + break; + case JsonArray a: + foreach (var e in a) AssertNoCredential(e, where); + break; + } + } + + private static async Task<(int Status, JsonNode? Body)> SendAsync(HttpClient c, string method, string path, object? body = null) + { + var req = new HttpRequestMessage(new HttpMethod(method), path); + if (body is not null) req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + var res = await c.SendAsync(req); + var text = await res.Content.ReadAsStringAsync(); + foreach (var v in CredentialValues) + Assert.DoesNotContain(v, text); // by value: no key spelling can hide it + return ((int)res.StatusCode, string.IsNullOrEmpty(text) ? null : JsonNode.Parse(text)); + } + + private static async Task>> ReadAccountsAsync(string connString) + { + await using var c = new Npgsql.NpgsqlConnection(connString); + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = "SELECT \"id\", \"name\", \"tokenHash\", \"pinHash\", \"displayName\" FROM \"accounts\" ORDER BY \"id\""; + await using var r = await cmd.ExecuteReaderAsync(); + var rows = new List>(); + while (await r.ReadAsync()) + { + string? S(int i) => r.IsDBNull(i) ? null : Convert.ToString(r.GetValue(i)); + rows.Add(new() { ["id"] = S(0), ["name"] = S(1), ["tokenHash"] = S(2), ["pinHash"] = S(3), ["displayName"] = S(4) }); + } + return rows; + } + + // Every spelling a client could send for the denied fields: the field name, the resolved property name + // under the camel and the snake host, and their capitalized forms. + private static Dictionary ForgedBody(string name) => new() + { + ["name"] = name, + ["pinHash"] = "forged", ["tokenHash"] = "forged", ["role"] = "admin", + ["pinSecret"] = "forged", ["PinSecret"] = "forged", ["pin_secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", + ["pin_hash"] = "forged", ["token_hash"] = "forged", ["api_token"] = "forged", + }; + + [Theory] + [MemberData(nameof(Hosts))] + public async Task A_credential_is_never_returned_and_never_written_whatever_the_host_does_to_keys(string naming, string policy) + { + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await SecretFieldsGeneratedServerFactory.StartAsync(pg, AccountHost(naming, policy)); + await server.ApplySeedAsync(); + using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + + // Reads: item, list, list with count. No credential key under any spelling; the form-excluded token stays. + var item = await SendAsync(client, "GET", "/api/accounts/1"); + Assert.Equal(200, item.Status); + AssertNoCredential(item.Body, "GET item"); + Assert.Contains(item.Body!.AsObject(), kv => Normalize(kv.Key) is "tokenhash" or "apitoken"); + var list = await SendAsync(client, "GET", "/api/accounts?sort=id:asc"); + Assert.Equal(200, list.Status); + AssertNoCredential(list.Body, "GET list"); + Assert.Equal(2, list.Body!.AsArray().Count); + var counted = await SendAsync(client, "GET", "/api/accounts?withCount=1&sort=id:asc"); + Assert.Equal(200, counted.Status); + AssertNoCredential(counted.Body, "GET list withCount"); + Assert.Equal(2, counted.Body!["rows"]!.AsArray().Count); + + // Writes: PATCH and PUT with the denied fields under every spelling are ignored; the multi-word + // ordinary field is applied under the host's own key for it. + // The key a client echoes is the serializer's: the policy over the (possibly renamed) property. + var displayKey = (naming, policy) switch + { + ("rename", "snake") => "shown_as", ("rename", _) => "shownAs", + (_, "snake") => "display_name", _ => "displayName", + }; + foreach (var (method, id) in new[] { ("PATCH", 1), ("PUT", 2) }) + { + var body = ForgedBody($"{method}-probe"); + body[displayKey] = $"{method}-shown"; + var res = await SendAsync(client, method, $"/api/accounts/{id}", body); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, method); + Assert.Equal($"{method}-probe", res.Body!["name"]!.GetValue()); + } + + // Creates: the denied fields are ignored (stored null), the response carries no credential. + var created = await SendAsync(client, "POST", "/api/accounts", ForgedBody("Grace Hopper")); + Assert.Equal(201, created.Status); + AssertNoCredential(created.Body, "POST"); + + var stored = await ReadAccountsAsync(pg.ConnectionString); + Assert.Equal(3, stored.Count); + Assert.Equal("pin-hash-1", stored[0]["pinHash"]); + Assert.Equal("token-hash-1", stored[0]["tokenHash"]); + Assert.Equal("pin-hash-2", stored[1]["pinHash"]); + Assert.Equal("token-hash-2", stored[1]["tokenHash"]); + Assert.Equal("PATCH-shown", stored[0]["displayName"]); // N3: a multi-word key is applied under the policy + Assert.Equal("PUT-shown", stored[1]["displayName"]); + Assert.Null(stored[2]["pinHash"]); + Assert.Null(stored[2]["tokenHash"]); + } + + // ---- a credential declared on a TPH subtype ---- + + private static string TphMeta() => File.ReadAllText(ApiContractCorpusPaths.TphMetaJson).Replace( + "{ \"field.string\": { \"name\": \"approver\", \"@maxLength\": 80, \"@filterable\": true, \"@sortable\": true } }", + "{ \"field.string\": { \"name\": \"approver\", \"@maxLength\": 80, \"@filterable\": true, \"@sortable\": true } },\n" + + " { \"field.string\": { \"name\": \"pinHash\", \"@maxLength\": 80, \"children\": [ { \"view.password\": {} } ] } },\n" + + " { \"field.string\": { \"name\": \"permitNote\", \"@maxLength\": 80 } }"); + + private const string TphDdl = "ALTER TABLE \"auths\" ADD COLUMN \"pinHash\" VARCHAR(80) NULL;\nALTER TABLE \"auths\" ADD COLUMN \"permitNote\" VARCHAR(80) NULL;"; + + private static string TphSpelling(MetaField f) => f.Name switch + { + "pinHash" => "PermitSecret", + "permitNote" => "PermitMemo", + _ => CSharpNaming.Pascal(f.Name), + }; + + public static IEnumerable TphHosts() => + [ + ["rename", "snake"], + ["plain", "snake"], + ["rename", "camel"], + ]; + + [Theory] + [MemberData(nameof(TphHosts))] + public async Task A_subtype_credential_is_never_returned_or_written_on_the_polymorphic_and_subtype_routes(string naming, string policy) + { + await using var pg = await PostgresContainer.StartAsync(); + var host = new TphHost( + PropertyNaming: naming == "rename" ? TphSpelling : null, + JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, + MetaJson: TphMeta(), ExtraDdl: TphDdl); + await using var server = await TphGeneratedServerFactory.StartAsync(pg, host); + await server.ApplySeedAsync(); + await using (var c = new Npgsql.NpgsqlConnection(pg.ConnectionString)) + { + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = "UPDATE \"auths\" SET \"pinHash\" = 'permit-secret' WHERE \"id\" = 3"; + await cmd.ExecuteNonQueryAsync(); + } + using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + + foreach (var path in new[] { "/api/auths?sort=id:asc", "/api/auths?withCount=1&sort=id:asc", "/api/auths/permit?sort=id:asc", "/api/auths/permit?withCount=1&sort=id:asc", "/api/auths/permit/3", "/api/auths/3" }) + { + var res = await SendAsync(client, "GET", path); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, "GET " + path); + } + Assert.DoesNotContain("permit-secret", (await SendAsync(client, "GET", "/api/auths")).Body!.ToJsonString()); + + var noteKey = (naming, policy) switch + { + ("rename", "snake") => "permit_memo", ("rename", _) => "permitMemo", + (_, "snake") => "permit_note", _ => "permitNote", + }; + foreach (var method in new[] { "PATCH", "PUT" }) + { + var res = await SendAsync(client, method, "/api/auths/permit/3", new Dictionary + { + ["approver"] = $"{method}-approver", [noteKey] = $"{method}-note", + ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["PermitSecret"] = "forged", ["permit_secret"] = "forged", + }); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, method + " permit"); + Assert.Equal($"{method}-approver", res.Body!["approver"]!.GetValue()); + } + var created = await SendAsync(client, "POST", "/api/auths/permit", new Dictionary + { + ["reference"] = "REF-NEW", ["approver"] = "Dr. New", ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["permit_secret"] = "forged", + }); + Assert.Equal(201, created.Status); + AssertNoCredential(created.Body, "POST permit"); + + await using var conn = new Npgsql.NpgsqlConnection(pg.ConnectionString); + await conn.OpenAsync(); + await using var q = conn.CreateCommand(); + q.CommandText = "SELECT \"id\", \"pinHash\", \"permitNote\" FROM \"auths\" ORDER BY \"id\""; + await using var r = await q.ExecuteReaderAsync(); + var rows = new List<(long Id, string? Pin, string? Note)>(); + while (await r.ReadAsync()) rows.Add((r.GetInt64(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2))); + Assert.Equal("permit-secret", rows.Single(x => x.Id == 3).Pin); + Assert.Equal("PUT-note", rows.Single(x => x.Id == 3).Note); // a multi-word subtype field is applied under the policy + Assert.Null(rows.Single(x => x.Id > 3).Pin); + } + + // ---- a host whose serializer contract cannot be read must be refused, never leak ---- + + // Every property loses its reflection member: what a custom type-info resolver, a modifier that rebuilds + // properties, or a source-generated context that does not carry it can do. + private static void NoReflectionMembers(JsonSerializerOptions o) + { + var resolver = new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { foreach (var p in ti.Properties) p.AttributeProvider = null; }); + o.TypeInfoResolver = resolver; + } + + private static bool Refused(Exception e) + { + for (var x = e; x is not null; x = x.InnerException!) + if (x.Message.Contains("cannot strip the credential", StringComparison.Ordinal)) return true; + return false; + } + + [Fact] + public async Task A_host_whose_contract_cannot_be_read_refuses_to_start_instead_of_leaking_the_account_credential() + { + await using var pg = await PostgresContainer.StartAsync(); + var host = AccountHost("rename", "snake") with { ConfigureJson = NoReflectionMembers }; + var ex = await Assert.ThrowsAnyAsync(async () => + { + await using var server = await SecretFieldsGeneratedServerFactory.StartAsync(pg, host); + }); + Assert.True(Refused(ex), ex.ToString()); + Assert.DoesNotContain("pin-hash", ex.ToString()); + } + + [Fact] + public async Task A_host_whose_contract_cannot_be_read_refuses_to_start_instead_of_leaking_the_subtype_credential() + { + await using var pg = await PostgresContainer.StartAsync(); + var host = new TphHost(PropertyNaming: TphSpelling, JsonPolicy: JsonNamingPolicy.SnakeCaseLower, + MetaJson: TphMeta(), ExtraDdl: TphDdl, ConfigureJson: NoReflectionMembers); + var ex = await Assert.ThrowsAnyAsync(async () => + { + await using var server = await TphGeneratedServerFactory.StartAsync(pg, host); + }); + Assert.True(Refused(ex), ex.ToString()); + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedAuthorServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedAuthorServerFactory.cs index 8c3c351f1d..32e6f19b92 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedAuthorServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedAuthorServerFactory.cs @@ -101,9 +101,9 @@ bio VARCHAR(1000), } var generatedAssembly = CompileGeneratedServer(); - var dbContextType = generatedAssembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(generatedAssembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); - var routesType = generatedAssembly.GetType($"{GeneratedNamespace}.AuthorRoutes") + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(generatedAssembly, $"{GeneratedNamespace}.AuthorRoutes") ?? throw new InvalidOperationException("generated AuthorRoutes type not found"); var builder = WebApplication.CreateBuilder(); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedRoutesServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedRoutesServer.cs index ccf7db45ba..d01530fb7d 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedRoutesServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/GeneratedRoutesServer.cs @@ -78,7 +78,7 @@ public static async Task StartAsync( throw new InvalidOperationException("generated server failed to compile:\n " + string.Join("\n ", emit.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}"))); var assembly = Assembly.Load(ms.ToArray()); - var dbContextType = assembly.GetType($"{ns}.AppDbContext") ?? throw new InvalidOperationException("no AppDbContext"); + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{ns}.AppDbContext") ?? throw new InvalidOperationException("no AppDbContext"); var builder = WebApplication.CreateBuilder(); LoopbackKestrel.BindAnyPort(builder); @@ -91,7 +91,7 @@ public static async Task StartAsync( var app = builder.Build(); foreach (var name in routedNames) - assembly.GetType($"{ns}.{name}Routes")!.GetMethod($"Map{name}Routes", BindingFlags.Public | BindingFlags.Static)! + MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{ns}.{name}Routes")!.GetMethod($"Map{name}Routes", BindingFlags.Public | BindingFlags.Static)! .Invoke(null, [app, "/api"]); await app.StartAsync(); return new GeneratedRoutesServer(app, LoopbackKestrel.BoundUrl(app)); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs index 47bcb9a520..fe61423832 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs @@ -52,7 +52,7 @@ public static async Task StartAsync(PostgresContain await JsonbFixture.ProvisionSchemaAsync(pg.ConnectionString); var (assembly, routeEntities) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -69,7 +69,7 @@ public static async Task StartAsync(PostgresContain // Invoke each generated MapRoutes(app, "/api"). foreach (var entity in routeEntities) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/M2mGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/M2mGeneratedServerFactory.cs index c026b5310a..447684afde 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/M2mGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/M2mGeneratedServerFactory.cs @@ -50,7 +50,7 @@ public static async Task StartAsync(PostgresContainer await M2mFixture.ProvisionSchemaAsync(pg.ConnectionString); var (assembly, entityNames) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -64,7 +64,7 @@ public static async Task StartAsync(PostgresContainer // traversal routes are mounted by the SOURCE entity's route class (Post, Person). foreach (var entity in entityNames) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; // composite-/no-PK-only entities still emit a routes class var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/MapNullColumnGeneratedServerTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/MapNullColumnGeneratedServerTest.cs index 53ba549dbf..e1687cd916 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/MapNullColumnGeneratedServerTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/MapNullColumnGeneratedServerTest.cs @@ -220,7 +220,7 @@ private static async Task ProvisionAsync(string connString) private static async Task<(string BaseUrl, WebApplication App)> StartGeneratedServerAsync(PostgresContainer pg) { var (assembly, routeEntities) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -231,7 +231,7 @@ private static async Task ProvisionAsync(string connString) var app = builder.Build(); foreach (var entity in routeEntities) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs index be2b6b732e..deb5e74a0a 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs @@ -187,7 +187,7 @@ private static async Task ProvisionAsync(string connString) private static async Task<(string BaseUrl, WebApplication App)> StartGeneratedServerAsync(PostgresContainer pg) { var (assembly, routeEntities) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -205,7 +205,7 @@ private static async Task ProvisionAsync(string connString) var app = builder.Build(); foreach (var entity in routeEntities) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ProjectionGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ProjectionGeneratedServerFactory.cs index d80f1fe45b..804bc7ddbe 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ProjectionGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ProjectionGeneratedServerFactory.cs @@ -52,7 +52,7 @@ public static async Task StartAsync(PostgresCo await ProjectionFixture.ProvisionSchemaAsync(pg.ConnectionString); var (assembly, routedNames) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -67,7 +67,7 @@ public static async Task StartAsync(PostgresCo // coexist; only the projection's routes carry scenarios. foreach (var name in routedNames) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{name}Routes") + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{name}Routes") ?? throw new InvalidOperationException($"generated {name}Routes type not found"); var mapMethod = routesType.GetMethod($"Map{name}Routes", BindingFlags.Public | BindingFlags.Static) ?? throw new InvalidOperationException($"generated Map{name}Routes method not found"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ReportGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ReportGeneratedServerFactory.cs index e37c2d3e1a..24c1b9a066 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ReportGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ReportGeneratedServerFactory.cs @@ -81,7 +81,7 @@ private static async Task StartAsync(ScenarioEngin await ReportFixture.ProvisionSchemaAsync(connectionString, engine); var (assembly, routedNames) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -102,7 +102,7 @@ private static async Task StartAsync(ScenarioEngin // lane also proves the two coexist; only the reports' routes carry scenarios. foreach (var name in routedNames) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{name}Routes") + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{name}Routes") ?? throw new InvalidOperationException($"generated {name}Routes type not found"); var mapMethod = routesType.GetMethod($"Map{name}Routes", BindingFlags.Public | BindingFlags.Static) ?? throw new InvalidOperationException($"generated Map{name}Routes method not found"); @@ -181,13 +181,13 @@ private static (Assembly Assembly, IReadOnlyList RoutedNames) CompileGen // The emitted tree itself: a routes file for each expected name, and no file at // all for the sourceless report. foreach (var name in ExpectedRoutedNames) - if (!files.Any(f => f.Path == name + "Routes.g.cs")) + if (!files.Any(f => Path.GetFileName(f.Path) == name + "Routes.g.cs")) throw new InvalidOperationException($"no {name}Routes.g.cs was generated"); // ...and an export module for each served report (the shared writer once), none for the sourceless one. var servedReports = root.Objects().Where(o => o.IsReport() && RoutesGenerator.AppliesTo(o, root)) .Select(o => CSharpNaming.Pascal(o.Name)).ToList(); - var exportFiles = files.Where(f => f.Path.EndsWith("Export.g.cs", StringComparison.Ordinal) || f.Path == "ReportExportWriter.g.cs") - .Select(f => f.Path).OrderBy(p => p, StringComparer.Ordinal).ToList(); + var exportFiles = files.Where(f => f.Path.EndsWith("Export.g.cs", StringComparison.Ordinal) || Path.GetFileName(f.Path) == "ReportExportWriter.g.cs") + .Select(f => Path.GetFileName(f.Path)).OrderBy(p => p, StringComparer.Ordinal).ToList(); var wantExport = servedReports.Select(n => n + "Export.g.cs").Append("ReportExportWriter.g.cs") .OrderBy(p => p, StringComparer.Ordinal).ToList(); if (!exportFiles.SequenceEqual(wantExport)) @@ -205,7 +205,9 @@ private static (Assembly Assembly, IReadOnlyList RoutedNames) CompileGen var comp = CSharpCompilation.Create( "apicontract_report_generated_" + Guid.NewGuid().ToString("N"), trees, refs, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + // Item 14: a concurrent Roslyn build inside a test host that is already running the + // other api-contract servers' builds flaked; one thread per compilation is deterministic. + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, concurrentBuild: false)); using var ms = new MemoryStream(); var emit = comp.Emit(ms); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs index 7818486b16..39cd3fd606 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs @@ -17,12 +17,12 @@ internal static class SecretFieldsFixture ); """; - public static async Task ProvisionSchemaAsync(string connString) + public static async Task ProvisionSchemaAsync(string connString, string? extraDdl = null) { await using var c = new NpgsqlConnection(connString); await c.OpenAsync(); await using var cmd = c.CreateCommand(); - cmd.CommandText = SchemaDdl; + cmd.CommandText = SchemaDdl + (extraDdl is null ? "" : "\n" + extraDdl); await cmd.ExecuteNonQueryAsync(); } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs index c2ec132342..24c24e5d01 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs @@ -19,6 +19,18 @@ namespace MetaObjects.IntegrationTests.Api; +/// +/// A host variant for the secret-fields lane: how the generated property names are spelled +/// (), the host's JSON naming policy, and an optional change +/// to the corpus model (extra fields) with the DDL its table needs. +/// +internal sealed record SecretFieldsHost( + Func? PropertyNaming = null, + System.Text.Json.JsonNamingPolicy? JsonPolicy = null, + string? MetaJson = null, + string? ExtraDdl = null, + Action? ConfigureJson = null); + internal sealed class SecretFieldsGeneratedServerFactory : IAsyncDisposable { private const string GeneratedNamespace = "MetaObjects.ApiContract.SecretFieldsGenerated"; @@ -35,17 +47,23 @@ private SecretFieldsGeneratedServerFactory(PostgresContainer pg, WebApplication BaseUrl = baseUrl; } - public static async Task StartAsync(PostgresContainer pg) + public static async Task StartAsync(PostgresContainer pg, SecretFieldsHost? host = null) { - await SecretFieldsFixture.ProvisionSchemaAsync(pg.ConnectionString); + await SecretFieldsFixture.ProvisionSchemaAsync(pg.ConnectionString, host?.ExtraDdl); - var (assembly, entityNames) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var (assembly, entityNames) = CompileGeneratedServer(host); + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); LoopbackKestrel.BindAnyPort(builder); builder.Logging.ClearProviders(); + if (host is not null) + builder.Services.ConfigureHttpJsonOptions(o => + { + if (host.JsonPolicy is { } policy) o.SerializerOptions.PropertyNamingPolicy = policy; + host.ConfigureJson?.Invoke(o.SerializerOptions); + }); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); @@ -54,7 +72,7 @@ public static async Task StartAsync(Postgres // emit a routes class; only Order's secret-fields routes are exercised. foreach (var entity in entityNames) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); @@ -73,12 +91,19 @@ public async ValueTask DisposeAsync() try { await _app.DisposeAsync(); } catch { /* ignored */ } } - private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer() + private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer(SecretFieldsHost? host) { - var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.SecretFieldsMetaJson)]); + var loadResult = new MetaDataLoader().Load([host?.MetaJson is { } json + ? new InMemoryStringSource(json, id: "secret-fields-variant.json") + : new FileSource(ApiContractCorpusPaths.SecretFieldsMetaJson)]); // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; + // The host-variant credential tests post every spelling a client could forge for a denied field, + // most of which are no declared field at all. They pin credential stripping, not unknown-field + // handling (the default `api.unknownFields: reject` answers those with a 400, covered by the + // api-contract corpus), so those servers run under `drop`. + if (host is not null) loadResult.Root.Api = loadResult.Root.Api with { UnknownFields = UnknownFieldsMode.Drop }; if (loadResult.Errors.Count != 0) throw new InvalidOperationException( "secret-fields corpus metadata failed to load: " + @@ -106,6 +131,7 @@ private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGen // is the only lane that proves an Names.NAME reference // actually RESOLVES against a real EF Core compile. IncludeNames = true, + PropertyNaming = host?.PropertyNaming, }, }; diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs index 7fd05aae18..326a0815bd 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs @@ -1,8 +1,8 @@ // TphFixture — shared schema-provisioning + seed for the FR-017 TPH api-contract // lanes (reference + generated). One physical `auths` table holds every subtype; -// subtype-only columns (quantity / copayAmount / approver) are nullable. The DDL +// subtype-only columns (quantity / couponAmount / approver) are nullable. The DDL // mirrors fixtures/persistence-conformance/canonical/schema.postgres.sql's `auths` -// table (literal column naming — `copayAmount` stays camelCase under the C# literal +// table (literal column naming — `couponAmount` stays camelCase under the C# literal // strategy). The seed is tph/seed.json (rows keyed under the `auths` table name). using System.Globalization; @@ -32,7 +32,7 @@ internal static class TphFixture "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), -- FR-037 R1: the @mutability "writeOnce" column, declared on the TPH BASE so -- every subtype inherits it. @@ -40,20 +40,20 @@ internal static class TphFixture "autoCreatedAt" TIMESTAMPTZ, "autoUpdatedAt" TIMESTAMPTZ, CONSTRAINT "auths_pkey" PRIMARY KEY ("id"), - CONSTRAINT "auths_type_chk" CHECK (type IN ('Bridge', 'Copay', 'PriorAuth')) + CONSTRAINT "auths_type_chk" CHECK (type IN ('Bridge', 'Coupon', 'Permit')) ); """; private static readonly string[] Cols = - { "id", "type", "reference", "quantity", "copayAmount", "approver", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt" }; + { "id", "type", "reference", "quantity", "couponAmount", "approver", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt" }; /// Create the single `auths` table on a fresh container. - public static async Task ProvisionSchemaAsync(string connString) + public static async Task ProvisionSchemaAsync(string connString, string? extraDdl = null) { await using var c = new NpgsqlConnection(connString); await c.OpenAsync(); await using var cmd = c.CreateCommand(); - cmd.CommandText = SchemaDdl; + cmd.CommandText = SchemaDdl + (extraDdl is null ? "" : "\n" + extraDdl); await cmd.ExecuteNonQueryAsync(); } @@ -93,8 +93,8 @@ public static async Task ApplySeedAsync(string connString, string seedPath) : Cols[i] switch { "id" or "quantity" => v.GetValue(), - // copayAmount is authored as a string ("12.50") to preserve scale. - "copayAmount" => decimal.Parse(v.GetValue(), System.Globalization.CultureInfo.InvariantCulture), + // couponAmount is authored as a string ("12.50") to preserve scale. + "couponAmount" => decimal.Parse(v.GetValue(), System.Globalization.CultureInfo.InvariantCulture), // #203 / ADR-0045 — the seed writes the OLD @autoSet sentinel VERBATIM // (a direct insert, NOT a stamping create) so the seeded row keeps the // old value; the offset-less wire form is interpreted as UTC (the diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs index c7a765d6b1..7255e62820 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs @@ -1,7 +1,7 @@ // TphGeneratedServerFactory — FR-017: the C# GENERATED-server lane for TPH. // // Runs the real MetaObjects.Codegen generators (Entity + DbContext + FilterAllowlist -// + Routes) on the tph corpus model (Auth + Bridge/Copay/PriorAuth subtypes), +// + Routes) on the tph corpus model (Auth + Bridge/Coupon/Permit subtypes), // Roslyn-compiles the emitted sources in-memory, and hosts them on a real ASP.NET // Core host (Kestrel) against Testcontainers Postgres. The EMITTED AuthRoutes // (polymorphic GET + per-subtype CRUD) is the artifact under test — a failing @@ -32,6 +32,15 @@ namespace MetaObjects.IntegrationTests.Api; +/// A host variant for the TPH lane: property naming, the host JSON naming policy, a changed +/// corpus model and the DDL it needs (see ). +internal sealed record TphHost( + Func? PropertyNaming = null, + System.Text.Json.JsonNamingPolicy? JsonPolicy = null, + string? MetaJson = null, + string? ExtraDdl = null, + Action? ConfigureJson = null); + internal sealed class TphGeneratedServerFactory : IAsyncDisposable { private const string GeneratedNamespace = "MetaObjects.ApiContract.TphGenerated"; @@ -48,12 +57,12 @@ private TphGeneratedServerFactory(PostgresContainer pg, WebApplication app, stri BaseUrl = baseUrl; } - public static async Task StartAsync(PostgresContainer pg) + public static async Task StartAsync(PostgresContainer pg, TphHost? host = null) { - await TphFixture.ProvisionSchemaAsync(pg.ConnectionString); + await TphFixture.ProvisionSchemaAsync(pg.ConnectionString, host?.ExtraDdl); - var (assembly, baseRouteEntities) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var (assembly, baseRouteEntities) = CompileGeneratedServer(host); + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -62,6 +71,12 @@ public static async Task StartAsync(PostgresContainer // TPH host concern: serialize the discriminator enum as its string symbol. builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter())); + if (host is not null) + builder.Services.ConfigureHttpJsonOptions(o => + { + if (host.JsonPolicy is { } policy) o.SerializerOptions.PropertyNamingPolicy = policy; + host.ConfigureJson?.Invoke(o.SerializerOptions); + }); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); @@ -71,7 +86,7 @@ public static async Task StartAsync(PostgresContainer // Routes type, so the lookup simply skips them. foreach (var entity in baseRouteEntities) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); @@ -90,12 +105,19 @@ public async ValueTask DisposeAsync() try { await _app.DisposeAsync(); } catch { /* ignored */ } } - private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileGeneratedServer() + private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileGeneratedServer(TphHost? host) { - var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.TphMetaJson)]); + var loadResult = new MetaDataLoader().Load([host?.MetaJson is { } json + ? new InMemoryStringSource(json, id: "tph-variant.json") + : new FileSource(ApiContractCorpusPaths.TphMetaJson)]); // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; + // The host-variant credential tests post every spelling a client could forge for a denied field, + // most of which are no declared field at all. They pin credential stripping, not unknown-field + // handling (the default `api.unknownFields: reject` answers those with a 400, covered by the + // api-contract corpus), so those servers run under `drop`. + if (host is not null) loadResult.Root.Api = loadResult.Root.Api with { UnknownFields = UnknownFieldsMode.Drop }; if (loadResult.Errors.Count != 0) throw new InvalidOperationException( "tph corpus metadata failed to load: " + @@ -125,6 +147,7 @@ private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileG // is the only lane that proves an Names.NAME reference // actually RESOLVES against a real EF Core compile. IncludeNames = true, + PropertyNaming = host?.PropertyNaming, }, }; diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs index 54a3596a3e..dca01ef17b 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs @@ -11,8 +11,8 @@ // PUT /api/auths//{id} alias of PATCH // DELETE /api/auths//{id} per-subtype delete (404 cross-subtype) // -// The per-subtype segment is the discriminator value lowercased (bridge/copay/ -// priorauth). This is the contract the GENERATED lane (TphGeneratedServerFactory) +// The per-subtype segment is the discriminator value lowercased (bridge/coupon/ +// permit). This is the contract the GENERATED lane (TphGeneratedServerFactory) // must also satisfy; the corpus + assertion vocabulary are shared. using System.Globalization; @@ -33,14 +33,14 @@ internal sealed class TphReferenceServer : IAsyncDisposable // api.unknownFields: reject (the default, unchanged by this corpus): the union of the base's and every // subtype's declared fields, so a sibling subtype's column is known on another subtype's route. private static readonly HashSet DeclaredKeys = new(StringComparer.Ordinal) - { "id", "type", "reference", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", "quantity", "copayAmount", "approver" }; + { "id", "type", "reference", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", "quantity", "couponAmount", "approver" }; // segment (lowercased @discriminatorValue) → discriminator value. private static readonly Dictionary SegmentToValue = new(StringComparer.Ordinal) { ["bridge"] = "Bridge", - ["copay"] = "Copay", - ["priorauth"] = "PriorAuth", + ["coupon"] = "Coupon", + ["permit"] = "Permit", }; // Every column the `auths` table carries (base + every subtype-only column). @@ -48,12 +48,12 @@ internal sealed class TphReferenceServer : IAsyncDisposable // from this caller-settable projection, so a presented value is STRIPPED on PATCH // rather than rejected (the same treatment autoCreatedAt/autoUpdatedAt get by being // absent here). It IS written on create, explicitly, below. Do NOT add it here. - private static readonly string[] AllCols = { "id", "type", "reference", "quantity", "copayAmount", "approver" }; + private static readonly string[] AllCols = { "id", "type", "reference", "quantity", "couponAmount", "approver" }; // The subtype-only columns, by discriminator value. A create stores only its own subtype's // (1.2.x input contract: a sibling subtype's column in the body is dropped, not stored). private static readonly Dictionary SubtypeCol = new() { - ["Bridge"] = "quantity", ["Copay"] = "copayAmount", ["PriorAuth"] = "approver", + ["Bridge"] = "quantity", ["Coupon"] = "couponAmount", ["Permit"] = "approver", }; private readonly PostgresContainer _pg; @@ -131,7 +131,7 @@ private async Task DispatchAsync(HttpContext ctx) return; } - // segs[2] is either a subtype segment (bridge/copay/priorauth) or an {id}. + // segs[2] is either a subtype segment (bridge/coupon/permit) or an {id}. if (segs.Length >= 3 && SegmentToValue.TryGetValue(segs[2], out var disc)) { // Per-subtype routes. @@ -158,13 +158,13 @@ private async Task DispatchAsync(HttpContext ctx) } // FR-036 — the per-subtype CREATE validates every constraint, matching the generated // controller's Dto DataAnnotations: the @required keys (the base `reference`, the - // BridgeAuth `quantity`), the @maxLength:80 columns and copayAmount's decimal(10,2). + // BridgeAuth `quantity`), the @maxLength:80 columns and couponAmount's decimal(10,2). // Every issue is listed, not just the first. var createIssues = new List>(); if (!PresentNonNull(body, "reference")) createIssues.Add(ReferenceValidation.Required("reference")); if (disc == "Bridge" && !PresentNonNull(body, "quantity")) createIssues.Add(ReferenceValidation.Required("quantity")); AddMaxLengthIssues(body, createIssues); - AddCopayIssues(body, createIssues); + AddCouponIssues(body, createIssues); if (createIssues.Count > 0) { await SendJsonAsync(ctx, 400, ReferenceValidation.Envelope(createIssues)); @@ -194,14 +194,14 @@ private async Task DispatchAsync(HttpContext ctx) // FR-036 Program B: a present null on the @required (NOT NULL) base // `reference` column is a 400, matching the generated controller's // not-null merge guard. In the single TPH table only base-required - // columns are NOT NULL; subtype columns (quantity/copayAmount/approver) + // columns are NOT NULL; subtype columns (quantity/couponAmount/approver) // are nullable, so a present null there clears them (FR-035 tristate). // A present value exceeding @maxLength:80 (reference/approver) is a 400 too. var patchIssues = new List>(); if (body.ContainsKey("reference") && !PresentNonNull(body, "reference")) patchIssues.Add(ReferenceValidation.Required("reference")); AddMaxLengthIssues(body, patchIssues); - AddCopayIssues(body, patchIssues); + AddCouponIssues(body, patchIssues); if (patchIssues.Count > 0) { await SendJsonAsync(ctx, 400, ReferenceValidation.Envelope(patchIssues)); @@ -243,13 +243,13 @@ private async Task DispatchAsync(HttpContext ctx) }; // A per-subtype collection filters by the base's columns plus that subtype's own. Only - // CopayAuth.copayAmount is filterable among the subtype columns the corpus exercises; a + // CouponAuth.couponAmount is filterable among the subtype columns the corpus exercises; a // decimal operand is compared exactly (ADR-0019 Amendment 1, W2). private static IReadOnlyDictionary SubtypeFilterOps(string discriminator) { var ops = new Dictionary(BaseFilterOps, StringComparer.Ordinal); ops.Remove("type"); - if (discriminator == "Copay") ops["copayAmount"] = new[] { "eq", "ne", "gt", "gte", "lt", "lte", "in" }; + if (discriminator == "Coupon") ops["couponAmount"] = new[] { "eq", "ne", "gt", "gte", "lt", "lte", "in" }; return ops; } @@ -271,7 +271,7 @@ private static (List Filters, string? Error, string? Field) ParseFil string raw = query[key].ToString(); string[] values = op == "in" ? raw.Split(',') : new[] { raw }; if (field == "id" && values.Any(v => !long.TryParse(v, out _))) return (filters, "invalid_filter_value", field); - if (field == "copayAmount" && values.Any(v => !DecimalWire.TryParse(v, out _))) return (filters, "invalid_filter_value", field); + if (field == "couponAmount" && values.Any(v => !DecimalWire.TryParse(v, out _))) return (filters, "invalid_filter_value", field); filters.Add(new BaseFilter(field, op, values)); } return (filters, null, null); @@ -291,7 +291,7 @@ private static (List Filters, string? Error, string? Field) ParseFil object Bind(string v) => f.Field switch { "id" => long.Parse(v), - "copayAmount" => DecimalWire.TryParse(v, out var d) ? d : throw new FormatException(v), + "couponAmount" => DecimalWire.TryParse(v, out var d) ? d : throw new FormatException(v), _ => v, }; var names = new List(); @@ -436,7 +436,7 @@ private async Task DeleteAsync(string discriminator, long id) // -------- helpers -------- // FR-036 — the TPH @maxLength:80 string columns: `reference` (base) and `approver` - // (PriorAuth subtype). A present value exceeding 80 chars is a 400 {error:"validation"} + // (Permit subtype). A present value exceeding 80 chars is a 400 {error:"validation"} // (mirrors the generated Dto's [MaxLength(80)] + the vanilla ExceedsAuthorMaxLength // guard), rejected before the PG write (which would otherwise 500 with 22001) — on the // per-subtype create AND on a present PATCH value. @@ -456,7 +456,7 @@ private static bool PresentNonNull(JsonObject body, string key) => private static object CoerceColumn(string col, JsonNode v) => col switch { "quantity" => v.GetValue(), - "copayAmount" => ReadDecimal(v) ?? throw new FormatException("copayAmount"), + "couponAmount" => ReadDecimal(v) ?? throw new FormatException("couponAmount"), _ => v.GetValue(), }; @@ -468,18 +468,18 @@ private static bool PresentNonNull(JsonObject body, string key) => ? d : null; - // W3: copayAmount is decimal(10,2); a value the column would round or overflow is refused + // W3: couponAmount is decimal(10,2); a value the column would round or overflow is refused // rather than stored rounded. Absent or null is the caller's business, not this check's. - // ADR-0019 Amendment 1 (W3): copayAmount is decimal(10,2); a value it would round or overflow is a + // ADR-0019 Amendment 1 (W3): couponAmount is decimal(10,2); a value it would round or overflow is a // 400 validation (too_big), never stored rounded; a value that is no decimal at all is invalid_type. - private static void AddCopayIssues(JsonObject body, List> issues) + private static void AddCouponIssues(JsonObject body, List> issues) { - if (!body.TryGetPropertyValue("copayAmount", out var node) || node is null + if (!body.TryGetPropertyValue("couponAmount", out var node) || node is null || node.GetValueKind() == JsonValueKind.Null) return; if (ReadDecimal(node) is not { } d) - issues.Add(ReferenceValidation.Issue("invalid_type", "copayAmount", "copayAmount is not a decimal")); + issues.Add(ReferenceValidation.Issue("invalid_type", "couponAmount", "couponAmount is not a decimal")); else if (!DecimalWire.Fits(d, 10, 2)) - issues.Add(ReferenceValidation.Issue("too_big", "copayAmount", "copayAmount exceeds decimal(10,2)")); + issues.Add(ReferenceValidation.Issue("too_big", "couponAmount", "couponAmount exceeds decimal(10,2)")); } // Map a DB row into the wire dictionary. `type` is the discriminator value (text); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/WriteThroughGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/WriteThroughGeneratedServerFactory.cs index de4a9f03d7..0f7f82e6ee 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/WriteThroughGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/WriteThroughGeneratedServerFactory.cs @@ -49,7 +49,7 @@ public static async Task StartAsync(Postgres await WriteThroughFixture.ProvisionSchemaAsync(pg.ConnectionString); var (assembly, entityNames) = CompileGeneratedServer(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); @@ -63,7 +63,7 @@ public static async Task StartAsync(Postgres // emit a routes class; only Order's write-through routes are exercised. foreach (var entity in entityNames) { - var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + var routesType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.{entity}Routes"); if (routesType is null) continue; var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); mapMethod?.Invoke(null, new object[] { app, "/api" }); diff --git a/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs b/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs index 8a76d60fa7..f890bac36f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs @@ -32,8 +32,8 @@ public void Model_builds_without_error() var auth = model.FindEntityType(typeof(Auth)); Assert.NotNull(auth); Assert.NotNull(model.FindEntityType(typeof(BridgeAuth))); - Assert.NotNull(model.FindEntityType(typeof(CopayAuth))); - Assert.NotNull(model.FindEntityType(typeof(PriorAuthAuth))); + Assert.NotNull(model.FindEntityType(typeof(CouponAuth))); + Assert.NotNull(model.FindEntityType(typeof(PermitAuth))); Assert.Equal("auths", auth!.GetTableName()); } diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index eb882e272b..62bf5ec23a 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -169,6 +169,37 @@ public void An_entity_derived_field_is_no_column_of_the_entity() Assert.Null(patient.ClrType.GetProperty("HasConsent")); } + // ── rc.21: @stringValueMap — a member's stored string ──────────────────────────────────── + + private const string StoredStringModel = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Article", "children": [ + { "source.rdb": { "@table": "articles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["Draft", "Published"], "@default": "Draft", "@maxLength": 12, + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void A_string_value_map_enum_converts_member_and_stored_string_both_ways() + { + var gen = GeneratedEfModel.Compile(StoredStringModel, "Acme.Stored"); + using var db = gen.ModelOnlyContext(); + var status = EntityType(db, "Article").FindProperty("Status")!; + var converter = status.GetValueConverter()!; + var enumType = Nullable.GetUnderlyingType(status.ClrType) ?? status.ClrType; + var delivered = Enum.Parse(enumType, "Published"); + Assert.Equal("published", converter.ConvertToProvider(delivered)); + Assert.Equal(delivered, converter.ConvertFromProvider("published")); + Assert.Throws(() => converter.ConvertFromProvider("lost")); + Assert.Equal(12, status.GetMaxLength()); + // The column default is the member; EF writes it through the converter, as 'draft'. + Assert.Equal("draft", converter.ConvertToProvider(status.GetDefaultValue())); + } + // ── reference half: an identity.reference over a flattened value-object member ────── private const string FlattenedReferenceModel = """ @@ -206,6 +237,102 @@ public void A_reference_over_a_flattened_member_is_a_foreign_key_of_the_owned_ty Assert.Equal(DeleteBehavior.Restrict, fk.DeleteBehavior); } + // rc.21 (U6): the owned type carries a navigation to the target (an adopter's hand-written + // member here, as a partial class would add). EF's convention builds the relationship from it, + // so the reference is configured through that navigation: ONE foreign key over CountryId, no + // shadow `CountryId1`, and the declared delete behaviour on it. + private sealed class AddressWithCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? Country {{ get; set; }}"); + } + } + + [Fact] + public void A_reference_over_a_flattened_member_uses_the_owned_types_navigation() + { + var gen = GeneratedEfModel.Compile(FlattenedReferenceModel, "Acme.FlatNav", entities: new AddressWithCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fk = Assert.Single(address.GetForeignKeys(), f => f.PrincipalEntityType.ClrType.Name == "Country"); + Assert.Equal(new[] { "CountryId" }, fk.Properties.Select(p => p.Name)); + Assert.Equal("Country", fk.DependentToPrincipal?.Name); + Assert.Equal(DeleteBehavior.Restrict, fk.DeleteBehavior); + Assert.DoesNotContain(address.GetProperties(), p => p.Name.StartsWith("CountryId", StringComparison.Ordinal) && p.Name != "CountryId"); + } + + // rc.21 fix round (M6): the owned type's only navigation to the target is used whatever its name. + private sealed class AddressWithHomeCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? HomeCountry {{ get; set; }}"); + } + } + + [Fact] + public void A_reference_over_a_flattened_member_uses_the_owned_types_only_navigation_whatever_its_name() + { + var gen = GeneratedEfModel.Compile(FlattenedReferenceModel, "Acme.FlatHome", entities: new AddressWithHomeCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fk = Assert.Single(address.GetForeignKeys(), f => f.PrincipalEntityType.ClrType.Name == "Country"); + Assert.Equal(new[] { "CountryId" }, fk.Properties.Select(p => p.Name)); + Assert.Equal("HomeCountry", fk.DependentToPrincipal?.Name); + Assert.DoesNotContain(address.GetProperties(), p => p.Name is "HomeCountryId" or "CountryId1"); + } + + // rc.21 part B (N3): two references from one owned member to one target. The owned type has a + // navigation for one of them only; the other must not take it as "the sole navigation". + private const string TwoFlattenedReferencesModel = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Country", "children": [ + { "source.rdb": { "@table": "countries" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.value": { "name": "Address", "children": [ + { "field.long": { "name": "homeCountryId" } }, + { "field.long": { "name": "billingCountryId" } } + ]}}, + { "object.entity": { "name": "Plan", "children": [ + { "source.rdb": { "@table": "plans" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { "name": "homeCountryId", "@fields": "address.homeCountryId", "@references": "Country" } }, + { "identity.reference": { "name": "billingCountryId", "@fields": "address.billingCountryId", "@references": "Country" } } + ]}} + ]}} + """; + + private sealed class AddressWithBillingCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? BillingCountry {{ get; set; }}"); + } + } + + [Fact] + public void A_sole_navigation_of_another_reference_is_not_taken() + { + var gen = GeneratedEfModel.Compile(TwoFlattenedReferencesModel, "Acme.FlatTwo", entities: new AddressWithBillingCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fks = address.GetForeignKeys().Where(f => f.PrincipalEntityType.ClrType.Name == "Country").ToList(); + Assert.Equal(2, fks.Count); + var billing = Assert.Single(fks, f => f.Properties.Select(p => p.Name).SequenceEqual(new[] { "BillingCountryId" })); + Assert.Equal("BillingCountry", billing.DependentToPrincipal?.Name); + var home = Assert.Single(fks, f => f.Properties.Select(p => p.Name).SequenceEqual(new[] { "HomeCountryId" })); + Assert.Null(home.DependentToPrincipal); + Assert.DoesNotContain(address.GetProperties(), p => p.IsShadowProperty() && !p.IsPrimaryKey()); + } + [Fact] public void A_reference_carries_its_constraint_name_and_its_principal_key_into_the_model() { @@ -1220,6 +1347,17 @@ public void A_tph_subtypes_own_fields_carry_their_indexes_and_comments() Assert.Equal("The vehicle id number.", car.FindProperty("Vin")!.GetComment()); } + [Fact] + public void An_expression_index_is_an_sql_artifact() + { + // EF's HasIndex takes properties only, so an @expr index is written as SQL, applied after + // the schema EF builds (IF NOT EXISTS, so the file re-applies). + var sql = Assert.Single(new MetaObjects.Codegen.Generators.ExpressionIndexesGenerator() + .Generate(GeneratedEfModel.Context(NativeVocabularyModel, "Acme.Native"))).Content; + Assert.Contains("CREATE INDEX IF NOT EXISTS \"ix_tickets_lower_email\" ON \"tickets\" (lower(email));", sql); + Assert.DoesNotContain("ix_tickets_opened", sql); + } + // A JSON column's comment. EF 8's JsonColumn carries no comment, so the generated // model puts the text (the field's @description, else its value object's) on the owned type as // an annotation, and the generated design-time differ scaffolds it as COMMENT ON COLUMN, Up and Down. @@ -1386,7 +1524,10 @@ public async Task The_checks_the_model_declares_are_the_ones_meta_migrate_create await db.Database.EnsureCreatedAsync(); using var expected = System.Text.Json.JsonDocument.Parse(File.ReadAllText(Path.Combine(corpus, "expected.postgres.json"))); - foreach (var table in expected.RootElement.EnumerateObject()) + // The corpus's expected file covers every input model (checks, stored, tph); this test compiles + // meta.checks.json only, so it asserts the tables that model declares. + foreach (var table in expected.RootElement.EnumerateObject() + .Where(t => model.Contains($"\"@table\": \"{t.Name}\"", StringComparison.Ordinal))) { var names = table.Value.EnumerateArray().Select(c => c.GetProperty("name").GetString()!).OrderBy(n => n, StringComparer.Ordinal); var live = (await Rows(pg.ConnectionString, $""" diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs index 521532262e..c8ca738935 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs @@ -62,7 +62,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasNoKey().ToView("v_all_types_breakdown"); modelBuilder.Entity().Property(x => x.Level).HasConversion(); - modelBuilder.Entity().Property(x => x.LegacyStatus).HasConversion(v => v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT ? 0 : v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED ? 5 : v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED ? 9 : UnmappedEnumMember(v, "legacyStatus"), v => v == 0 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT : v == 5 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED : v == 9 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED : UnmappedEnumValue(v, "legacyStatus")); + modelBuilder.Entity().Property(x => x.LegacyStatus).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT ? 0 : v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED ? 5 : v == AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED ? 9 : UnmappedEnumMember(v, "legacyStatus"), v => v == 0 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT : v == 5 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED : v == 9 ? AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED : UnmappedEnumValue(v, "legacyStatus"))); modelBuilder.Entity().HasNoKey().ToView("v_asset_activity"); modelBuilder.Entity().HasNoKey().ToView("v_asset_days"); modelBuilder.Entity().HasNoKey().ToView("v_auths_by_kind"); @@ -96,7 +96,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().OwnsOne(x => x.Settings, b => b.ToJson(AllTypesNames.SettingsColumn)); modelBuilder.Entity().OwnsMany(x => x.Labels, b => b.ToJson(AllTypesNames.LabelsColumn)); modelBuilder.Entity().Property(x => x.EnumVal).HasConversion(); - modelBuilder.Entity().Property(x => x.IntEnumVal).HasConversion(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED ? 9 : UnmappedEnumMember(v, "intEnumVal"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED : UnmappedEnumValue(v, "intEnumVal")); + modelBuilder.Entity().Property(x => x.IntEnumVal).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED ? 9 : UnmappedEnumMember(v, "intEnumVal"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED : UnmappedEnumValue(v, "intEnumVal"))); modelBuilder.Entity().Property(x => x.DecVal).HasPrecision(18, 6); modelBuilder.Entity().Property(x => x.TsVal).HasColumnType("timestamp without time zone"); modelBuilder.Entity().Property(x => x.TsTzVal).HasColumnType("timestamp with time zone"); @@ -112,8 +112,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Property(x => x.ExternalId).HasColumnType("uuid").HasConversion(v => System.Guid.Parse(v!), g => g.ToString("D")); modelBuilder.Entity().Property(x => x.Payload).HasColumnType("jsonb"); modelBuilder.Entity().Property(x => x.Type).HasConversion(); - modelBuilder.Entity().HasDiscriminator(e => e.Type).HasValue(Auth.AuthType.Bridge).HasValue(Auth.AuthType.Copay).HasValue(Auth.AuthType.PriorAuth).HasValue(Auth.AuthType.Referral); - modelBuilder.Entity().Property(x => x.CopayAmount).HasPrecision(10, 2); + modelBuilder.Entity().HasDiscriminator(e => e.Type).HasValue(Auth.AuthType.Bridge).HasValue(Auth.AuthType.Coupon).HasValue(Auth.AuthType.Permit).HasValue(Auth.AuthType.Referral); + modelBuilder.Entity().Property(x => x.CouponAmount).HasPrecision(10, 2); modelBuilder.Entity().Property(x => x.Urgency).HasDefaultValue("routine").HasSentinel("routine"); modelBuilder.Entity().Property(x => x.Amount).HasPrecision(28, 10); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.FollowerId).OnDelete(DeleteBehavior.NoAction); @@ -121,7 +121,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.PersonAId).OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.PersonBId).OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.GadgetId).OnDelete(DeleteBehavior.NoAction); - modelBuilder.Entity().Property(x => x.State).HasConversion(v => v == PublishState.DRAFT ? 0 : v == PublishState.PUBLISHED ? 5 : v == PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "state"), v => v == 0 ? PublishState.DRAFT : v == 5 ? PublishState.PUBLISHED : v == 9 ? PublishState.ARCHIVED : UnmappedEnumValue(v, "state")); + modelBuilder.Entity().Property(x => x.State).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == PublishState.DRAFT ? 0 : v == PublishState.PUBLISHED ? 5 : v == PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "state"), v => v == 0 ? PublishState.DRAFT : v == 5 ? PublishState.PUBLISHED : v == 9 ? PublishState.ARCHIVED : UnmappedEnumValue(v, "state"))); modelBuilder.Entity().PrimitiveCollection(x => x.History).ElementType().HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == PublishState.DRAFT ? 0 : v == PublishState.PUBLISHED ? 5 : v == PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "history"), v => v == 0 ? PublishState.DRAFT : v == 5 ? PublishState.PUBLISHED : v == 9 ? PublishState.ARCHIVED : UnmappedEnumValue(v, "history"))); modelBuilder.Entity().Property(x => x.PreciseKg).HasPrecision(9, 4); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.ParentId).OnDelete(DeleteBehavior.NoAction); diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/Auth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/Auth.g.cs index a6f7badee4..dba8944f41 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/Auth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/Auth.g.cs @@ -10,12 +10,12 @@ namespace MetaObjects.IntegrationTests.Generated; [Table(AuthNames.SourcePrimaryTable)] [System.Text.Json.Serialization.JsonDerivedType(typeof(BridgeAuth))] -[System.Text.Json.Serialization.JsonDerivedType(typeof(CopayAuth))] -[System.Text.Json.Serialization.JsonDerivedType(typeof(PriorAuthAuth))] +[System.Text.Json.Serialization.JsonDerivedType(typeof(CouponAuth))] +[System.Text.Json.Serialization.JsonDerivedType(typeof(PermitAuth))] [System.Text.Json.Serialization.JsonDerivedType(typeof(ReferralAuth))] public abstract class Auth { - public enum AuthType { Bridge, Copay, PriorAuth, Referral } + public enum AuthType { Bridge, Coupon, Permit, Referral } [Key] [Column(AuthNames.IdColumn)] public long Id { get; set; } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AuthsByKind.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AuthsByKind.g.cs index b232b1d9eb..d15b0725af 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AuthsByKind.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AuthsByKind.g.cs @@ -10,7 +10,7 @@ namespace MetaObjects.IntegrationTests.Generated; public class AuthsByKind { - public enum AuthsByKindKind { Bridge, Copay, PriorAuth, Referral } + public enum AuthsByKindKind { Bridge, Coupon, Permit, Referral } [Column("kind")] public AuthsByKindKind? Kind { get; set; } [Column("auths")] diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuth.g.cs similarity index 73% rename from server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuth.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuth.g.cs index 48dbdcc91e..fa58f91d44 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuth.g.cs @@ -8,9 +8,9 @@ namespace MetaObjects.IntegrationTests.Generated; -public class CopayAuth : Auth +public class CouponAuth : Auth { - [Column(CopayAuthNames.CopayAmountColumn)] + [Column(CouponAuthNames.CouponAmountColumn)] [DecimalWire.Declared(10, 2)] - public decimal? CopayAmount { get; set; } + public decimal? CouponAmount { get; set; } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuthNames.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuthNames.g.cs similarity index 60% rename from server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuthNames.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuthNames.g.cs index b212c124f2..0a0f3e53fd 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/CopayAuthNames.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/CouponAuthNames.g.cs @@ -6,20 +6,20 @@ namespace MetaObjects.IntegrationTests.Generated; /// -/// GENERATED — per-object physical database names for CopayAuth (spec A1/A2/A6). +/// GENERATED — per-object physical database names for CouponAuth (spec A1/A2/A6). /// -public abstract class CopayAuthNames : AuthNames +public abstract class CouponAuthNames : AuthNames { public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "CopayAuth"; + public new const string Name = "CouponAuth"; - public const string CopayAmountField = "copayAmount"; - public const string CopayAmountColumn = "copayAmount"; + public const string CouponAmountField = "couponAmount"; + public const string CouponAmountColumn = "couponAmount"; public static new readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal) { - ["copayAmount"] = CopayAmountColumn, + ["couponAmount"] = CouponAmountColumn, ["id"] = IdColumn, ["reference"] = ReferenceColumn, ["type"] = TypeColumn, diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuth.g.cs similarity index 82% rename from server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuth.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuth.g.cs index a992da743f..6697114272 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuth.g.cs @@ -8,9 +8,9 @@ namespace MetaObjects.IntegrationTests.Generated; -public class PriorAuthAuth : Auth +public class PermitAuth : Auth { - [Column(PriorAuthAuthNames.ApproverColumn)] + [Column(PermitAuthNames.ApproverColumn)] [MaxLength(80)] public string? Approver { get; set; } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuthNames.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuthNames.g.cs similarity index 77% rename from server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuthNames.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuthNames.g.cs index f641369f01..68e0f58f89 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/PriorAuthAuthNames.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/PermitAuthNames.g.cs @@ -6,13 +6,13 @@ namespace MetaObjects.IntegrationTests.Generated; /// -/// GENERATED — per-object physical database names for PriorAuthAuth (spec A1/A2/A6). +/// GENERATED — per-object physical database names for PermitAuth (spec A1/A2/A6). /// -public abstract class PriorAuthAuthNames : AuthNames +public abstract class PermitAuthNames : AuthNames { public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "PriorAuthAuth"; + public new const string Name = "PermitAuth"; public const string ApproverField = "approver"; public const string ApproverColumn = "approver"; diff --git a/server/csharp/MetaObjects.IntegrationTests/GeneratedEfModel.cs b/server/csharp/MetaObjects.IntegrationTests/GeneratedEfModel.cs index 851c8d6806..3190a449a3 100644 --- a/server/csharp/MetaObjects.IntegrationTests/GeneratedEfModel.cs +++ b/server/csharp/MetaObjects.IntegrationTests/GeneratedEfModel.cs @@ -88,7 +88,7 @@ public static GeneratedEfModel Compile( } public Type Type(string name) => - Assembly.GetType($"{Namespace}.{name}") ?? throw new InvalidOperationException($"no generated type {name}"); + MetaObjects.IntegrationTests.GeneratedTypes.Find(Assembly, $"{Namespace}.{name}") ?? throw new InvalidOperationException($"no generated type {name}"); public DbContext NewContext(Action configure) { diff --git a/server/csharp/MetaObjects.IntegrationTests/GeneratedTypes.cs b/server/csharp/MetaObjects.IntegrationTests/GeneratedTypes.cs new file mode 100644 index 0000000000..50491bbc6d --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/GeneratedTypes.cs @@ -0,0 +1,31 @@ +// rc.19 R65: a generated type's namespace is its metadata package, so a harness can no longer +// assume every generated type is in the namespace it configured — only the package-less artifacts +// (the context) are. A harness finds a generated type by its simple name instead: the type of that +// name in the configured namespace when there is one, else the one type of that name anywhere in +// the generated assembly (two would be ambiguous, and the lookup says so). + +using System.Reflection; + +namespace MetaObjects.IntegrationTests; + +internal static class GeneratedTypes +{ + /// The generated type named 's last segment, preferring + /// itself; null when the assembly declares none. + public static Type? Find(Assembly assembly, string qualified) + { + if (assembly.GetType(qualified) is { } exact) return exact; + var name = qualified[(qualified.LastIndexOf('.') + 1)..]; + // A nested type (`Ticket+TicketSolo`): find the outer type, then its member. + if (name.IndexOf('+') is var plus and > 0) + return Find(assembly, name[..plus])?.GetNestedType(name[(plus + 1)..], BindingFlags.Public | BindingFlags.NonPublic); + var matches = assembly.GetTypes().Where(t => t.Name == name && !t.IsNested).ToList(); + return matches.Count switch + { + 0 => null, + 1 => matches[0], + _ => throw new InvalidOperationException( + $"{matches.Count} generated types are named {name}: {string.Join(", ", matches.Select(t => t.FullName))}"), + }; + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/IntBackedEnumArrayPersistenceTests.cs b/server/csharp/MetaObjects.IntegrationTests/IntBackedEnumArrayPersistenceTests.cs index 2ecc6d7828..765781075c 100644 --- a/server/csharp/MetaObjects.IntegrationTests/IntBackedEnumArrayPersistenceTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/IntBackedEnumArrayPersistenceTests.cs @@ -237,7 +237,7 @@ private static void AssertUnmappedElementThrows(Func newDb) // ── reflection plumbing over the compiled generated assembly ───────────────── private static Type Type(string name) => - Generated.Value.GetType($"{Ns}.{name}") ?? throw new InvalidOperationException($"no generated type {name}"); + MetaObjects.IntegrationTests.GeneratedTypes.Find(Generated.Value, $"{Ns}.{name}") ?? throw new InvalidOperationException($"no generated type {name}"); private static DbContext NewContext(Action configure) { diff --git a/server/csharp/MetaObjects.IntegrationTests/Issue294EfModelDeleteBehaviorTests.cs b/server/csharp/MetaObjects.IntegrationTests/Issue294EfModelDeleteBehaviorTests.cs index 754ab5bfb5..fdf63d6d56 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Issue294EfModelDeleteBehaviorTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Issue294EfModelDeleteBehaviorTests.cs @@ -137,7 +137,7 @@ private static IEntityType FindEntityType(IModel model, string shortName) => private static DbContext BuildGeneratedContext() { var assembly = CompileGenerated(); - var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var optionsBuilder = (DbContextOptionsBuilder)Activator.CreateInstance( diff --git a/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs new file mode 100644 index 0000000000..2234dffff8 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs @@ -0,0 +1,164 @@ +// ValueMappedEnumContainsPostgresTests — a parameterised `Contains` over a scalar value-mapped +// field.enum (@intValueMap or @stringValueMap), through the GENERATED entity + AppDbContext, +// compiled in memory and run against a real Postgres. +// +// The generated converter used to be the bare lambda pair handed to HasConversion(...), which EF +// types on the property's CLR type: ValueConverter for an OPTIONAL field. Npgsql EF 8 +// cannot build the JSON collection reader for a parameterised collection over that converter, so +// +// E?[] active = { E.LIVE }; +// db.Widgets.Where(w => active.Contains(w.Status)).Count(); +// +// threw: InvalidOperationException ("When building an array mapping over 'Nullable`1', the +// JsonValueReaderWriter for element mapping ... is incorrect") on the EF 8.0.10 this project pins, +// MissingMethodException on JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E] on later 8.0 +// patches. The converter is now typed on the non-nullable enum. Required fields and string-stored +// enums are covered alongside, so each shape the converter takes is queried. +// +// Postgres needs METAOBJECTS_TEST_PG_URL (a fresh database is created and dropped) or Docker: +// dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj \ +// --filter "FullyQualifiedName~ValueMappedEnumContainsPostgresTests" + +using System.Linq.Expressions; +using System.Reflection; +using MetaObjects.IntegrationTests.Runner; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using Xunit; + +namespace MetaObjects.IntegrationTests; + +public sealed class ValueMappedEnumContainsPostgresTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["DRAFT", "LIVE", "GONE"], + "@intValueMap": { "DRAFT": 0, "LIVE": 5, "GONE": 9 } } }, + { "field.enum": { "name": "grade", "@required": true, "@values": ["LOW", "HIGH"], + "@intValueMap": { "LOW": 1, "HIGH": 7 } } }, + { "field.enum": { "name": "phase", "@maxLength": 12, "@values": ["OPEN", "SHUT"], + "@stringValueMap": { "OPEN": "open_v1", "SHUT": "shut_v1" } } }, + { "field.enum": { "name": "stage", "@required": true, "@maxLength": 10, "@values": ["NEW", "OLD"], + "@stringValueMap": { "NEW": "new", "OLD": "old" } } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}} + ]}} + """; + + private const string Ddl = """ + CREATE TABLE "widgets" ( + "id" BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + "status" INTEGER, + "grade" INTEGER NOT NULL, + "phase" VARCHAR(12), + "stage" VARCHAR(10) NOT NULL + ); + """; + + private static readonly Lazy Gen = new(() => GeneratedEfModel.Compile(Model, "Acme.EnumContains")); + + private static object Member(string enumType, string member) => Gen.Value.Enum("Widget+" + enumType, member); + + private static Type EnumType(string enumType) => Gen.Value.Type("Widget+" + enumType); + + private static object Widget(string? status, string grade, string? phase, string stage) => + Gen.Value.New("Widget", + ("Status", status is null ? null : Member("WidgetStatus", status)), + ("Grade", Member("WidgetGrade", grade)), + ("Phase", phase is null ? null : Member("WidgetPhase", phase)), + ("Stage", Member("WidgetStage", stage))); + + [Fact] + public async Task Postgres_runs_a_parameterised_Contains_over_each_value_mapped_enum_shape() + { + await using var pg = await PostgresContainer.StartAsync(); + await using (var conn = new NpgsqlConnection(pg.ConnectionString)) + { + await conn.OpenAsync(); + await using var ddl = new NpgsqlCommand(Ddl, conn); + await ddl.ExecuteNonQueryAsync(); + } + + using (var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString))) + { + db.Add(Widget("DRAFT", "LOW", "OPEN", "NEW")); + db.Add(Widget("LIVE", "HIGH", "SHUT", "OLD")); + db.Add(Widget("GONE", "HIGH", "SHUT", "OLD")); + db.Add(Widget(null, "LOW", null, "NEW")); + db.SaveChanges(); + } + + // An optional value-mapped column reads NULL back as null, int-stored and string-stored alike: + // EF never hands null to the typed converter, so it is neither refused nor read as a member. + using (var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString))) + { + var rows = GeneratedEfModel.All(db, Gen.Value.Type("Widget")); + Assert.Equal(4, rows.Count); + var unset = Assert.Single(rows, r => GeneratedEfModel.Get(r, "Status") is null); + Assert.Null(GeneratedEfModel.Get(unset, "Phase")); + Assert.Equal(Member("WidgetGrade", "LOW"), GeneratedEfModel.Get(unset, "Grade")); + Assert.Equal(Member("WidgetStage", "NEW"), GeneratedEfModel.Get(unset, "Stage")); + Assert.Single(rows, r => GeneratedEfModel.Get(r, "Phase") is null); + } + + // Every shape is queried and every outcome reported together, so one failure does not hide + // whether the others hold. + var failures = new List(); + void Expect(int expected, string property, string enumType, bool nullable, params object?[] members) + { + using var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString)); + var label = $"{property} in [{string.Join(", ", members.Select(m => m?.ToString() ?? "null"))}]"; + try + { + var actual = CountIn(db, property, EnumType(enumType), nullable, members); + if (actual != expected) failures.Add($"{label}: counted {actual}, expected {expected}"); + } + catch (Exception e) + { + var inner = GeneratedEfModel.Chain(e).Last(); + failures.Add($"{label}: {inner.GetType().Name}: {inner.Message}"); + } + } + + // Optional int-stored: the repro. Two of the three non-null rows match. + Expect(2, "Status", "WidgetStatus", nullable: true, Member("WidgetStatus", "LIVE"), Member("WidgetStatus", "GONE")); + // Optional string-stored. + Expect(1, "Phase", "WidgetPhase", nullable: true, Member("WidgetPhase", "OPEN")); + // A list holding null matches the row whose column is NULL, as well as the members listed. + Expect(2, "Status", "WidgetStatus", nullable: true, null, Member("WidgetStatus", "LIVE")); + Expect(2, "Phase", "WidgetPhase", nullable: true, null, Member("WidgetPhase", "OPEN")); + // Required int-stored and string-stored. + Expect(2, "Grade", "WidgetGrade", nullable: false, Member("WidgetGrade", "HIGH")); + Expect(2, "Stage", "WidgetStage", nullable: false, Member("WidgetStage", "NEW")); + + Assert.True(failures.Count == 0, string.Join("\n", failures)); + } + + // `db.Set().Where(w => active.Contains(w.)).Count()`, with `active` a + // CAPTURED array — a query parameter, not constants inlined into the SQL — typed as the + // property is: E?[] for an optional field, E[] for a required one. A null member is a null + // element of the E?[] list. + private static int CountIn(DbContext db, string property, Type enumType, bool nullable, params object?[] members) + { + var elementType = nullable ? typeof(Nullable<>).MakeGenericType(enumType) : enumType; + var active = Array.CreateInstance(elementType, members.Length); + for (var i = 0; i < members.Length; i++) active.SetValue(members[i], i); + return (int)typeof(ValueMappedEnumContainsPostgresTests) + .GetMethod(nameof(CountInOf), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(Gen.Value.Type("Widget"), elementType) + .Invoke(null, [db, property, active])!; + } + + private static int CountInOf(DbContext db, string property, TElement[] active) + where TEntity : class + { + var w = Expression.Parameter(typeof(TEntity), "w"); + Expression> captured = () => active; + var body = Expression.Call(typeof(Enumerable), nameof(Enumerable.Contains), [typeof(TElement)], + captured.Body, Expression.Property(w, property)); + return db.Set().Where(Expression.Lambda>(body, w)).Count(); + } +} diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index d29e1028f7..1879883c09 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -39,6 +39,97 @@ public static class ExpressionGrammar public const string EXPR_CASE_OPERAND = "operand"; public const string EXPR_NOW = "now"; public const string EXPR_NOW_START_OF = "startOf"; + // rc.21 part B (U12): { cast: , as: "", dbColumnType?: "" }. + public const string EXPR_CAST = "cast"; + public const string EXPR_CAST_AS = "as"; + public const string EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType"; + + /// A function parameter's kind: a string, an integer, any scalar, or the type the "same" ones share. + private enum ParamKind { String, Int, Scalar, Same } + /// One function's signature: arity, each parameter's kind (the last repeats) and the result. + private sealed record FnSignature(int Min, int Max, ParamKind[] Params, string Result, bool Ordered = false); + + /// + /// rc.21 part B (U11, U13): the closed, typed function set beside coalesce, by name — the TS + /// EXPR_FUNCTIONS table, entry for entry. Never free SQL. + /// + private static readonly Dictionary Functions = new(StringComparer.Ordinal) + { + [EXPR_FN_COALESCE] = new(1, int.MaxValue, [ParamKind.Same], "same"), + ["greatest"] = new(1, int.MaxValue, [ParamKind.Same], "same", Ordered: true), + ["least"] = new(1, int.MaxValue, [ParamKind.Same], "same", Ordered: true), + ["nullif"] = new(2, 2, [ParamKind.Same, ParamKind.Same], "same"), + ["lower"] = new(1, 1, [ParamKind.String], "string"), + ["upper"] = new(1, 1, [ParamKind.String], "string"), + ["btrim"] = new(1, 2, [ParamKind.String, ParamKind.String], "string"), + ["splitPart"] = new(3, 3, [ParamKind.String, ParamKind.String, ParamKind.Int], "string"), + ["concat"] = new(1, int.MaxValue, [ParamKind.Scalar], "string"), + ["concatWs"] = new(2, int.MaxValue, [ParamKind.String, ParamKind.Scalar], "string"), + ["substring"] = new(2, 3, [ParamKind.String, ParamKind.Int, ParamKind.Int], "string"), + ["replace"] = new(3, 3, [ParamKind.String, ParamKind.String, ParamKind.String], "string"), + ["left"] = new(2, 2, [ParamKind.String, ParamKind.Int], "string"), + ["right"] = new(2, 2, [ParamKind.String, ParamKind.Int], "string"), + ["length"] = new(1, 1, [ParamKind.String], "int"), + }; + + /// The field subtypes a cast may name in as. + public static readonly IReadOnlyList CastTargets = + [ + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, + ]; + private static readonly HashSet NumericSubtypes = new(StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, + }; + private static readonly HashSet IntegerSubtypes = new(StringComparer.Ordinal) { FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG }; + private static readonly HashSet NonScalarSubtypes = new(StringComparer.Ordinal) { FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP }; + + /// Why a value of cannot be cast to , or null — TS castProblem. + public static string? CastProblem(string? from, string to, bool intStoredEnum) + { + if (from is null) return null; + if (NonScalarSubtypes.Contains(from)) return $"a field.{from} value cannot be cast"; + if (from == to) return null; + if (from == FIELD_SUBTYPE_ENUM) + { + if (to == FIELD_SUBTYPE_STRING) return intStoredEnum ? "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int" : null; + if (IntegerSubtypes.Contains(to)) return intStoredEnum ? null : "only an enum stored as an integer (@intValueMap) can be cast to a number"; + return $"an enum cannot be cast to {to}"; + } + if (to == FIELD_SUBTYPE_STRING) return null; + if (from == FIELD_SUBTYPE_STRING) return null; + // Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if (NumericSubtypes.Contains(to)) + { + if (from == FIELD_SUBTYPE_BOOLEAN) return to == FIELD_SUBTYPE_INT ? null : $"a boolean casts only to int, not {to}"; + return NumericSubtypes.Contains(from) ? null : $"a {from} cannot be cast to {to}"; + } + if (to == FIELD_SUBTYPE_BOOLEAN) return from == FIELD_SUBTYPE_INT ? null : $"a {from} cannot be cast to boolean; only an int can"; + if (to is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP) + return from is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP ? null : $"a {from} cannot be cast to {to}"; + return $"a {from} cannot be cast to {to}"; + } + + /// + /// The first node a CHECK condition cannot hold (case, now, cast, a function other than coalesce, + /// a path), or null — TS exprViewOnlyNode. + /// + public static string? ExprViewOnlyNode(object? node) + { + if (node is not IReadOnlyDictionary n) return null; + if (n.ContainsKey(EXPR_CAST)) return EXPR_CAST; + if (n.ContainsKey(EXPR_CASE)) return EXPR_CASE; + if (n.ContainsKey(EXPR_NOW)) return EXPR_NOW; + if (n.ContainsKey(KEY_FN) && !Equals(Get(n, KEY_FN), EXPR_FN_COALESCE)) return Str(Get(n, KEY_FN)); + if (Get(n, KEY_FIELD) is string f && f.Contains('.')) return $"the path \"{f}\""; + foreach (var key in new[] { KEY_LEFT, KEY_RIGHT, KEY_ARG }) + if (ExprViewOnlyNode(Get(n, key)) is { } hit) return hit; + if (Get(n, KEY_ARGS) is IEnumerable args) + foreach (var a in args) + if (ExprViewOnlyNode(a) is { } hit) return hit; + return null; + } // Node-kind keys (verbatim from the @expr tree — not metamodel attrs). private const string KEY_FIELD = "field"; @@ -76,11 +167,6 @@ private static readonly (string Kind, string[] Keys)[] NodeKeys = (KEY_OP, [KEY_OP, KEY_LEFT, KEY_RIGHT, KEY_ARG, KEY_ARGS]), ]; - private static readonly HashSet NumericSubtypes = new(StringComparer.Ordinal) - { - FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, - }; - /// The field names an expression tree references, in order of appearance. public static List FieldRefs(object? node) => Nodes(node).Select(n => Get(n, KEY_FIELD)).OfType().ToList(); @@ -97,6 +183,7 @@ void Walk(object? x) Walk(Get(n, KEY_RIGHT)); Walk(Get(n, KEY_ARG)); if (Get(n, KEY_ARGS) is IEnumerable args) foreach (var a in args) Walk(a); + Walk(Get(n, EXPR_CAST)); Walk(Get(n, EXPR_CASE_OPERAND)); Walk(Get(n, EXPR_CASE_ELSE)); if (Get(n, EXPR_CASE) is IEnumerable arms) @@ -178,13 +265,30 @@ public static List ValidateExprNode(object? node) return errs; } + if (n.ContainsKey(EXPR_CAST)) + { + var extra = n.Keys.Where(k => k != EXPR_CAST && k != EXPR_CAST_AS && k != EXPR_CAST_DB_COLUMN_TYPE).ToList(); + if (extra.Count > 0) + return [$"expression '{EXPR_CAST}' takes only '{EXPR_CAST_AS}' and '{EXPR_CAST_DB_COLUMN_TYPE}' beside it, not {string.Join(", ", extra)}"]; + if (Get(n, EXPR_CAST_AS) is not string to || !CastTargets.Contains(to)) + return [$"'{EXPR_CAST}' requires '{EXPR_CAST_AS}': one of {string.Join(", ", CastTargets)}"]; + if (n.ContainsKey(EXPR_CAST_DB_COLUMN_TYPE)) + { + var parsed = Get(n, EXPR_CAST_DB_COLUMN_TYPE) is string spelling ? MetaObjects.Persistence.Db.DbConstants.ParseDbColumnType(spelling) : null; + if (parsed is null || parsed.Kind is "uuid" or "jsonb" || to != FIELD_SUBTYPE_STRING) + return [$"'{EXPR_CAST}' '{EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '{EXPR_CAST_AS}: {FIELD_SUBTYPE_STRING}'"]; + } + return ValidateExprNode(Get(n, EXPR_CAST)); + } + if (n.ContainsKey(KEY_FN)) { - if (Get(n, KEY_FN) is not string fn || fn != EXPR_FN_COALESCE) + if (Get(n, KEY_FN) is not string fn || !Functions.TryGetValue(fn, out var sig)) return [$"unknown expression fn '{Str(Get(n, KEY_FN))}'"]; - return Get(n, KEY_ARGS) is IReadOnlyList args && args.Count >= 1 - ? args.SelectMany(ValidateExprNode).ToList() - : [$"'{EXPR_FN_COALESCE}' requires a non-empty args array"]; + if (Get(n, KEY_ARGS) is not IReadOnlyList args || args.Count < Math.Max(sig.Min, 1)) + return [sig.Min <= 1 ? $"'{fn}' requires a non-empty args array" : $"'{fn}' requires at least {sig.Min} args"]; + if (args.Count > sig.Max) return [$"'{fn}' takes at most {sig.Max} args, got {args.Count}"]; + return args.SelectMany(ValidateExprNode).ToList(); } if (n.ContainsKey(KEY_OP)) @@ -212,7 +316,7 @@ public static List ValidateExprNode(object? node) return [$"unknown expression op '{op}'"]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"]; } // ------------------------------------------------------------------------- @@ -229,8 +333,9 @@ public static List ValidateExprNode(object? node) /// coalesce → the unified arg subType. Also enforces per-operand op legality /// against the shared filter bands. Mirrors TS inferExprType. /// - public static InferResult InferExprType(object? node, Func resolveField) + public static InferResult InferExprType(object? node, Func resolveField, Func? isIntStoredEnum = null) { + isIntStoredEnum ??= _ => false; var structural = ValidateExprNode(node); if (structural.Count > 0) return new InferResult(null, structural); var n = (IReadOnlyDictionary)node!; @@ -255,28 +360,28 @@ public static InferResult InferExprType(object? node, Func reso { var errors = new List(); var arms = (IReadOnlyList)Get(n, EXPR_CASE)!; - InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField) : null; + InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField, isIntStoredEnum) : null; if (operand is { } o) errors.AddRange(o.Errors); var results = new List(); var resultNodes = new List(); foreach (var armObj in arms) { var arm = (IReadOnlyDictionary)armObj!; - var w = InferExprType(Get(arm, EXPR_CASE_WHEN), resolveField); + var w = InferExprType(Get(arm, EXPR_CASE_WHEN), resolveField, isIntStoredEnum); errors.AddRange(w.Errors); if (operand is null && w.Type is not null && w.Type != FIELD_SUBTYPE_BOOLEAN) errors.Add($"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.Type}"); if (operand is { Type: { } ot } && w.Type is not null && Get(arm, EXPR_CASE_WHEN) is IReadOnlyDictionary wn && !wn.ContainsKey(KEY_VALUE) && w.Type != ot) errors.Add($"a simple '{EXPR_CASE}' compares its {ot} '{EXPR_CASE_OPERAND}' with a {w.Type} '{EXPR_CASE_WHEN}'"); - var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField); + var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField, isIntStoredEnum); errors.AddRange(t.Errors); results.Add(t.Type); resultNodes.Add(Get(arm, EXPR_CASE_THEN)); } if (n.ContainsKey(EXPR_CASE_ELSE)) { - var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField); + var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField, isIntStoredEnum); errors.AddRange(e.Errors); results.Add(e.Type); resultNodes.Add(Get(n, EXPR_CASE_ELSE)); @@ -287,29 +392,56 @@ public static InferResult InferExprType(object? node, Func reso return new InferResult(unified, errors); } - if (n.ContainsKey(KEY_FN)) // coalesce + if (n.ContainsKey(EXPR_CAST)) + { + var inner = Get(n, EXPR_CAST); + var operand = InferExprType(inner, resolveField, isIntStoredEnum); + var to = (string)Get(n, EXPR_CAST_AS)!; + var fieldRef = inner is IReadOnlyDictionary innerNode ? Get(innerNode, KEY_FIELD) as string : null; + var problem = CastProblem(operand.Type, to, fieldRef is not null && isIntStoredEnum(fieldRef)); + return new InferResult(to, problem is null ? operand.Errors : [.. operand.Errors, $"'{EXPR_CAST}': {problem}"]); + } + + if (n.ContainsKey(KEY_FN)) { + var name = (string)Get(n, KEY_FN)!; + var sig = Functions[name]; var args = (IReadOnlyList)Get(n, KEY_ARGS)!; - var argResults = args.Select(a => InferExprType(a, resolveField)).ToList(); + var argResults = args.Select(a => InferExprType(a, resolveField, isIntStoredEnum)).ToList(); var errors = argResults.SelectMany(a => a.Errors).ToList(); - var (unified, differing) = UnifyTypes(args, argResults.Select(a => a.Type).ToList()); + var same = new List(); + var sameNodes = new List(); + for (var i = 0; i < argResults.Count; i++) + { + var t = argResults[i].Type; + if (t is null) continue; // a null literal fits any parameter + var kind = sig.Params[Math.Min(i, sig.Params.Length - 1)]; + if (kind == ParamKind.Same) { same.Add(t); sameNodes.Add(args[i]); } + else if (kind == ParamKind.String && t != FIELD_SUBTYPE_STRING) errors.Add($"'{name}' argument {i + 1} must be a string, got {t}"); + else if (kind == ParamKind.Int && t != FIELD_SUBTYPE_INT) errors.Add($"'{name}' argument {i + 1} must be an int, got {t}{(t == FIELD_SUBTYPE_LONG ? "; cast it ({ cast: , as: int })" : "")}"); + else if (kind == ParamKind.Scalar && NonScalarSubtypes.Contains(t)) errors.Add($"'{name}' argument {i + 1} must be a scalar, got {t}"); + } + var (unified, differing) = UnifyTypes(sameNodes, same); if (differing is not null) - errors.Add($"'{EXPR_FN_COALESCE}' arguments have differing types ({string.Join(", ", differing)})"); - return new InferResult(unified, errors); + errors.Add($"'{name}' arguments have differing types ({string.Join(", ", differing)})"); + if (sig.Ordered && unified is not null && (unified == FIELD_SUBTYPE_BOOLEAN || NonScalarSubtypes.Contains(unified))) + errors.Add($"'{name}' needs ordered arguments, got {unified}"); + var type = sig.Result == "same" ? unified : sig.Result == "int" ? FIELD_SUBTYPE_INT : FIELD_SUBTYPE_STRING; + return new InferResult(type, errors); } var op = (string)Get(n, KEY_OP)!; if (ComparisonOps.Contains(op)) { - var l = InferExprType(Get(n, KEY_LEFT), resolveField); - var r = InferExprType(Get(n, KEY_RIGHT), resolveField); + var l = InferExprType(Get(n, KEY_LEFT), resolveField, isIntStoredEnum); + var r = InferExprType(Get(n, KEY_RIGHT), resolveField, isIntStoredEnum); var errors = l.Errors.Concat(r.Errors).ToList(); if (l.Type is not null && !OpsForSubType(l.Type).Contains(op)) errors.Add($"op '{op}' is not legal for a {l.Type} operand"); return new InferResult(FIELD_SUBTYPE_BOOLEAN, errors); } if (NullOps.Contains(op)) - return new InferResult(FIELD_SUBTYPE_BOOLEAN, InferExprType(Get(n, KEY_ARG), resolveField).Errors.ToList()); + return new InferResult(FIELD_SUBTYPE_BOOLEAN, InferExprType(Get(n, KEY_ARG), resolveField, isIntStoredEnum).Errors.ToList()); if (op == EXPR_OP_NOT || VariadicLogicOps.Contains(op)) { var kids = op == EXPR_OP_NOT @@ -318,7 +450,7 @@ public static InferResult InferExprType(object? node, Func reso var errors = new List(); foreach (var k in kids) { - var kt = InferExprType(k, resolveField); + var kt = InferExprType(k, resolveField, isIntStoredEnum); errors.AddRange(kt.Errors); if (kt.Type is not null && kt.Type != FIELD_SUBTYPE_BOOLEAN) errors.Add($"op '{op}' requires boolean operands, got {kt.Type}"); diff --git a/server/csharp/MetaObjects/Core/Field/FieldConstants.cs b/server/csharp/MetaObjects/Core/Field/FieldConstants.cs index 22c891a0df..9cb274e7bb 100644 --- a/server/csharp/MetaObjects/Core/Field/FieldConstants.cs +++ b/server/csharp/MetaObjects/Core/Field/FieldConstants.cs @@ -241,6 +241,14 @@ public static class FieldConstants /// public const string FIELD_ATTR_INT_VALUE_MAP = "intValueMap"; + /// + /// field.enum (rc.21) — optional per-member stored strings ({ member: string }), the string + /// twin of , for a string-stored enum whose database spelling + /// differs from its member symbols. Keys must exactly match @values; values are unique non-empty + /// strings. Refused with @intValueMap and on an array enum. + /// + public const string FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap"; + /// /// Regex pattern each enum member symbol must satisfy: must start with /// a letter or underscore, followed by letters, digits, or underscores. diff --git a/server/csharp/MetaObjects/Core/Field/FieldSchema.cs b/server/csharp/MetaObjects/Core/Field/FieldSchema.cs index afb721f810..20ac6a1579 100644 --- a/server/csharp/MetaObjects/Core/Field/FieldSchema.cs +++ b/server/csharp/MetaObjects/Core/Field/FieldSchema.cs @@ -214,6 +214,13 @@ public static class FieldSchema Required: false, Description: "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers."); + /// rc.21 — the @stringValueMap attr — only on field.enum. Optional object of strings. + public static readonly AttrSchema StringValueMapAttr = new AttrSchema( + Name: FieldConstants.FIELD_ATTR_STRING_VALUE_MAP, + ValueType: AttrConstants.ATTR_SUBTYPE_PROPERTIES, + Required: false, + Description: "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols. Keys must exactly match @values; values must be unique non-empty strings."); + // FR-033 — the field.enum tolerant-extract overlays (@enumAlias / @enumDoc / // @coerceDefault / @normalize) and object.value's @normalize default are NO LONGER // declared here. They are re-homed to the metaobjects-prompt concern provider diff --git a/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs b/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs index cdee773888..42a4dd1d59 100644 --- a/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs +++ b/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs @@ -47,9 +47,7 @@ public static class ObjectConstants /// public const string OBJECT_ATTR_DISCRIMINATOR_VALUE = "discriminatorValue"; - /// The object's collection name (the EF Core DbSet property), in place of the plural - /// derived from its name. On - /// object.entity, object.projection and object.report. + /// The object's collection name (DbSet, REST segment, TS exports, reverse hop). public const string OBJECT_ATTR_COLLECTION_NAME = "collectionName"; /// @@ -76,6 +74,11 @@ public static class ObjectConstants /// max 1). Mirrors TS OBJECT_PROJECTION_ATTR_FILTER. /// public const string OBJECT_PROJECTION_ATTR_FILTER = "filter"; + /// rc.21 part B: a projection UNIONed with others (U15), and one with a row per array element (U14). + public const string OBJECT_PROJECTION_ATTR_UNION = "union"; + public const string OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll"; + public const string OBJECT_PROJECTION_ATTR_GRAIN = "grain"; + public const string OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal"; // ----------------------------------------------------------------------- // FR-044 — object.report attrs. Mirrors TS OBJECT_REPORT_ATTR_*. diff --git a/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs b/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs index 0aa43f1b57..4d4d7b5a51 100644 --- a/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs +++ b/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs @@ -55,9 +55,8 @@ public static class ObjectSchema ]; /// - /// @collectionName, the name of the object's collection in its own casing (the C# DbSet - /// property). Registered on object.entity, object.projection and - /// object.report (see CoreTypes); the description is single-sourced from spec/metamodel/object.json. + /// @collectionName, the name of the object's collection in its own casing (the DbSet + /// property, the REST segment, the reverse @via hop). The description is single-sourced from spec/metamodel/object.json. /// public static readonly AttrSchema CollectionNameAttr = new AttrSchema( @@ -65,7 +64,8 @@ public static class ObjectSchema ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, Description: - "The name of this object's collection, in the object's own casing: the C# DbSet property."); + "The name of this object's collection, in the object's own casing: the DbSet property, the REST " + + "collection segment, the collection exports and the reverse @via hop."); /// /// #207 — the optional row-scope @filter on an object.projection (a portable @@ -87,4 +87,20 @@ public static class ObjectSchema "returns — lowered to an outer SQL WHERE. Resolves against the " + "projection's own declared fields; an aggregate-derived field is not " + "addressable (fail-closed)."); + + /// + /// rc.21 part B — @union / @unionAll (U15) and @grain / @grainOrdinal (U14) on an + /// object.projection. Descriptions are single-sourced from spec/metamodel/object.json. + /// + public static readonly IReadOnlyList ProjectionShapeAttrs = + [ + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_UNION, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "rc.21: the view is this projection's rows UNIONed with each named projection's rows."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_UNION_ALL, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false, + Description: "rc.21: with @union, keep duplicate rows (UNION ALL)."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_GRAIN, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "rc.21: the view has one row per element of this base-entity field.object array."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "rc.21: with @grain, the projection field that holds the element's 1-based position."), + ]; } diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs index 9dc7b88c6c..2e769349de 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs @@ -55,6 +55,14 @@ public static class ValidatorConstants public const string VALIDATOR_ATTR_CONDITION = "condition"; /// A CHECK-generating validator (db provider): the database name of that CHECK. public const string VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; + /// A CHECK-generating validator or field.enum (db provider): false generates no database CHECK. Absent: true. + public const string VALIDATOR_ATTR_DB_CHECK = "dbCheck"; + + /// The cross-field validators: enforced only by their CHECK, so @dbCheck: false is refused on them. + public static readonly IReadOnlyList CROSS_FIELD_VALIDATOR_SUBTYPES_FOR_DB_CHECK = + [ + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE, VALIDATOR_SUBTYPE_EXACTLY_ONE, + ]; /// The validators meta migrate renders as a CHECK (and so may carry @constraintName): /// numeric, length, regex and the cross-field ones. required is NOT NULL; array and base have none. diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 37615de07a..d357b4b908 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -319,7 +319,7 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) // declare; its structural child graph also comes from the spec. List objectAttrs = subType switch { - OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, ObjectSchema.CollectionNameAttr], + OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, .. ObjectSchema.ProjectionShapeAttrs, ObjectSchema.CollectionNameAttr], OBJECT_SUBTYPE_REPORT => [.. ObjectSchema.ObjectAttrs, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr], OBJECT_SUBTYPE_ENTITY => [.. ObjectSchema.ObjectAttrs, ObjectSchema.CollectionNameAttr], _ => ObjectSchema.ObjectAttrs.ToList(), @@ -368,7 +368,7 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) // tolerant-extract overlays (@enumAlias / @enumDoc / @coerceDefault / // @normalize) are re-homed to the metaobjects-prompt concern provider // (reads prompt.json's field.enum extends). - FIELD_SUBTYPE_ENUM => [.. FieldSchema.CommonFieldAttrs, FieldSchema.EnumValuesAttr, FieldSchema.ProvidedAttr, FieldSchema.IntValueMapAttr], + FIELD_SUBTYPE_ENUM => [.. FieldSchema.CommonFieldAttrs, FieldSchema.EnumValuesAttr, FieldSchema.ProvidedAttr, FieldSchema.IntValueMapAttr, FieldSchema.StringValueMapAttr], _ => FieldSchema.CommonFieldAttrs.ToList(), }; diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 02f6de2b9a..728d590f3d 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -311,6 +311,10 @@ public enum ErrorCode ERR_SEQUENCE_WITHOUT_INCREMENT, // identity.primary @sequenceStart below 1, or past what its key field can hold. ERR_SEQUENCE_START_OUT_OF_RANGE, + // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + // A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. + ERR_CROSS_FIELD_WITHOUT_CHECK, } /// diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 7b6d852fc7..0192498084 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -473,7 +473,7 @@ public LoadResult Load(IReadOnlyList sources) continue; } errors.Add(new MetaError( - $"the SuperClass '{failure.Ref}' does not exist (referenced by {failure.NodeFqn}){NamingRefs.DidYouMeanSuperHint(root, failure.Ref)}", + $"the SuperClass '{failure.Ref}' does not exist (referenced by {failure.NodeFqn}){failure.MemberHint ?? NamingRefs.DidYouMeanSuperHint(root, failure.Ref)}", ErrorCode.ERR_UNRESOLVED_SUPER, Envelope: envelope)); } @@ -492,6 +492,8 @@ public LoadResult Load(IReadOnlyList sources) // Pass 4: filterable-without-index drift warning warnings.AddRange(ValidationPasses.ValidateFilterableHasIndex(root)); + // rc.21 part B (I2): an extender whose view widened with the identity-anchor rule. + warnings.AddRange(ValidationPasses.ValidateExtenderSubtypeScope(root)); // Pass 4b: @filterable on a subtype with no operator band, or an array → error (SP-H Unit9 / #335) errors.AddRange(ValidationPasses.ValidateFilterableHasSupportedOps(root)); @@ -527,6 +529,10 @@ public LoadResult Load(IReadOnlyList sources) // aggregate-derived field-ref fails closed with ERR_BAD_ATTR_FILTER. errors.AddRange(ValidationPasses.ValidateProjectionFilter(root)); errors.AddRange(ValidationPasses.ValidateOriginSegmentsAndCorrelation(root)); + // rc.21 part B — @union shapes and @grain projections. + errors.AddRange(ValidationPasses.ValidateProjectionUnionAndGrain(root)); + // rc.21 part B fix round 2 (N3): a derived field that depends on itself has no SQL. + errors.AddRange(ValidationPasses.ValidateDerivedCycles(root)); // Pass 7c (FR-044): reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). @@ -541,6 +547,7 @@ public LoadResult Load(IReadOnlyList sources) errors.AddRange(ValidationPasses.ValidateEnumMaxLength(root)); errors.AddRange(ValidationPasses.ValidateIdentitySequence(root)); errors.AddRange(ValidationPasses.ValidateCrossFieldValidators(root, _strict)); + errors.AddRange(ValidationPasses.ValidateDbCheck(root)); // Pass 9: template @payloadRef / @requiredSlots resolution errors.AddRange(ValidationPasses.ValidateTemplatePayloadRefs(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 7d720f0d58..608bc0ff38 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -513,6 +513,29 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) } var fromTarget = ValidateFromPath(from, root, obj, field.Name, errors, "origin.passthrough.@from", origin.Source); + // rc.21 part B (U14): on a @grain projection, a @from on the grain field's value + // object reads a member of the array element; there is no path to walk. + if (fromTarget is ResolvedFromTarget gt && GrainValueObject(obj, root) is { } grainVo + && ReferenceEquals(gt.Entity, grainVo)) + { + bool gconvert = origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_CONVERT) is true; + CheckPassthroughType(field, gt.Field, from, gconvert, obj, origin.Source, errors); + if ((gt.Field is MetaField gmf && gmf.ResolvedIsArray()) || gt.Field.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" is not a scalar member of the @grain element.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) is not null) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" reads the @grain element, which takes no @via.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + // fix round M2: a value-mapped enum member is held in the document as its symbol. + if (gt.Field.SubType == FIELD_SUBTYPE_ENUM && (gt.Field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null || gt.Field.Attr(FIELD_ATTR_STRING_VALUE_MAP) is not null)) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" is an enum with a value map, but a @grain element holds the member's symbol; " + + "read it as a field.string, or drop the map on the value object's member.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + continue; + } // FR-024 B6 — extends/origin agreement (host-agnostic; runs // whether @via is explicit, inferred, or a base-relation column). if (fromTarget is ResolvedFromTarget ft1) @@ -781,23 +804,34 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) // Type inference against the base entity's EFFECTIVE fields (ADR-0039). var computedBase = DeriveBaseEntity(obj, root, field.Name, src, errors); if (computedBase is null) continue; - // A ref names one of the projection's own fields + // rc.19 computed-over-joined: a ref names one of the projection's own fields // first (a passthrough, an origin.first, another computed — never itself, never // an aggregate), else a base field. + // rc.21 part B: also a scalar origin.aggregate (U13, read on the grouped row) and, + // on a projection, a PATH of to-one hops from the base (U3). Never a collect. + Func fieldNode = name => + { + if (!ReferenceEquals(obj, computedBase) && name != field.Name + && obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name) is { } own) + return own; + var baseField = computedBase!.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name); + if (baseField is not null || ReferenceEquals(obj, computedBase) || !name.Contains('.')) return baseField; + return computedBase is MetaObject bo ? FilterPaths.Resolve(bo, name, out _)?.Field : null; + }; // ADR-0039: own — origin.* never inherits (ADR-0029), so a field's origin is declared on it. Func ownOriginOf = name => obj.Children() .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.OwnChildren() .FirstOrDefault(c => c.Type == TYPE_ORIGIN); Func resolveField = name => { - if (!ReferenceEquals(obj, computedBase) && name != field.Name - && obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name) is { } own) - { - return ownOriginOf(name)?.SubType == ORIGIN_SUBTYPE_AGGREGATE ? null : own.SubType; - } - return computedBase!.Children() - .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.SubType; + if (fieldNode(name) is not { } node) return null; + var nodeOrigin = node.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + if (!ReferenceEquals(node, field) && nodeOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE + && nodeOrigin.OwnAttr(ORIGIN_AGGREGATE_ATTR_AGG) as string == AGG_COLLECT) return null; + return node.SubType; }; + Func isIntStoredEnum = name => + fieldNode(name) is { } node && node.SubType == FIELD_SUBTYPE_ENUM && node.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null; // A sibling computed ref is inlined by the view, so the refs must not lead back here. // ADR-0039: own — origin.* never inherits (ADR-0029), so @expr is declared on the origin. Func> computedRefs = name => ownOriginOf(name) is { SubType: ORIGIN_SUBTYPE_COMPUTED } o @@ -818,15 +852,11 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) HashSet reached = !ReferenceEquals(obj, computedBase) ? reach(field.Name) : []; if (reached.Contains(field.Name)) { - // One error per cycle, on its first-declared member. - var first = obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && reached.Contains(f.Name) && reach(f.Name).Contains(field.Name)); - if (first?.Name == field.Name) - errors.Add(new MetaError( - $"origin.computed on {obj.Name}.{field.Name}: @expr refers back to this field through other computed fields; a view cannot inline a cycle.", - ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + // The cycle itself is refused, once per cycle, by ValidateDerivedCycles; here the + // field is only skipped, since its type cannot be inferred through the cycle. continue; } - var inferred = ExpressionGrammar.InferExprType(expr, resolveField); + var inferred = ExpressionGrammar.InferExprType(expr, resolveField, isIntStoredEnum); if (inferred.Errors.Count > 0) { foreach (var m in inferred.Errors) @@ -859,6 +889,10 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) $"origin.computed on {obj.Name}.{field.Name}: @expr infers field.{inferred.Type} but the field is declared field.{field.SubType} — a computed column's type is derived from its expression and must match (no @convert escape).", ErrorCode.ERR_COMPUTED_TYPE_MISMATCH, Envelope: src)); } + else if (origin.SubType == ORIGIN_SUBTYPE_FUNCTION) + { + ValidateFunctionOrigin(origin, obj, field, root, errors); + } else if (origin.SubType == ORIGIN_SUBTYPE_FIRST) { // #195 — pick one related row by @orderBy along @via, project @of. @@ -1267,7 +1301,8 @@ private static bool IsReferenceHop(MetaData hop) errors.Add(new MetaError( $"origin.@via \"{viaAttr}\" on {projectionName}.{fieldName}: " + $"no such relationship or reference \"{relName}\" on {currentObj.Name}. " + - $"Deepest valid prefix was \"{prefix}\".", + $"Deepest valid prefix was \"{prefix}\"." + + (currentObj is MetaObject from && root is MetaRoot all ? ReverseReferenceHops.Hint(from, all.Objects()) : ""), ErrorCode.ERR_INVALID_ORIGIN, Envelope: ResolvedSource.From(originSource, referrer, viaAttr))); return null; @@ -1319,13 +1354,46 @@ private static bool IsReferenceHop(MetaData hop) /// A hop's effective @cardinality, or null when not declared. A reference hop /// (a forward FK) is inherently to-one — a child names the parent it points at. - private static string? HopCardinality(MetaData rel, IReadOnlyDictionary? reverse = null) + private static string? HopCardinality(MetaData rel, IReadOnlyDictionary? reverse = null, bool uniqueReverseIsOne = false) => reverse is not null && reverse.ContainsKey(rel) - ? CARDINALITY_MANY // A reference walked backwards reaches every row that references the walked-from one + // R-walk: a reference walked backwards reaches every row that references the walked-from one — + // unless (rc.21 part B) its holder declares a unique identity over exactly its fields. + // (only a passthrough asks: an aggregate over such a hop stays legal, as it was). + ? (uniqueReverseIsOne && ReverseHopIsUnique(rel) ? CARDINALITY_ONE : CARDINALITY_MANY) : IsReferenceHop(rel) ? CARDINALITY_ONE : rel.Attr(RELATIONSHIP_ATTR_CARDINALITY) as string; + /// The field names an identity or reference declares (@fields), sorted. + private static string IdentityFieldSet(MetaData node) + { + var raw = node.Attr(IDENTITY_ATTR_FIELDS); + IEnumerable list = raw switch + { + IReadOnlyList l => l.Select(x => x?.ToString() ?? ""), + string s => s.Split(','), + _ => [], + }; + return string.Join(",", list.Select(f => f.Trim()).Where(f => f.Length > 0).OrderBy(f => f, StringComparer.Ordinal)); + } + + /// + /// rc.21 part B: whether a reference walked backwards reaches at most one row — its holder declares + /// (resolving) an identity.primary or identity.secondary over exactly the reference's fields. TS + /// _reverseHopIsUnique. + /// + private static bool ReverseHopIsUnique(MetaData rel) + { + if (rel.Parent is not { } holder) return false; + var fields = IdentityFieldSet(rel); + if (fields.Length == 0) return false; + // A partial (@where) or expression (@expr) unique index never makes the hop to-one. + return holder.Children().Any(c => c.Type == TYPE_IDENTITY + && (c.SubType == IDENTITY_SUBTYPE_PRIMARY || c.SubType == IDENTITY_SUBTYPE_SECONDARY) + && c.Attr(IDENTITY_ATTR_WHERE) is null && c.Attr(IDENTITY_ATTR_EXPR) is null + && IdentityFieldSet(c) == fields); + } + /// FR-024: the entity NAMED by a node's dotted extends ref — the OWNER part /// of `....` resolved as an object. Differs from /// SuperData.Parent when the resolved child is INHERITED. @@ -1346,6 +1414,61 @@ private static bool IsReferenceHop(MetaData hop) /// Derive the BASE entity a no-`@via` origin path anchors at (spec §5). /// Returns null when no base is derivable (an error has been pushed). + /// + /// rc.21 part B (I2): warn when an extender's view WIDENED with the identity-anchor rule — no identity + /// of its own, a super anchored on a TPH base, a field bound to a column only a subtype carries, and no + /// discriminator filter. TS validateExtenderSubtypeScope, message for message. + /// + public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) + { + var warnings = new List(); + // ADR-0039: effective children, the nodes TS iterates (fix round 2, N4). + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + { + // An abstract extender emits no view, so nothing it declares widened one. + if (obj.IsAbstract) continue; + if (obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY)) continue; + if (obj.SuperData is not { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } sup || !AnchorsByIdentity(sup)) continue; + if (DeriveBaseEntity(obj, root, "@extends", obj.Source, new List()) is not { } baseEntity) continue; + string? discriminator = null; + for (var cur = baseEntity; cur is { Type: TYPE_OBJECT }; cur = cur.SuperData) + if (cur.OwnAttr(OBJECT_ATTR_DISCRIMINATOR) is string d) { discriminator = d; break; } + if (discriminator is null) continue; + if (ProjectionFilters.Effective(obj) is IReadOnlyDictionary filter && FilterKeys(filter).Contains(discriminator)) continue; + var pkg = NamingRefs.EffectivePackage(obj); + // Only the extender's OWN fields chose its base before rc.21, so only they can have widened it. + var subtypeFields = new List(); + MetaData? subtype = null; + foreach (var f in obj.OwnChildren().Where(c => c.Type == TYPE_FIELD)) + { + var owner = RefNamedOwner(f, root, pkg); + if (owner is null || ReferenceEquals(owner, baseEntity)) continue; + 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( + $"object.projection {obj.Name}: {string.Join(", ", subtypeFields)} read columns only a subtype carries, over the TPH base " + + $"{baseEntity.Name} with no @filter on its discriminator \"{discriminator}\", so the view returns every {baseEntity.Name} row " + + "(rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped " + + $"view, add @filter {{ {discriminator}: }} or declare identity.primary {{ extends: {subtype.Name}.primary }}."); + } + return warnings.AsReadOnly(); + } + + /// rc.21 part B: whether a projection (or one it extends) anchors its base with an extended identity. + private static bool AnchorsByIdentity(MetaData obj) + { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY && c.SuperData is { Type: TYPE_IDENTITY })) return true; + return obj.SuperData is { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } sup && AnchorsByIdentity(sup); + } + private static MetaData? DeriveBaseEntity( MetaData obj, MetaData root, string fieldName, ErrorSource originSource, List errors) { @@ -1367,6 +1490,13 @@ private static bool IsReferenceHop(MetaData hop) } } + // 1b) rc.21 part B (G13): an extender with no identity of its own keeps the identity its super + // anchors with, so its own fields (a TPH subtype's columns, say) do not move the base. + if (!obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY) + && obj.SuperData is { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } anchoredSuper + && AnchorsByIdentity(anchoredSuper)) + return DeriveBaseEntity(anchoredSuper, root, fieldName, originSource, errors); + // 2) Fallback: the single distinct entity targeted by plain field-extends — // preferring the ref-named owner over the physical declaring ancestor. var targets = new HashSet(); @@ -1459,7 +1589,7 @@ private static void CheckPassthroughCardinality( { foreach (var rel in hops) { - if (HopCardinality(rel, reverse) == CARDINALITY_MANY) + if (HopCardinality(rel, reverse, uniqueReverseIsOne: true) == CARDINALITY_MANY) { errors.Add(new MetaError( $"origin.passthrough on {obj.Name}.{fieldName}: @via hop \"{(reverse is not null && reverse.TryGetValue(rel, out var hop) ? hop : rel.Name)}\" is to-many " + @@ -1663,7 +1793,7 @@ private static bool ExtendsChainReaches(MetaData node, MetaData target) // ========================================================================= - // The entity fields projections REACH without outputting them (a + // rc.19 entity-derived — the entity fields projections REACH without outputting them (a // @filter key naming a base field or a to-one path, a passthrough @from). Ported from // validation-passes.ts projectionReachedEntityFields. // ========================================================================= @@ -1676,7 +1806,7 @@ private static HashSet ProjectionReachedEntityFields(MetaData root) var silent = new List(); var baseEntity = DeriveBaseEntity(obj, root, "@filter", obj.Source, silent); if (baseEntity is MetaObject baseObject && !ReferenceEquals(baseEntity, obj) - // The effective filter — an extender reaches what its supers' filters name. + // C1: the effective filter — an extender reaches what its supers' filters name. && ProjectionFilters.Effective(obj) is IReadOnlyDictionary filter) { foreach (var key in FilterKeys(filter)) @@ -1688,16 +1818,103 @@ private static HashSet ProjectionReachedEntityFields(MetaData root) } } foreach (var field in obj.Children().Where(c => c.Type == TYPE_FIELD)) + { foreach (var origin in field.OwnChildren().Where(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_PASSTHROUGH)) if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_FROM) is string from && ValidateFromPath(from, root, obj, field.Name, silent, "origin.passthrough.@from", origin.Source) is { } target) reached.Add(target.Field); + // rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + if (baseEntity is MetaObject bo2 && !ReferenceEquals(baseEntity, obj)) + foreach (var origin in field.OwnChildren().Where(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_COMPUTED)) + foreach (var name in ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Where(n => n.Contains('.'))) + if (FilterPaths.Resolve(bo2, name, out _) is { } p) reached.Add(p.Field); + } } + // rc.21 part B fix round (I4): a reached origin.function's arguments are reached too. + foreach (var f in reached.ToList()) ReachFunctionArgs(f, reached); return reached; } + private static void ReachFunctionArgs(MetaData f, HashSet reached) + { + var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_FUNCTION); + if (origin is null || f.Parent is not { } host) return; + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var names = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + foreach (var name in names.OfType()) + if (host.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) is { } arg && reached.Add(arg)) + ReachFunctionArgs(arg, reached); + } + + // ========================================================================= + // rc.21 part B fix round 2 (N3): no derived field depends on itself. A view inlines a derived + // field's dependencies on the same row (an origin.function's @args, an origin.computed + // expression's field refs), so a cycle has no SQL and would recurse forever. Refused once per + // cycle, naming the path (ERR_INVALID_ORIGIN). Ported from validation-passes.ts + // validateDerivedCycles. // ========================================================================= - // Origin segments and correlated filters, on every origin.first / origin.aggregate: + + public static IReadOnlyList ValidateDerivedCycles(MetaData root) + { + var errors = new List(); + // ADR-0039: effective children, as TS iterates them. + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT)) + { + // ADR-0039: effective — an inherited field's origin is inlined on the extender's row too. + var fields = obj.Children().Where(c => c.Type == TYPE_FIELD).ToList(); + var byName = new Dictionary(); + foreach (var f in fields) byName.TryAdd(f.Name, f); + // ADR-0039: own — origin.* never inherits (ADR-0029). + MetaData? OriginOf(MetaData f) => f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + List Deps(MetaData f) + { + var origin = OriginOf(f); + var names = new List(); + // A function naming itself in @args is refused by ValidateFunctionOrigin already. On an + // entity, a computed expression reading its own name reads itself: a one-node cycle, + // reported here (M3). On a projection that name is the base entity's field: no cycle. + var selfAllowed = origin?.SubType == ORIGIN_SUBTYPE_COMPUTED && obj.SubType != OBJECT_SUBTYPE_PROJECTION; + if (origin?.SubType == ORIGIN_SUBTYPE_FUNCTION) + { + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var list = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + names.AddRange(list.OfType()); + } + else if (origin?.SubType == ORIGIN_SUBTYPE_COMPUTED) + { + names.AddRange(ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Select(n => n.Split('.')[0])); + } + return names.Select(n => byName.TryGetValue(n, out var d) ? d : null) + .Where(d => d is not null && (selfAllowed || !ReferenceEquals(d, f)) && OriginOf(d) is not null).Select(d => d!).ToList(); + } + var done = new HashSet(ReferenceEqualityComparer.Instance); + var reported = new HashSet(); + void Visit(MetaData f, List path) + { + var at = path.FindIndex(x => ReferenceEquals(x, f)); + if (at >= 0) + { + var cycle = path.Skip(at).Append(f).Select(x => x.Name).ToList(); + var key = string.Join(",", cycle.Take(cycle.Count - 1).OrderBy(n => n, StringComparer.Ordinal)); + if (reported.Add(key)) + { + errors.Add(new MetaError( + $"{obj.Name}.{f.Name}: a derived field depends on itself through {string.Join(" → ", cycle)}; a view inlines each dependency on the same row, so the cycle has no SQL. Break it.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: (OriginOf(f) ?? f).Source)); + } + return; + } + if (done.Contains(f)) return; + foreach (var d in Deps(f)) Visit(d, [.. path, f]); + done.Add(f); + } + foreach (var f in fields.Where(f => OriginOf(f) is not null)) Visit(f, []); + } + return errors; + } + + // ========================================================================= + // rc.19 origin-segment and correlated-filter, on every origin.first / origin.aggregate: // @segment names a segment of the related entity (ERR_INVALID_ORIGIN); an @filter operand // { field: "" } names a base-row field with a column-comparing op, and the null-safe // ops take only such an operand (ERR_BAD_ATTR_FILTER). Ported from validation-passes.ts @@ -1730,7 +1947,160 @@ public static IReadOnlyList ValidateOriginSegmentsAndCorrelation(Meta if (origin.OwnAttr(ORIGIN_FIRST_ATTR_FILTER) is not IReadOnlyDictionary filter) continue; var silent = new List(); if (DeriveBaseEntity(obj, root, field.Name, origin.Source, silent) is not { } baseEntity) continue; - CheckCorrelatedOperands(filter, baseEntity, where, origin.Source, errors); + CheckCorrelatedOperands(filter, baseEntity, where, origin.Source, errors, obj.SubType == OBJECT_SUBTYPE_PROJECTION); + } + } + } + return errors.AsReadOnly(); + } + + /// + /// rc.21 part B (U10) — origin.function: its name and schema are plain identifiers (never free + /// SQL); each argument names a scalar field of the host entity, or of the projection (not an + /// aggregate, not the field itself) or its base. Mirrors TS _validateFunctionOrigin. + /// + private static void ValidateFunctionOrigin(MetaData origin, MetaData obj, MetaData field, MetaData root, List errors) + { + var src = origin.Source; + var where = $"origin.function on {obj.Name}.{field.Name}"; + foreach (var attr in new[] { ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA }) + { + var v = origin.OwnAttr(attr); + if (v is not null && (v is not string sv || !ORIGIN_FUNCTION_IDENTIFIER.IsMatch(sv))) + errors.Add(new MetaError( + $"{where}: @{attr} {System.Text.Json.JsonSerializer.Serialize(v?.ToString())} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + } + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var args = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + // rc.21 part B fix round (I4): the declared signature (TS _validateFunctionOrigin, message for message). + var rawParams = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + var parameters = rawParams switch { null => new List(), IReadOnlyList pl => pl.ToList(), _ => new List { rawParams } }; + var returns = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + foreach (var t in parameters.Concat(returns is null ? [] : new[] { returns })) + if (t is not string ts || !ExpressionGrammar.CastTargets.Contains(ts)) + errors.Add(new MetaError( + $"{where}: {System.Text.Json.JsonSerializer.Serialize(t?.ToString())} is not a parameter or return type; use one of {string.Join(", ", ExpressionGrammar.CastTargets)}.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + if (returns is string r && r != field.SubType) + errors.Add(new MetaError( + $"{where}: @returns {r}, but the field is field.{field.SubType}; the declared return type must be the field's type.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + if (parameters.Count != args.Count) + errors.Add(new MetaError( + $"{where}: @params declares {parameters.Count} parameter type(s) for {args.Count} argument(s); declare one per @args entry.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + var isProjection = obj.SubType == OBJECT_SUBTYPE_PROJECTION; + var baseEntity = isProjection ? DeriveBaseEntity(obj, root, field.Name, src, new List()) : obj; + for (var index = 0; index < args.Count; index++) + { + var a = args[index]; + var name = a as string; + var own = name is not null && name != field.Name + ? obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) : null; + var ownOrigin = own?.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + var arg = own ?? (name is not null && baseEntity is not null + ? baseEntity.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) : null); + if (arg is null || name == field.Name) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", which is not a field of {(isProjection ? "the projection or its base entity" : $"\"{obj.Name}\"")}.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (ownOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", an origin.aggregate; a function takes values of the row, not of the group.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (arg.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP || (arg is MetaField af && af.ResolvedIsArray())) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", a field.{arg.SubType}{(arg is MetaField af2 && af2.ResolvedIsArray() ? " array" : "")}; a function argument is a scalar.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (index < parameters.Count && parameters[index] is string p && arg.SubType != p) + errors.Add(new MetaError( + $"{where}: argument {index + 1} \"{a}\" is a field.{arg.SubType}, but parameter {index + 1} is declared {p}; " + + $"pass an origin.computed field that casts it ({{ cast: {{ field: {a} }}, as: {p} }}).", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + } + } + + /// rc.21 part B (U14): the value object a @grain projection's rows are elements of. + private static MetaData? GrainValueObject(MetaData obj, MetaData root) + { + if (obj.SubType != OBJECT_SUBTYPE_PROJECTION || obj.Attr(OBJECT_PROJECTION_ATTR_GRAIN) is not string grain) return null; + var baseEntity = DeriveBaseEntity(obj, root, "@grain", obj.Source, new List()); + var field = baseEntity?.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == grain); + return field is null ? null : NamingRefs.RefTarget(field, FIELD_ATTR_OBJECT_REF); + } + + /// + /// rc.21 part B — @union shapes (U15) and @grain projections (U14). Mirrors TS + /// validateProjectionUnionAndGrain, message for message. + /// + public static IReadOnlyList ValidateProjectionUnionAndGrain(MetaData root) + { + var errors = new List(); + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + { + void Bad(string message) => errors.Add(new MetaError($"object.projection {obj.Name}: {message}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: obj.Source)); + // ADR-0039: own — a projection's @union / @grain names ITS view's shape. + var union = obj.OwnAttr(OBJECT_PROJECTION_ATTR_UNION); + if (obj.OwnAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) is not null && union is null) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION_ALL} needs @{OBJECT_PROJECTION_ATTR_UNION}."); + if (union is not null) + { + var pkg = NamingRefs.EffectivePackage(obj); + var mine = obj.Children().Where(c => c.Type == TYPE_FIELD).ToList(); + var names = union is IReadOnlyList l ? l.ToList() : new List { union }; + static string Describe(MetaData f) + { + var arr = f is MetaField mf && mf.ResolvedIsArray() ? "[]" : ""; + var col = f.Attr(FIELD_ATTR_COLUMN) is string c ? $" @column {c}" : ""; + // fix round M4: an enum's members and value maps are part of the column's meaning. + var enumShape = f.SubType != FIELD_SUBTYPE_ENUM ? "" + : " " + System.Text.Json.JsonSerializer.Serialize(new object?[] { f.Attr(FIELD_ATTR_VALUES), f.Attr(FIELD_ATTR_INT_VALUE_MAP), f.Attr(FIELD_ATTR_STRING_VALUE_MAP) }); + return $"{f.Name}: field.{f.SubType}{arr}{col}{enumShape}"; + } + foreach (var nameObj in names) + { + var member = nameObj is string name ? NamingRefs.ResolveObjectRef(root, name, pkg) : null; + if (member is null || member.Type != TYPE_OBJECT || member.SubType != OBJECT_SUBTYPE_PROJECTION) + { + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} names \"{nameObj}\", which is not an object.projection."); + continue; + } + if (ReferenceEquals(member, obj)) + { + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} names the projection itself."); + continue; + } + if (member.OwnAttr(OBJECT_PROJECTION_ATTR_UNION) is not null) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} member \"{member.Name}\" declares its own @{OBJECT_PROJECTION_ATTR_UNION}; name its members here instead."); + var a = mine.Select(Describe).ToList(); + var b = member.Children().Where(c => c.Type == TYPE_FIELD).Select(Describe).ToList(); + if (!a.SequenceEqual(b)) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} member \"{member.Name}\" has a different shape: " + + $"({string.Join(", ", b)}) where this view is ({string.Join(", ", a)}). A union's members have the same fields, in order."); + } + } + var grain = obj.OwnAttr(OBJECT_PROJECTION_ATTR_GRAIN); + var ordinal = obj.OwnAttr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); + if (ordinal is not null && grain is null) Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} needs @{OBJECT_PROJECTION_ATTR_GRAIN}."); + if (grain is string g) + { + var baseEntity = DeriveBaseEntity(obj, root, "@grain", obj.Source, new List()); + var field = baseEntity?.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == g); + var isArray = field is MetaField gf && gf.ResolvedIsArray(); + var storage = field?.Attr(FIELD_ATTR_STORAGE) as string; + if (field is null || field.SubType != FIELD_SUBTYPE_OBJECT || !isArray || (storage is not null && storage != STORAGE_JSONB) + || NamingRefs.RefTarget(field, FIELD_ATTR_OBJECT_REF) is null) + Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN} \"{g}\" must name a field.object array (isArray, jsonb storage, with @objectRef) of the base entity{(baseEntity is null ? "" : $" \"{baseEntity.Name}\"")}."); + foreach (var f in obj.Children().Where(c => c.Type == TYPE_FIELD)) + if (f.OwnChildren().Any(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_AGGREGATE)) + Bad($"\"{f.Name}\" is an origin.aggregate; a @grain view has one row per element and groups nothing."); + if (ordinal is not null) + { + var f = obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == ordinal as string); + if (f is null || (f.SubType != FIELD_SUBTYPE_INT && f.SubType != FIELD_SUBTYPE_LONG) + || f.OwnChildren().Any(c => c.Type == TYPE_ORIGIN) || f.SuperRef is not null) + Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} \"{ordinal}\" must name a field.int or field.long of the projection, with no origin and no extends."); } } } @@ -1759,7 +2129,8 @@ public static IReadOnlyList ValidateOriginSegmentsAndCorrelation(Meta } private static void CheckCorrelatedOperands( - IReadOnlyDictionary filter, MetaData baseEntity, string where, ErrorSource source, List errors) + IReadOnlyDictionary filter, MetaData baseEntity, string where, ErrorSource source, List errors, + bool onProjection) { foreach (var (key, clause) in filter) { @@ -1768,7 +2139,7 @@ private static void CheckCorrelatedOperands( if (clause is IReadOnlyList subs) foreach (var sub in subs) if (sub is IReadOnlyDictionary subFilter) - CheckCorrelatedOperands(subFilter, baseEntity, where, source, errors); + CheckCorrelatedOperands(subFilter, baseEntity, where, source, errors, onProjection); continue; } if (clause is not IReadOnlyDictionary ops) continue; @@ -1789,9 +2160,20 @@ private static void CheckCorrelatedOperands( $"{where}: @filter on \"{key}\" compares with a base-row field using \"{op}\"; a correlated operand takes {string.Join(", ", CorrelatedFilterOps)}.", ErrorCode.ERR_BAD_ATTR_FILTER, Envelope: source)); else if (name is null || !baseEntity.Children().Any(c => c.Type == TYPE_FIELD && c.Name == name)) + { + // rc.21 part B (U4): on a projection, a PATH of to-one hops from the base row. + string? why = null; + var path = name is not null && name.Contains('.') && onProjection && baseEntity is MetaObject bo + ? FilterPaths.Resolve(bo, name, out why) : null; + if (path is not null) continue; errors.Add(new MetaError( - $"{where}: @filter on \"{key}\" names base-row field \"{name}\", which \"{baseEntity.Name}\" does not declare.", + why is not null + ? $"{where}: @filter on \"{key}\" compares with the base-row path \"{name}\": {why}." + : name is not null && name.Contains('.') && !onProjection + ? $"{where}: @filter on \"{key}\" compares with the path \"{name}\"; a path operand is legal only on a projection, whose view joins it." + : $"{where}: @filter on \"{key}\" names base-row field \"{name}\", which \"{baseEntity.Name}\" does not declare.", ErrorCode.ERR_BAD_ATTR_FILTER, Envelope: source)); + } } } } @@ -1822,7 +2204,8 @@ public static IReadOnlyList ValidateDerivedFieldProvidability(MetaDat if (origin is null) continue; // A derived field a projection reaches (its @filter or a passthrough // @from) is lowered inline there, so it needs no read source. Only the inlinable origins. - if ((origin.SubType == ORIGIN_SUBTYPE_FIRST || origin.SubType == ORIGIN_SUBTYPE_COMPUTED) && reached.Contains(field)) + if ((origin.SubType == ORIGIN_SUBTYPE_FIRST || origin.SubType == ORIGIN_SUBTYPE_COMPUTED + || origin.SubType == ORIGIN_SUBTYPE_FUNCTION) && reached.Contains(field)) continue; errors.Add(new MetaError( $"derived field \"{obj.Name}.{field.Name}\" carries an origin.* but entity \"{obj.Name}\" declares no " + @@ -2063,7 +2446,7 @@ public static IReadOnlyList ValidateProjectionFilter(MetaData root) var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); if (origin is not null && origin.SubType != ORIGIN_SUBTYPE_PASSTHROUGH && - origin.SubType != ORIGIN_SUBTYPE_COMPUTED) + (origin.SubType != ORIGIN_SUBTYPE_COMPUTED || ComputedReadsAggregate(f, obj, new HashSet(StringComparer.Ordinal)))) { aggregateDerived.Add(f.Name); } @@ -2111,6 +2494,26 @@ public static IReadOnlyList ValidateProjectionFilter(MetaData root) /// when it is an aggregate (a WHERE runs before grouping); its column, an origin.computed or an /// origin.first (a correlated scalar subquery) can (entity-derived). origin.* never inherits. /// + /// + /// rc.21 part B (U13): whether an origin.computed reads an origin.aggregate of its projection, + /// directly or through another computed — a value of the grouped row a WHERE cannot hold. + /// + private static bool ComputedReadsAggregate(MetaData f, MetaData obj, HashSet seen) + { + if (!seen.Add(f.Name)) return false; + // ADR-0039: own — origin.* never inherits (ADR-0029). + var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + if (origin?.SubType != ORIGIN_SUBTYPE_COMPUTED) return false; + foreach (var name in ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR))) + { + if (name == f.Name) continue; + var other = obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name); + if (other is null) continue; + if (EntityFieldAggregates(other) || ComputedReadsAggregate(other, obj, seen)) return true; + } + return false; + } + private static bool EntityFieldAggregates(MetaData f) => f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN) is { SubType: ORIGIN_SUBTYPE_AGGREGATE }; @@ -2546,6 +2949,9 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo var kind = unrenderable.ContainsKey(ExpressionGrammar.EXPR_CASE) ? ExpressionGrammar.EXPR_CASE : ExpressionGrammar.EXPR_NOW; return $"is not a valid expression: a condition takes no '{kind}' node, since a CHECK can hold neither a CASE nor the current time."; } + // A CHECK holds only the subset every port's CHECK emitter renders. + if (MetaObjects.Core.Attr.ExpressionGrammar.ExprViewOnlyNode(condition) is { } viewOnly) + return $"uses {viewOnly}, which a CHECK condition cannot hold: it takes fields, literals, comparisons, null tests, and / or / not, and coalesce."; var fields = new Dictionary(StringComparer.Ordinal); foreach (var f in obj.Fields()) fields.TryAdd(f.Name, f); var inferred = MetaObjects.Core.Attr.ExpressionGrammar.InferExprType( @@ -2684,6 +3090,50 @@ public static IReadOnlyList ValidateIdentitySequence(MetaData root) return errors; } + // --------------------------------------------------------------------------- + // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no + // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only + // by its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one + // error such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either + // of the two itself. Mirrors TS validateDbCheck. + // --------------------------------------------------------------------------- + public static IReadOnlyList ValidateDbCheck(MetaData root) + { + var errors = new List(); + const string dbCheck = MetaObjects.Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK; + const string constraintName = MetaObjects.Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME; + void Visit(MetaData node, string? owner) + { + var checkedNode = (node.Type == TYPE_VALIDATOR && MetaObjects.Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES.Contains(node.SubType)) + || (node.Type == TYPE_FIELD && node.SubType == FIELD_SUBTYPE_ENUM); + var label = $"{node.Type}.{node.SubType} \"{(owner is null ? "" : owner + ".")}{node.Name}\""; + var declares = checkedNode && (node.OwnAttr(dbCheck) is not null || node.OwnAttr(constraintName) is not null); + if (declares && node.Attr(dbCheck) is false && node.Type == TYPE_VALIDATOR + && MetaObjects.Core.Validator.ValidatorConstants.CROSS_FIELD_VALIDATOR_SUBTYPES_FOR_DB_CHECK.Contains(node.SubType)) + { + // A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.Add(new MetaError( + $"{label} sets @dbCheck: false, but this validator is enforced only by its CHECK, so the rule would be " + + "enforced nowhere. Remove the validator, or remove @dbCheck: false.", + ErrorCode.ERR_CROSS_FIELD_WITHOUT_CHECK, + Envelope: node.Source)); + } + else if (declares && node.Attr(dbCheck) is false && node.Attr(constraintName) is string { Length: > 0 } name) + { + errors.Add(new MetaError( + $"{label} sets @dbCheck: false and @constraintName \"{name}\"; with no CHECK there is nothing for the name to name. " + + "Remove @constraintName, or remove @dbCheck: false.", + ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + Envelope: node.Source)); + } + var next = node.Type == TYPE_OBJECT || node.Type == TYPE_FIELD ? node.Name : owner; + foreach (var child in node.OwnChildren()) Visit(child, next); + } + foreach (var child in root.OwnChildren()) Visit(child, null); + return errors; + } + // --------------------------------------------------------------------------- // field.enum @maxLength — the column length of a string-stored enum: // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the @@ -2707,7 +3157,7 @@ void Visit(MetaData node) } void CheckEnum(MetaField field) { - var declares = new[] { FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP } + var declares = new[] { FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP } .Any(a => field.OwnAttr(a) is not null); if (!declares || field.MaxLength is not { } maxLength) return; var owner = field.Parent; @@ -2720,14 +3170,15 @@ void CheckEnum(MetaField field) Envelope: field.Source)); return; } - var tooLong = (field.EffectiveEnumValues ?? []) + // The column holds each member's STORED string (@stringValueMap), so that is what must fit. + var tooLong = EnumStorage.StoredValues(field) .Where(v => v.Length > maxLength) .OrderByDescending(v => v.Length) .FirstOrDefault(); if (tooLong is not null) { errors.Add(new MetaError( - $"field.enum \"{label}\" @maxLength {maxLength} is shorter than its member \"{tooLong}\" ({tooLong.Length} characters). Raise @maxLength to at least {tooLong.Length}, or shorten the member.", + $"field.enum \"{label}\" @maxLength {maxLength} is shorter than its {(EnumStorage.StringValueMapOf(field) is null ? "member" : "stored value")} \"{tooLong}\" ({tooLong.Length} characters). Raise @maxLength to at least {tooLong.Length}, or shorten the member.", ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, Envelope: field.Source)); } @@ -3364,6 +3815,60 @@ private static void WalkEnumValues(MetaData node, List errors) } } } + + // Rule 6 (rc.21): @stringValueMap content rules — the string twin of Rule 5, with its + // policies (own-only; a shared enum's backing owned by the shared declaration). Keys must + // exactly match @values; values are unique non-empty strings. An enum that is not + // string-stored refuses it: an @intValueMap enum stores integers, and an array enum + // stores its members as text[] elements, which no port maps through it. + if (field.OwnAttr(FIELD_ATTR_STRING_VALUE_MAP) is { } rawStringMap) + { + void Bad(string message, ErrorCode code = ErrorCode.ERR_BAD_ATTR_VALUE) => errors.Add(new MetaError( + $"field.enum '{field.Name}' attribute '@{FIELD_ATTR_STRING_VALUE_MAP}' {message}", code, Envelope: field.Source)); + if (SharedEnumSuper(field) is { } sharedStringSuper) + { + Bad($"is declared on a field extending shared abstract enum '{sharedStringSuper.Name}' — a shared enum's " + + $"stored strings are owned by the shared declaration; move it onto '{sharedStringSuper.Name}' to inherit it.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT); + } + else if (field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null) + { + Bad($"is refused beside '@{FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one."); + } + else if (field.ResolvedIsArray()) + { + Bad($"is refused on an array enum: its column holds the members as text[] elements, which no port maps through @{FIELD_ATTR_STRING_VALUE_MAP}."); + } + else if (rawStringMap is not IReadOnlyDictionary stringMap) + { + Bad("must be an object of { member: storedString }."); + } + else + { + var effective = field.EffectiveEnumValues ?? new List(); + var memberSet = new HashSet(effective, StringComparer.Ordinal); + var keySet = new HashSet(stringMap.Keys, StringComparer.Ordinal); + var missing = effective.Where(m => !keySet.Contains(m)).ToList(); + var extra = stringMap.Keys.Where(k => !memberSet.Contains(k)).ToList(); + if (missing.Count > 0 || extra.Count > 0) + Bad($"keys must exactly match '@{FIELD_ATTR_VALUES}' members" + + (missing.Count > 0 ? $" (missing: {string.Join(", ", missing)})" : "") + + (extra.Count > 0 ? $" (unknown: {string.Join(", ", extra)})" : "") + "."); + var seen = new Dictionary(StringComparer.Ordinal); + foreach (var (member, value) in stringMap) + { + if (value is not string { Length: > 0 } stored) + { + Bad($"member '{member}' must map to a non-empty string."); + continue; + } + if (seen.TryGetValue(stored, out var owner)) + Bad($"members '{owner}' and '{member}' share the stored string '{stored}'; every member must have a unique one."); + else + seen[stored] = member; + } + } + } } foreach (var child in node.OwnChildren()) @@ -3491,33 +3996,35 @@ private static void WalkDbColumnType(MetaData node, List errors) { if (node is MetaField field && field.DbColumnType is { } value) { - // Rule 1: recognized value. - if (!VALID_DB_COLUMN_TYPES.Contains(value)) + // Rule 1: recognized value (rc.21: the text spellings, sized ones included). + var parsed = ParseDbColumnType(value); + if (parsed is null) { errors.Add(new MetaError( $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not a valid value; " + - $"allowed: {string.Join(", ", VALID_DB_COLUMN_TYPES)}", + $"allowed: {string.Join(", ", VALID_DB_COLUMN_TYPES.Concat(DB_COLUMN_TYPE_SIZED_SPELLINGS))}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: field.Source)); } - else + else if (field.SubType != FIELD_SUBTYPE_STRING) { - // Rule 2: legal (subtype × value) pairing. - var requiredSubType = value switch - { - DB_COLUMN_TYPE_UUID or DB_COLUMN_TYPE_JSONB => FIELD_SUBTYPE_STRING, - _ => null, // unreachable (Rule 1) - }; - if (requiredSubType is not null && field.SubType != requiredSubType) - { - errors.Add(new MetaError( - $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not valid on " + - $"field.{field.SubType} (requires field.{requiredSubType}); allowed pairings: " + - $"{DB_COLUMN_TYPE_UUID}→field.{FIELD_SUBTYPE_STRING}, " + - $"{DB_COLUMN_TYPE_JSONB}→field.{FIELD_SUBTYPE_STRING}", - ErrorCode.ERR_BAD_ATTR_VALUE, - Envelope: field.Source)); - } + // Rule 2: legal (subtype × value) pairing — every value is field.string's. + errors.Add(new MetaError( + $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not valid on " + + $"field.{field.SubType} (requires field.{FIELD_SUBTYPE_STRING}); every @{FIELD_ATTR_DB_COLUMN_TYPE} value is a field.{FIELD_SUBTYPE_STRING}'s", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: field.Source)); + } + else if (parsed.Length is { } n && field.Attr(FIELD_ATTR_MAX_LENGTH) is { } maxObj + && Convert.ToInt64(maxObj, System.Globalization.CultureInfo.InvariantCulture) > n) + { + // Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength (resolving) + // would let the app accept a value the column refuses. + errors.Add(new MetaError( + $"field.string '{field.Name}' declares @{FIELD_ATTR_MAX_LENGTH}: {maxObj} over '@{FIELD_ATTR_DB_COLUMN_TYPE}: {value}', " + + $"which holds {n}; a value the field accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: field.Source)); } } diff --git a/server/csharp/MetaObjects/Meta/CollectionNames.cs b/server/csharp/MetaObjects/Meta/CollectionNames.cs index 6ab5928f55..6868fc95d0 100644 --- a/server/csharp/MetaObjects/Meta/CollectionNames.cs +++ b/server/csharp/MetaObjects/Meta/CollectionNames.cs @@ -1,5 +1,4 @@ -// An object's collection name: its own @collectionName, else the project's pluralizer -// (naming.collections) over its name. Ported from +// rc.19 (R57) — an object's collection name: its own @collectionName, else the project's pluralizer (naming.collections) over its name. Ported from // typescript/packages/metadata/src/naming.ts (collectionNameOf, declaredCollectionName). using static MetaObjects.Core.Object.ObjectConstants; @@ -18,20 +17,11 @@ public static class CollectionNames public static string Of(MetaObject obj) => Declared(obj) ?? NamingStrategies.Pluralizer(ConfiguredPluralizer(obj) ?? NamingStrategies.DefaultPluralizer)(obj.Name); - /// The pluralizer the project configures (naming.collections), or null when it names none. - public static string? ConfiguredPluralizer(MetaData node) => PhysicalNaming.Of(node).Collections; - - /// The collection name declares (@collectionName), or null. - public static string? Declared(MetaObject obj) => - // ADR-0039: own — a collection name is the declaring object's alone (see Of). - obj.OwnAttr(OBJECT_ATTR_COLLECTION_NAME) is string { Length: > 0 } own ? own : null; - /// - /// The REST collection segment is served under - /// (fixtures/naming-conformance/collection-segments.json, shared with TypeScript): its - /// declared @collectionName, else the configured pluralizer's output over its name, each - /// snake_cased by ; with neither, - /// over the name, so an unconfigured project's segments never move. + /// rc.19 fix round (I3) — the REST collection segment, shared with TypeScript + /// (fixtures/naming-conformance/collection-segments.json): a declared name wins, else a + /// configured pluralizer's output over the name, each snake_cased by ; + /// with neither, (the historical rule, byte-identical) over the name. /// public static string Segment(MetaObject obj, Func unconfigured) { @@ -41,9 +31,9 @@ public static string Segment(MetaObject obj, Func unconfigured) } /// - /// snake_case a collection name with an acronym-aware split: a trailing plural s / es - /// after a capital is a suffix of the acronym, not a word of its own (FAQs → faqs, - /// TaxIDs → tax_ids, PDFBoxes → pdf_boxes). + /// snake_case a collection name with an acronym-aware split: a trailing plural s / + /// es after a capital is a suffix of the acronym, not a word of its own (FAQs → + /// faqs, TaxIDs → tax_ids). Mirrors TS snakeCollectionName. /// public static string SnakeCollectionName(string s) { @@ -53,6 +43,14 @@ public static string SnakeCollectionName(string s) : Persistence.Source.SourceNaming.ToSnakeCase(s); } + /// The pluralizer the project configures (naming.collections), or null when it names none. + public static string? ConfiguredPluralizer(MetaData node) => PhysicalNaming.Of(node).Collections; + + /// The collection name declares (@collectionName), or null. + public static string? Declared(MetaObject obj) => + // ADR-0039: own — a collection name is the declaring object's alone (see Of). + obj.OwnAttr(OBJECT_ATTR_COLLECTION_NAME) is string { Length: > 0 } own ? own : null; + /// /// The standard pluralizer, the rule every port shares (fixtures/naming-conformance): /// an already-plural name stays, else the suffix rule. diff --git a/server/csharp/MetaObjects/Meta/EnumLength.cs b/server/csharp/MetaObjects/Meta/EnumLength.cs index 9990ff980c..1e0bd30548 100644 --- a/server/csharp/MetaObjects/Meta/EnumLength.cs +++ b/server/csharp/MetaObjects/Meta/EnumLength.cs @@ -37,14 +37,15 @@ public static class EnumLength if (field.ResolvedIsArray()) return null; if (field.MaxLength is { } own) return own; if (EnumDefaults.Of(field).MaxLength is not { } fallback) return null; - var longest = (field.EffectiveEnumValues ?? []) + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + var longest = EnumStorage.StoredValues(field) .OrderByDescending(v => v.Length).FirstOrDefault(); if (longest is not null && longest.Length > fallback) { var owner = field.Parent; var label = owner is not null && owner.Type == TYPE_OBJECT ? $"{owner.Name}.{field.Name}" : field.Name; throw new MetaModelException( - $"field.enum \"{label}\" has the member \"{longest}\" ({longest.Length} characters), longer than " + + $"field.enum \"{label}\" has the {(EnumStorage.StringValueMapOf(field) is null ? "member" : "stored value")} \"{longest}\" ({longest.Length} characters), longer than " + $"the project's enums.maxLength {fallback}. Give the field its own @maxLength of at least " + $"{longest.Length}, raise enums.maxLength, or shorten the member.", ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH); diff --git a/server/csharp/MetaObjects/Meta/EnumStorage.cs b/server/csharp/MetaObjects/Meta/EnumStorage.cs new file mode 100644 index 0000000000..d38c9d94b5 --- /dev/null +++ b/server/csharp/MetaObjects/Meta/EnumStorage.cs @@ -0,0 +1,23 @@ +// rc.21 — the string a string-stored field.enum member is stored as: its @stringValueMap entry, +// else the member itself. ONE definition every consumer that writes a member into the database +// (a CHECK, a column length, a converter, a @condition literal) reads. Mirrors TypeScript's +// core/field/enum-storage.ts. + +using static MetaObjects.Core.Field.FieldConstants; + +namespace MetaObjects.Meta; + +public static class EnumStorage +{ + /// The effective (ADR-0039: resolving) @stringValueMap, or null. + public static IReadOnlyDictionary? StringValueMapOf(MetaData field) => + field.Attr(FIELD_ATTR_STRING_VALUE_MAP) as IReadOnlyDictionary; + + /// The string is stored as: its @stringValueMap entry, else the member. + public static string StoredValue(MetaData field, string member) => + StringValueMapOf(field) is { } map && map.TryGetValue(member, out var v) && v is string { Length: > 0 } s ? s : member; + + /// Every member of @values (resolving), as stored, in declaration order. + public static IReadOnlyList StoredValues(MetaField field) => + (field.EffectiveEnumValues ?? []).Select(m => StoredValue(field, m)).ToList(); +} diff --git a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs index f81daccada..aadf78f2db 100644 --- a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs +++ b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs @@ -20,7 +20,7 @@ public static class ReverseReferenceHops /// public static string HopName(MetaObject holder) { - // the holder's collection name — its @collectionName, else the project's pluralizer. + // The holder's collection name — its @collectionName, else the project's pluralizer. var plural = CollectionNames.Of(holder); return plural.Length == 0 ? plural : char.ToLowerInvariant(plural[0]) + plural[1..]; } @@ -44,4 +44,34 @@ public static IReadOnlyList Find(MetaObject target, string } return found; } + + /// + /// rc.21 — every reverse hop a @via may take from : one per + /// identity.reference onto it from a concrete object, under that object's . + /// For the "no such relationship" message, so an author who guessed a hop name (the reference's + /// own name, a plural the holder's @collectionName overrides) sees the one the rule gives. + /// + public static IReadOnlyList<(string HopName, ReverseReferenceHop Hop)> OnTo(MetaObject target, IEnumerable objects) + { + var found = new List<(string, ReverseReferenceHop)>(); + foreach (var holder in objects) + { + if (holder.IsAbstract) continue; + foreach (var r in holder.ReferenceIdentities()) + // ADR-0059 R7: compare the bound target, never a short name. + if (ReferenceEquals(NamingRefs.RefTarget(r, IDENTITY_REFERENCE_ATTR_REFERENCES), target)) + found.Add((HopName(holder), new ReverseReferenceHop(holder, r))); + } + return found; + } + + /// The message suffix naming 's hops, or "" when there are none. + public static string Hint(MetaObject target, IEnumerable objects) + { + var hops = OnTo(target, objects); + if (hops.Count == 0) return ""; + return $" The reverse hops from {target.Name} are: " + + string.Join(", ", hops.Select(h => $"\"{h.HopName}\" (walks {h.Hop.Holder.Name}.{h.Hop.Reference.Name} backwards)")) + + " — a reverse hop is named by the holder's collection name (its @collectionName, else the plural), first letter lowercased."; + } } diff --git a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs index dc0f4ed6d7..d202e03457 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs @@ -83,10 +83,50 @@ public static class DbConstants /// @dbColumnType: jsonb — genuinely-open JSON column (legal on field.string). public const string DB_COLUMN_TYPE_JSONB = "jsonb"; - /// The closed set of legal @dbColumnType values. + /// rc.21 part B (U2): the text column spellings @dbColumnType takes on a field.string. + public const string DB_COLUMN_TYPE_TEXT = "text"; + public const string DB_COLUMN_TYPE_VARCHAR = "varchar"; + public const string DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying"; + + /// The closed set of legal bare @dbColumnType values; the sized spellings + /// varchar(n), character varying(n) and character(n) are parsed by . public static readonly IReadOnlyList VALID_DB_COLUMN_TYPES = new[] { DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, }; + + /// The sized spellings, as written in a message. + public static readonly IReadOnlyList DB_COLUMN_TYPE_SIZED_SPELLINGS = new[] + { + "varchar(n)", "character varying(n)", "character(n)", + }; + + /// A parsed @dbColumnType: uuid, jsonb, text, varchar or char, and a sized spelling's length. + public sealed record ParsedDbColumnType(string Kind, int? Length); + + private static readonly System.Text.RegularExpressions.Regex SizedDbColumnType = + new(@"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$", System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + /// + /// rc.21 part B (U2): parse a @dbColumnType value, or null for one that is not legal. + /// Postgres's own spellings, matched exactly, as every port parses them (TS parseDbColumnType). + /// + public static ParsedDbColumnType? ParseDbColumnType(string value) + { + switch (value) + { + case DB_COLUMN_TYPE_UUID: return new("uuid", null); + case DB_COLUMN_TYPE_JSONB: return new("jsonb", null); + case DB_COLUMN_TYPE_TEXT: return new("text", null); + case DB_COLUMN_TYPE_VARCHAR or DB_COLUMN_TYPE_CHARACTER_VARYING: return new("varchar", null); + } + var m = SizedDbColumnType.Match(value); + if (!m.Success) return null; + var n = int.Parse(m.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture); + return m.Groups[1].Value == "character" ? new("char", n) : new("varchar", n); + } } diff --git a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs index 300a7dc76c..e5c9b960e7 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs @@ -57,13 +57,13 @@ public void RegisterTypes(TypeRegistry registry) registry.Extend( MetaObjects.Shared.BaseTypes.TYPE_FIELD, FieldConstants.FIELD_SUBTYPE_ENUM, - attributes: [DbSchema.EnumConstraintNameSchema]); + attributes: [DbSchema.EnumConstraintNameSchema, DbSchema.EnumDbCheckSchema]); foreach (string subType in Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES) { registry.Extend( MetaObjects.Shared.BaseTypes.TYPE_VALIDATOR, subType, - attributes: [DbSchema.ValidatorConstraintNameSchema]); + attributes: [DbSchema.ValidatorConstraintNameSchema, DbSchema.ValidatorDbCheckSchema]); } // @flattenedColumnPrefix is field.object-ONLY (the flattened-member column prefix), mirroring diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 26dd53d7e9..113a7e8ae5 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -29,23 +29,17 @@ public static class DbSchema /// /// R6 Plan 2b: @dbColumnType — physical DB column-type override on every field - /// subtype. The closed value set (ADR-0036 Wave 1) is - /// — surfaced as the manifest's allowedValues; the subtype × value pairing is + /// subtype. The bare values are plus the sized text + /// spellings (rc.21), so the manifest carries no allowedValues; the subtype × value pairing is /// validated own-only by the loader (ValidateDbColumnType → ERR_BAD_ATTR_VALUE). /// public static readonly AttrSchema DbColumnTypeSchema = new AttrSchema( Name: DbConstants.FIELD_ATTR_DB_COLUMN_TYPE, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - AllowedValues: [.. DbConstants.VALID_DB_COLUMN_TYPES], - Description: - "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, " + - "both on field.string (uuid = native Postgres uuid column over a string-typed field; " + - "jsonb = genuinely-open JSON column). The logical field type and its native binding are " + - "unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from " + - "a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — " + - "timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive " + - "opt-out), per ADR-0036 Wave 2."); + // rc.21 part B (U2): no allowedValues — the sized spellings (varchar(n), character(n)) are no + // closed set; ValidateDbColumnType parses the value (DbConstants.ParseDbColumnType). + Description: "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2."); /// /// ADR-0036 Wave 2: @localTime — the naive-timestamp opt-out on field.timestamp @@ -88,21 +82,21 @@ public static class DbSchema Name: DbConstants.IDENTITY_ATTR_WHERE, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - Description: "Partial-index predicate (raw SQL, e.g. \"delivered_at IS NULL\"). When set, the index covers only rows matching the predicate — smaller and cheaper for queries that always filter on it. Absent = a full index over every row. RDB-physical — contributed by the db provider."); + Description: "Partial-index predicate (raw SQL, e.g. \"delivered_at IS NULL\"). When set, the index covers only rows matching the predicate — smaller and cheaper for queries that always filter on it. Absent = a full index over every row. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); /// @expr — raw key expression for a functional/expression index; on identity.secondary. public static readonly AttrSchema ExprSchema = new AttrSchema( Name: DbConstants.IDENTITY_ATTR_EXPR, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - Description: "Raw key EXPRESSION for a functional/expression index (e.g. \"lower(email)\"). Used INSTEAD of @fields — the index key is the expression rather than plain columns. RDB-physical — contributed by the db provider."); + Description: "Raw key EXPRESSION for a functional/expression index (e.g. \"lower(email)\"). Used INSTEAD of @fields — the index key is the expression rather than plain columns. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); /// @using — index access method (e.g. "gin"); default "btree"; on identity.secondary. public static readonly AttrSchema UsingSchema = new AttrSchema( Name: DbConstants.IDENTITY_ATTR_USING, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - Description: "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider."); + Description: "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); /// @constraintName on a validator — the database name of the CHECK it generates. public static readonly AttrSchema ValidatorConstraintNameSchema = new AttrSchema( @@ -111,6 +105,20 @@ public static class DbSchema Required: false, Description: "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); + /// @dbCheck on a validator — false generates no database CHECK for it. + public static readonly AttrSchema ValidatorDbCheckSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, + ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, + Required: false, + Description: "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); + + /// @dbCheck on a field.enum — false generates no membership CHECK. + public static readonly AttrSchema EnumDbCheckSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, + ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, + Required: false, + Description: "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); + /// @constraintName on a field.enum — the database name of its membership CHECK. public static readonly AttrSchema EnumConstraintNameSchema = new AttrSchema( Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME, @@ -137,7 +145,7 @@ public static class DbSchema Name: DbConstants.IDENTITY_ATTR_CONSTRAINT_NAME, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - Description: "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider."); + Description: "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); /// @onDelete — referential action on parent delete, the explicit per-FK override; on identity.reference (ADR-0047). public static readonly AttrSchema ReferenceOnDeleteSchema = new AttrSchema( @@ -145,7 +153,7 @@ public static class DbSchema ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, AllowedValues: ["cascade", "set-null", "restrict", "no-action"], - Description: "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider."); + Description: "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); /// @onUpdate — referential action on key update, the explicit per-FK override; on identity.reference (ADR-0047). public static readonly AttrSchema ReferenceOnUpdateSchema = new AttrSchema( @@ -153,5 +161,5 @@ public static class DbSchema ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, AllowedValues: ["cascade", "set-null", "restrict", "no-action"], - Description: "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider."); + Description: "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1."); } diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs index f3b0824a70..bc9112c2db 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs @@ -30,6 +30,8 @@ public static class OriginConstants // along @via, projecting @of (argmax-then-project). public const string ORIGIN_SUBTYPE_COMPUTED = "computed"; public const string ORIGIN_SUBTYPE_FIRST = "first"; + // rc.21 part B (U10): a value computed by a database function the project owns. + public const string ORIGIN_SUBTYPE_FUNCTION = "function"; public static readonly string[] ORIGIN_SUBTYPES = [ @@ -38,6 +40,7 @@ public static class OriginConstants ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ]; // #210 — the ASSEMBLY origins: they derive a value by rolling up, computing, @@ -51,6 +54,7 @@ public static class OriginConstants ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, }; // passthrough attrs @@ -85,6 +89,15 @@ public static class OriginConstants public const string ORIGIN_FIRST_ATTR_VIA = "via"; public const string ORIGIN_FIRST_ATTR_FILTER = "filter"; + // rc.21 part B (U10) origin.function attrs. + public const string ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; + public const string ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; + public const string ORIGIN_FUNCTION_ATTR_ARGS = "args"; + public const string ORIGIN_FUNCTION_ATTR_PARAMS = "params"; + public const string ORIGIN_FUNCTION_ATTR_RETURNS = "returns"; + /// A plain SQL identifier: what @function and @schema may hold (never free SQL). + public static readonly System.Text.RegularExpressions.Regex ORIGIN_FUNCTION_IDENTIFIER = new("^[A-Za-z_][A-Za-z0-9_]*$"); + // aggregate function vocabulary. // // AGGREGATE_FUNCTIONS is the NUMERIC/ORDINAL reduce set — each maps directly to diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs index 31e430d675..7d2682ad0c 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs @@ -129,6 +129,21 @@ public static class OriginSchema Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; + // function: a call of a database function the project owns. + private static readonly IReadOnlyList FunctionOriginAttrs = + [ + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_FUNCTION, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, + Description: "The function's name as the database names it: a plain identifier."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_SCHEMA, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "The schema the function lives in, a plain identifier. Absent: public."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_ARGS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "The fields passed to the function, in parameter order."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_PARAMS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "The function's declared parameter types, one field subtype per @args entry."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_RETURNS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, + Description: "The function's declared return type, the carrying field's subtype."), + ]; + /// /// Attrs per origin subtype. base has none; passthrough, aggregate, /// computed (#195), and first (#195) carry their respective attrs. @@ -141,5 +156,6 @@ public static class OriginSchema [OriginConstants.ORIGIN_SUBTYPE_AGGREGATE] = [.. AggregateOriginAttrs], [OriginConstants.ORIGIN_SUBTYPE_COMPUTED] = [.. ComputedOriginAttrs], [OriginConstants.ORIGIN_SUBTYPE_FIRST] = [.. FirstOriginAttrs], + [OriginConstants.ORIGIN_SUBTYPE_FUNCTION] = [.. FunctionOriginAttrs], }; } diff --git a/server/csharp/MetaObjects/SpecMetamodel/attr.json b/server/csharp/MetaObjects/SpecMetamodel/attr.json index 19031ccb34..ec55a95947 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/attr.json +++ b/server/csharp/MetaObjects/SpecMetamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index 4e087e72f0..1c61a0bdac 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { @@ -85,7 +87,7 @@ "type": "identity", "subType": "reference", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider." }, { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider." } ] diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index 3b4a4ce9fc..46a2f064ce 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index 244fd1655a..d169a02544 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -53,7 +53,11 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index d5b5b85415..e8cfe7e735 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -27,8 +27,8 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -42,6 +42,19 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } + ] + }, { "type": "origin", "subType": "first", @@ -52,8 +65,8 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] diff --git a/server/csharp/MetaObjects/SuperResolve.cs b/server/csharp/MetaObjects/SuperResolve.cs index 8316596b13..8edda83465 100644 --- a/server/csharp/MetaObjects/SuperResolve.cs +++ b/server/csharp/MetaObjects/SuperResolve.cs @@ -231,7 +231,8 @@ public sealed record DeferredSuperFailure( MetaData? Node = null, SuperFailureKind Kind = SuperFailureKind.Unresolved, TypeIdentity? Target = null, - TypeIdentity? Referrer = null); + TypeIdentity? Referrer = null, + string? MemberHint = null); /// /// Resolve every node's SuperRef against the full root, collecting unresolved @@ -350,10 +351,40 @@ void ResolveNode(MetaData node) } else { - failures.Add(new DeferredSuperFailure(node.Fqn(), node.SuperRef, node)); + failures.Add(new DeferredSuperFailure(node.Fqn(), node.SuperRef, node, + MemberHint: DottedMemberHint(node, effectivePkg))); } } + // rc.21 (U1): a dotted ref whose OWNER resolves but whose member does not names the + // owner's members of the referrer's type, inherited ones included — the usual cause is an + // identity spelled by its field (`Owner.id`) where the identity is named otherwise (an + // unnamed identity.primary is "primary"). Without it the only hint was the same-named + // object's FQN, which is wrong advice when the owner was found. + string? DottedMemberHint(MetaData node, string pkg) + { + if (!IsChildTargetingRef(node.SuperRef!) || ParseChildTargetingRef(node.SuperRef!) is not { } parsed) return null; + if (TryResolve(parsed.OwnerRef, pkg) is not MetaData current) return null; + foreach (var seg in parsed.Path[..^1]) + { + var matches = current.Children().Where(c => c.Name == seg).ToList(); + if (matches.Count != 1) return null; + current = matches[0]; + } + var last = parsed.Path[^1]; + // ADR-0039: resolving — an inherited member is a legal target. + var candidates = current.Children().Where(c => c.Type == node.Type).ToList(); + var owner = current is MetaObject ? current.ResolutionKey() : current.Fqn(); + var listed = candidates.Count == 0 + ? $"it has no {node.Type} children" + : $"its {node.Type} children are: {string.Join(", ", candidates.Select(c => $"\"{c.Name}\" ({c.Type}.{c.SubType})"))}"; + // The default name of an unnamed identity.primary is its subtype (the registry's defaultName). + var unnamed = node.Type == BaseTypes.TYPE_IDENTITY && candidates.Any(c => c.Name == IdentityConstants.IDENTITY_SUBTYPE_PRIMARY) + ? $" An {BaseTypes.TYPE_IDENTITY}.{IdentityConstants.IDENTITY_SUBTYPE_PRIMARY} declared without a name is named \"{IdentityConstants.IDENTITY_SUBTYPE_PRIMARY}\"." + : ""; + return $" '{owner}' has no {node.Type} named \"{last}\"; {listed}.{unnamed}"; + } + foreach (var node in pending) ResolveNode(node); return failures.AsReadOnly(); } diff --git a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt index e307a00419..3229e37335 100644 --- a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt +++ b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt @@ -35,7 +35,7 @@ import kotlin.test.assertTrue * Generates the FULL shared fitness corpus (not a trimmed selection) with * `exposedApi=1`, using every generator a real build would wire alongside the controller * (Entity, ExposedTable, Names, Relations, FilterAllowlist, Validator, SpringController) so the - * corpus's TPH hierarchy (Auth/Bridge/Copay/PriorAuth/Referral — exercises `emitTph`), its M:N + * corpus's TPH hierarchy (Auth/Bridge/Coupon/Permit/Referral — exercises `emitTph`), its M:N * associations (tags/referrals/following/friends — exercises `emitM2mEndpoint` + * `KotlinRelationsGenerator`'s M:N join helpers), its view projections (exercises * `emitReadOnly`), and its mixed scalar subtypes (string/enum/int-backed-enum/boolean/numeric/ diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 99ebd08d80..4763bf2444 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -2739,11 +2739,23 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase $simple.valueOf(v as String) }, { e -> e.name })" + if (intMap == null) { + // rc.21: a @stringValueMap enum holds each member's stored string — a VARCHAR + // customEnumeration with the member <-> stored-string mapping inlined, as below. + val length = KotlinTypeMapper.enumVarcharLength(field) + val stored = readStringValueMap(field) + ?: return length?.let { "enumerationByName($colExpr, $it, $simple::class)" } + // No length configured: `meta migrate` creates `text`, and `enumerationByName` + // needs a length, so store the member name over a TEXT column instead. + ?: "customEnumeration($colExpr, \"TEXT\", { v -> $simple.valueOf(v as String) }, { e -> e.name })" + val fromDb = stored.entries.joinToString("; ") { (sym, s) -> "${kotlinString(s)} -> $simple.$sym" } + val toDb = stored.entries.joinToString("; ") { (sym, s) -> "$simple.$sym -> ${kotlinString(s)}" } + val sqlType = if (length == null) "TEXT" else "VARCHAR($length)" + return "customEnumeration($colExpr, \"$sqlType\", " + + "{ v -> when (v as String) { $fromDb; " + + "else -> error(\"unmapped stored value \$v for $simple\") } }, " + + "{ e -> when (e) { $toDb } })" + } // `; ` separates the branches: this is a one-line `when`, and space-separated // branches do not parse (`Foo.DRAFT 5 -> ...`). @@ -2759,6 +2771,25 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase when (e) { $toDb } })" } + private fun kotlinString(text: String): String = + "\"" + KotlinGenUtil.kotlinStringLiteral(text) + "\"" + + /** rc.21 — the declared member→stored-string map (`@stringValueMap`, resolving), or null. */ + private fun readStringValueMap(field: EnumField): Map? { + if (!field.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null + val raw = runCatching { field.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).value }.getOrNull() + val m = (raw as? Map<*, *>) ?: return null + // In @values order, so the emitted `when` is deterministic (a Properties map is unordered). + val out = LinkedHashMap() + val members = (runCatching { field.getMetaAttr(EnumField.ATTR_VALUES).value }.getOrNull() as? List<*>) + ?.map { it.toString() } ?: emptyList() + for (member in members) { + val s = m[member] as? String ?: continue + out[member] = s + } + return out.ifEmpty { null } + } + /** The declared symbol→int map (`@intValueMap`), or null when the enum is string-backed. */ private fun readIntValueMap(field: EnumField): Map? { if (!field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt index d45460a02f..e27534e9ae 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt @@ -34,7 +34,7 @@ object KotlinM2mSupport { /** * FW-3 — the target of an M:N is a TPH subtype: its rows live in the discriminator base's * shared table, so a stage-2 select against that table must be narrowed back to just this - * subtype's rows, or a sibling subtype's row (e.g. a Copay reached through `Auth`'s shared + * subtype's rows, or a sibling subtype's row (e.g. a Coupon reached through `Auth`'s shared * table) comes back tagged as this one. * * @property column the discriminator field's physical column name (on the STORAGE object) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt index 3382b012b6..166c19f788 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt @@ -245,7 +245,7 @@ open class KotlinNamesGenerator : } // Inherited constants, re-exported by REFERENCE — the literal is spelled once, // on the base. `const val` folds the reference at compile time, so a consumer - // reading `CopayAuthNames.ID_COLUMN` is unaffected by which object declared it. + // reading `CouponAuthNames.ID_COLUMN` is unaffected by which object declared it. // A TPH subtype's SOURCE members arrive here for the same reason its inherited // columns do: it declares no source of its own, so the own set has none. if (inherited.isNotEmpty()) append("\n") diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index 2fbe752b15..45203ad6e0 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -904,7 +904,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseValidation shape // is built from, so the create/PATCH validated set never drifts from the annotated class. This - // is per-subtype so a PriorAuth patch never touches a Bridge-only column. + // is per-subtype so a Permit patch never touches a Bridge-only column. fun subtypePatchFields(st: KotlinTphPlan.Subtype) = KotlinTphPlan.subtypeSettableFields(st.entity) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt index 05d62eb586..321d11ef05 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt @@ -410,6 +410,14 @@ object KotlinTypeMapper { else -> null } + /** rc.21 part B: the Exposed column for a text `@dbColumnType` spelling, or null for none. */ + private fun textSpellingColumn(value: String?, colExpr: String): String? { + if (value == null) return null + if (value == "text" || value == "varchar" || value == "character varying") return "text($colExpr)" + val m = Regex("^(varchar|character varying|character)\\(([1-9][0-9]{0,8})\\)$").matchEntire(value) ?: return null + return if (m.groupValues[1] == "character") "char($colExpr, ${m.groupValues[2]})" else "varchar($colExpr, ${m.groupValues[2]})" + } + /** * Map a MetaField to the Exposed `Table` column statement (e.g., `varchar("name", 100)`). * @@ -531,7 +539,10 @@ object KotlinTypeMapper { // (the `{ it }` identity codec would have left it `Column`). The table file // imports `kotlinx.serialization.json.Json` (see KotlinExposedTableGenerator). DB_COLUMN_TYPE_JSONB -> "jsonb($colExpr, { it.toString() }, { Json.parseToJsonElement(it) })" - else -> { + // rc.21 part B (fix round M6): the text spellings. `character(n)` is Exposed's + // `char(name, n)`, a sized varchar `varchar(name, n)`; an unbounded varchar or `text` + // is `text(name)` (Exposed has no unbounded varchar; Postgres treats them alike). + else -> textSpellingColumn(dbColumnType(field), colExpr) ?: run { // Dispatch to Exposed `text(name)` when the field is unbounded text: // (1) no `@maxLength` declared — the DEFAULT for `field.string` (Phase 1: // no-maxLength string → `text`, matching the canonical TS Postgres DDL), OR diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt index 9818a9f7a5..c2abf1c3db 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt @@ -42,16 +42,16 @@ class KotlinApiDocsSourceSelectionKtTest { const val PROJECT = "apidocs-source-selection" } - // PhaseSummary declares its @role:replica VIEW source FIRST and its @role:primary + // StageSummary declares its @role:replica VIEW source FIRST and its @role:primary // STORED-PROC source SECOND. Both are read-only kinds, so nothing about the shape is // exotic beyond the declaration order, and it loads with zero errors. private val fixture = """{ "metadata.root": { "package": "acme::demo", "children": [ - { "object.projection": { "name": "PhaseSummary", "children": [ + { "object.projection": { "name": "StageSummary", "children": [ { "source.rdb": { "name": "replicaView", "@kind": "view", - "@table": "v_phase_summary", "@role": "replica" } }, + "@table": "v_stage_summary", "@role": "replica" } }, { "source.rdb": { "name": "primaryProc", "@kind": "storedProc", - "@proc": "fn_phase_summary", "@role": "primary" } }, + "@proc": "fn_stage_summary", "@role": "primary" } }, { "field.int": { "name": "id" } }, { "field.string": { "name": "label" } } ] } } @@ -95,7 +95,7 @@ class KotlinApiDocsSourceSelectionKtTest { @Test fun twoDistinctlyNamedSourcesBothSurviveOnChildren() { - val obj = loader.metaObjects.single { it.name.endsWith("::PhaseSummary") } + val obj = loader.metaObjects.single { it.name.endsWith("::StageSummary") } val sources = obj.getChildren(RdbSource::class.java, true) assertEquals( listOf("primaryProc", "replicaView"), @@ -109,11 +109,11 @@ class KotlinApiDocsSourceSelectionKtTest { // Ground truth: what the real generators actually wrote. Both select by role, so // the primary storedProc wins and the replica view contributes nothing. assertTrue( - Files.exists(outDir.resolve("acme/demo/PhaseSummaryProc.kt")), - "expected PhaseSummaryProc.kt; files=${Files.walk(outDir).toList()}", + Files.exists(outDir.resolve("acme/demo/StageSummaryProc.kt")), + "expected StageSummaryProc.kt; files=${Files.walk(outDir).toList()}", ) assertFalse( - Files.exists(outDir.resolve("acme/demo/PhaseSummaryTable.kt")), + Files.exists(outDir.resolve("acme/demo/StageSummaryTable.kt")), "the primary source is a storedProc, so no Exposed table object is emitted", ) } @@ -121,22 +121,22 @@ class KotlinApiDocsSourceSelectionKtTest { @Test fun theDocumentedDataAccessSymbolIsTheOneTheGeneratorsEmit() { val model = KotlinApiModelBuilder(com.metaobjects.generator.kotlin.Fr019SharedEnum.ProvidedEnumConfig.fromArgs(null)).build(loader, PROJECT) - val unit = model.units.single { it.node.endsWith("PhaseSummary") } + val unit = model.units.single { it.node.endsWith("StageSummary") } val dataAccess = unit.symbols.filter { it.kind == ApiSymbolKind.DATA_ACCESS } assertEquals( - listOf("PhaseSummaryProc"), + listOf("StageSummaryProc"), dataAccess.map { it.name }, "the docs must name the symbol the role-scoped generators emit, not the one the " + "first-DECLARED source would suggest", ) // ...and the symbol it names is really in the generated source. assertTrue( - "object PhaseSummaryProc" in allGenerated, + "object StageSummaryProc" in allGenerated, "the documented data-access symbol must exist in the generated Kotlin", ) assertFalse( - "PhaseSummaryTable" in allGenerated, + "StageSummaryTable" in allGenerated, "guards the inverse: the wrongly-documented symbol is emitted by nothing", ) } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt new file mode 100644 index 0000000000..daff2c6c7a --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt @@ -0,0 +1,61 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.metadata.ktx.loadDirectory +import com.tschuchort.compiletesting.KotlinCompilation +import com.tschuchort.compiletesting.SourceFile +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.isRegularFile +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * rc.21 — a string-stored `field.enum` with `@stringValueMap` on the Exposed table generator: a + * VARCHAR `customEnumeration` mapping member <-> stored string in both directions, compiled + * against the real Exposed API. + */ +@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class) +class KotlinExposedTableStringValueMapEnumTest { + + private val models: Path = run { + var p: Path? = Path.of(System.getProperty("user.dir")).toAbsolutePath() + while (p != null && !Files.exists(p.resolve("src/test/resources/models"))) { + p = p.parent + } + assertTrue(p != null, "could not locate src/test/resources/models from user.dir") + p!!.resolve("src/test/resources/models") + } + + private fun compile(outDir: Path): KotlinCompilation.Result { + val sources = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() + .map { path -> SourceFile.kotlin(path.parent.relativize(path).toString().replace('/', '_'), path.readText()) } + return KotlinCompilation().apply { + this.sources = sources + inheritClassPath = true + messageOutputStream = System.out + }.compile() + } + + @Test fun `stringValueMap enum emits customEnumeration over VARCHAR and still compiles`() { + val outDir = Files.createTempDirectory("ktbl-stored-enum-") + try { + val loader = loadDirectory("enum-string-value-map", models.resolve("enum-string-value-map")) + for (gen in listOf(KotlinEntityGenerator(), KotlinExposedTableGenerator())) { + gen.setArgs(mapOf("outputDir" to outDir.toString())) + gen.execute(loader) + } + val src = outDir.resolve("acme/shop/ArticleTable.kt").readText() + // No `enums.maxLength` configured: `meta migrate` creates `text`, so the column is TEXT. + assertTrue("customEnumeration(\"status\", \"TEXT\"" in src, + "status must use customEnumeration over TEXT; saw:\n$src") + assertTrue("\"draft\" -> ArticleStatus.Draft" in src && "ArticleStatus.Published -> \"published\"" in src, + "both lambdas must carry the stored strings; saw:\n$src") + val result = compile(outDir) + assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, result.messages) + } finally { + outDir.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt index 8e4747eb6a..dd8fc00851 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt @@ -18,7 +18,7 @@ import kotlin.test.assertNull */ class KotlinM2mSupportAbstractMidLevelTargetTest { - /** `Party` (`@discriminator`) -> abstract `Auth` (mid-level, no @discriminatorValue) -> {BridgeAuth, CopayAuth}. */ + /** `Party` (`@discriminator`) -> abstract `Auth` (mid-level, no @discriminatorValue) -> {BridgeAuth, CouponAuth}. */ private val abstractMidLevelFixture = """{ "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Party", "children": [ @@ -31,14 +31,14 @@ class KotlinM2mSupportAbstractMidLevelTargetTest { { "object.entity": { "name": "Auth", "abstract": true, "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "PartyAuth", "children": [ { "source.rdb": { "@table": "party_auths" } }, diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt index a1417eb49a..7b5fc9b9d4 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt @@ -434,26 +434,26 @@ class KotlinNamesGeneratorTest { { "object.entity": { "name": "Auth", "@discriminator": "kind", "children": [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "@fields": ["id"], "@generation": "increment" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "zz_copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "zz_coupon_cents" } } ] } } ] } }""".trimIndent() - val src = emit(model).getValue("acme/CopayAuthNames.kt") + val src = emit(model).getValue("acme/CouponAuthNames.kt") // The subtype declares no source of its own, so every SOURCE_* member lands in the // inherited half and is re-exported by reference from the base. No `inheritsSource` // flag decides that — the own-source map is simply empty, which is the same // structural question answered by the accessor that had to be consulted anyway. assertTrue("const val SOURCE_PRIMARY_TABLE: String = AuthNames.SOURCE_PRIMARY_TABLE" in src, src) assertTrue("const val ID_COLUMN: String = AuthNames.ID_COLUMN" in src, src) - assertTrue("const val COPAY_AMOUNT_COLUMN: String = \"zz_copay_cents\"" in src, src) + assertTrue("const val COUPON_AMOUNT_COLUMN: String = \"zz_coupon_cents\"" in src, src) // ...while its OWN identity is restated, because it differs: `NAME` is the object's - // metamodel name, so the subtype's must say "CopayAuth", not the base's. - assertTrue("const val NAME: String = \"CopayAuth\"" in src, src) + // metamodel name, so the subtype's must say "CouponAuth", not the base's. + assertTrue("const val NAME: String = \"CouponAuth\"" in src, src) // The whole point: the subtype used to restate the base's table name and columns. assertFalse("zz_auths" in src, src) } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt index 472a946aba..eedc4ad991 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt @@ -55,7 +55,7 @@ class KotlinOutputCompilesTest { ] } }""".trimIndent() - // FR-017 TPH regression guard: a subtype's OWN field.enum (CopayAuth.tier) folds into the base + // FR-017 TPH regression guard: a subtype's OWN field.enum (CouponAuth.tier) folds into the base // Auth union data class, so the base must emit that enum class (owner = base) — else the union // references a type no generated file defines. The subtypes themselves emit nothing. private val tphSubtypeEnumFixture = """{ @@ -63,13 +63,13 @@ class KotlinOutputCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ { "field.enum": { "name": "tier", "@values": ["Standard", "Premium"] } } ] } } ] } @@ -87,15 +87,15 @@ class KotlinOutputCompilesTest { // The base emits the union + the discriminator enum + the folded subtype enum; the // subtypes emit NO entity data class or enum of their own (they fold into the base). assertTrue("AuthTier.kt" in names, - "the folded subtype enum (CopayAuth.tier) must be emitted by the base; got $names") - assertFalse("BridgeAuth.kt" in names || "CopayAuth.kt" in names, + "the folded subtype enum (CouponAuth.tier) must be emitted by the base; got $names") + assertFalse("BridgeAuth.kt" in names || "CouponAuth.kt" in names, "TPH subtypes must emit no entity data class of their own; got $names") - assertFalse("BridgeAuthTier.kt" in names || "CopayAuthTier.kt" in names, + assertFalse("BridgeAuthTier.kt" in names || "CouponAuthTier.kt" in names, "a subtype must not re-emit a folded enum under its own name; got $names") // FR-036: each concrete subtype DOES emit a validation-only Validation shape (the // base controller validates per-subtype POST/PATCH present values against it) — BridgeAuth - // has a @required `quantity`, CopayAuth an unconstrained enum `tier`. - assertTrue("BridgeAuthValidation.kt" in names && "CopayAuthValidation.kt" in names, + // has a @required `quantity`, CouponAuth an unconstrained enum `tier`. + assertTrue("BridgeAuthValidation.kt" in names && "CouponAuthValidation.kt" in names, "each concrete TPH subtype must emit its annotated Validation shape; got $names") val result = KotlinCompilation().apply { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt new file mode 100644 index 0000000000..117565d451 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt @@ -0,0 +1,89 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.metadata.ktx.loadString +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * A generated create route writes only what a client may set: a server-generated key, a `readOnly` + * column and (TPH) the discriminator and a sibling subtype's column are never bound from the body + * (1.2.x security patch). Behaviour is gated by the api-contract `input-server-owned-dropped` + * scenarios; this pins the generated source, including the TPH subtype `readOnly` case. + */ +class KotlinServerOwnedInputTest { + + private val plain = """{ + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Doc", "children": [ + { "source.rdb": { "@table": "docs" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@maxLength": 100 } }, + { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ] } } + ] } + }""".trimIndent() + + private val tph = """{ + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Permit"] } }, + { "field.string": { "name": "reference", "@maxLength": 80 } }, + { "field.string": { "name": "grade", "@maxLength": 20, "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity" } } + ] } }, + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ + { "field.string": { "name": "approver", "@maxLength": 80 } } + ] } } + ] } + }""".trimIndent() + + private fun gen(name: String, json: String): java.nio.file.Path { + val out = Files.createTempDirectory("kowned-") + val loader = loadString(name, json) + KotlinEntityGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader) + KotlinSpringControllerGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader) + return out + } + + @Test + fun `plain create writes neither the generated key nor a readOnly column`() { + val out = gen("owned-plain", plain) + try { + val controller = Files.readString(out.resolve("acme/own/DocController.kt")) + val create = controller.substringAfter("fun create(").substringBefore("fun update(") + assertTrue("it[DocTable.title] = dto.title" in create, create) + assertFalse("it[DocTable.role]" in create, create) + assertFalse("it[DocTable.id] = dto.id" in create, create) + } finally { + out.toFile().deleteRecursively() + } + } + + @Test + fun `TPH create writes only the route subtype's own settable columns`() { + val out = gen("owned-tph", tph) + try { + val controller = Files.readString(out.resolve("acme/own/AuthController.kt")) + val bridge = controller.substringAfter("fun createBridge(").substringBefore("@RequestMapping") + val permit = controller.substringAfter("fun createPermit(").substringBefore("@RequestMapping") + assertTrue("it[AuthTable.reference] = dto.reference" in bridge, bridge) + assertTrue("it[AuthTable.quantity] = dto.quantity" in bridge, bridge) + assertFalse("it[AuthTable.approver]" in bridge, bridge) + assertFalse("it[AuthTable.grade]" in bridge, bridge) + assertFalse("it[AuthTable.type] = dto.type" in bridge, bridge) + assertTrue("it[AuthTable.approver] = dto.approver" in permit, permit) + assertFalse("it[AuthTable.quantity]" in permit, permit) + assertFalse("it[AuthTable.grade]" in permit, permit) + } finally { + out.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt index 2ff2b1bf99..8d0277c9a0 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt @@ -32,7 +32,7 @@ class KotlinTphM2mCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -43,8 +43,8 @@ class KotlinTphM2mCodegenTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -112,9 +112,9 @@ class KotlinTphM2mCodegenTest { assertTrue("@GetMapping(\"/bridge/{id}/tags\")" in src, "expected /bridge/{id}/tags; saw:\n$src") assertTrue("fun tagsBridge(@PathVariable id: Long): ResponseEntity>" in src, "expected tagsBridge() handler; saw:\n$src") - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in src, "expected /copay/{id}/tags; saw:\n$src") - assertTrue("fun tagsCopay(@PathVariable id: Long): ResponseEntity>" in src, - "expected tagsCopay() handler; saw:\n$src") + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in src, "expected /coupon/{id}/tags; saw:\n$src") + assertTrue("fun tagsCoupon(@PathVariable id: Long): ResponseEntity>" in src, + "expected tagsCoupon() handler; saw:\n$src") // Rule (c): Stage 0 verifies the source id names a row of THIS subtype before the SAME // AuthTable.tagsQuery(id) helper the base mount uses — a sibling's id must return []. assertTrue( @@ -138,9 +138,9 @@ class KotlinTphM2mCodegenTest { assertTrue("fun linkedAuthsBridge(@PathVariable id: Long): ResponseEntity>" in src, "expected linkedAuthsBridge() returning List (the storage/union type); saw:\n$src") assertFalse("List" in src, "BridgeAuth has no data class to reference; saw:\n$src") - // linkedAuths is declared on BridgeAuth only — Copay never resolves it. - assertFalse("/copay/{id}/linkedAuths" in src, "Copay must not mount linkedAuths; saw:\n$src") - assertFalse("linkedAuthsCopay" in src, "Copay must not get a linkedAuths handler; saw:\n$src") + // linkedAuths is declared on BridgeAuth only — Coupon never resolves it. + assertFalse("/coupon/{id}/linkedAuths" in src, "Coupon must not mount linkedAuths; saw:\n$src") + assertFalse("linkedAuthsCoupon" in src, "Coupon must not get a linkedAuths handler; saw:\n$src") } @Test fun subtypeOwnRelationTargetingASubtypeBindsToTheStorageTableAndFiltersByDiscriminator() { @@ -171,6 +171,6 @@ class KotlinTphM2mCodegenTest { val src = controller() assertTrue("@RequestMapping(\"/api/auths\")" in src) assertTrue("@GetMapping(\"/bridge\")" in src) - assertTrue("@GetMapping(\"/copay\")" in src) + assertTrue("@GetMapping(\"/coupon\")" in src) } } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt index 59fd54b74d..d339dd1d2b 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt @@ -21,13 +21,13 @@ import kotlin.test.assertTrue * so pre-fix the generated code COMPILES (every reference is a statically valid `Column`, * regardless of which query actually produced the `ResultRow`) but the per-subtype endpoint * calls the WRONG-target shared helper: `AuthTable.tagsQuery(id)` returns rows joined against - * `Tag`/`AuthTag`, then the Copay-scoped endpoint tries to read `SpecialTagTable.*` columns off + * `Tag`/`AuthTag`, then the Coupon-scoped endpoint tries to read `SpecialTagTable.*` columns off * those rows — a `ResultRow` access that is well-typed but throws at RUNTIME (the column was * never selected), or silently maps unrelated data. * * Model: `Auth` (base, `@discriminator: type`) declares a hetero M:N `tags -> Tag` through - * `AuthTag` (resolved unchanged by `BridgeAuth`). `CopayAuth` SHADOWS `tags`, redeclaring it as - * `tags -> SpecialTag` through `CopaySpecialTag` — same relation NAME, genuinely different + * `AuthTag` (resolved unchanged by `BridgeAuth`). `CouponAuth` SHADOWS `tags`, redeclaring it as + * `tags -> SpecialTag` through `CouponSpecialTag` — same relation NAME, genuinely different * target + junction. */ class KotlinTphM2mShadowedCodegenTest { @@ -37,7 +37,7 @@ class KotlinTphM2mShadowedCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -46,10 +46,10 @@ class KotlinTphM2mShadowedCodegenTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", - "@objectRef": "SpecialTag", "@through": "CopaySpecialTag" } } + "@objectRef": "SpecialTag", "@through": "CouponSpecialTag" } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -71,12 +71,12 @@ class KotlinTphM2mShadowedCodegenTest { { "identity.reference": { "name": "fkAuth", "@fields": "authId", "@references": "Auth" } }, { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } ] } }, - { "object.entity": { "name": "CopaySpecialTag", "children": [ - { "source.rdb": { "@table": "copay_special_tags" } }, - { "field.long": { "name": "copayAuthId", "@required": true } }, + { "object.entity": { "name": "CouponSpecialTag", "children": [ + { "source.rdb": { "@table": "coupon_special_tags" } }, + { "field.long": { "name": "couponAuthId", "@required": true } }, { "field.long": { "name": "specialTagId", "@required": true } }, - { "identity.primary": { "@fields": ["copayAuthId", "specialTagId"] } }, - { "identity.reference": { "name": "fkCopay", "@fields": "copayAuthId", "@references": "CopayAuth" } }, + { "identity.primary": { "@fields": ["couponAuthId", "specialTagId"] } }, + { "identity.reference": { "name": "fkCoupon", "@fields": "couponAuthId", "@references": "CouponAuth" } }, { "identity.reference": { "name": "fkSpecialTag", "@fields": "specialTagId", "@references": "SpecialTag" } } ] } } ] } @@ -119,8 +119,8 @@ class KotlinTphM2mShadowedCodegenTest { @Test fun shadowingSubtypeShapeGetsItsOwnDistinctHelper() { val src = relations() - // The shadowing CopayAuth->SpecialTag shape must NOT collapse into tagsQuery — it needs - // its own helper, joining SpecialTagTable/CopaySpecialTagTable, not TagTable/AuthTagTable. + // The shadowing CouponAuth->SpecialTag shape must NOT collapse into tagsQuery — it needs + // its own helper, joining SpecialTagTable/CouponSpecialTagTable, not TagTable/AuthTagTable. assertFalse( src.contains(Regex("""fun AuthTable\.tagsQuery\([^)]*\): Query =\s*\n\s*SpecialTagTable""")), "the shared tagsQuery helper must not join SpecialTagTable; saw:\n$src", @@ -134,34 +134,34 @@ class KotlinTphM2mShadowedCodegenTest { val shadowName = distinctHelpers.first { it != "tags" } val shadowFn = src.substringAfter("fun AuthTable.${shadowName}Query").substringBefore("\n\n") assertTrue("SpecialTagTable" in shadowFn, "expected the shadow helper to join SpecialTagTable; saw:\n$shadowFn") - assertTrue("CopaySpecialTagTable" in shadowFn, "expected the shadow helper to join CopaySpecialTagTable; saw:\n$shadowFn") + assertTrue("CouponSpecialTagTable" in shadowFn, "expected the shadow helper to join CouponSpecialTagTable; saw:\n$shadowFn") assertFalse( "AuthTagTable" in shadowFn, "the shadow helper must not join the BASE shape's junction (AuthTagTable); saw:\n$shadowFn", ) } - // --- controller: the Copay-scoped mount must call ITS OWN helper, not the base's ----- + // --- controller: the Coupon-scoped mount must call ITS OWN helper, not the base's ----- - @Test fun copayScopedMountReturnsSpecialTagAndCallsItsOwnHelper() { + @Test fun couponScopedMountReturnsSpecialTagAndCallsItsOwnHelper() { val src = controller() - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in src, "expected /copay/{id}/tags; saw:\n$src") - assertTrue("fun tagsCopay(@PathVariable id: Long): ResponseEntity>" in src, - "expected tagsCopay() to return List (already correct pre-fix); saw:\n$src") + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in src, "expected /coupon/{id}/tags; saw:\n$src") + assertTrue("fun tagsCoupon(@PathVariable id: Long): ResponseEntity>" in src, + "expected tagsCoupon() to return List (already correct pre-fix); saw:\n$src") - val tagsCopayBody = src.substringAfter("fun tagsCopay(").substringBefore("\n }\n") + val tagsCouponBody = src.substringAfter("fun tagsCoupon(").substringBefore("\n }\n") - // THE regression this fix targets: tagsCopay() must NOT delegate to the base/Bridge + // THE regression this fix targets: tagsCoupon() must NOT delegate to the base/Bridge // shape's AuthTable.tagsQuery(id) helper — that helper joins Tag/AuthTag, not - // SpecialTag/CopaySpecialTag, so reading SpecialTagTable columns off its rows throws + // SpecialTag/CouponSpecialTag, so reading SpecialTagTable columns off its rows throws // at runtime (a well-typed but empty-record-set ResultRow access). - assertFalse("AuthTable.tagsQuery(id)" in tagsCopayBody, - "tagsCopay() must not call the base-shape tagsQuery helper (wrong target/junction); saw:\n$tagsCopayBody") - assertTrue(Regex("""AuthTable\.tags\w+Query\(id\)""").containsMatchIn(tagsCopayBody), - "expected tagsCopay() to call its OWN disambiguated helper; saw:\n$tagsCopayBody") + assertFalse("AuthTable.tagsQuery(id)" in tagsCouponBody, + "tagsCoupon() must not call the base-shape tagsQuery helper (wrong target/junction); saw:\n$tagsCouponBody") + assertTrue(Regex("""AuthTable\.tags\w+Query\(id\)""").containsMatchIn(tagsCouponBody), + "expected tagsCoupon() to call its OWN disambiguated helper; saw:\n$tagsCouponBody") // And the row-mapping columns (already correct pre-fix) must be SpecialTagTable's. - assertTrue("row[SpecialTagTable." in tagsCopayBody, "expected row mapping off SpecialTagTable; saw:\n$tagsCopayBody") + assertTrue("row[SpecialTagTable." in tagsCouponBody, "expected row mapping off SpecialTagTable; saw:\n$tagsCouponBody") } @Test fun bridgeScopedMountIsUnaffectedByTheShadow() { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt index 236b75f7c3..452e2d5b49 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt @@ -336,6 +336,21 @@ class KotlinTypeMapperTest { assertEquals(STRING, KotlinTypeMapper.payloadTypeName(f)) } + @Test fun `string field with a text dbColumnType spelling emits that column`() { + // rc.21 part B (fix round M6): character(n), varchar(n), and an unbounded varchar or text. + for ((spelling, expected) in listOf( + "character(3)" to "char(\"code\", 3)", + "varchar(20)" to "varchar(\"code\", 20)", + "character varying(20)" to "varchar(\"code\", 20)", + "varchar" to "text(\"code\")", + "text" to "text(\"code\")", + )) { + val f = StringField("code") + f.addMetaAttr(StringAttribute.create("dbColumnType", spelling)) + assertEquals(expected, KotlinTypeMapper.exposedColumnSpec(f), spelling) + } + } + @Test fun `string field with dbColumnType=jsonb is case-insensitive`() { // `@dbColumnType` lookup case-folds (see `KotlinTypeMapper.dbColumnType`); both // `"JSONB"` and `"jsonb"` route to the JSONB branch. diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt index d348c13167..0e45df38f2 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt @@ -86,7 +86,7 @@ class KotlinUuidPrimaryKeyCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.uuid": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "@fields": "id", "@generation": "uuid" } } ] } }, @@ -94,9 +94,9 @@ class KotlinUuidPrimaryKeyCodegenTest { "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", - "@discriminatorValue": "Copay", "children": [ - { "field.string": { "name": "copayCode", "@maxLength": 40 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", + "@discriminatorValue": "Coupon", "children": [ + { "field.string": { "name": "couponCode", "@maxLength": 40 } } ] } } ] } }""".trimIndent() @@ -176,8 +176,8 @@ class KotlinUuidPrimaryKeyCodegenTest { "expected per-subtype getBridge(@PathVariable id: UUID); saw:\n$src") assertTrue("fun updateBridge(@PathVariable id: UUID," in src, "expected per-subtype updateBridge(@PathVariable id: UUID, ...); saw:\n$src") - assertTrue("fun deleteCopay(@PathVariable id: UUID)" in src, - "expected per-subtype deleteCopay(@PathVariable id: UUID); saw:\n$src") + assertTrue("fun deleteCoupon(@PathVariable id: UUID)" in src, + "expected per-subtype deleteCoupon(@PathVariable id: UUID); saw:\n$src") assertTrue("import java.util.UUID" in src, "expected import java.util.UUID; saw:\n$src") assertTrue("@PathVariable id: Long" !in src, diff --git a/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt b/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt index c207c43b62..d33e03f21f 100644 --- a/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt +++ b/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt @@ -712,7 +712,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseValidation shape // is built from, so the create/PATCH validated set never drifts from the annotated class. This - // is per-subtype so a PriorAuth patch never touches a Bridge-only column. + // is per-subtype so a Permit patch never touches a Bridge-only column. fun subtypePatchFields(st: KotlinTphPlan.Subtype) = KotlinTphPlan.subtypeSettableFields(st.entity) diff --git a/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json b/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json index 67ce6a00f9..6045a66275 100644 --- a/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json +++ b/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true, "@sortableDefaultOrder": "desc" } }, { "relationship.composition": { "name": "lines", "@cardinality": "many", "@objectRef": "AuthLine", "@onDelete": "cascade" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } @@ -23,19 +23,19 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ - { "field.string": { "name": "priorAuthNumber", "@maxLength": 80, "@filterable": true, "@sortable": true } } + { "field.string": { "name": "permitNumber", "@maxLength": 80, "@filterable": true, "@sortable": true } } ] }}, { "object.entity": { diff --git a/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json new file mode 100644 index 0000000000..5284bc6315 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Article", + "children": [ + { "source.rdb": { "name": "src", "@table": "articles", "@kind": "table" } }, + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } + } + }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + } + } + ] + } +} diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt index 451b2d787c..2e701e4ede 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt @@ -18,8 +18,8 @@ public data class Auth( public val reference: String? = null, public val quantity: Int? = null, @param:JsonDeserialize(using = MetaDecimalWire.Deserializer::class) - public val copayAmount: BigDecimal? = null, - public val priorAuthNumber: String? = null, + public val couponAmount: BigDecimal? = null, + public val permitNumber: String? = null, ) { /** * Fluent builder — lets a JAVA caller set a subset of properties. @@ -33,9 +33,9 @@ public data class Auth( private var quantity: Int? = null - private var copayAmount: BigDecimal? = null + private var couponAmount: BigDecimal? = null - private var priorAuthNumber: String? = null + private var permitNumber: String? = null public fun id(v: Long?): Builder { this.id = v @@ -57,13 +57,13 @@ public data class Auth( return this } - public fun copayAmount(v: BigDecimal?): Builder { - this.copayAmount = v + public fun couponAmount(v: BigDecimal?): Builder { + this.couponAmount = v return this } - public fun priorAuthNumber(v: String?): Builder { - this.priorAuthNumber = v + public fun permitNumber(v: String?): Builder { + this.permitNumber = v return this } @@ -72,8 +72,8 @@ public data class Auth( type = type, reference = reference, quantity = quantity, - copayAmount = copayAmount, - priorAuthNumber = priorAuthNumber + couponAmount = couponAmount, + permitNumber = permitNumber ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt index 32593e805e..c713e990e2 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt @@ -51,7 +51,7 @@ private val AuthSortDefaultOrder: Map = mapOf( ) /** GENERATED — every field Auth declares, as named on the wire: a body key outside it is refused. */ -private val AuthKnownFields: Set = setOf("id", "type", "reference", "quantity", "copayAmount", "priorAuthNumber") +private val AuthKnownFields: Set = setOf("id", "type", "reference", "quantity", "couponAmount", "permitNumber") private fun parseAuthSort(raw: String): Pair? { val parts = raw.split(":", limit = 2) @@ -159,8 +159,8 @@ private fun coerceAuthValue(field: String, op: String, raw: String): AuthCoerced "type" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) "reference" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) "quantity" -> coerceAuthInt(op, raw) - "copayAmount" -> coerceAuthDecimal(op, raw) - "priorAuthNumber" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) + "couponAmount" -> coerceAuthDecimal(op, raw) + "permitNumber" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) else -> null } } @@ -298,24 +298,24 @@ private fun AuthWhereOp(predicates: List): Op? { "isNull" -> if (p.value as Boolean) AuthTable.quantity.isNull() else AuthTable.quantity.isNotNull() else -> throw IllegalStateException("unsupported op for quantity: " + p.op) } - "copayAmount" -> when (p.op) { - "eq" -> AuthTable.copayAmount eq (p.value as BigDecimal) - "ne" -> AuthTable.copayAmount neq (p.value as BigDecimal) - "gt" -> AuthTable.copayAmount greater (p.value as BigDecimal) - "gte" -> AuthTable.copayAmount greaterEq (p.value as BigDecimal) - "lt" -> AuthTable.copayAmount less (p.value as BigDecimal) - "lte" -> AuthTable.copayAmount lessEq (p.value as BigDecimal) - "in" -> AuthTable.copayAmount inList (p.value as List) - "isNull" -> if (p.value as Boolean) AuthTable.copayAmount.isNull() else AuthTable.copayAmount.isNotNull() - else -> throw IllegalStateException("unsupported op for copayAmount: " + p.op) + "couponAmount" -> when (p.op) { + "eq" -> AuthTable.couponAmount eq (p.value as BigDecimal) + "ne" -> AuthTable.couponAmount neq (p.value as BigDecimal) + "gt" -> AuthTable.couponAmount greater (p.value as BigDecimal) + "gte" -> AuthTable.couponAmount greaterEq (p.value as BigDecimal) + "lt" -> AuthTable.couponAmount less (p.value as BigDecimal) + "lte" -> AuthTable.couponAmount lessEq (p.value as BigDecimal) + "in" -> AuthTable.couponAmount inList (p.value as List) + "isNull" -> if (p.value as Boolean) AuthTable.couponAmount.isNull() else AuthTable.couponAmount.isNotNull() + else -> throw IllegalStateException("unsupported op for couponAmount: " + p.op) } - "priorAuthNumber" -> when (p.op) { - "eq" -> AuthTable.priorAuthNumber eq (p.value as String) - "ne" -> AuthTable.priorAuthNumber neq (p.value as String) - "in" -> AuthTable.priorAuthNumber inList (p.value as List) - "like" -> AuthTable.priorAuthNumber like (p.value as String) - "isNull" -> if (p.value as Boolean) AuthTable.priorAuthNumber.isNull() else AuthTable.priorAuthNumber.isNotNull() - else -> throw IllegalStateException("unsupported op for priorAuthNumber: " + p.op) + "permitNumber" -> when (p.op) { + "eq" -> AuthTable.permitNumber eq (p.value as String) + "ne" -> AuthTable.permitNumber neq (p.value as String) + "in" -> AuthTable.permitNumber inList (p.value as List) + "like" -> AuthTable.permitNumber like (p.value as String) + "isNull" -> if (p.value as Boolean) AuthTable.permitNumber.isNull() else AuthTable.permitNumber.isNotNull() + else -> throw IllegalStateException("unsupported op for permitNumber: " + p.op) } else -> continue } @@ -331,8 +331,8 @@ private fun rowToAuth(row: ResultRow): Auth = Auth( type = row[AuthTable.type], reference = row[AuthTable.reference], quantity = row[AuthTable.quantity], - copayAmount = row[AuthTable.copayAmount], - priorAuthNumber = row[AuthTable.priorAuthNumber], + couponAmount = row[AuthTable.couponAmount], + permitNumber = row[AuthTable.permitNumber], ) /** @@ -480,9 +480,9 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat else ResponseEntity.noContent().build() } - // --- subtype Copay (segment /copay) --- - @GetMapping("/copay") - fun listCopay( + // --- subtype Coupon (segment /coupon) --- + @GetMapping("/coupon") + fun listCoupon( @RequestParam(required = false) limit: Int?, @RequestParam(required = false) offset: Int?, @RequestParam(required = false) sort: String?, @@ -492,7 +492,7 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf("error" to filterResult.error, "field" to filterResult.field) as Any) val whereOp = AuthWhereOp(filterResult.predicates) var q = AuthTable.selectAll().where { - val d = AuthTable.type eq AuthType.Copay + val d = AuthTable.type eq AuthType.Coupon if (whereOp != null) d and whereOp else d } if (sort != null) { @@ -510,15 +510,15 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat ResponseEntity.ok(rows as Any) } - @GetMapping("/copay/{id}") - fun getCopay(@PathVariable id: Long): ResponseEntity = transaction { - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }.singleOrNull() + @GetMapping("/coupon/{id}") + fun getCoupon(@PathVariable id: Long): ResponseEntity = transaction { + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }.singleOrNull() ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) ResponseEntity.ok(rowToAuth(row) as Any) } - @PostMapping("/copay") - fun createCopay(@RequestBody body: JsonNode): ResponseEntity = transaction { + @PostMapping("/coupon") + fun createCoupon(@RequestBody body: JsonNode): ResponseEntity = transaction { if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add("invalid_type", emptyList(), "request body must be a JSON object").body() as Any) val unknownKeys = MetaUnknownBodyKeys.refusal(body, AuthKnownFields) if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any) @@ -528,59 +528,59 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any) } val issues = MetaValidationIssues.Collector() - issues.addAt(validator.validateValue(CopayAuthValidation::class.java, "copayAmount", dto.copayAmount), "copayAmount") - if (!MetaDecimalWire.fits(dto.copayAmount, 10, 2)) issues.add("too_big", listOf("copayAmount"), "decimal does not fit the declared precision and scale") - issues.addAt(validator.validateValue(CopayAuthValidation::class.java, "reference", dto.reference), "reference") + issues.addAt(validator.validateValue(CouponAuthValidation::class.java, "couponAmount", dto.couponAmount), "couponAmount") + if (!MetaDecimalWire.fits(dto.couponAmount, 10, 2)) issues.add("too_big", listOf("couponAmount"), "decimal does not fit the declared precision and scale") + issues.addAt(validator.validateValue(CouponAuthValidation::class.java, "reference", dto.reference), "reference") if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any) val newId = AuthTable.insert { - it[AuthTable.type] = AuthType.Copay + it[AuthTable.type] = AuthType.Coupon it[AuthTable.reference] = dto.reference!! - it[AuthTable.copayAmount] = dto.copayAmount + it[AuthTable.couponAmount] = dto.couponAmount }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) } - @RequestMapping(value = ["/copay/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) - fun updateCopay(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { + @RequestMapping(value = ["/coupon/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) + fun updateCoupon(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { val issues = MetaValidationIssues.Collector() if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add("invalid_type", emptyList(), "request body must be a JSON object").body() as Any) val unknownKeys = MetaUnknownBodyKeys.refusal(body, AuthKnownFields) if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any) if (body.has("reference") && body.get("reference").isNull) issues.add("invalid_type", listOf("reference"), "field 'reference' cannot be null") - if (listOf("copayAmount", "reference").any { body.has(it) }) { + if (listOf("couponAmount", "reference").any { body.has(it) }) { run { - val hasCopayAmount = body.has("copayAmount") - val nullCopayAmount = hasCopayAmount && body.get("copayAmount").isNull - val vCopayAmount: java.math.BigDecimal? = if (hasCopayAmount && !nullCopayAmount) issues.bind("copayAmount") { MetaDecimalWire.fromNode(body.get("copayAmount")) } else null - if (vCopayAmount != null) issues.addAt(validator.validateValue(CopayAuthValidation::class.java, "copayAmount", vCopayAmount), "copayAmount") - if (!MetaDecimalWire.fits(vCopayAmount, 10, 2)) issues.add("too_big", listOf("copayAmount"), "decimal does not fit the declared precision and scale") + val hasCouponAmount = body.has("couponAmount") + val nullCouponAmount = hasCouponAmount && body.get("couponAmount").isNull + val vCouponAmount: java.math.BigDecimal? = if (hasCouponAmount && !nullCouponAmount) issues.bind("couponAmount") { MetaDecimalWire.fromNode(body.get("couponAmount")) } else null + if (vCouponAmount != null) issues.addAt(validator.validateValue(CouponAuthValidation::class.java, "couponAmount", vCouponAmount), "couponAmount") + if (!MetaDecimalWire.fits(vCouponAmount, 10, 2)) issues.add("too_big", listOf("couponAmount"), "decimal does not fit the declared precision and scale") val hasReference = body.has("reference") val nullReference = hasReference && body.get("reference").isNull val vReference: kotlin.String? = if (hasReference && !nullReference) issues.bind("reference") { objectMapper.treeToValue(body.get("reference"), object : TypeReference() {}) } else null - if (vReference != null) issues.addAt(validator.validateValue(CopayAuthValidation::class.java, "reference", vReference), "reference") + if (vReference != null) issues.addAt(validator.validateValue(CouponAuthValidation::class.java, "reference", vReference), "reference") if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any) - AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }) { - if (hasCopayAmount) { if (nullCopayAmount) it[AuthTable.copayAmount] = null else it[AuthTable.copayAmount] = vCopayAmount } + AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }) { + if (hasCouponAmount) { if (nullCouponAmount) it[AuthTable.couponAmount] = null else it[AuthTable.couponAmount] = vCouponAmount } if (hasReference) it[AuthTable.reference] = vReference!! } } } - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }.singleOrNull() + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }.singleOrNull() if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.ok(rowToAuth(row) as Any) } - @DeleteMapping("/copay/{id}") - fun deleteCopay(@PathVariable id: Long): ResponseEntity = transaction { - val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) } } + @DeleteMapping("/coupon/{id}") + fun deleteCoupon(@PathVariable id: Long): ResponseEntity = transaction { + val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) } } if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.noContent().build() } - // --- subtype PriorAuth (segment /priorauth) --- - @GetMapping("/priorauth") - fun listPriorAuth( + // --- subtype Permit (segment /permit) --- + @GetMapping("/permit") + fun listPermit( @RequestParam(required = false) limit: Int?, @RequestParam(required = false) offset: Int?, @RequestParam(required = false) sort: String?, @@ -590,7 +590,7 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf("error" to filterResult.error, "field" to filterResult.field) as Any) val whereOp = AuthWhereOp(filterResult.predicates) var q = AuthTable.selectAll().where { - val d = AuthTable.type eq AuthType.PriorAuth + val d = AuthTable.type eq AuthType.Permit if (whereOp != null) d and whereOp else d } if (sort != null) { @@ -608,15 +608,15 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat ResponseEntity.ok(rows as Any) } - @GetMapping("/priorauth/{id}") - fun getPriorAuth(@PathVariable id: Long): ResponseEntity = transaction { - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }.singleOrNull() + @GetMapping("/permit/{id}") + fun getPermit(@PathVariable id: Long): ResponseEntity = transaction { + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }.singleOrNull() ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) ResponseEntity.ok(rowToAuth(row) as Any) } - @PostMapping("/priorauth") - fun createPriorAuth(@RequestBody body: JsonNode): ResponseEntity = transaction { + @PostMapping("/permit") + fun createPermit(@RequestBody body: JsonNode): ResponseEntity = transaction { if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add("invalid_type", emptyList(), "request body must be a JSON object").body() as Any) val unknownKeys = MetaUnknownBodyKeys.refusal(body, AuthKnownFields) if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any) @@ -626,50 +626,50 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any) } val issues = MetaValidationIssues.Collector() - issues.addAt(validator.validateValue(PriorAuthAuthValidation::class.java, "priorAuthNumber", dto.priorAuthNumber), "priorAuthNumber") - issues.addAt(validator.validateValue(PriorAuthAuthValidation::class.java, "reference", dto.reference), "reference") + issues.addAt(validator.validateValue(PermitAuthValidation::class.java, "permitNumber", dto.permitNumber), "permitNumber") + issues.addAt(validator.validateValue(PermitAuthValidation::class.java, "reference", dto.reference), "reference") if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any) val newId = AuthTable.insert { - it[AuthTable.type] = AuthType.PriorAuth + it[AuthTable.type] = AuthType.Permit it[AuthTable.reference] = dto.reference!! - it[AuthTable.priorAuthNumber] = dto.priorAuthNumber + it[AuthTable.permitNumber] = dto.permitNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) } - @RequestMapping(value = ["/priorauth/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) - fun updatePriorAuth(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { + @RequestMapping(value = ["/permit/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) + fun updatePermit(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { val issues = MetaValidationIssues.Collector() if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add("invalid_type", emptyList(), "request body must be a JSON object").body() as Any) val unknownKeys = MetaUnknownBodyKeys.refusal(body, AuthKnownFields) if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any) if (body.has("reference") && body.get("reference").isNull) issues.add("invalid_type", listOf("reference"), "field 'reference' cannot be null") - if (listOf("priorAuthNumber", "reference").any { body.has(it) }) { + if (listOf("permitNumber", "reference").any { body.has(it) }) { run { - val hasPriorAuthNumber = body.has("priorAuthNumber") - val nullPriorAuthNumber = hasPriorAuthNumber && body.get("priorAuthNumber").isNull - val vPriorAuthNumber: kotlin.String? = if (hasPriorAuthNumber && !nullPriorAuthNumber) issues.bind("priorAuthNumber") { objectMapper.treeToValue(body.get("priorAuthNumber"), object : TypeReference() {}) } else null - if (vPriorAuthNumber != null) issues.addAt(validator.validateValue(PriorAuthAuthValidation::class.java, "priorAuthNumber", vPriorAuthNumber), "priorAuthNumber") + val hasPermitNumber = body.has("permitNumber") + val nullPermitNumber = hasPermitNumber && body.get("permitNumber").isNull + val vPermitNumber: kotlin.String? = if (hasPermitNumber && !nullPermitNumber) issues.bind("permitNumber") { objectMapper.treeToValue(body.get("permitNumber"), object : TypeReference() {}) } else null + if (vPermitNumber != null) issues.addAt(validator.validateValue(PermitAuthValidation::class.java, "permitNumber", vPermitNumber), "permitNumber") val hasReference = body.has("reference") val nullReference = hasReference && body.get("reference").isNull val vReference: kotlin.String? = if (hasReference && !nullReference) issues.bind("reference") { objectMapper.treeToValue(body.get("reference"), object : TypeReference() {}) } else null - if (vReference != null) issues.addAt(validator.validateValue(PriorAuthAuthValidation::class.java, "reference", vReference), "reference") + if (vReference != null) issues.addAt(validator.validateValue(PermitAuthValidation::class.java, "reference", vReference), "reference") if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any) - AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }) { - if (hasPriorAuthNumber) { if (nullPriorAuthNumber) it[AuthTable.priorAuthNumber] = null else it[AuthTable.priorAuthNumber] = vPriorAuthNumber } + AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }) { + if (hasPermitNumber) { if (nullPermitNumber) it[AuthTable.permitNumber] = null else it[AuthTable.permitNumber] = vPermitNumber } if (hasReference) it[AuthTable.reference] = vReference!! } } } - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }.singleOrNull() + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }.singleOrNull() if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.ok(rowToAuth(row) as Any) } - @DeleteMapping("/priorauth/{id}") - fun deletePriorAuth(@PathVariable id: Long): ResponseEntity = transaction { - val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) } } + @DeleteMapping("/permit/{id}") + fun deletePermit(@PathVariable id: Long): ResponseEntity = transaction { + val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) } } if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.noContent().build() } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt index 98d49ef76c..d02fcc202b 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt @@ -11,8 +11,8 @@ object AuthFilterAllowlist { "type", "reference", "quantity", - "copayAmount", - "priorAuthNumber", + "couponAmount", + "permitNumber", ) val OPS_BY_FIELD: Map> = mapOf( @@ -20,7 +20,7 @@ object AuthFilterAllowlist { "type" to setOf("eq", "ne", "in", "like", "isNull"), "reference" to setOf("eq", "ne", "in", "like", "isNull"), "quantity" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "copayAmount" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "priorAuthNumber" to setOf("eq", "ne", "in", "like", "isNull") + "couponAmount" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), + "permitNumber" to setOf("eq", "ne", "in", "like", "isNull") ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt index 3c9fa910fb..ab25528d05 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt @@ -8,8 +8,8 @@ object AuthTable : Table("auths") { val type = customEnumeration("type", "TEXT", { v -> AuthType.valueOf(v as String) }, { e -> e.name }).nullable() val reference = varchar("reference", 80) val quantity = integer("quantity").nullable() - val copayAmount = portableDecimal("copay_amount", 10, 2).nullable() - val priorAuthNumber = varchar("prior_auth_number", 80).nullable() + val couponAmount = portableDecimal("coupon_amount", 10, 2).nullable() + val permitNumber = varchar("permit_number", 80).nullable() override val primaryKey = PrimaryKey(id) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt index 8b0dd0211a..e4bea82374 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt @@ -8,6 +8,6 @@ import kotlinx.serialization.Serializable @Serializable public enum class AuthType { Bridge, - Copay, - PriorAuth, + Coupon, + Permit, } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt similarity index 73% rename from server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt rename to server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt index ec665b3de8..adc4da3bd7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt @@ -7,12 +7,12 @@ import kotlin.String /** * GENERATED — do not hand-edit. Regenerated from metadata. - * FR-036 validation-only shape for the CopayAuth TPH subtype: the base controller's + * FR-036 validation-only shape for the CouponAuth TPH subtype: the base controller's * per-subtype POST/PATCH validates present values against these field constraints * (the folded union base data class is annotation-free). Never persisted or bound. */ -public data class CopayAuthValidation( - public val copayAmount: BigDecimal? = null, +public data class CouponAuthValidation( + public val couponAmount: BigDecimal? = null, @field:NotNull @field:Size(min = 1, max = 80) public val reference: String? = null, diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt similarity index 73% rename from server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt rename to server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt index e51e608de8..ce1dcfc7bb 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt @@ -6,13 +6,13 @@ import kotlin.String /** * GENERATED — do not hand-edit. Regenerated from metadata. - * FR-036 validation-only shape for the PriorAuthAuth TPH subtype: the base controller's + * FR-036 validation-only shape for the PermitAuth TPH subtype: the base controller's * per-subtype POST/PATCH validates present values against these field constraints * (the folded union base data class is annotation-free). Never persisted or bound. */ -public data class PriorAuthAuthValidation( +public data class PermitAuthValidation( @field:Size(max = 80) - public val priorAuthNumber: String? = null, + public val permitNumber: String? = null, @field:NotNull @field:Size(min = 1, max = 80) public val reference: String? = null, diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java index 1e7021ce1d..9072857681 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java @@ -72,7 +72,13 @@ private Fr019SharedEnum() { /* no instances */ } */ public record SharedEnum(String name, List values, boolean provided, String metaPackage, String javaPackage, - Map intValueMap) { } + Map intValueMap, Map stringValueMap) { + /** The record without a {@code @stringValueMap} (rc.21), for callers that predate it. */ + public SharedEnum(String name, List values, boolean provided, String metaPackage, String javaPackage, + Map intValueMap) { + this(name, values, provided, metaPackage, javaPackage, intValueMap, null); + } + } /** Per-port codegen config for resolving a {@code @provided} enum's Java namespace (ADR-0001). * Generator args, never metadata: a package→namespace map (keyed by metadata package in @@ -128,7 +134,7 @@ public static SharedEnum sharedEnumForField(MetaField field) { String name = SpringNaming.capitalize(split[1]); String metaPackage = metaPackageOf(decl.getName()); return new SharedEnum(name, values, isProvided((EnumField) decl), metaPackage, javaPackage, - SpringTypeMapper.intValueMap((EnumField) decl)); + SpringTypeMapper.intValueMap((EnumField) decl), SpringTypeMapper.stringValueMap((EnumField) decl)); } /** The declaration's metadata package in {@code ::} form, stripped of the trailing {@code ::Name} @@ -213,7 +219,7 @@ public static void emitMaterialized(MetaDataLoader loader, Path outRoot) { } src.append("/** GENERATED — shared enum ").append(shared.name()) .append(". Do not hand-edit; regenerated from metadata. */\n"); - src.append(SpringTypeMapper.enumDeclaration(shared.name(), shared.values(), shared.intValueMap())) + src.append(SpringTypeMapper.enumDeclaration(shared.name(), shared.values(), shared.intValueMap(), shared.stringValueMap())) .append("\n"); try { Path outFile = outRoot.resolve(shared.javaPackage().replace('.', '/')) diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java index 84d7ad0491..bda50c8518 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java @@ -1026,7 +1026,7 @@ private static List collectEnumDecls(MetaObject owner, List f String typeName = SpringTypeMapper.enumTypeName(owner, ef); if (!seen.add(typeName)) continue; // dedup shared abstract-enum types List values = SpringTypeMapper.effectiveEnumValues(ef); - decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef))); + decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef), SpringTypeMapper.stringValueMap(ef))); } return decls; } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index 2b6c90139f..5a7b9f4ac1 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 @@ -586,7 +586,7 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean src.append(" * GENERATED — per-object physical database names for ").append(shortName).append(".\n"); src.append(" */\n"); // `abstract`, not `final`: this class is now a base other names classes extend - // rather than restate. Java inherits static members, so `CopayAuthNames.ID_COLUMN` + // rather than restate. Java inherits static members, so `CouponAuthNames.ID_COLUMN` // resolves through the base and every consumption site is unchanged; `abstract` // keeps the "no instances" guarantee `final` + a private constructor used to give, // while still allowing a subclass. diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java index e9a2efb61a..9c8f9f263f 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java @@ -428,6 +428,36 @@ public static java.util.Map intValueMap(EnumField field) { * other port agrees with. */ public static String enumDeclaration(String typeName, List values, java.util.Map intValueMap) { + return enumDeclaration(typeName, values, intValueMap, null); + } + + /** + * rc.21 — as {@link #enumDeclaration(String, List, java.util.Map)}, and with a + * {@code @stringValueMap} the enum carries each member's stored STRING ({@code dbValue()}) + * and the reverse lookup ({@code fromDbValue(String)}), which throws on an unmapped one. + */ + public static String enumDeclaration(String typeName, List values, java.util.Map intValueMap, + java.util.Map stringValueMap) { + if (intValueMap == null && stringValueMap != null) { + StringBuilder sb = new StringBuilder("public enum ").append(typeName).append(" {\n"); + List members = new java.util.ArrayList<>(); + for (String v : values) { + String stored = stringValueMap.getOrDefault(v, v).replace("\\", "\\\\").replace("\"", "\\\""); + members.add(" " + v + "(\"" + stored + "\")"); + } + sb.append(String.join(",\n", members)).append(";\n\n"); + sb.append(" private final String dbValue;\n\n"); + sb.append(" ").append(typeName).append("(String dbValue) { this.dbValue = dbValue; }\n\n"); + sb.append(" /** The stored string this member maps to, from the declared @stringValueMap. */\n"); + sb.append(" public String dbValue() { return dbValue; }\n\n"); + sb.append(" /** The member a stored string maps to; throws on a value the map does not declare. */\n"); + sb.append(" public static ").append(typeName).append(" fromDbValue(String value) {\n"); + sb.append(" for (").append(typeName).append(" e : values()) if (e.dbValue.equals(value)) return e;\n"); + sb.append(" throw new IllegalArgumentException(\"unmapped stored value \" + value + \" for ") + .append(typeName).append("\");\n"); + sb.append(" }\n}"); + return sb.toString(); + } if (intValueMap == null) { return "public enum " + typeName + " { " + String.join(", ", values) + " }"; } @@ -448,6 +478,17 @@ public static String enumDeclaration(String typeName, List values, java. return sb.toString(); } + /** rc.21 — the declared member → stored string ({@code @stringValueMap}, resolving), or null. */ + public static java.util.Map stringValueMap(EnumField field) { + if (!field.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null; + Object raw = field.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + if (!(raw instanceof java.util.Map m)) return null; + java.util.Map out = new java.util.LinkedHashMap<>(); + for (java.util.Map.Entry e : m.entrySet()) + if (e.getKey() != null && e.getValue() instanceof String s) out.put(String.valueOf(e.getKey()), s); + return out.isEmpty() ? null : out; + } + public static List effectiveEnumValues(EnumField field) { if (!field.hasMetaAttr(EnumField.ATTR_VALUES)) return List.of(); Object raw = field.getMetaAttr(EnumField.ATTR_VALUES).getValue(); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java index 75aa7ef581..846d7b7c91 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java @@ -277,7 +277,7 @@ private static List collectEnumDecls(MetaObject owner, List f if (values.isEmpty()) continue; String typeName = SpringTypeMapper.enumTypeName(owner, ef); if (!seen.add(typeName)) continue; - decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef))); + decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef), SpringTypeMapper.stringValueMap(ef))); } return decls; } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java index 3d45060758..b98e7cc157 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java @@ -39,7 +39,7 @@ public record Plan(MetaObject base, String discriminatorField, List sub /** * The per-subtype REST route segment for a discriminator value — the ONE place this rule * lives: the value lowercased ({@code "Bridge"} → {@code bridge}, - * {@code "PriorAuth"} → {@code priorauth}). + * {@code "Permit"} → {@code permit}). */ public static String routeSegment(String discriminatorValue) { return discriminatorValue.toLowerCase(Locale.ROOT); diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java index b72e34d363..b701a77c45 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java @@ -74,8 +74,8 @@ public class GeneratedTphM2mTraversalCompileRunTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -121,9 +121,9 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(Map.of("id", 10, "name", "red"), Map.of("id", 20, "name", "green")), - // auth 1 (Bridge) -> tag 10; auth 2 (Copay) -> tag 20. + // auth 1 (Bridge) -> tag 10; auth 2 (Coupon) -> tag 20. "auth_tags", List.of(Map.of("authId", 1, "tagId", 10), Map.of("authId", 2, "tagId", 20)), // auth 1 (Bridge) links to auth 2 — a hetero-looking row, but AuthLink only // ever references BridgeAuth ids on both sides by the fixture's own FK. @@ -135,21 +135,21 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws rows(seed, "auths"), rows(seed, "tags"), rows(seed, "auth_tags"), rows(seed, "auth_links")); // Rule (a): a base-declared relationship's finder is UNSCOPED — every row, - // Bridge or Copay, is a legitimate source. + // Bridge or Coupon, is a legitimate source. assertNamesEqual(List.of("red"), invokeFinder(repo, "findTags", 1L)); assertNamesEqual(List.of("green"), invokeFinder(repo, "findTags", 2L)); // Rule (b)+(c): the Bridge-scoped finder answers for a REAL Bridge id... assertNamesEqual(List.of("red"), invokeFinder(repo, "findTagsForBridge", 1L)); // ...and returns EMPTY — not the sibling's rows, not an exception — for a - // Copay id, because the junction FK cannot itself distinguish the subtypes. + // Coupon id, because the junction FK cannot itself distinguish the subtypes. assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForBridge", 2L)); - // Symmetric proof on the Copay-scoped finder. - assertNamesEqual(List.of("green"), invokeFinder(repo, "findTagsForCopay", 2L)); - assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForCopay", 1L)); + // Symmetric proof on the Coupon-scoped finder. + assertNamesEqual(List.of("green"), invokeFinder(repo, "findTagsForCoupon", 2L)); + assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForCoupon", 1L)); // Subtype-OWN relationship (linkedAuths, self-join on BridgeAuth): resolves for - // a real Bridge id, empty for the Copay id. The target — BridgeAuth itself — is + // a real Bridge id, empty for the Coupon id. The target — BridgeAuth itself — is // ALSO a concrete TPH subtype, so the finder now takes the build-time-resolved // "Bridge" literal as a second argument (FW-8 follow-up, target-side gate). assertReferencesEqual(List.of("b1"), invokeFinderWithSubtype(repo, "findLinkedAuthsForBridge", 1L, "Bridge")); @@ -165,13 +165,13 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws * implementation that actually USES it to filter the join returns only rows of that * subtype, never a same-table sibling's. {@code linkedAuths}' {@code @objectRef} names * {@code BridgeAuth} — a concrete TPH subtype of {@code Auth} — so its rows physically - * share the {@code auths} table with {@code CopayAuth} rows; nothing in the junction FK + * share the {@code auths} table with {@code CouponAuth} rows; nothing in the junction FK * itself (a plain {@code Long} id) can distinguish them. Unlike the SOURCE-side rule (c), * Java's generated controller CANNOT enforce this itself (the join is entirely * consumer-owned) — the seam can only be WIDENED so a conforming implementation has what * it needs, exactly the same limitation the Python port documents for its own * {@code target_subtype} parameter. This test's junction data is deliberately corrupted - * (a link row pointing at a same-table Copay row) to prove a conforming, FILTERING + * (a link row pointing at a same-table Coupon row) to prove a conforming, FILTERING * repository correctly excludes it once it is handed {@code "Bridge"}. */ @Test @@ -194,12 +194,12 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(), "auth_tags", List.of(), // auth 1 (Bridge) links to itself (a GENUINE Bridge target) AND — a corrupted row // that should never exist under a correctly-enforced physical schema — to auth 2, - // whose type is Copay. Nothing in the junction FK's plain Long id distinguishes them. + // whose type is Coupon. Nothing in the junction FK's plain Long id distinguishes them. "auth_links", List.of( Map.of("fromAuthId", 1, "toAuthId", 1), Map.of("fromAuthId", 1, "toAuthId", 2))); @@ -216,7 +216,7 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi Object controller = ctor.newInstance(repo, new ObjectMapper(), validator); // Direct repository call: the FILTERING implementation excludes the corrupted - // Copay-typed target even though the junction row itself does not. + // Coupon-typed target even though the junction row itself does not. assertReferencesEqual(List.of("b1"), invokeFinderWithSubtype(repo, "findLinkedAuthsForBridge", 1L, "Bridge")); @@ -231,7 +231,7 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi /** * The distinguishing test: enforcement, not delegation. {@link NaiveAuthRepository}'s - * {@code findTagsForBridge}/{@code findTagsForCopay} are a copy-paste of the UNSCOPED + * {@code findTagsForBridge}/{@code findTagsForCoupon} are a copy-paste of the UNSCOPED * {@code findTags} — no discriminator check at all — which javac, the repository * interface's type system, and a corpus scenario against a delegating port all wave * through. Only the GENERATED CONTROLLER's own composition of @@ -264,7 +264,7 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(Map.of("id", 10, "name", "red"), Map.of("id", 20, "name", "green")), "auth_tags", List.of(Map.of("authId", 1, "tagId", 10), Map.of("authId", 2, "tagId", 20))); @@ -285,8 +285,8 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter assertEquals(200, bridgeResp.getStatusCode().value()); assertNamesEqual(List.of("red"), (List) bridgeResp.getBody()); - // The Copay id: NaiveAuthRepository.findTagsForBridge would happily return the - // Copay's OWN tags (["green"]) if the controller ever called it — it has no + // The Coupon id: NaiveAuthRepository.findTagsForBridge would happily return the + // Coupon's OWN tags (["green"]) if the controller ever called it — it has no // discriminator check of its own. It must NOT be called: the controller's // findByIdAndType(2, "Bridge") composition returns empty first, short-circuiting // to [] before the naive finder runs. @@ -294,8 +294,8 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter assertEquals(200, mismatchResp.getStatusCode().value()); assertNamesEqual(List.of(), (List) mismatchResp.getBody()); - // Mirror on the Copay-scoped finder with the Bridge id. - ResponseEntity mismatchResp2 = invokeControllerFinder(controller, "findTagsForCopay", 1L); + // Mirror on the Coupon-scoped finder with the Bridge id. + ResponseEntity mismatchResp2 = invokeControllerFinder(controller, "findTagsForCoupon", 1L); assertEquals(200, mismatchResp2.getStatusCode().value()); assertNamesEqual(List.of(), (List) mismatchResp2.getBody()); } @@ -441,8 +441,8 @@ public InMemoryAuthRepository(List> authRows, return isType(sourceId, "Bridge") ? tagsFor(sourceId) : List.of(); } - @Override public List findTagsForCopay(Long sourceId) { - return isType(sourceId, "Copay") ? tagsFor(sourceId) : List.of(); + @Override public List findTagsForCoupon(Long sourceId) { + return isType(sourceId, "Coupon") ? tagsFor(sourceId) : List.of(); } // Subtype-OWN "linkedAuths" (directed self-join through AuthLink). The relationship's @@ -550,7 +550,7 @@ public NaiveAuthRepository(List> authRows, // must not ship this, but nothing except the generated controller's own gate // stops it from doing so and still passing every OTHER test. @Override public List findTagsForBridge(Long sourceId) { return tagsFor(sourceId); } - @Override public List findTagsForCopay(Long sourceId) { return tagsFor(sourceId); } + @Override public List findTagsForCoupon(Long sourceId) { return tagsFor(sourceId); } @Override public List findLinkedAuthsForBridge(Long sourceId, String targetSubtype) { return List.of(); } private List tagsFor(Long sourceId) { @@ -631,7 +631,7 @@ public FilteringAuthRepository(List> authRows, @Override public List findTags(Long sourceId) { return List.of(); } @Override public List findTagsForBridge(Long sourceId) { return List.of(); } - @Override public List findTagsForCopay(Long sourceId) { return List.of(); } + @Override public List findTagsForCoupon(Long sourceId) { return List.of(); } // The load-bearing method: filters the joined targets down to rows whose OWN // discriminator matches the literal the generated controller now hands in — diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java index 7fdc79331e..2968104279 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java @@ -340,7 +340,7 @@ public void tphUnionDtoAndSubPatchCarryTheStampingHelpers() throws Exception { Path classesDir = tmp.newFolder("tph-classes").toPath(); MetaDataLoader loader = SpringTestFixtures.loadFixture(tmp.newFolder("tph-fx").toPath(), "auth", TPH_AUTOSET_JSON); runGenerator(new SpringDtoGenerator(), loader, srcDir); - // Real javac compile of the DTO layer (AuthDto + BridgeAuthDto/Copay.../Patch) — not just + // Real javac compile of the DTO layer (AuthDto + BridgeAuthDto/Coupon.../Patch) — not just // string assertions. Catches exactly the class of bug found while implementing this: a // subtype-typed stampForInsert(BridgeAuthDto) would NOT type-check if the controller ever // called it with an AuthDto argument (the union type repository.createWithType binds). diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java index 4b7b09f32e..d1b34335f2 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java @@ -167,14 +167,14 @@ private Object build(String meta, String name, String repoFqn, String controller { "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", "@values": ["OPEN", "SHUT"], "@default": "SHUT" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@default": 3 } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Coupon", "children": [ { "field.int": { "name": "amount" } } ] } } ] } } """; diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java index 8b6100fe06..1743ac404b 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java @@ -158,14 +158,14 @@ public void operatorGatingPerSubtype() throws Exception { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@filterable": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] } } ] } } @@ -183,8 +183,8 @@ public void aTphSubtypeDecimalIsFilterableAndParsedExactly() throws Exception { gen.execute(loader); String src = Files.readString(outDir.resolve("acme/auth/AuthFilterAllowlist.java")); - assertTrue(src, src.contains("\"copayAmount\"")); - assertTrue(src, src.contains("DECIMAL_FIELDS = Set.of(\"copayAmount\")")); + assertTrue(src, src.contains("\"couponAmount\"")); + assertTrue(src, src.contains("DECIMAL_FIELDS = Set.of(\"couponAmount\")")); assertTrue(src, src.contains("\"quantity\"")); } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java index 8021b7b0a7..82e7dfbc09 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java @@ -72,4 +72,33 @@ public void anIntBackedEnumMapsBothWaysAndRefusesAnUnmappedValue() throws Except } } } + + // rc.21: a @stringValueMap enum carries its stored STRING both ways, and a shared declaration + // (Fr019SharedEnum) keeps it (fix round M4). + @Test + public void aStringValueMapEnumMapsBothWaysAndRefusesAnUnmappedValue() throws Exception { + Map stored = new LinkedHashMap<>(); + stored.put("DRAFT", "draft_v1"); + stored.put("PUBLISHED", "published_v1"); + String decl = SpringTypeMapper.enumDeclaration("Phase", List.of("DRAFT", "PUBLISHED"), null, stored); + Path src = tmp.newFolder("src2").toPath(); + Path out = tmp.newFolder("out2").toPath(); + Path file = src.resolve("Phase.java"); + Files.writeString(file, decl + "\n"); + assertEquals("generated enum must compile", 0, + ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", out.toString(), file.toString())); + try (URLClassLoader cl = new URLClassLoader(new URL[]{ out.toUri().toURL() }, null)) { + Class phase = cl.loadClass("Phase"); + assertEquals("PUBLISHED", ((Enum) phase.getMethod("fromDbValue", String.class).invoke(null, "published_v1")).name()); + assertEquals("draft_v1", phase.getMethod("dbValue").invoke(Enum.valueOf(phase.asSubclass(Enum.class), "DRAFT"))); + try { + phase.getMethod("fromDbValue", String.class).invoke(null, "lost"); + fail("an unmapped stored value must throw"); + } catch (InvocationTargetException e) { + assertTrue(e.getCause() instanceof IllegalArgumentException); + } + } + Fr019SharedEnum.SharedEnum shared = new Fr019SharedEnum.SharedEnum("Phase", List.of("DRAFT", "PUBLISHED"), false, "acme", "acme", null, stored); + assertEquals(stored, shared.stringValueMap()); + } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java index bc7a7c4b4e..6e5a475982 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java @@ -21,9 +21,9 @@ * non-TPH entity) declares a hetero M:N {@code bridgeAuths -> BridgeAuth}, where * {@code BridgeAuth} is a CONCRETE TPH subtype of {@code Auth} * ({@code @discriminatorValue: "Bridge"}). {@code BridgeAuth}'s rows physically - * live in the shared {@code auths} table alongside {@code CopayAuth} rows, so an + * live in the shared {@code auths} table alongside {@code CouponAuth} rows, so an * unscoped junction traversal cannot itself tell a genuine Bridge row from a - * same-table Copay row. Java's repository interface is consumer-implemented — it + * same-table Coupon row. Java's repository interface is consumer-implemented — it * cannot AND a discriminator into a join it does not write — so the fix widens the * finder seam with a build-time-literal {@code targetSubtype} argument, exactly as * for the self-join case in {@link SpringTphM2mCodegenTest}, but here proving the @@ -41,15 +41,15 @@ public class SpringM2mTargetTphCodegenTest extends SharedRegistryTestBase { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Sponsor", "children": [ { "source.rdb": { "@table": "sponsors" } }, diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java new file mode 100644 index 0000000000..a561a02c43 --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java @@ -0,0 +1,133 @@ +package com.metaobjects.generator.spring; + +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * A generated create route hands the repository only what a client may set: a server-generated + * key, a {@code readOnly} field and (TPH) the discriminator and a sibling subtype's column are + * dropped from the bound body before the repository sees it (1.2.x security patch). Behaviour is + * gated by the api-contract {@code input-server-owned-dropped} scenarios; this pins the generated + * source, including the TPH subtype {@code readOnly} case the shared TPH model does not declare. + */ +public class SpringServerOwnedInputCodegenTest extends SharedRegistryTestBase { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private static final String PLAIN = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Doc", "children": [ + { "source.rdb": { "@table": "docs" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title" } }, + { "field.string": { "name": "role", "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.string": { "name": "code" } }, + { "field.string": { "name": "label" } }, + { "identity.primary": { "name": "pk", "@fields": ["code"] } } + ] } } + ] } + } + """; + + private static final String TPH = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Permit"] } }, + { "field.string": { "name": "reference" } }, + { "field.string": { "name": "grade", "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity" } } + ] } }, + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ + { "field.string": { "name": "approver" } } + ] } } + ] } + } + """; + + private static final String VO = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.value": { "name": "Stamp", "children": [ + { "field.string": { "name": "by" } } + ] } }, + { "object.entity": { "name": "Note", "children": [ + { "source.rdb": { "@table": "notes" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "body" } }, + { "field.object": { "name": "stamp", "@objectRef": "Stamp", "@storage": "jsonb", + "@required": true, "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + } + """; + + private Path generate(String name, String fixture) throws Exception { + Path gen = tmp.newFolder("gen-" + name).toPath(); + MetaDataLoader loader = SpringTestFixtures.loadFixture(tmp.newFolder("ws-" + name).toPath(), name, fixture); + for (var g : new com.metaobjects.generator.direct.MultiFileDirectGeneratorBase[] { + new SpringControllerGenerator(), new SpringDtoGenerator() }) { + Map args = new HashMap<>(); + args.put("outputDir", gen.toString()); + g.setArgs(args); + g.execute(loader); + } + return gen; + } + + @Test + public void plainCreateDropsTheGeneratedKeyAndReadOnlyField() throws Exception { + Path gen = generate("plain", PLAIN); + String controller = Files.readString(gen.resolve("acme/own/DocController.java")); + assertTrue("generated id and readOnly role are nulled; saw:\n" + controller, + controller.contains("dto = new DocDto(null, dto.title(), null);")); + // an assigned key (no @generation) is the caller's on create + String tag = Files.readString(gen.resolve("acme/own/TagController.java")); + assertFalse("assigned key must be kept; saw:\n" + tag, tag.contains("dto = new TagDto(")); + } + + @Test + public void aRequiredReadOnlyValueObjectIsNulledAndItsNotNullIgnored() throws Exception { + Path gen = generate("vo", VO); + String controller = Files.readString(gen.resolve("acme/own/NoteController.java")); + assertTrue("readOnly VO component is nulled on create; saw:\n" + controller, + controller.contains("dto = new NoteDto(null, dto.body(), null);")); + // the strip nulls `stamp`, so its @NotNull must not turn every POST into a 400 + assertTrue("stamp must be server-owned for create validation; saw:\n" + controller, + controller.matches("(?s).*SERVER_OWNED_ON_CREATE = Set\\.of\\([^)]*\"stamp\".*")); + } + + @Test + public void tphCreateDropsKeyDiscriminatorReadOnlyAndSiblingColumns() throws Exception { + Path gen = generate("tph", TPH); + String controller = Files.readString(gen.resolve("acme/own/AuthController.java")); + // union components: id, type, reference, grade, quantity, approver + assertTrue("Bridge route keeps reference and quantity only; saw:\n" + controller, + controller.contains("dto = new AuthDto(null, null, dto.reference(), null, dto.quantity(), null);")); + assertTrue("Permit route keeps reference and approver only; saw:\n" + controller, + controller.contains("dto = new AuthDto(null, null, dto.reference(), null, null, dto.approver());")); + } +} diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java index 82d363976f..37597aa938 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java @@ -26,7 +26,7 @@ * {@code tags -> Tag} through {@code AuthTag} — resolved by the base AND, inherited, by * every concrete subtype. {@code BridgeAuth} ALSO declares its own directed self-join M:N * {@code linkedAuths -> BridgeAuth} through {@code AuthLink} — resolved by Bridge only. - * {@code CopayAuth} declares no M:N of its own.

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

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

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

* *

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

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

*/ public class TphDiscriminatorEnumConformanceTest extends SharedRegistryTestBase { @@ -58,7 +58,7 @@ public void tphEnumDiscriminatorIsTypedAsTheEnumNotString() throws Exception { assertTrue("the @discriminator field.enum must be typed as the generated enum; saw:\n" + src, src.contains("AuthType type")); assertTrue("the discriminator enum must be materialized with its @values; saw:\n" + src, - src.contains("public enum AuthType { Bridge, Copay, PriorAuth }")); + src.contains("public enum AuthType { Bridge, Coupon, Permit }")); assertFalse("the @discriminator must NOT regress to a raw String component; saw:\n" + src, src.contains("String type")); } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt new file mode 100644 index 0000000000..1dff73a42e --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt @@ -0,0 +1,38 @@ +package com.metaobjects.integration.kotlin + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.test.assertEquals + +/** + * field.duration orders on every engine (port-local scenario `duration-ordering/`): a range + * filter, an equality across spellings and a sort, through Exposed, on Postgres (native interval) + * and SQLite (a 64-bit microsecond count). + */ +internal class DurationOrderingScenarioTest { + + private fun scenario(): Scenarios.QueryScenario { + val dir = Path.of(DurationOrderingScenarioTest::class.java.getResource("/duration-ordering")!!.toURI()) + val all = ScenarioLoader.loadQueries(dir) + assertEquals(1, all.size) + return all[0] + } + + @Test + fun `orders on SQLite`(@TempDir dir: Path) { + val s = scenario() + assertDoesNotThrow { + QueryScenarioRunner.run(s, "jdbc:sqlite:${dir.resolve("duration.db")}", "", "", ScenarioEngine.SQLITE) + } + } + + @Test + fun `orders on Postgres`() { + val s = scenario() + assertDoesNotThrow { + PostgresContainer().use { pg -> QueryScenarioRunner.run(s, pg) } + } + } +} diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt index 5032150ae4..9e0bb0809d 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt @@ -552,7 +552,7 @@ object QueryScenarioRunner { "LedgerEntry" -> LedgerEntryTable "ArchivedLedgerEntry" -> ArchivedLedgerEntryTable // FR-017 TPH: the discriminator base + all its subtypes share the single `auths` table. - "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth" -> AuthTable + "Auth", "BridgeAuth", "CouponAuth", "PermitAuth" -> AuthTable else -> error("No Exposed Table registered for entity '$entity' — extend QueryScenarioRunner.tableFor or tables/ReportViews") } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/UnknownFieldsHostMapperIndependenceTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/UnknownFieldsHostMapperIndependenceTest.kt index 2811613e83..1f99c3895b 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/UnknownFieldsHostMapperIndependenceTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/UnknownFieldsHostMapperIndependenceTest.kt @@ -169,13 +169,13 @@ internal class UnknownFieldsHostMapperIndependenceTest { ] } }, { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ { "field.string": { "name": "approver" } } ] } } ] } } """.trimIndent() diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt index c90f06be67..8a682c71b4 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt @@ -30,8 +30,8 @@ import kotlin.test.assertTrue * The `Auth` base owns `lines: many AuthLine`, inherited by every subtype. If any generator failed * to fold a subtype into the base — the table's back-FK inference (`buildGlobalFkMap`), the relations * helper, or the validator registry — it would emit a reference to a `BridgeAuthTable` / - * `CopayAuthTable` / `PriorAuthAuthTable` that the table generator no longer emits, and this compile - * would fail. `CopayAuth` also carries a non-discriminator `@filterable field.enum` (`tier`) that + * `CouponAuthTable` / `PermitAuthTable` that the table generator no longer emits, and this compile + * would fail. `CouponAuth` also carries a non-discriminator `@filterable field.enum` (`tier`) that * folds into the union, so the TPH controller emits `castTo(TextColumnType())` for it — this * gate also covers the #179 enum-filter import block on the TPH controller path. */ @@ -43,7 +43,7 @@ class TphFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true } }, { "relationship.composition": { "name": "lines", "@cardinality": "many", "@objectRef": "AuthLine", "@onDelete": "cascade" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } @@ -51,12 +51,12 @@ class TphFullSuiteCompilesTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true, "@filterable": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } }, { "field.enum": { "name": "tier", "@values": ["Standard", "Premium"], "@filterable": true } } ] } }, - { "object.entity": { "name": "PriorAuthAuth", "extends": "Auth", "@discriminatorValue": "PriorAuth", "children": [ - { "field.string": { "name": "priorAuthNumber", "@maxLength": 80, "@filterable": true } } + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ + { "field.string": { "name": "permitNumber", "@maxLength": 80, "@filterable": true } } ] } }, { "object.entity": { "name": "AuthLine", "children": [ { "source.rdb": { "@table": "auth_lines" } }, @@ -90,8 +90,8 @@ class TphFullSuiteCompilesTest { val names = emitted.map { it.fileName.toString() }.toSet() // The subtypes fold into the base — no per-subtype persistence artifact of any kind. for (dead in listOf( - "BridgeAuthTable.kt", "CopayAuthTable.kt", "PriorAuthAuthTable.kt", - "BridgeAuthRelations.kt", "CopayAuthRelations.kt", "PriorAuthAuthRelations.kt", + "BridgeAuthTable.kt", "CouponAuthTable.kt", "PermitAuthTable.kt", + "BridgeAuthRelations.kt", "CouponAuthRelations.kt", "PermitAuthRelations.kt", )) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -115,7 +115,7 @@ class TphFullSuiteCompilesTest { @Test fun `FR-017 full TPH generator suite with the names artifact in the run compiles and folds the subtype columns`() { // Task 6 — the names-ON arm. The base's AuthTable references `Names.
_COLUMN` - // for every SUBTYPE column it folds in (quantity / copayAmount / tier / priorAuthNumber + // for every SUBTYPE column it folds in (quantity / couponAmount / tier / permitNumber // belong to the subtypes' artifacts, not AuthNames). A text assertion proves the // reference is SPELLED; only the compiler proves it RESOLVES, and only the compiled // Exposed object proves it folds to the column the database has. @@ -140,10 +140,10 @@ class TphFullSuiteCompilesTest { val emitted = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() val authTable = emitted.first { it.fileName.toString() == "AuthTable.kt" }.readText() assertTrue("integer(BridgeAuthNames.QUANTITY_COLUMN).nullable()" in authTable, authTable) - assertTrue("portableDecimal(CopayAuthNames.COPAY_AMOUNT_COLUMN, 10, 2).nullable()" in authTable, authTable) - assertTrue("varchar(PriorAuthAuthNames.PRIOR_AUTH_NUMBER_COLUMN, 80).nullable()" in authTable, authTable) + assertTrue("portableDecimal(CouponAuthNames.COUPON_AMOUNT_COLUMN, 10, 2).nullable()" in authTable, authTable) + assertTrue("varchar(PermitAuthNames.PERMIT_NUMBER_COLUMN, 80).nullable()" in authTable, authTable) // An enum with no configured length is a text column, as `meta migrate` creates it. - assertTrue("customEnumeration(CopayAuthNames.TIER_COLUMN, \"TEXT\", { v -> AuthTier.valueOf(v as String) }, { e -> e.name }).nullable()" in authTable, authTable) + assertTrue("customEnumeration(CouponAuthNames.TIER_COLUMN, \"TEXT\", { v -> AuthTier.valueOf(v as String) }, { e -> e.name }).nullable()" in authTable, authTable) val sources = emitted.map { path -> SourceFile.kotlin(outDir.relativize(path).toString().replace('/', '_'), path.readText()) @@ -161,7 +161,7 @@ class TphFullSuiteCompilesTest { val table = result.classLoader.loadClass("acme.auth.AuthTable").getDeclaredField("INSTANCE").get(null) as Table assertEquals("auths", table.tableName) val columns = table.columns.map { it.name }.toSet() - for (col in listOf("id", "type", "reference", "quantity", "copay_amount", "tier", "prior_auth_number")) { + for (col in listOf("id", "type", "reference", "quantity", "coupon_amount", "tier", "permit_number")) { assertTrue(col in columns, "AuthTable is missing column $col; has $columns") } } finally { diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt index f0a516c332..30627ddd48 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt @@ -59,7 +59,7 @@ internal class TphGeneratedApiContractConformanceTest { @Test @Suppress("UNCHECKED_CAST") fun tphListsSupportFr009Filters() { - HARNESS.reset() // seed: Bridge id1 (quantity 5), Copay id2, PriorAuth id3 + HARNESS.reset() // seed: Bridge id1 (quantity 5), Coupon id2, Permit id3 val r1 = HARNESS.exchange("GET", "/api/auths?filter[quantity][eq]=5&sort=id:asc", null) assertEquals(200, r1.status) val rows1 = HARNESS.parseBody(r1.body) as List> @@ -76,7 +76,7 @@ internal class TphGeneratedApiContractConformanceTest { assertEquals("invalid_filter_field", (HARNESS.parseBody(r4.body) as Map)["error"]) // Polymorphic list filtered by the DISCRIMINATOR (FR-017 "Filter allowlists": the base // allowlist includes it). Kotlin excluded it until 1.0.5 and answered this with r4's 400. - val r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Copay&sort=id:asc", null) + val r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc", null) assertEquals(200, r5.status, r5.body) val rows5 = HARNESS.parseBody(r5.body) as List> assertEquals(listOf(1, 2), rows5.map { (it["id"] as Number).toInt() }) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt index 679fd9e287..8c2a564b52 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt @@ -41,7 +41,7 @@ class TphM2mFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -52,8 +52,8 @@ class TphM2mFullSuiteCompilesTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -103,7 +103,7 @@ class TphM2mFullSuiteCompilesTest { val names = emitted.map { it.fileName.toString() }.toSet() // The subtypes fold into the base — no per-subtype persistence artifact of any kind, // M:N included (the whole point: linkedAuths must NOT try to reference BridgeAuthTable). - for (dead in listOf("BridgeAuthTable.kt", "CopayAuthTable.kt", "BridgeAuthRelations.kt", "CopayAuthRelations.kt")) { + for (dead in listOf("BridgeAuthTable.kt", "CouponAuthTable.kt", "BridgeAuthRelations.kt", "CouponAuthRelations.kt")) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -119,9 +119,9 @@ class TphM2mFullSuiteCompilesTest { val controller = emitted.first { it.fileName.toString() == "AuthController.kt" }.readText() assertTrue("@GetMapping(\"/{id}/tags\")" in controller, controller) assertTrue("@GetMapping(\"/bridge/{id}/tags\")" in controller, controller) - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in controller, controller) + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in controller, controller) assertTrue("@GetMapping(\"/bridge/{id}/linkedAuths\")" in controller, controller) - assertFalse("/copay/{id}/linkedAuths" in controller, controller) + assertFalse("/coupon/{id}/linkedAuths" in controller, controller) val sources = emitted.map { path -> SourceFile.kotlin(outDir.relativize(path).toString().replace('/', '_'), path.readText()) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt index 39e0e76e28..9e82dc3dfb 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt @@ -25,11 +25,11 @@ import kotlin.test.assertTrue * [TphM2mFullSuiteCompilesTest], which covers the (unshadowed) base-declared + subtype-own case. * * Before this fix, [com.metaobjects.generator.kotlin.KotlinRelationsGenerator]'s TPH-wide M:N nav - * union deduped by relation NAME alone (first-seen wins), so `CopayAuth`'s shadowing `tags -> + * union deduped by relation NAME alone (first-seen wins), so `CouponAuth`'s shadowing `tags -> * SpecialTag` nav was silently DROPPED and `AuthRelations.kt` emitted only ONE `tagsQuery` helper * — built from `Auth`'s own `tags -> Tag` shape. [com.metaobjects.generator.kotlin.KotlinSpringControllerGenerator], * however, independently RE-RESOLVES each subtype's own nav for its return type + row mapping, so - * the generated `tagsCopay()` endpoint declared `ResponseEntity>` and mapped + * the generated `tagsCoupon()` endpoint declared `ResponseEntity>` and mapped * `row[SpecialTagTable.*]` — off rows the WRONG-target `AuthTable.tagsQuery(id)` helper produced * (a `Tag`/`AuthTag` join). This is the "compiles, wrong at runtime" shape: every reference here * is a statically valid `Column`, so the pre-fix code compiles cleanly and only throws when the @@ -45,7 +45,7 @@ class TphM2mShadowedFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -54,10 +54,10 @@ class TphM2mShadowedFullSuiteCompilesTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", - "@objectRef": "SpecialTag", "@through": "CopaySpecialTag" } } + "@objectRef": "SpecialTag", "@through": "CouponSpecialTag" } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -79,12 +79,12 @@ class TphM2mShadowedFullSuiteCompilesTest { { "identity.reference": { "name": "fkAuth", "@fields": "authId", "@references": "Auth" } }, { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } ] } }, - { "object.entity": { "name": "CopaySpecialTag", "children": [ - { "source.rdb": { "@table": "copay_special_tags" } }, - { "field.long": { "name": "copayAuthId", "@required": true } }, + { "object.entity": { "name": "CouponSpecialTag", "children": [ + { "source.rdb": { "@table": "coupon_special_tags" } }, + { "field.long": { "name": "couponAuthId", "@required": true } }, { "field.long": { "name": "specialTagId", "@required": true } }, - { "identity.primary": { "@fields": ["copayAuthId", "specialTagId"] } }, - { "identity.reference": { "name": "fkCopay", "@fields": "copayAuthId", "@references": "CopayAuth" } }, + { "identity.primary": { "@fields": ["couponAuthId", "specialTagId"] } }, + { "identity.reference": { "name": "fkCoupon", "@fields": "couponAuthId", "@references": "CouponAuth" } }, { "identity.reference": { "name": "fkSpecialTag", "@fields": "specialTagId", "@references": "SpecialTag" } } ] } } ] } @@ -111,7 +111,7 @@ class TphM2mShadowedFullSuiteCompilesTest { val emitted = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() val names = emitted.map { it.fileName.toString() }.toSet() - for (dead in listOf("BridgeAuthTable.kt", "CopayAuthTable.kt", "BridgeAuthRelations.kt", "CopayAuthRelations.kt")) { + for (dead in listOf("BridgeAuthTable.kt", "CouponAuthTable.kt", "BridgeAuthRelations.kt", "CouponAuthRelations.kt")) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -124,25 +124,25 @@ class TphM2mShadowedFullSuiteCompilesTest { assertTrue("TagTable" in tagsQueryBody, tagsQueryBody) assertFalse("SpecialTagTable" in tagsQueryBody, tagsQueryBody) - // The shadowing CopayAuth shape must have gotten its OWN, distinctly-named helper - // (not collapsed into tagsQuery), joining SpecialTag/CopaySpecialTag. + // The shadowing CouponAuth shape must have gotten its OWN, distinctly-named helper + // (not collapsed into tagsQuery), joining SpecialTag/CouponSpecialTag. val helperNames = Regex("""fun AuthTable\.(tags\w*)Query\(""").findAll(relations) .map { it.groupValues[1] }.toSet() assertTrue(helperNames.size >= 2, "expected >=2 distinct tags*Query helpers; found $helperNames in:\n$relations") val shadowHelper = helperNames.first { it != "tags" } val shadowBody = relations.substringAfter("fun AuthTable.${shadowHelper}Query").substringBefore("\n\n") assertTrue("SpecialTagTable" in shadowBody, shadowBody) - assertTrue("CopaySpecialTagTable" in shadowBody, shadowBody) + assertTrue("CouponSpecialTagTable" in shadowBody, shadowBody) assertFalse("AuthTagTable" in shadowBody, shadowBody) val controller = emitted.first { it.fileName.toString() == "AuthController.kt" }.readText() - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in controller, controller) - val tagsCopayBody = controller.substringAfter("fun tagsCopay(").substringBefore("\n }\n") - assertFalse("AuthTable.tagsQuery(id)" in tagsCopayBody, - "tagsCopay() must not delegate to the base-shape helper (wrong target); saw:\n$tagsCopayBody") - assertTrue("AuthTable.${shadowHelper}Query(id)" in tagsCopayBody, - "expected tagsCopay() to call its own $shadowHelper Query helper; saw:\n$tagsCopayBody") - assertTrue("row[SpecialTagTable." in tagsCopayBody, tagsCopayBody) + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in controller, controller) + val tagsCouponBody = controller.substringAfter("fun tagsCoupon(").substringBefore("\n }\n") + assertFalse("AuthTable.tagsQuery(id)" in tagsCouponBody, + "tagsCoupon() must not delegate to the base-shape helper (wrong target); saw:\n$tagsCouponBody") + assertTrue("AuthTable.${shadowHelper}Query(id)" in tagsCouponBody, + "expected tagsCoupon() to call its own $shadowHelper Query helper; saw:\n$tagsCouponBody") + assertTrue("row[SpecialTagTable." in tagsCouponBody, tagsCouponBody) // The unaffected mounts still delegate to the plain shared helper. val tagsBridgeBody = controller.substringAfter("fun tagsBridge(").substringBefore("\n }\n") diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt index 1dff027311..930abb1ec8 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt @@ -30,7 +30,7 @@ import kotlin.io.path.readText /** * FR-017 Tier 4/5 — host the GENERATED Kotlin Spring `@RestController` for the TPH corpus - * (`Auth` base + `Bridge`/`Copay`/`PriorAuth` subtypes) over real HTTP (an embedded Tomcat) + * (`Auth` base + `Bridge`/`Coupon`/`Permit` subtypes) over real HTTP (an embedded Tomcat) * and drive the polymorphic-CRUD scenarios against it. * * Mechanism (the SP-F generate→compile→load pattern, mirroring [com.metaobjects.integration.kotlin.api.generated.GeneratedAuthorControllerHarness]): @@ -151,7 +151,7 @@ class GeneratedTphControllerHarness( // autoCreatedAt stays OLD — the two robustly diverge. // // `id` is OMITTED so the auto-increment PK assigns 1..3 in the seed's own order (empty table), - // exactly as the prior POST-seed did (1=Bridge, 2=Copay, 3=PriorAuth). Columns are matched by + // exactly as the prior POST-seed did (1=Bridge, 2=Coupon, 3=Permit). Columns are matched by // NAME normalized (lowercase, underscores stripped) so the field camelCase (autoCreatedAt) // resolves to the generated snake_case physical column (auto_created_at) regardless of naming // strategy; typed inserts (not raw SQL) let Exposed handle all dialect identifier quoting. @@ -175,7 +175,7 @@ class GeneratedTphControllerHarness( stmt[columnFor("autoCreatedAt")] = parseSeedInstant(r["autoCreatedAt"] as String) stmt[columnFor("autoUpdatedAt")] = parseSeedInstant(r["autoUpdatedAt"] as String) stmt[columnFor("quantity")] = (r["quantity"] as? Number)?.toInt() - stmt[columnFor("copayAmount")] = (r["copayAmount"] as? String)?.let { java.math.BigDecimal(it) } + stmt[columnFor("couponAmount")] = (r["couponAmount"] as? String)?.let { java.math.BigDecimal(it) } stmt[columnFor("approver")] = r["approver"] as String? } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt index 6c500413e7..78db46f75c 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt @@ -5,7 +5,7 @@ import org.jetbrains.exposed.sql.Table /** * Hand-written reference Exposed Table for the FR-017 Table-Per-Hierarchy (TPH) `auths` table * from `fixtures/persistence-conformance/canonical/meta.fitness.json` — the SINGLE physical table - * shared by the `Auth` discriminator base and its `BridgeAuth` / `CopayAuth` / `PriorAuthAuth` + * shared by the `Auth` discriminator base and its `BridgeAuth` / `CouponAuth` / `PermitAuth` * subtypes (single-table inheritance). * * Every subtype-only column is NULLABLE — a row of any other subtype stores NULL there, even @@ -18,15 +18,15 @@ import org.jetbrains.exposed.sql.Table * - `type` TEXT (discriminator, CHECK in DDL) → `varchar("type", 64)` * - `reference` VARCHAR(80) NOT NULL → `varchar("reference", 80)` * - `quantity` INTEGER (BridgeAuth-only) → `integer("quantity").nullable()` - * - `copayAmount` NUMERIC(10,2) (CopayAuth-only) → `decimal("copayAmount", 10, 2).nullable()` - * - `approver` VARCHAR(80) (PriorAuthAuth-only) → `varchar("approver", 80).nullable()` + * - `couponAmount` NUMERIC(10,2) (CouponAuth-only) → `decimal("couponAmount", 10, 2).nullable()` + * - `approver` VARCHAR(80) (PermitAuth-only) → `varchar("approver", 80).nullable()` */ object AuthTable : Table("auths") { val id = long("id").autoIncrement() val type = varchar("type", 64) val reference = varchar("reference", 80) val quantity = integer("quantity").nullable() - val copayAmount = portableDecimal("copayAmount", 10, 2).nullable() + val couponAmount = portableDecimal("couponAmount", 10, 2).nullable() val approver = varchar("approver", 80).nullable() override val primaryKey = PrimaryKey(id) diff --git a/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml b/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml new file mode 100644 index 0000000000..05518659bd --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml @@ -0,0 +1,71 @@ +name: duration-ordering +description: | + Port-local (Kotlin / Exposed runner; the SQLite seed spells timestamps the way Exposed's SQLite + dialect reads them): field.duration orders on every engine. Postgres keeps a + native interval; SQLite stores a 64-bit count of microseconds. A range filter (gt / lte), an + equality on a differently-spelled span, and a sort all compare spans, never text. +engines: [postgres, sqlite] +seed-data: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', '00:30:00'), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', '01:30:00'), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', '-00:01:30'), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', '26:00:00'), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +seed-data-engine: + sqlite: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', 1800000000), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', 5400000000), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', -90000000), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', 93600000000), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +queries: + - name: longer-than-an-hour + op: count + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + expect: 2 + + - name: at-most-thirty-minutes-includes-a-negative-span + op: count + entity: AllTypes + filter: { durationVal: { lte: "PT30M" } } + expect: 2 + + - name: equality-across-spellings + op: count + entity: AllTypes + filter: { durationVal: { eq: "PT5400S" } } + expect: 1 + + - name: longer-than-an-hour-longest-first + op: list + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + sort: [{ field: durationVal, dir: desc }] + expect: + - { id: "00000004-0000-4000-8000-000000000004", sVal: "long", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000004-0000-4000-8000-000000000004", uriVal: "urn:example:long", + inetVal: "10.0.0.4", inet6Val: "fe80::4", durationVal: "PT26H", settings: null, labels: null } + - { id: "00000002-0000-4000-8000-000000000002", sVal: "ninety", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000002-0000-4000-8000-000000000002", uriVal: "urn:example:ninety", + inetVal: "10.0.0.2", inet6Val: "fe80::2", durationVal: "PT1H30M", settings: null, labels: null } + + - name: shortest-two + op: list + entity: AllTypes + filter: { durationVal: { isNull: false } } + sort: [{ field: durationVal, dir: asc }] + limit: 2 + expect: + - { id: "00000003-0000-4000-8000-000000000003", sVal: "minus", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000003-0000-4000-8000-000000000003", uriVal: "urn:example:minus", + inetVal: "10.0.0.3", inet6Val: "fe80::3", durationVal: "-PT1M30S", settings: null, labels: null } + - { id: "00000001-0000-4000-8000-000000000001", sVal: "thirty", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000001-0000-4000-8000-000000000001", uriVal: "urn:example:thirty", + inetVal: "10.0.0.1", inet6Val: "fe80::1", durationVal: "PT30M", settings: null, labels: null } diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java new file mode 100644 index 0000000000..5b9f60c11f --- /dev/null +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java @@ -0,0 +1,59 @@ +package com.metaobjects.integration; + +import com.metaobjects.integration.Scenarios.QueryScenario; +import com.metaobjects.object.value.ValueObject; +import com.metaobjects.registry.ObjectClassRegistry; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * field.duration orders on every engine (port-local scenario {@code duration-ordering/}): a range + * filter, an equality across spellings and a sort, through OMDB, on Postgres (native interval) + * and SQLite (a 64-bit microsecond count). + */ +final class DurationOrderingScenarioTests { + + private static final Path CORPUS = ScenarioLoader.findCorpusRoot(); + + private static QueryScenario scenario() throws URISyntaxException { + Path dir = Path.of(DurationOrderingScenarioTests.class.getResource("/duration-ordering").toURI()); + List all = ScenarioLoader.loadQueries(dir); + assertEquals(1, all.size()); + return all.get(0); + } + + @BeforeAll + static void beforeAll() { + ObjectClassRegistry reg = new ObjectClassRegistry(); + reg.register(() -> Map.of("fitness::AllTypes", ValueObject.class)); + ObjectClassRegistry.setGlobal(reg); + } + + @Test + void ordersOnSqlite() throws Exception { + QueryScenario s = scenario(); + assertDoesNotThrow(() -> { + try (SqliteDatabase db = new SqliteDatabase()) { + QueryScenarioRunner.run(s, db, CORPUS.resolve("canonical"), ScenarioEngine.SQLITE); + } + }); + } + + @Test + void ordersOnPostgres() throws Exception { + QueryScenario s = scenario(); + assertDoesNotThrow(() -> { + try (PostgresContainer pg = new PostgresContainer()) { + QueryScenarioRunner.run(s, pg, CORPUS.resolve("canonical")); + } + }); + } +} diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java index a62615fc69..677bee9ad5 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java @@ -109,8 +109,8 @@ static void beforeAll() { // FR-017 TPH corpus entities — the discriminator base + its three subtypes (single table). bindings.put("fitness::Auth", ValueObject.class); bindings.put("fitness::BridgeAuth", ValueObject.class); - bindings.put("fitness::CopayAuth", ValueObject.class); - bindings.put("fitness::PriorAuthAuth", ValueObject.class); + bindings.put("fitness::CouponAuth", ValueObject.class); + bindings.put("fitness::PermitAuth", ValueObject.class); // ADR-0019 Amendment 1 decimal corpus + the redeclared-field report's tables. bindings.put("fitness::Entry", ValueObject.class); bindings.put("fitness::Gadget", ValueObject.class); diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java index 3279ef8aae..4f78d2b08d 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java @@ -108,7 +108,7 @@ void scenario(String name, ApiScenario scenario) { @Test @SuppressWarnings("unchecked") void tphListsSupportFr009Filters() throws Exception { - HARNESS.reset(); // seed: Bridge id1 (quantity 5), Copay id2, PriorAuth id3 + HARNESS.reset(); // seed: Bridge id1 (quantity 5), Coupon id2, Permit id3 // (a) polymorphic list filtered by a SUBTYPE column — only the Bridge row carries quantity. var r1 = HARNESS.exchange("GET", "/api/auths?filter[quantity][eq]=5&sort=id:asc", null); org.junit.jupiter.api.Assertions.assertEquals(200, r1.status()); @@ -130,7 +130,7 @@ void tphListsSupportFr009Filters() throws Exception { ((Map) HARNESS.parseBody(r4.body())).get("error")); // (e) polymorphic list filtered by the DISCRIMINATOR (FR-017 "Filter allowlists": the base // allowlist includes it). Java excluded it until 1.0.5 and answered this with (d)'s 400. - var r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Copay&sort=id:asc", null); + var r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc", null); org.junit.jupiter.api.Assertions.assertEquals(200, r5.status(), r5.body()); var rows5 = (List>) HARNESS.parseBody(r5.body()); org.junit.jupiter.api.Assertions.assertEquals(List.of(1, 2), diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java index 9ec45f7154..f34e48315d 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java @@ -45,7 +45,7 @@ /** * FR-017 Tier 4/5 — host the GENERATED Java Spring {@code @RestController} for the TPH corpus - * ({@code Auth} base + {@code Bridge}/{@code Copay}/{@code PriorAuth} subtypes) over HTTP + * ({@code Auth} base + {@code Bridge}/{@code Coupon}/{@code Permit} subtypes) over HTTP * (a real embedded Tomcat, {@link TomcatHost}) and drive the polymorphic-CRUD scenarios against it. * *

Mechanism (the SP-F generate→compile→load pattern, mirroring @@ -82,7 +82,7 @@ public final class GeneratedTphControllerHarness implements AutoCloseable { private final ObjectMapper mapper; private final URLClassLoader classLoader; // (Long id, AuthType type, String reference, Instant autoCreatedAt, Instant autoUpdatedAt, - // Integer quantity, BigDecimal copayAmount, String approver) + // Integer quantity, BigDecimal couponAmount, String approver) private final Constructor dtoCtor; private final Class authTypeClass; // the generated value-constrained enum discriminator (AuthDto.AuthType) private final Constructor controllerCtor; // (AuthRepository, ObjectMapper, Validator) @@ -227,15 +227,15 @@ private Object dtoFromRow(Map row) throws Exception { Object autoUpdatedRaw = row.get("autoUpdatedAt"); Instant autoUpdatedAt = autoUpdatedRaw == null ? null : parseInstant(String.valueOf(autoUpdatedRaw)); Integer quantity = row.get("quantity") == null ? null : ((Number) row.get("quantity")).intValue(); - Object copayRaw = row.get("copayAmount"); - BigDecimal copayAmount = copayRaw == null ? null : new BigDecimal(String.valueOf(copayRaw)); + Object couponRaw = row.get("couponAmount"); + BigDecimal couponAmount = couponRaw == null ? null : new BigDecimal(String.valueOf(couponRaw)); String approver = (String) row.get("approver"); // Coerce the seed's String discriminator into the generated AuthType enum value. @SuppressWarnings({ "unchecked", "rawtypes" }) Object typeEnum = type == null ? null : Enum.valueOf((Class) authTypeClass, type); return dtoCtor.newInstance( id, typeEnum, reference, issuedCurrency, autoCreatedAt, autoUpdatedAt, - quantity, copayAmount, approver); + quantity, couponAmount, approver); } /** diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java index f8343cbb49..6f249ff607 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java @@ -116,7 +116,7 @@ public AuthDto createWithType(String discriminator, AuthDto dto) { // FR-037 R1: writeOnce IS bound on create — settable exactly once. dto.issuedCurrency(), dto.autoCreatedAt(), dto.autoUpdatedAt(), - dto.quantity(), dto.copayAmount(), dto.approver()); + dto.quantity(), dto.couponAmount(), dto.approver()); rows.add(saved); return saved; } @@ -134,7 +134,7 @@ public Optional updateByIdAndType(Long id, String discriminator, AuthDt dto.autoCreatedAt() != null ? dto.autoCreatedAt() : cur.autoCreatedAt(), dto.autoUpdatedAt() != null ? dto.autoUpdatedAt() : cur.autoUpdatedAt(), dto.quantity() != null ? dto.quantity() : cur.quantity(), - dto.copayAmount() != null ? dto.copayAmount() : cur.copayAmount(), + dto.couponAmount() != null ? dto.couponAmount() : cur.couponAmount(), dto.approver() != null ? dto.approver() : cur.approver()); rows.set(i, merged); return Optional.of(merged); @@ -166,7 +166,7 @@ public Optional patchByIdAndType(Long id, String discriminator, Map a.type(); case "reference" -> a.reference(); case "quantity" -> a.quantity(); - case "copayAmount" -> a.copayAmount(); + case "couponAmount" -> a.couponAmount(); case "approver" -> a.approver(); default -> throw new IllegalStateException("unknown column: " + field); }; diff --git a/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml b/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml new file mode 100644 index 0000000000..a9f12641ac --- /dev/null +++ b/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml @@ -0,0 +1,70 @@ +name: duration-ordering +description: | + Port-local (Java / Kotlin JVM runners): field.duration orders on every engine. Postgres keeps a + native interval; SQLite stores a 64-bit count of microseconds. A range filter (gt / lte), an + equality on a differently-spelled span, and a sort all compare spans, never text. +engines: [postgres, sqlite] +seed-data: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', '00:30:00'), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', '01:30:00'), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', '-00:01:30'), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', '26:00:00'), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +seed-data-engine: + sqlite: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', 1800000000), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', 5400000000), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', -90000000), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', 93600000000), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +queries: + - name: longer-than-an-hour + op: count + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + expect: 2 + + - name: at-most-thirty-minutes-includes-a-negative-span + op: count + entity: AllTypes + filter: { durationVal: { lte: "PT30M" } } + expect: 2 + + - name: equality-across-spellings + op: count + entity: AllTypes + filter: { durationVal: { eq: "PT5400S" } } + expect: 1 + + - name: longer-than-an-hour-longest-first + op: list + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + sort: [{ field: durationVal, dir: desc }] + expect: + - { id: "00000004-0000-4000-8000-000000000004", sVal: "long", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000004-0000-4000-8000-000000000004", uriVal: "urn:example:long", + inetVal: "10.0.0.4", inet6Val: "fe80::4", durationVal: "PT26H", settings: null, labels: null } + - { id: "00000002-0000-4000-8000-000000000002", sVal: "ninety", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000002-0000-4000-8000-000000000002", uriVal: "urn:example:ninety", + inetVal: "10.0.0.2", inet6Val: "fe80::2", durationVal: "PT1H30M", settings: null, labels: null } + + - name: shortest-two + op: list + entity: AllTypes + filter: { durationVal: { isNull: false } } + sort: [{ field: durationVal, dir: asc }] + limit: 2 + expect: + - { id: "00000003-0000-4000-8000-000000000003", sVal: "minus", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000003-0000-4000-8000-000000000003", uriVal: "urn:example:minus", + inetVal: "10.0.0.3", inet6Val: "fe80::3", durationVal: "-PT1M30S", settings: null, labels: null } + - { id: "00000001-0000-4000-8000-000000000001", sVal: "thirty", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000001-0000-4000-8000-000000000001", uriVal: "urn:example:thirty", + inetVal: "10.0.0.1", inet6Val: "fe80::1", durationVal: "PT30M", settings: null, labels: null } diff --git a/server/java/metadata/conformance-expected-failures.json b/server/java/metadata/conformance-expected-failures.json index 6a7cb91a2c..10f1aeecf9 100644 --- a/server/java/metadata/conformance-expected-failures.json +++ b/server/java/metadata/conformance-expected-failures.json @@ -3,5 +3,12 @@ "_comment": "FR-013/FR-014/FR-015 validation passes shipped. The former subtype-field-override gap (MergedSource envelopes on extends-overrides) is RETIRED: FR-024's addressing-model fix (bare nested names + own-children-only overlay lookup in BaseMetaDataParser) made subtype same-name children SHADOWING REDECLARATIONS per the cross-port contract, which was the root cause \u2014 error-field-readonly-downgrade and field-readonly-upgrade-on-subtype now pass byte-identically.", "_comment_ai_pilot": "ai-trace-* fixtures now pass in Java (@responseRef + template.* child admitted)", "_comment_fr024": "FR-024 validation parity SHIPPED in this port (ValidationPhase.java): subtype rules (identity-name, value purity, projection licensing), projection identity pass-through + key correspondence, source-role B4b cutover (ERR_ENTITY_PRIMARY_SOURCE_READONLY), origin @via single-hop inference + cardinality + extends/origin agreement, and derived-field providability. All 13 FR-024 error fixtures emit their expected code + envelope. Kotlin rides this same JVM loader. B4b landed with the FR-024 projection-codegen increment (proc/view-primary entity fixtures migrated to object.projection).", - "fixtures": [] + "_comment_rc21": "rc.21 view vocabulary validation is not implemented in Java; these fixtures also fail on origin/fix/rc19; implementedIn typescript, csharp. A listed fixture that starts passing fails the run (fixed-but-listed), so remove it from this list then.", + "fixtures": [ + "projection-view-vocabulary-rc21", + "error-computed-cast-enum-not-int-stored", + "error-origin-function-free-sql", + "error-projection-grain-not-object-array", + "error-projection-union-shape" + ] } diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 9c594edf01..c3edaf70fd 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -305,6 +305,10 @@ public enum ErrorCode { ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, ERR_SEQUENCE_WITHOUT_INCREMENT, ERR_SEQUENCE_START_OUT_OF_RANGE, + /** A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. */ + ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + /** A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. */ + ERR_CROSS_FIELD_WITHOUT_CHECK, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java index c745277398..b88617dd51 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java @@ -148,6 +148,11 @@ public WireFormat getWireFormat() { return wireFormat; } + /** The project's enum storage defaults ({@code enums} in this file). Never {@code null}. */ + public EnumDefaults getEnumDefaults() { + return enumDefaults; + } + /** * The project's {@code api} block ({@code api.pagination}, {@code api.unknownFields}), absent * keys at their defaults (no page size, {@code reject}). Never {@code null}. @@ -156,11 +161,6 @@ public ApiSettings getApiSettings() { return apiSettings; } - /** The project's enum storage defaults ({@code enums} in this file). Never {@code null}. */ - public EnumDefaults getEnumDefaults() { - return enumDefaults; - } - /** The schema settings a mapping generator agrees with ({@code migrate.foreignKeyIndexes} and friends). */ public MigrateSettings getMigrateSettings() { return migrateSettings; diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java index 5ed395ec73..2b4d181db4 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java @@ -107,7 +107,26 @@ public class CoreDBMetaDataProvider implements MetaDataTypeProvider { * with the Kotlin port via this JVM provider.

*/ public static final java.util.List VALID_DB_COLUMN_TYPES = java.util.List.of( - DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB); + DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, "text", "varchar", "character varying"); + + /** rc.21 part B (U2): the sized text spellings, as written in a message. */ + public static final java.util.List DB_COLUMN_TYPE_SIZED_SPELLINGS = + java.util.List.of("varchar(n)", "character varying(n)", "character(n)"); + + private static final java.util.regex.Pattern SIZED_DB_COLUMN_TYPE = + java.util.regex.Pattern.compile("^(varchar|character varying|character)\\(([1-9][0-9]{0,8})\\)$"); + + /** + * rc.21 part B (U2): the declared length of a sized {@code @dbColumnType} spelling + * ({@code varchar(n)}, {@code character varying(n)}, {@code character(n)}), 0 for a legal bare + * value, or -1 when the value is not legal. Postgres's own spellings, as every port parses them. + */ + public static int dbColumnTypeLength(String value) { + if (value == null) return -1; + if (VALID_DB_COLUMN_TYPES.contains(value)) return 0; + java.util.regex.Matcher m = SIZED_DB_COLUMN_TYPE.matcher(value); + return m.matches() ? Integer.parseInt(m.group(2)) : -1; + } @Override public String getProviderId() { @@ -165,6 +184,10 @@ public void registerTypes(MetaDataRegistry registry) { registry.extendType(c, def -> def .optionalAttributeWithConstraints(com.metaobjects.validator.MetaValidator.ATTR_CONSTRAINT_NAME) .ofType(StringAttribute.SUBTYPE_STRING).asSingle()); + // @dbCheck: false asks the same node for no CHECK at all (rc.20). + registry.extendType(c, def -> def + .optionalAttributeWithConstraints(com.metaobjects.validator.MetaValidator.ATTR_DB_CHECK) + .ofType(com.metaobjects.attr.BooleanAttribute.SUBTYPE_BOOLEAN).asSingle()); } // --- index.lookup RDB-physical attrs --- diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java index 8867237376..d4bc455988 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java @@ -45,7 +45,8 @@ public static Long resolveMaxLength(MetaField field) { ? field.getMetaAttr(EnumField.ATTR_VALUES).getValue() : null; if (raw instanceof List values) { for (Object o : values) { - String v = String.valueOf(o); + // rc.21: the column holds each member's STORED string (@stringValueMap). + String v = EnumField.storedValue(field, String.valueOf(o)); if (longest == null || v.length() > longest.length()) longest = v; } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java index 6693bbc236..6f1fb44283 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java @@ -99,6 +99,20 @@ public class EnumField extends PrimitiveField { */ public static final String ATTR_INT_VALUE_MAP = "intValueMap"; + /** + * rc.21 — optional per-member stored strings ({member: string}) of a string-stored enum, the + * string twin of {@link #ATTR_INT_VALUE_MAP}. Keys must match {@code @values}; values are unique + * non-empty strings; refused with {@code @intValueMap} and on an array enum (ValidationPhase). + */ + public static final String ATTR_STRING_VALUE_MAP = "stringValueMap"; + + /** rc.21 — the string {@code member} is stored as: its {@code @stringValueMap} entry (resolving), else the member. */ + public static String storedValue(MetaField field, String member) { + if (!field.hasMetaAttr(ATTR_STRING_VALUE_MAP)) return member; + Object raw = field.getMetaAttr(ATTR_STRING_VALUE_MAP).getValue(); + return raw instanceof java.util.Map map && map.get(member) instanceof String s && !s.isEmpty() ? s : member; + } + /** * Name of the optional per-member description map (properties). * Each key is an enum member symbol from {@code @values}; the value is a @@ -226,6 +240,12 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(com.metaobjects.attr.IntMapAttribute.SUBTYPE_INT_MAP) .asSingle(); + // rc.21 — optional @stringValueMap ({member: string}); content rules in + // ValidationPhase.validateEnumStringValueMap. + def.optionalAttributeWithConstraints(ATTR_STRING_VALUE_MAP) + .ofType(com.metaobjects.attr.PropertiesAttribute.SUBTYPE_PROPERTIES) + .asSingle(); + // Optional @maxLength — the column length of a string-stored enum (VARCHAR(n)). // Every member must fit, and it is refused beside @intValueMap; both checked // post-load in ValidationPhase.validateEnumMaxLength. diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 6342303203..d501356d0f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -268,6 +268,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { validateIdentitySequence(root, collected); validateCrossFieldValidators(root, collected, loader != null && loader.getLoaderOptions() != null && loader.getLoaderOptions().isStrict()); + validateDbCheck(root, collected); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -834,6 +835,7 @@ private static void validateEnumNode(MetaData node) { // owned by this node is validated here against the node's EFFECTIVE @values // (own or inherited via extends), mirroring the TS/C# port structure exactly. validateEnumIntValueMap(node); + validateEnumStringValueMap(node); // --- Own @values content check --- if (node.hasMetaAttr(EnumField.ATTR_VALUES, false)) { @@ -984,6 +986,72 @@ private static void validateEnumIntValueMap(MetaData node) { } } + /** + * rc.21 — {@code @stringValueMap} content rules: the string twin of + * {@link #validateEnumIntValueMap}, with its policies (own-only; a shared enum's backing owned by + * the shared declaration). Keys must exactly match the effective {@code @values}; values are + * unique non-empty strings. Refused beside {@code @intValueMap} and on an array enum. Mirrors + * TypeScript {@code attr-schema-validate} Check 5c. + */ + private static void validateEnumStringValueMap(MetaData node) { + if (!node.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP, false)) { + return; + } + String prefix = ": field.enum '" + node.getName() + "' attribute '@" + EnumField.ATTR_STRING_VALUE_MAP + "' "; + MetaData sharedSuper = sharedEnumSuper(node); + if (sharedSuper != null) { + throw new MetaDataException(ErrorMessageConstants.ERR_ENUM_EXTENDS_VALUES_CONFLICT + prefix + + "is declared on a field extending shared abstract enum '" + sharedSuper.getName() + + "' - a shared enum's stored strings are owned by the shared declaration; move it onto '" + + sharedSuper.getName() + "' to inherit it.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT, node.getSource()); + } + if (node.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "is refused beside '@" + EnumField.ATTR_INT_VALUE_MAP + + "': an @intValueMap enum is stored as integers, not strings. Keep one.", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + if (node instanceof MetaField field && field.isArrayType()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "is refused on an array enum: its column holds the members as text[] elements, which no port maps through @" + + EnumField.ATTR_STRING_VALUE_MAP + ".", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + Object raw = node.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP, false).getValue(); + if (!(raw instanceof Map map)) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "must be an object of { member: storedString }.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + List effective = effectiveEnumValues(node); + Set memberSet = new HashSet<>(effective); + Set keySet = new HashSet<>(); + for (Object k : map.keySet()) keySet.add(String.valueOf(k)); + List missing = effective.stream().filter(m -> !keySet.contains(m)).toList(); + List extra = keySet.stream().filter(k -> !memberSet.contains(k)).sorted().toList(); + if (!missing.isEmpty() || !extra.isEmpty()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "keys must exactly match '@" + EnumField.ATTR_VALUES + "' members" + + (missing.isEmpty() ? "" : " (missing: " + String.join(", ", missing) + ")") + + (extra.isEmpty() ? "" : " (unknown: " + String.join(", ", extra) + ")") + ".", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + Map seen = new HashMap<>(); + for (String member : effective) { + Object value = map.get(member); + if (!(value instanceof String stored) || stored.isEmpty()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "member '" + member + "' must map to a non-empty string.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + String owner = seen.putIfAbsent(stored, member); + if (owner != null) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "members '" + owner + "' and '" + member + "' share the stored string '" + stored + + "'; every member must have a unique one.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + } + } + /** * FR-011 own-attr validation for a {@code field.enum} node: *
    @@ -1187,24 +1255,35 @@ private static void validateDbColumnTypeNode(MetaData node) { String value = node.getMetaAttr(CoreDBMetaDataProvider.DB_COLUMN_TYPE, false) .getValueAsString(); - // Rule 1: recognized value. - if (value == null || !CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES.contains(value)) { + // Rule 1: recognized value (rc.21: the text spellings, sized ones included). + int length = CoreDBMetaDataProvider.dbColumnTypeLength(value); + if (length < 0) { throw new MetaDataException( ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": field '" + node.getName() + "' @" + CoreDBMetaDataProvider.DB_COLUMN_TYPE + " '" + value + "' is not a valid value; allowed: " - + CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES, + + CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES + " and " + + CoreDBMetaDataProvider.DB_COLUMN_TYPE_SIZED_SPELLINGS, ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); } + // Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength would let the + // app accept a value the column refuses. ADR-0039: resolving. + if (length > 0 && node.hasMetaAttr("maxLength")) { + Object max = node.getMetaAttr("maxLength").getValue(); + if (max instanceof Number n && n.longValue() > length) { + throw new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + + ": field.string '" + node.getName() + "' declares @maxLength: " + n + + " over '@" + CoreDBMetaDataProvider.DB_COLUMN_TYPE + ": " + value + "', which holds " + + length + "; a value the field accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + } - // Rule 2: legal (subtype × value) pairing. + // Rule 2: legal (subtype × value) pairing — every value is field.string's. String subType = node.getSubType(); - String requiredSubType = switch (value) { - case CoreDBMetaDataProvider.DB_COLUMN_TYPE_UUID, - CoreDBMetaDataProvider.DB_COLUMN_TYPE_JSONB -> StringField.SUBTYPE_STRING; - default -> null; // unreachable — Rule 1 already rejected unknown values - }; + String requiredSubType = StringField.SUBTYPE_STRING; if (requiredSubType != null && !requiredSubType.equals(subType)) { throw new MetaDataException( ErrorMessageConstants.ERR_BAD_ATTR_VALUE @@ -2757,6 +2836,58 @@ private static void validateEnumMaxLengthNode(EnumField field) { } } + + // ========================================================================= + // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no + // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only + // by its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one + // error such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either + // of the two itself. Mirrors TS validateDbCheck. + // ========================================================================= + + private static final java.util.Set CROSS_FIELD_DB_CHECK_SUBTYPES = java.util.Set.of( + "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"); + + private static final java.util.Set DB_CHECK_VALIDATOR_SUBTYPES = java.util.Set.of( + "numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"); + + static void validateDbCheck(MetaRoot root, List out) { + for (MetaData child : root.getChildren(MetaData.class, false)) visitDbCheck(child, null, out); + } + + private static void visitDbCheck(MetaData node, String owner, List out) { + if (node instanceof com.metaobjects.attr.MetaAttribute) return; + String dbCheck = com.metaobjects.validator.MetaValidator.ATTR_DB_CHECK; + String constraintName = com.metaobjects.validator.MetaValidator.ATTR_CONSTRAINT_NAME; + boolean checked = ("validator".equals(node.getType()) && DB_CHECK_VALIDATOR_SUBTYPES.contains(node.getSubType())) + || ("field".equals(node.getType()) && "enum".equals(node.getSubType())); + if (checked && (node.hasMetaAttr(dbCheck, false) || node.hasMetaAttr(constraintName, false)) + && node.hasMetaAttr(dbCheck)) { + boolean off = "false".equalsIgnoreCase(String.valueOf(node.getMetaAttr(dbCheck).getValue())); + String name = node.hasMetaAttr(constraintName) ? node.getMetaAttr(constraintName).getValueAsString() : null; + String label = node.getType() + "." + node.getSubType() + " \"" + (owner == null ? "" : owner + ".") + + node.getShortName() + "\""; + if (off && "validator".equals(node.getType()) && CROSS_FIELD_DB_CHECK_SUBTYPES.contains(node.getSubType())) { + // A cross-field validator has no app-level enforcement: its CHECK is the rule. + out.add(new MetaDataException( + ErrorMessageConstants.ERR_CROSS_FIELD_WITHOUT_CHECK + + ": " + label + " sets @dbCheck: false, but this validator is enforced only by its CHECK," + + " so the rule would be enforced nowhere. Remove the validator, or remove @dbCheck: false.", + ErrorCode.ERR_CROSS_FIELD_WITHOUT_CHECK, node.getSource())); + } else if (off && name != null && !name.isEmpty()) { + out.add(new MetaDataException( + ErrorMessageConstants.ERR_CONSTRAINT_NAME_WITHOUT_CHECK + + ": " + label + " sets @dbCheck: false and @constraintName \"" + name + "\"; with no CHECK" + + " there is nothing for the name to name. Remove @constraintName, or remove @dbCheck: false.", + ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, node.getSource())); + } + } + String next = ("object".equals(node.getType()) || "field".equals(node.getType())) ? node.getShortName() : owner; + for (MetaData child : node.getChildren(MetaData.class, false)) visitDbCheck(child, next, out); + } + + static void validateObjectFieldStorage(MetaRoot root) { walkObjectFieldStorage(root); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java index 66860cbdff..8e33812bf5 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java @@ -255,6 +255,16 @@ public static void registerEntityValueTypes(MetaDataRegistry registry) { // object.projection, so it survives pruning here while staying off entity/value. def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); + // rc.21 part B: @union / @unionAll (U15) and @grain / @grainOrdinal (U14), registered + // so a strict load accepts them; the shape rules run in TypeScript and C#. + def.optionalAttributeWithConstraints("union") + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints("unionAll") + .ofType(com.metaobjects.attr.BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("grain") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints("grainOrdinal") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); }); // FR-044 — object.report: a fixed combination of dimensions and measures of ONE diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java new file mode 100644 index 0000000000..533e68aa68 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java @@ -0,0 +1,59 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.origin; + +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; + +/** + * rc.21 part B (U10) — {@code origin.function}: a value computed by a database function the + * project owns, named ({@code @function}, {@code @schema}) and typed by its argument fields + * ({@code @args}). Registered so a strict load accepts it; the call rules run in TypeScript + * and C#, and only the TypeScript view emitter lowers it. + */ +public class FunctionOrigin extends MetaOrigin { + + /** Function origin subtype constant. */ + public static final String SUBTYPE_FUNCTION = "function"; + public static final String ATTR_FUNCTION = "function"; + public static final String ATTR_SCHEMA = "schema"; + public static final String ATTR_ARGS = "args"; + public static final String ATTR_PARAMS = "params"; + public static final String ATTR_RETURNS = "returns"; + + public FunctionOrigin(String name) { + super(SUBTYPE_FUNCTION, name); + } + + /** Register the concrete {@code origin.function} subtype with the registry. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(FunctionOrigin.class, def -> { + def.type(TYPE_ORIGIN).subType(SUBTYPE_FUNCTION) + .description("Function origin — a value computed by a database function the project owns") + .inheritsFrom(TYPE_ORIGIN, SUBTYPE_BASE); + def.requiredAttributeWithConstraints(ATTR_FUNCTION) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_SCHEMA) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_ARGS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(ATTR_PARAMS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.requiredAttributeWithConstraints(ATTR_RETURNS) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + }); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java index 2187d9fb5c..790f65e3b0 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java @@ -31,6 +31,7 @@ public void registerTypes(MetaDataRegistry registry) { AggregateOrigin.registerTypes(registry); ComputedOrigin.registerTypes(registry); FirstOrigin.registerTypes(registry); + FunctionOrigin.registerTypes(registry); } @Override diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java index 25216933fe..490297e3da 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java +++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java @@ -82,6 +82,7 @@ public final class ReportReadModel extends ReportMetaObject CurrencyField.ATTR_CURRENCY, EnumField.ATTR_VALUES, EnumField.ATTR_INT_VALUE_MAP, + EnumField.ATTR_STRING_VALUE_MAP, MetaField.ATTR_MAX_LENGTH, MetaField.ATTR_PRECISION, MetaField.ATTR_SCALE, diff --git a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java index 2771809b23..b49aa487d1 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java @@ -204,6 +204,20 @@ private ErrorMessageConstants() { */ public static final String ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE"; + /** + * A CHECK-generating validator or {@code field.enum} sets {@code @dbCheck: false} (no CHECK) and + * {@code @constraintName} (the CHECK's name). Cross-language contract: + * {@code ERR_CONSTRAINT_NAME_WITHOUT_CHECK}. + */ + public static final String ERR_CONSTRAINT_NAME_WITHOUT_CHECK = "ERR_CONSTRAINT_NAME_WITHOUT_CHECK"; + + /** + * A cross-field validator ({@code comparison}, {@code requiredWhen}, {@code presentIff}, + * {@code atLeastOne}) sets {@code @dbCheck: false}; it is enforced only by its CHECK. + * Cross-language contract: {@code ERR_CROSS_FIELD_WITHOUT_CHECK}. + */ + public static final String ERR_CROSS_FIELD_WITHOUT_CHECK = "ERR_CROSS_FIELD_WITHOUT_CHECK"; + /** * Error code emitted when {@code field.object @storage} is set on a field that * has no {@code @objectRef} — storage shape only applies to referenced objects. diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java index c0ba1630c3..58aa9ee45e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java @@ -48,6 +48,8 @@ public abstract class MetaValidator extends MetaData { /** The database name of the CHECK a CHECK-generating validator (or a field.enum's membership) generates. */ public final static String ATTR_CONSTRAINT_NAME = "constraintName"; + /** A CHECK-generating validator or field.enum (db provider): {@code false} generates no database CHECK. Absent: true. */ + public final static String ATTR_DB_CHECK = "dbCheck"; /** * Register this type with the MetaDataRegistry (called by provider) diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java index 86f4a815a1..0105234b4c 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/ConformanceTest.java @@ -103,7 +103,7 @@ public class ConformanceTest { private static final Path CORPUS = CorpusRoot.locate(); private static final Set REGISTERED_CODES = FixtureLint.loadRegisteredCodes(CORPUS); - private static final ExpectedFailures.Ledger LEDGER = ExpectedFailures.load(locateLedger()); + static final ExpectedFailures.Ledger LEDGER = ExpectedFailures.load(locateLedger()); /** * Cross-language provider-id aliases: the corpus uses canonical provider diff --git a/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java index 01b25e613d..b2cde4a7ab 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/conformance/YamlTwinConformanceTest.java @@ -45,6 +45,7 @@ import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** @@ -129,6 +130,12 @@ public void roundTrip() throws IOException { String loaderName = ConformanceTest.detectLoaderName(List.of(expectedFile)); Outcome o = load(fix, List.of(expectedFile), List.of(expected), loaderName, MetaDataSource.MetaDataFormat.JSON); + if (ConformanceTest.LEDGER.fixtures.contains(fix.name)) { + // Known gap (conformance-expected-failures.json): must still fail to load; a clean load means the list is stale. + assertFalse(fix.name + " is listed as a known gap but now loads cleanly: remove it from the ledger", + o.errorCodes.isEmpty()); + return; + } assertTrue(fix.name + ": expected.json did not load cleanly: " + o.errorCodes, o.errorCodes.isEmpty()); assertEquals(fix.name + ": expected.json does not round-trip", diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java index 2d86686825..ad88ca833b 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java @@ -31,7 +31,8 @@ * Tests for {@link ValidationPhase#validateDbColumnType} (R6 Plan 2b). The * {@code @dbColumnType} physical attribute is validated own-only against: *
      - *
    1. a closed value set ({@code uuid|jsonb} — {@code timestamp_with_tz} was retired + *
    2. a closed value set ({@code uuid|jsonb}, and since rc.21 the text spellings on a + * {@code field.string} — {@code timestamp_with_tz} was retired * in ADR-0036 Wave 2); and
    3. *
    4. the legal (logical-subtype × value) pairing.
    5. *
    @@ -174,17 +175,20 @@ public void textArrayValueIsRejected() { } @Test - public void textValueIsRejected() { - // The vestigial dbColumnType:text value is REMOVED (Phase 1): a no-maxLength - // field.string already defaults to a text column — `text` is not an opt-in. - String canonical = "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [" + - " { \"object.entity\": { \"name\": \"Asset\", \"children\": [" + - " { \"field.long\": { \"name\": \"id\" } }," + - " { \"field.string\": { \"name\": \"body\", \"@dbColumnType\": \"text\" } }," + - " { \"identity.primary\": { \"@fields\": \"id\" } }" + - " ] } }" + - "] } }"; - assertBadAttrValue(canonical, "text-value-removed.json"); + public void textSpellingsOnStringAreLegal() { + // rc.21: the text spellings (text, varchar, varchar(n), character varying(n), + // character(n)) are legal on a field.string again, so a view column can carry + // the database's own type name. + for (String spelling : List.of("text", "varchar", "varchar(40)", "character varying(40)", "character(2)")) { + String canonical = "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [" + + " { \"object.entity\": { \"name\": \"Asset\", \"children\": [" + + " { \"field.long\": { \"name\": \"id\" } }," + + " { \"field.string\": { \"name\": \"body\", \"@dbColumnType\": \"" + spelling + "\" } }," + + " { \"identity.primary\": { \"@fields\": \"id\" } }" + + " ] } }" + + "] } }"; + loadThrough(canonical, "text-spelling-" + spelling + ".json"); + } } @Test diff --git a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java index 2010e26c07..fb79703820 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java @@ -323,6 +323,33 @@ public void aMeasureWithDefaultYieldsADetachedFieldWithRequiredTrue() { assertFalse(required(model.getMetaField("revenueRaw"))); } + @Test + public void anEnumDimensionCarriesItsStringValueMap() { + // rc.21 part B (N5): the row carries @stringValueMap from its type source, as C#, TS and + // Python do, so OMDB's codec decodes the stored string to the member. + MetaRoot root = loadJson(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Article", "children": [ + { "source.rdb": { "@table": "articles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "status", "@of": "Article.status" } }, + { "dimension.attribute": { "name": "kind", "@of": "Article.kind" } }, + { "measure.aggregate": { "name": "articles", "@agg": "count", "@of": "Article.id" } } + ] } }, + { "object.report": { "name": "ByStatus", "@from": "Article", "@dimensions": ["status", "kind"], "@measures": ["articles"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_by_status" } } ] } } + ] } } + """); + ReportReadModel model = ReportReadModel.of(object(root, "ByStatus"), root); + Object map = model.getMetaField("status").getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + assertEquals(java.util.Map.of("Draft", "draft", "Published", "published"), map); + assertFalse(model.getMetaField("kind").hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)); + } + @Test public void aSourcelessReportHasAShapeAndNoView() { MetaRoot root = loadJson(SALES_MODEL); diff --git a/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java b/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java index 41961c5f8f..9b149e005f 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java @@ -188,10 +188,10 @@ public void step1KindMatchingViewForViewKind() { @Test public void step1KindMatchingProcForStoredProcKind() { MetaDataLoader l = loadThrough( - oneSourceEntity("PhaseSummary", - "{ \"@kind\": \"storedProc\", \"@proc\": \"fn_get_phase_summary\" }"), + oneSourceEntity("StageSummary", + "{ \"@kind\": \"storedProc\", \"@proc\": \"fn_get_stage_summary\" }"), "fr016-step1-proc.json"); - assertEquals("fn_get_phase_summary", firstSource(l).getPhysicalName()); + assertEquals("fn_get_stage_summary", firstSource(l).getPhysicalName()); } @Test @@ -216,10 +216,10 @@ public void step1KindMatchingFunctionForTableFunction() { public void step2LegacyTableForNonTableKind() { // Legacy: @table with non-table @kind still resolves (and emits a warning). MetaDataLoader l = loadThrough( - oneSourceEntity("PhaseSummary", - "{ \"@kind\": \"storedProc\", \"@table\": \"fn_legacy_phase_summary\" }"), + oneSourceEntity("StageSummary", + "{ \"@kind\": \"storedProc\", \"@table\": \"fn_legacy_stage_summary\" }"), "fr016-step2-legacy.json"); - assertEquals("fn_legacy_phase_summary", firstSource(l).getPhysicalName()); + assertEquals("fn_legacy_stage_summary", firstSource(l).getPhysicalName()); } @Test diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index 755f771e55..85269935b6 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -441,8 +441,25 @@ static final class EnumCodec implements JdbcFieldCodec { @Override public void readInto(Object o, MetaField f, ResultSet rs, int j) throws SQLException { Map intMap = intValueMap(f); if (intMap == null) { - f.setString(o, rs.getString(j)); - return; + String raw = rs.getString(j); + Map storedMap = stringValueMap(f); + if (storedMap == null || raw == null) { + f.setString(o, raw); + return; + } + // rc.21: a @stringValueMap enum holds the member's stored string; the caller gets + // the member. An unmapped stored string throws, as an unmapped int does. + for (Map.Entry e : storedMap.entrySet()) { + if (raw.equals(e.getValue())) { + f.setString(o, e.getKey()); + return; + } + } + throw new SQLException( + "field.enum '" + f.getName() + "' read stored value '" + raw + + "' with no member in @" + EnumField.ATTR_STRING_VALUE_MAP + + " (declared: " + storedMap + ") — the database holds a value the model " + + "does not describe."); } refuseArray(f); int stored = rs.getInt(j); @@ -472,8 +489,27 @@ static final class EnumCodec implements JdbcFieldCodec { @Override public void write(PreparedStatement s, MetaField f, int j, Object v) throws SQLException { Map intMap = intValueMap(f); if (intMap == null) { - if (v == null) s.setNull(j, Types.VARCHAR); - else s.setString(j, v.toString()); + if (v == null) { + s.setNull(j, Types.VARCHAR); + return; + } + // rc.21: a @stringValueMap enum binds the member's stored string. An unmapped + // member throws (every port): no CHECK need stand behind it (@dbCheck: false), + // and binding the symbol would store a spelling the column does not hold. + Map storedMap = stringValueMap(f); + String member = v.toString(); + if (storedMap == null) { + s.setString(j, member); + return; + } + String stored = storedMap.get(member); + if (stored == null) { + // One bind serves a write and a filter argument alike, so the message says "bind". + throw new SQLException("field.enum '" + f.getName() + "' cannot bind " + member + + ": it has no stored string in @" + EnumField.ATTR_STRING_VALUE_MAP + + " — the value is not one of the members the model declares."); + } + s.setString(j, stored); return; } refuseArray(f); @@ -501,6 +537,19 @@ private static void refuseArray(MetaField f) throws SQLException { + "the member symbols or read a member nobody stored."); } + /** rc.21 — the declared member→stored-string map ({@code @stringValueMap}, resolving), or null. */ + private static Map stringValueMap(MetaField f) { + if (!f.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null; + Object raw = f.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + if (!(raw instanceof Map)) return null; + Map out = new LinkedHashMap<>(); + for (Map.Entry e : ((Map) raw).entrySet()) { + if (e.getKey() == null || !(e.getValue() instanceof String)) continue; + out.put(String.valueOf(e.getKey()), (String) e.getValue()); + } + return out.isEmpty() ? null : out; + } + /** The declared symbol→int map, or null when the enum is string-backed. */ private static Map intValueMap(MetaField f) { if (!f.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null; diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 3f14a45b92..359a1f422e 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -56,6 +56,18 @@ import wiring itself (`from ._entity import `), which still needs path-resolution/import-base machinery; the config's per-target `outDir` is the prerequisite that is now in place. +## TPH body discriminator: 400, not a silent drop + +**Status:** known divergence, out of scope for the 1.2.x input patch. + +A per-subtype write route (`POST /api/auths/bridge`) validates the request body with +that subtype's model, whose discriminator accepts only the route's own value. A body +that names another subtype (`"type": "Coupon"`) is answered `400 {"error":"validation"}`. +Nothing is stored, so this is not a security hole, but the other ports drop the key +and create the row with the route's subtype. The shared +`tph-input-foreign-discriminator-dropped` scenario asserts the drop, and this port's +runner skips it with this reason (`tests/integration/test_api_contract_tph_generated.py`). + ## FR-015 stored-procedure callables are NOT generated by this port **Contract.** FR-015 gives a `source.rdb @kind: storedProc` / `tableFunction` a generated diff --git a/server/python/src/metaobjects/codegen/collection_name_collision.py b/server/python/src/metaobjects/codegen/collection_name_collision.py index 3f2304f17c..c503553191 100644 --- a/server/python/src/metaobjects/codegen/collection_name_collision.py +++ b/server/python/src/metaobjects/codegen/collection_name_collision.py @@ -32,8 +32,8 @@ def assert_no_collection_name_collisions(entities: list[MetaObject]) -> None: """Refuse a generation run in which two DISTINCT entities/projections pluralize to the same API-surface collection name. - Scope: this port writes every module into one flat package (``output_layout`` is flat - only) served by one app, so its scope is the whole run. Counted over the objects that + Scope: this port serves one app regardless of ``output_layout`` (``package`` splits + generated module directories, not route surfaces), so its scope is the whole run. Counted over the objects that emit a collection (:func:`_emits_collection`). A value object, an abstract object and a sourceless one never get a route, router module, or finder name, so they cannot collide on any of those — a layered model's abstract diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index a08a4cfe05..f814a083b0 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -276,8 +276,9 @@ def _flattened_member_consts( field: MetaData, members: list[tuple[str, str]] ) -> list[tuple[str, _Const]]: """A flattened value object's ``__COLUMN`` constants, one per member, - emitted beside the field's own ``_FIELD`` constant (a flattened field has no column - constant of its own).""" + emitted beside the field's own ``_FIELD``/``_COLUMN`` pair (kept as it always was, so + nothing that imports it changes; on a flattened field ``_COLUMN`` names no column of the + table).""" member = _member(field.name) return [ ( diff --git a/server/python/src/metaobjects/codegen/generators/tph_plan.py b/server/python/src/metaobjects/codegen/generators/tph_plan.py index 0d9c9b62a7..b7223d451b 100644 --- a/server/python/src/metaobjects/codegen/generators/tph_plan.py +++ b/server/python/src/metaobjects/codegen/generators/tph_plan.py @@ -7,7 +7,7 @@ TPH-aware generator reads, so the route-segment rule and subtype set never drift. The per-subtype REST route segment is the ``@discriminatorValue`` lowercased -(``"Bridge"`` → ``bridge``, ``"PriorAuth"`` → ``priorauth``) — derived in exactly +(``"Bridge"`` → ``bridge``, ``"BulkPermit"`` → ``bulkpermit``) — derived in exactly one place (:func:`route_segment`). """ from __future__ import annotations diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 43bdd51213..43dba03913 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -203,8 +203,8 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: libraries = _read_libraries(raw, path) naming = _read_naming(raw, path) wire = _read_wire(raw, path) - api = _read_api(raw, path) _check_enums(raw, path) + api = _read_api(raw, path) requirements_inherit = _read_requirements_inherit(raw, path) # Unknown top-level keys are IGNORED by design — see the module docstring. @@ -369,42 +369,6 @@ def _read_naming(raw: dict[str, object], path: Path) -> NamingRules: return NamingRules(columns=columns, tables=tables, collections=collections) -#: Every key the `enums` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). -_ENUMS_KEYS = ("maxLength",) - - -def _check_enums(raw: dict[str, object], path: Path) -> None: - """The `enums` block: `maxLength`, a positive integer, is the column length a port that - sizes a string-stored enum's column gives one with no @maxLength. This port sizes no - column (it emits no DDL and no column type), so it reads nothing from the block, but a - project shared with a port that does has one: the block is accepted, and its shape is - checked so a typo is refused here as it is there (a non-object block, an unknown key, or - a value that is not a positive integer).""" - if "enums" not in raw: - return - enums = raw["enums"] - if not isinstance(enums, dict): - raise ParseError(f"{path}: 'enums' must be an object", code=ErrorCode.ERR_BAD_ATTR_VALUE) - unknown = sorted(set(enums) - set(_ENUMS_KEYS)) - if unknown: - raise ParseError( - f"{path}: 'enums' has unknown key(s) {unknown}; accepted: {list(_ENUMS_KEYS)}", - code=ErrorCode.ERR_BAD_ATTR_VALUE, - ) - if "maxLength" not in enums: - return - value = enums["maxLength"] - # A whole number however JSON spells it (32, 32.0, 1e2): a reader that parses numbers as - # doubles (TypeScript's) cannot tell those apart, so every port accepts all three. - if isinstance(value, float) and value.is_integer(): - value = int(value) - if isinstance(value, bool) or not isinstance(value, int) or value <= 0: - raise ParseError( - f"{path}: 'enums.maxLength' must be a positive integer, got {value!r}", - code=ErrorCode.ERR_BAD_ATTR_VALUE, - ) - - _PAGE_SIZE_MAX = 2147483647 @@ -474,6 +438,42 @@ def _read_api(raw: dict[str, object], path: Path) -> ApiSettings: return ApiSettings(pagination=pagination, unknown_fields=unknown_fields) +#: Every key the `enums` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). +_ENUMS_KEYS = ("maxLength",) + + +def _check_enums(raw: dict[str, object], path: Path) -> None: + """The `enums` block: `maxLength`, a positive integer, is the column length a port that + sizes a string-stored enum's column gives one with no @maxLength. This port sizes no + column (it emits no DDL and no column type), so it reads nothing from the block, but a + project shared with a port that does has one: the block is accepted, and its shape is + checked so a typo is refused here as it is there (a non-object block, an unknown key, or + a value that is not a positive integer).""" + if "enums" not in raw: + return + enums = raw["enums"] + if not isinstance(enums, dict): + raise ParseError(f"{path}: 'enums' must be an object", code=ErrorCode.ERR_BAD_ATTR_VALUE) + unknown = sorted(set(enums) - set(_ENUMS_KEYS)) + if unknown: + raise ParseError( + f"{path}: 'enums' has unknown key(s) {unknown}; accepted: {list(_ENUMS_KEYS)}", + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + if "maxLength" not in enums: + return + value = enums["maxLength"] + # A whole number however JSON spells it (32, 32.0, 1e2): a reader that parses numbers as + # doubles (TypeScript's) cannot tell those apart, so every port accepts all three. + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ParseError( + f"{path}: 'enums.maxLength' must be a positive integer, got {value!r}", + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + + #: Every key the `wire` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). _WIRE_KEYS = ("decimals", "nullMembers", "durations") diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 003a737eb2..4564e9a559 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -10,6 +10,7 @@ ATTR_SUBTYPE_FILTER, ATTR_SUBTYPE_INT, ATTR_SUBTYPE_INT_MAP, + ATTR_SUBTYPE_PROPERTIES, ATTR_SUBTYPE_STRING, ATTR_SUBTYPES, ) @@ -21,6 +22,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_PROVIDED, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, @@ -347,6 +349,14 @@ def _register_subtypes( required=False, ) ) + # rc.21 part B: @union / @unionAll (U15), @grain / @grainOrdinal (U14). Registered so a + # strict load accepts them; the shape rules run in TypeScript and C# (see CHANGELOG). + _def.attrs.extend([ + AttrSchema(name="union", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="unionAll", value_type="boolean", required=False), + AttrSchema(name="grain", value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name="grainOrdinal", value_type=ATTR_SUBTYPE_STRING, required=False), + ]) break # FR-044 — object.report: declared dimensions x measures of ONE entity (@from), @@ -677,6 +687,15 @@ def _register_subtypes( value_type=ATTR_SUBTYPE_INT_MAP, required=False, ), + # rc.21 — @stringValueMap: optional per-member stored strings ({member: str}) of a + # string-stored enum (the string twin of @intValueMap). Content rules in + # _validate_enum_values (Rule 5). The ObjectManager writes and reads through it + # (see object_manager.py: _coerce_write_value, _decode_read_value). + AttrSchema( + name=FIELD_ATTR_STRING_VALUE_MAP, + value_type=ATTR_SUBTYPE_PROPERTIES, + required=False, + ), # FR-033 — the field.enum tolerant-extract overlays (@enumAlias / @enumDoc / # @coerceDefault / @normalize) are NO LONGER declared here; they are re-homed # to the prompt domain provider (`prompt_provider`, metaobjects-prompt) via @@ -1067,6 +1086,24 @@ def _register_subtypes( ) ) +# origin.function (rc.21 part B, U10) — a call of a database function the project owns: +# @function required, @schema and @args optional. Registered so a strict load accepts it. +core_provider.add( + TypeDefinition( + type=TYPE_ORIGIN, + sub_type="function", + factory=MetaOrigin, + attrs=[ + AttrSchema(name="function", value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name="schema", value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name="args", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="params", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="returns", value_type=ATTR_SUBTYPE_STRING, required=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) + # view.* (base + 13 control kinds). FR-033 — view.currency's @locale is re-homed to # the UI domain provider (`ui_provider`, metaobjects-ui) via TypeRegistry.extend # (ui.json declares @locale on view.currency), matching the TS uiProvider split. Core diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index 2c89e3745b..54e35f5960 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -212,6 +212,10 @@ class ErrorCode(str, Enum): ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP" ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT" ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE" + # A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + ERR_CONSTRAINT_NAME_WITHOUT_CHECK = "ERR_CONSTRAINT_NAME_WITHOUT_CHECK" + # A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. + ERR_CROSS_FIELD_WITHOUT_CHECK = "ERR_CROSS_FIELD_WITHOUT_CHECK" ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = ( "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE" ) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 49992127a9..2d8a3f1502 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -37,6 +37,7 @@ FIELD_ATTR_COERCE_DEFAULT, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_REQUIRED, @@ -71,6 +72,8 @@ DB_COLUMN_TYPE_UUID, FIELD_ATTR_DB_COLUMN_TYPE, VALID_DB_COLUMN_TYPES, + DB_COLUMN_TYPE_SIZED_SPELLINGS, + parse_db_column_type, ) from ..meta.core.object.collection_names import collection_name_of from ..meta.core.object.meta_object import MetaObject @@ -278,8 +281,11 @@ def run_validations( _validate_enum_max_length(root, errors) # identity.primary @sequenceStart / @sequenceName need @generation "increment". _validate_identity_sequence(root, errors) - # cross-field validators — exactlyOne names two or more fields; @condition names entity fields. + # cross-field validators — exactlyOne names two or more fields; + # @condition names entity fields. _validate_cross_field_validators(root, errors, strict) + # @dbCheck: false with @constraintName names a CHECK that is never created. + _validate_db_check(root, errors) # field.map — exactly one of @valueType (scalar) or @objectRef (VO), and # @valueType (when set) must name a known scalar subtype. _validate_field_map(root, errors) @@ -672,6 +678,7 @@ def _validate_enum_values( # continue` gate below so a concrete field.enum that inherits @values via # `extends` but declares its own @intValueMap is still validated. _validate_enum_int_value_map(node, errors) + _validate_enum_string_value_map(node, errors) # ADR-0039 sanctioned own: validates the AUTHORED @values membership on THIS # node (mirrors the TS attr-schema-validate `node.ownAttrs()`); an inherited @@ -821,6 +828,56 @@ def _validate_enum_int_value_map(node: MetaData, errors: list[MetaError]) -> Non seen_values[value] = member +def _validate_enum_string_value_map(node: MetaData, errors: list[MetaError]) -> None: + """rc.21 — ``@stringValueMap`` content rules: the string twin of + :func:`_validate_enum_int_value_map`, with its policies (own-only; a shared enum's + backing owned by the shared declaration). Keys must exactly match the EFFECTIVE + ``@values``; values are unique non-empty strings. Refused beside ``@intValueMap`` and + on an array enum (ERR_BAD_ATTR_VALUE). Mirrors TS ``attr-schema-validate`` Check 5c. + """ + # ADR-0039 sanctioned own: validates the map DECLARED on this node. + raw = node.attr(FIELD_ATTR_STRING_VALUE_MAP) + if raw is None: + return + label = _node_label(node) + prefix = f"{label} attribute '@{FIELD_ATTR_STRING_VALUE_MAP}'" + + def bad(message: str, code: ErrorCode = ErrorCode.ERR_BAD_ATTR_VALUE) -> None: + errors.append(MetaError(f"{prefix} {message}", code, envelope=node.source)) + + if node.super_data is not None and is_shared_enum_declaration(node.super_data): + bad("is declared on a field extending a shared abstract enum — a shared enum's stored " + "strings are owned by the shared declaration; move it onto the shared declaration.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT) + return + if node.attrs().get(FIELD_ATTR_INT_VALUE_MAP) is not None: + bad(f"is refused beside '@{FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one.") + return + if node.resolved_is_array(): + bad(f"is refused on an array enum: its column holds the members as text[] elements, which no port maps through @{FIELD_ATTR_STRING_VALUE_MAP}.") + return + if not isinstance(raw, dict): + bad("must be an object of { member: storedString }.") + return + effective_values = _effective_enum_values(node) + member_set = set(effective_values) + missing = [m for m in effective_values if m not in raw] + extra = [k for k in raw if k not in member_set] + if missing or extra: + parts = ([f"missing: {', '.join(missing)}"] if missing else []) + ([f"unknown: {', '.join(extra)}"] if extra else []) + bad(f"keys must exactly match '@{FIELD_ATTR_VALUES}' members ({'; '.join(parts)}).") + seen: dict[str, str] = {} + for member, value in raw.items(): + if not isinstance(value, str) or value == "": + bad(f"member {member!r} must map to a non-empty string.") + continue + owner = seen.get(value) + if owner is not None: + bad(f"members {owner!r} and {member!r} share the stored string {value!r}; every member must have a unique one.") + else: + seen[value] = member + + def _effective_enum_values(node: MetaData) -> list[str]: """The effective ``@values`` members of an enum node (own or inherited via ``extends:``). Empty list when absent. Mirrors Java ``effectiveEnumValues``.""" @@ -984,21 +1041,35 @@ def _validate_db_column_type(root: MetaData, errors: list[MetaError]) -> None: if not isinstance(value, str): continue - # Rule 1: recognized value. - if value not in VALID_DB_COLUMN_TYPES: + # Rule 1: recognized value (rc.21: the text spellings, sized ones included). + parsed = parse_db_column_type(value) + if parsed is None: errors.append( MetaError( f"field '{node.name}' attribute '@{FIELD_ATTR_DB_COLUMN_TYPE}' " f"value {value!r} is not a valid value; allowed: " - f"{', '.join(VALID_DB_COLUMN_TYPES)}", + f"{', '.join((*VALID_DB_COLUMN_TYPES, *DB_COLUMN_TYPE_SIZED_SPELLINGS))}", ErrorCode.ERR_BAD_ATTR_VALUE, envelope=node.source, ) ) continue + # Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength (resolving) + # would let the app accept a value the column refuses. + max_length = node.get_meta_attr(FIELD_ATTR_MAX_LENGTH) + if parsed[1] is not None and isinstance(max_length, int) and max_length > parsed[1]: + errors.append( + MetaError( + f"field.string '{node.name}' declares @{FIELD_ATTR_MAX_LENGTH}: {max_length} over " + f"'@{FIELD_ATTR_DB_COLUMN_TYPE}: {value}', which holds {parsed[1]}; a value the field " + f"accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, + envelope=node.source, + ) + ) - # Rule 2: legal (subtype × value) pairing. - required_subtype = _DB_COLUMN_TYPE_REQUIRED_SUBTYPE[value] + # Rule 2: legal (subtype × value) pairing — every value is field.string's. + required_subtype = FIELD_SUBTYPE_STRING if node.sub_type != required_subtype: # Derive the allowed-pairings list from the map so it stays the single # source of truth for pairing legality. @@ -4261,6 +4332,62 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None )) +# @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no +# database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the +# node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only by +# its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one error +# such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either of the +# two itself. Mirrors TS validateDbCheck. +def _validate_db_check(root: MetaData, errors: list[MetaError]) -> None: + from ..meta.core.field import field_constants as fc + from ..meta.core.validator import validator_constants as vc + + checked_validators = ( + vc.VALIDATOR_SUBTYPE_NUMERIC, + vc.VALIDATOR_SUBTYPE_LENGTH, + vc.VALIDATOR_SUBTYPE_REGEX, + *vc.CROSS_FIELD_VALIDATOR_SUBTYPES, + ) + + def visit(node: MetaData, owner: str | None) -> None: + checked = (node.type == TYPE_VALIDATOR and node.sub_type in checked_validators) or ( + node.type == TYPE_FIELD and node.sub_type == fc.FIELD_SUBTYPE_ENUM + ) + # ADR-0039 sanctioned own: reported where the node declares either attr itself. + declares = node.attr(vc.VALIDATOR_ATTR_DB_CHECK) is not None or node.attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) is not None + if checked and declares: + name = node.get_meta_attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) + off = node.get_meta_attr(vc.VALIDATOR_ATTR_DB_CHECK) is False + prefix = f"{owner}." if owner is not None else "" + if off and node.type == TYPE_VALIDATOR and node.sub_type in vc.CROSS_FIELD_VALIDATOR_SUBTYPES: + # A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.append(MetaError( + code=ErrorCode.ERR_CROSS_FIELD_WITHOUT_CHECK, + message=( + f'{node.type}.{node.sub_type} "{prefix}{node.name}" sets @dbCheck: false, but this validator ' + "is enforced only by its CHECK, so the rule would be enforced nowhere. Remove the validator, " + "or remove @dbCheck: false." + ), + envelope=node.source, + )) + elif off and isinstance(name, str) and name: + errors.append(MetaError( + code=ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + message=( + f'{node.type}.{node.sub_type} "{prefix}{node.name}" sets @dbCheck: false and ' + f'@constraintName "{name}"; with no CHECK there is nothing for the name to name. ' + "Remove @constraintName, or remove @dbCheck: false." + ), + envelope=node.source, + )) + nxt = node.name if node.type in (TYPE_OBJECT, TYPE_FIELD) else owner + for child in node.own_children(): + visit(child, nxt) + + for child in root.own_children(): + visit(child, None) + + # Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne / exactlyOne), which # the database enforces as CHECKs: exactlyOne @fields names two or more fields, # every field a @condition names a field of the owning entity, a requiredWhen / presentIff diff --git a/server/python/src/metaobjects/meta/core/field/field_constants.py b/server/python/src/metaobjects/meta/core/field/field_constants.py index 6cf388650b..9557a3cc22 100644 --- a/server/python/src/metaobjects/meta/core/field/field_constants.py +++ b/server/python/src/metaobjects/meta/core/field/field_constants.py @@ -189,3 +189,7 @@ # @values; values must be unique integers. The generated native type and wire # format are unchanged in every language. Mirrors TS FIELD_ATTR_INT_VALUE_MAP. FIELD_ATTR_INT_VALUE_MAP = "intValueMap" +# rc.21 — per-member stored strings ({member: str}) of a string-stored enum; the string twin of +# @intValueMap. Keys must match @values; values unique non-empty strings; refused with @intValueMap +# and on an array enum. +FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap" diff --git a/server/python/src/metaobjects/meta/core/object/object_constants.py b/server/python/src/metaobjects/meta/core/object/object_constants.py index b4ceb0bd78..14b3b08aa0 100644 --- a/server/python/src/metaobjects/meta/core/object/object_constants.py +++ b/server/python/src/metaobjects/meta/core/object/object_constants.py @@ -25,6 +25,7 @@ # ["csharp"]). Loaded and type-checked here on # object.entity / projection / report; no Python generator acts on it yet. OBJECT_ATTR_COLLECTION_NAME = "collectionName" +# Deprecated alias of collectionName (ports ["csharp"]; rc.19): the EF Core DbSet property name. # On object.base, so every object subtype carries them. ``@object`` (ADR-0001) is # cross-port vocabulary only Java implements so far; ``@objectAdapter`` (ADR-0005) is # JVM-only (ports ["java", "kotlin"]). Python loads and type-checks both; it acts on neither. @@ -36,6 +37,11 @@ # the SAME attr subtype as origin.aggregate's @filter) that lowers to an outer # SQL WHERE. Mirrors TS object-constants.ts OBJECT_PROJECTION_ATTR_FILTER. OBJECT_PROJECTION_ATTR_FILTER = "filter" +# rc.21 part B: a projection UNIONed with others (U15), one with a row per array element (U14). +OBJECT_PROJECTION_ATTR_UNION = "union" +OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll" +OBJECT_PROJECTION_ATTR_GRAIN = "grain" +OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal" # --------------------------------------------------------------------------- # FR-044 — object.report attrs. Mirrors TS object-constants.ts. diff --git a/server/python/src/metaobjects/meta/core/reporting/report_read_model.py b/server/python/src/metaobjects/meta/core/reporting/report_read_model.py index aee8c8c22f..f438df4419 100644 --- a/server/python/src/metaobjects/meta/core/reporting/report_read_model.py +++ b/server/python/src/metaobjects/meta/core/reporting/report_read_model.py @@ -39,6 +39,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_FILTERABLE, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_PRECISION, @@ -63,6 +64,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/python/src/metaobjects/meta/core/validator/validator_constants.py b/server/python/src/metaobjects/meta/core/validator/validator_constants.py index 522f802ea3..d7daf340e2 100644 --- a/server/python/src/metaobjects/meta/core/validator/validator_constants.py +++ b/server/python/src/metaobjects/meta/core/validator/validator_constants.py @@ -34,6 +34,8 @@ VALIDATOR_ATTR_CONDITION = "condition" # The database name of the CHECK a CHECK-generating validator generates (db provider). VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName" +# A CHECK-generating validator or field.enum (db provider): false generates no database CHECK. Absent: true. +VALIDATOR_ATTR_DB_CHECK = "dbCheck" # The cross-field validators (entity-scoped; the database enforces them as CHECKs). CROSS_FIELD_VALIDATOR_SUBTYPES = ( VALIDATOR_SUBTYPE_COMPARISON, diff --git a/server/python/src/metaobjects/meta/persistence/db/db_constants.py b/server/python/src/metaobjects/meta/persistence/db/db_constants.py index 6fc5ee76f2..072521b45f 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_constants.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_constants.py @@ -54,10 +54,39 @@ # The closed set of legal @dbColumnType values. ADR-0036 Wave 2 retires # timestamp_with_tz — the legal set is now just { uuid, jsonb }, both on field.string. +# rc.21 part B (U2): the text spellings, all on field.string; the sized ones are parsed. +DB_COLUMN_TYPE_TEXT = "text" +DB_COLUMN_TYPE_VARCHAR = "varchar" +DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying" VALID_DB_COLUMN_TYPES = ( DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, ) +DB_COLUMN_TYPE_SIZED_SPELLINGS = ("varchar(n)", "character varying(n)", "character(n)") + +import re as _re + +_SIZED_DB_COLUMN_TYPE = _re.compile(r"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$") + + +def parse_db_column_type(value: str) -> tuple[str, int | None] | None: + """rc.21 part B (U2): parse a @dbColumnType value to (kind, length), or None when it is + not legal. Postgres's own spellings, matched exactly, as every port parses them.""" + if value == DB_COLUMN_TYPE_UUID: + return ("uuid", None) + if value == DB_COLUMN_TYPE_JSONB: + return ("jsonb", None) + if value == DB_COLUMN_TYPE_TEXT: + return ("text", None) + if value in (DB_COLUMN_TYPE_VARCHAR, DB_COLUMN_TYPE_CHARACTER_VARYING): + return ("varchar", None) + m = _SIZED_DB_COLUMN_TYPE.fullmatch(value) + if m is None: + return None + return ("char" if m.group(1) == "character" else "varchar", int(m.group(2))) # --------------------------------------------------------------------------- # DB-domain physical attrs on identity subtypes (RDB index / FK-constraint diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index 25a3a4615c..3258f74fa0 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -65,7 +65,7 @@ name=FIELD_ATTR_DB_COLUMN_TYPE, value_type=ATTR_SUBTYPE_STRING, required=False, - allowed_values=VALID_DB_COLUMN_TYPES, + # rc.21 part B (U2): no allowed_values — the sized spellings are no closed set. ) # @localTime — boolean opt-out into a naive / wall-clock timestamp (ADR-0036 Wave @@ -210,6 +210,18 @@ "ADR-0023 Amendment 1." ), ) +_ENUM_DB_CHECK_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_DB_CHECK, + value_type=ATTR_SUBTYPE_BOOLEAN, + required=False, + description="false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", +) +_VALIDATOR_DB_CHECK_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_DB_CHECK, + value_type=ATTR_SUBTYPE_BOOLEAN, + required=False, + description="On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", +) # The validators meta migrate renders as a CHECK: required is NOT NULL; array and base have none. _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME = ( vc.VALIDATOR_SUBTYPE_NUMERIC, @@ -259,9 +271,10 @@ def _register(registry: TypeRegistry) -> None: ], ) # @constraintName names the CHECK a validator / a field.enum's membership generates. - registry.extend(TYPE_FIELD, fc.FIELD_SUBTYPE_ENUM, attributes=[_ENUM_CONSTRAINT_NAME_SCHEMA]) + # @dbCheck: false asks either of them for no CHECK at all. + registry.extend(TYPE_FIELD, fc.FIELD_SUBTYPE_ENUM, attributes=[_ENUM_CONSTRAINT_NAME_SCHEMA, _ENUM_DB_CHECK_SCHEMA]) for sub_type in _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME: - registry.extend(TYPE_VALIDATOR, sub_type, attributes=[_VALIDATOR_CONSTRAINT_NAME_SCHEMA]) + registry.extend(TYPE_VALIDATOR, sub_type, attributes=[_VALIDATOR_CONSTRAINT_NAME_SCHEMA, _VALIDATOR_DB_CHECK_SCHEMA]) # index.lookup: same RDB physical attrs as identity.secondary (@orders/@where/@expr/@using). registry.extend( TYPE_INDEX, diff --git a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py index 81bab0c2b8..dfa76e353a 100644 --- a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py +++ b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py @@ -15,13 +15,19 @@ # @via, projecting @of. ORIGIN_SUBTYPE_COMPUTED = "computed" ORIGIN_SUBTYPE_FIRST = "first" +# rc.21 part B (U10): a value computed by a database function the project owns. +ORIGIN_SUBTYPE_FUNCTION = "function" ORIGIN_SUBTYPES = ( SUBTYPE_BASE, ORIGIN_SUBTYPE_PASSTHROUGH, ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ) +ORIGIN_ATTR_FUNCTION = "function" +ORIGIN_ATTR_SCHEMA = "schema" +ORIGIN_ATTR_ARGS = "args" # #210 — the ASSEMBLY origins: they derive a value by rolling up, computing, or # collecting from a backing store, which is what an object.projection is for. @@ -33,6 +39,7 @@ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ) # passthrough attrs diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index 51557149b7..4f910a9f17 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1127,13 +1127,13 @@ def _coerce_filter_value(field: MetaField, value: Any) -> Any: value = True elif lowered in ("false", "0"): value = False - return _coerce_write_value(field, value) + return _coerce_write_value(field, value, for_filter=True) _INT_TEXT = _re.compile(r"^\s*-?\d+\s*$") -def _coerce_write_value(field: MetaField, value: Any) -> Any: +def _coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False) -> Any: if value is None: return None sub = field.sub_type @@ -1223,6 +1223,21 @@ def _coerce_write_value(field: MetaField, value: Any) -> Any: if _field_is_array(field) and isinstance(value, list): return [_encode_enum_member(int_map, v) for v in value] return _encode_enum_member(int_map, value) + # rc.21: a @stringValueMap enum stores the member's string (scalar only; the + # loader refuses it on an array). + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + if value in stored_map: + return stored_map[value] + # An unmapped member raises, written or filtered (rc.21 rulings, every port). Written: + # no CHECK need hold behind it (@dbCheck: false), and storing the symbol would write a + # spelling the column does not hold. Filtered: passed through, the symbol could equal + # ANOTHER member's stored string and match that member's rows. + verb = "filter on" if for_filter else "write" + raise ValueError( + f"field.enum '{field.name}' cannot {verb} {value!r}: it has no stored string in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} — the value is not one of the members the model declares." + ) # Everything else (string / int / long / double / float / boolean / enum) # is already the native type pg8000 binds directly. @@ -1327,6 +1342,13 @@ def _int_value_map(field: MetaField) -> dict[Any, Any] | None: return m if isinstance(m, dict) else None +def _string_value_map(field: MetaField) -> dict[str, str] | None: + """rc.21 — the declared ``@stringValueMap`` (member → stored string), or ``None``. + ADR-0039 resolving, as :func:`_int_value_map`.""" + m = field.get_meta_attr(fc.FIELD_ATTR_STRING_VALUE_MAP) + return m if isinstance(m, dict) else None + + def _decode_read_value(field: MetaField, value: Any) -> Any: """Decode a stored value back to its authoring form on read. @@ -1372,6 +1394,18 @@ def _decode_read_value(field: MetaField, value: Any) -> Any: return value int_map = _int_value_map(field) if int_map is None: + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + # rc.21: the stored string back to its member; an unmapped one RAISES, as an + # unmapped int does. + for member, stored in stored_map.items(): + if stored == value: + return member + raise ValueError( + f"field.enum '{field.name}' read stored value {value!r} with no member in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} (declared: {stored_map}) — the database holds " + f"a value the model does not describe." + ) return value if isinstance(value, list): # isArray=true (``integer[]``): decode element-wise; a null element stays null. diff --git a/server/python/src/metaobjects/spec_metamodel/attr.json b/server/python/src/metaobjects/spec_metamodel/attr.json index 19031ccb34..ec55a95947 100644 --- a/server/python/src/metaobjects/spec_metamodel/attr.json +++ b/server/python/src/metaobjects/spec_metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index 4e087e72f0..1c61a0bdac 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { @@ -85,7 +87,7 @@ "type": "identity", "subType": "reference", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider." }, { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider." } ] diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index 3b4a4ce9fc..46a2f064ce 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index 244fd1655a..d169a02544 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -53,7 +53,11 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index d5b5b85415..e8cfe7e735 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -27,8 +27,8 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -42,6 +42,19 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } + ] + }, { "type": "origin", "subType": "first", @@ -52,8 +65,8 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] diff --git a/server/python/tests/codegen/test_names_extends_chain.py b/server/python/tests/codegen/test_names_extends_chain.py index 866ab7a400..970a338e55 100644 --- a/server/python/tests/codegen/test_names_extends_chain.py +++ b/server/python/tests/codegen/test_names_extends_chain.py @@ -65,18 +65,18 @@ "children": [ {"source.rdb": {"@table": "zz_auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "kind", "@values": ["Copay"]}}, + {"field.enum": {"name": "kind", "@values": ["Coupon"]}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - {"field.long": {"name": "copayAmount", "@column": "zz_copay_cents"}} + {"field.long": {"name": "couponAmount", "@column": "zz_coupon_cents"}} ], } }, @@ -135,15 +135,15 @@ def test_the_child_imports_the_base_constant_instead_of_restating_it(tmp_path: P def test_a_tph_subtype_references_the_shared_table_name_rather_than_restating_it(tmp_path: Path) -> None: - src = _generate(tmp_path)["copay_auth_names.py"] - assert "COPAYAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE" in src - assert "COPAYAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN" in src - assert 'COPAYAUTH_COPAY_AMOUNT_COLUMN: Final[str] = "zz_copay_cents"' in src + src = _generate(tmp_path)["coupon_auth_names.py"] + assert "COUPONAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE" in src + assert "COUPONAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN" in src + assert 'COUPONAUTH_COUPON_AMOUNT_COLUMN: Final[str] = "zz_coupon_cents"' in src # A single-table hierarchy legitimately has two OBJECT names; only the physical one # is shared. So the subtype keeps its own name/type/subType as literals. - assert 'COPAYAUTH_NAME: Final[str] = "CopayAuth"' in src + assert 'COUPONAUTH_NAME: Final[str] = "CouponAuth"' in src # An inherited identity is reached through the base's constant, not restated. - assert "COPAYAUTH_IDENTITY_PK_NAME: Final[str] = AUTH_IDENTITY_PK_NAME" in src + assert "COUPONAUTH_IDENTITY_PK_NAME: Final[str] = AUTH_IDENTITY_PK_NAME" in src # The whole point: the subtype used to restate the base's table name and every column. assert "zz_auths" not in src @@ -241,27 +241,27 @@ def test_the_emitted_modules_import_and_an_inherited_constant_resolves(tmp_path: (pkg / "__init__.py").write_text("") sys.path.insert(0, str(tmp_path)) try: - spec = importlib.util.spec_from_file_location("gen.copay_auth_names", pkg / "copay_auth_names.py") + spec = importlib.util.spec_from_file_location("gen.coupon_auth_names", pkg / "coupon_auth_names.py") assert spec is not None and spec.loader is not None mod = importlib.util.module_from_spec(spec) - sys.modules["gen.copay_auth_names"] = mod + sys.modules["gen.coupon_auth_names"] = mod spec.loader.exec_module(mod) # An inherited constant, reached through the reference the generator emitted. - assert mod.COPAYAUTH_SOURCE_PRIMARY_TABLE == "zz_auths" - assert mod.COPAYAUTH_SOURCE_PRIMARY_KIND == "table" - assert mod.COPAYAUTH_IDENTITY_PK_SUB_TYPE == "primary" - assert mod.COPAYAUTH_NAME == "CopayAuth" - assert mod.COPAYAUTH_ID_COLUMN == "id" - assert mod.COPAYAUTH_COPAY_AMOUNT_COLUMN == "zz_copay_cents" + assert mod.COUPONAUTH_SOURCE_PRIMARY_TABLE == "zz_auths" + assert mod.COUPONAUTH_SOURCE_PRIMARY_KIND == "table" + assert mod.COUPONAUTH_IDENTITY_PK_SUB_TYPE == "primary" + assert mod.COUPONAUTH_NAME == "CouponAuth" + assert mod.COUPONAUTH_ID_COLUMN == "id" + assert mod.COUPONAUTH_COUPON_AMOUNT_COLUMN == "zz_coupon_cents" # COLUMNS_BY_FIELD stays COMPLETE — it is the lookup surface, and a miss on an # inherited field is the fallback-to-literal this artifact removes. - assert mod.COPAYAUTH_COLUMNS_BY_FIELD == { - "copayAmount": "zz_copay_cents", "id": "id", "kind": "kind", + assert mod.COUPONAUTH_COLUMNS_BY_FIELD == { + "couponAmount": "zz_coupon_cents", "id": "id", "kind": "kind", } finally: sys.path.remove(str(tmp_path)) - sys.modules.pop("gen.copay_auth_names", None) + sys.modules.pop("gen.coupon_auth_names", None) assert tree # keep the generated tree referenced for a readable failure @@ -455,18 +455,18 @@ def test_two_REPLICAS_that_disagree_are_still_refused_by_this_module() -> None: "children": [ {"source.rdb": {"@table": "zz_auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "kind", "@values": ["Copay"]}}, + {"field.enum": {"name": "kind", "@values": ["Coupon"]}}, {"identity.primary": {"@fields": ["id"], "@generation": "increment"}}, ], } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - {"field.long": {"name": "copayAmount", "@column": "zz_copay_cents"}}, + {"field.long": {"name": "couponAmount", "@column": "zz_coupon_cents"}}, ], } }, @@ -476,7 +476,7 @@ def test_two_REPLICAS_that_disagree_are_still_refused_by_this_module() -> None: def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: - # `metaobjects gen --entities CopayAuth`. Pass 1 emits the subtype; pass 2 walks up to + # `metaobjects gen --entities CouponAuth`. Pass 1 emits the subtype; pass 2 walks up to # `Auth` and used to render it as a FRAGMENT unconditionally. A fragment declares no # source, by design, because it has no physical name -- but `Auth` DOES have one: it is # the TPH base, and the shared table is named on it. So the base module came out with no @@ -492,7 +492,7 @@ def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: GenConfig(out_dir=str(out), column_naming="snake_case"), result.root, generators=[names_generator()], - entity_filter=["CopayAuth"], + entity_filter=["CouponAuth"], ) files = {str(p.relative_to(out)): p.read_text() for p in out.rglob("*.py")} @@ -501,7 +501,7 @@ def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: # Every name the subtype imports from the base must EXIST in it -- the assertion the # ImportError would have made at runtime, made here instead. - child = files["copay_auth_names.py"] + child = files["coupon_auth_names.py"] imported = [ alias.name for node in ast.walk(ast.parse(child)) diff --git a/server/python/tests/codegen/test_router_generator.py b/server/python/tests/codegen/test_router_generator.py index e57aaa8deb..ad771ecdfb 100644 --- a/server/python/tests/codegen/test_router_generator.py +++ b/server/python/tests/codegen/test_router_generator.py @@ -444,7 +444,7 @@ def test_no_primary_identity_defaults_to_int() -> None: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.uuid": {"name": "id", "@filterable": True, "@sortable": True}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"], "@filterable": True}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"], "@filterable": True}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "id", "@fields": "id", "@generation": "uuid"}}, ], @@ -458,9 +458,9 @@ def test_no_primary_identity_defaults_to_int() -> None: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], diff --git a/server/python/tests/codegen/test_router_generator_m2m_target_tph.py b/server/python/tests/codegen/test_router_generator_m2m_target_tph.py index 383a3bc2d6..f0b14ba739 100644 --- a/server/python/tests/codegen/test_router_generator_m2m_target_tph.py +++ b/server/python/tests/codegen/test_router_generator_m2m_target_tph.py @@ -66,7 +66,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], @@ -80,9 +80,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], diff --git a/server/python/tests/codegen/test_router_generator_tph_m2m.py b/server/python/tests/codegen/test_router_generator_tph_m2m.py index 5038576b99..17bf679cf6 100644 --- a/server/python/tests/codegen/test_router_generator_tph_m2m.py +++ b/server/python/tests/codegen/test_router_generator_tph_m2m.py @@ -70,9 +70,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: # every rule: # Auth (base, @discriminator "type") --tags--> Tag [rule a] # BridgeAuth (subtype) --linkedAuths--> BridgeAuth [rule b/c, self-join] -# CopayAuth (subtype) [no own M:N] +# CouponAuth (subtype) [no own M:N] # ScopedAuth (ABSTRACT, extends Auth) --auditors--> Tag [rule d] -# PriorAuthAuth (subtype, extends ScopedAuth) +# PermitAuth (subtype, extends ScopedAuth) # Auth (base) --priorityTickets--> PriorityTicket [target-discriminator; base-declared # (Ticket is an UNRELATED TPH hierarchy — see below), so ungated, but target IS TPH] _TPH_M2M_META = { @@ -94,7 +94,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay", "PriorAuth"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon", "Permit"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, # Declared on the BASE: legitimate for every row of the shared table. {"relationship.association": { @@ -133,9 +133,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -154,9 +154,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "ScopedAuth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ {"field.string": {"name": "approver", "@maxLength": 80}}, ], @@ -194,12 +194,12 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: {"field.long": {"name": "auditAuthId", "@required": True}}, {"field.long": {"name": "auditTagId", "@required": True}}, {"identity.primary": {"name": "pk", "@fields": ["auditAuthId", "auditTagId"]}}, - {"identity.reference": {"name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth"}}, + {"identity.reference": {"name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth"}}, {"identity.reference": {"name": "fkAuditTag", "@fields": "auditTagId", "@references": "Tag"}}, ], }}, # An UNRELATED TPH hierarchy — Auth.priorityTickets' target. Separate from - # Auth/BridgeAuth/CopayAuth/PriorAuthAuth entirely, so resolving the + # Auth/BridgeAuth/CouponAuth/PermitAuth entirely, so resolving the # relation via any Auth-hierarchy entity (base or subtype) never has # source is target (see the comment on priorityTickets above). {"object.entity": { @@ -291,12 +291,12 @@ def _gated_body( def test_inherited_m2m_mounted_under_every_concrete_subtype_too() -> None: # `tags` is declared on Auth, so every subtype resolves it. The overlap with the - # base mount is deliberate: /auths/bridge/{a Copay id}/tags must answer [] where + # base mount is deliberate: /auths/bridge/{a Coupon id}/tags must answer [] where # /auths/{that id}/tags does not, and only the subtype-scoped call can express that # — proven by the discriminator value actually being threaded through the GATE, # not just the join call. out = _render() - for value in ("Bridge", "Copay", "PriorAuth"): + for value in ("Bridge", "Coupon", "Permit"): segment = value.lower() assert f'@router.get("/{segment}/{{auth_id}}/tags")' in out, out assert _gated_body(value, "tags") in out, out @@ -309,14 +309,14 @@ def test_subtype_only_m2m_mounted_solely_under_its_own_subtype() -> None: # gate (this row must be a Bridge) AND the target-discriminator literal (the # related rows must be Bridge too) happen to carry the SAME value here — two # independent mechanisms, not one collapsed into the other (see - # test_priorauthlinks_target_discriminator_independent_of_source_gate below + # test_permitlinks_target_discriminator_independent_of_source_gate below # for a case where the two values DIFFER). assert _gated_body("Bridge", "linkedAuths", target_subtype="Bridge") in out # Not a base route (Auth does not declare/resolve linkedAuths)... assert '@router.get("/{auth_id}/linkedAuths")' not in out # ...and not on the sibling subtypes either (own-only on BridgeAuth, not inherited). - assert '@router.get("/copay/{auth_id}/linkedAuths")' not in out - assert '@router.get("/priorauth/{auth_id}/linkedAuths")' not in out + assert '@router.get("/coupon/{auth_id}/linkedAuths")' not in out + assert '@router.get("/permit/{auth_id}/linkedAuths")' not in out def test_priority_tickets_target_discriminator_independent_of_source_gate() -> None: @@ -336,20 +336,20 @@ def test_priority_tickets_target_discriminator_independent_of_source_gate() -> N ) in out # Inherited by every subtype too (rule b) — each subtype's OWN gate applies, # while the target literal stays fixed at "Priority" regardless. - for value in ("Bridge", "Copay", "PriorAuth"): + for value in ("Bridge", "Coupon", "Permit"): assert _gated_body(value, "priorityTickets", target_subtype="Priority") in out, out def test_abstract_mid_level_m2m_mounts_under_its_concrete_descendant_only() -> None: # `auditors` lives on ScopedAuth (abstract) — no path, no rows of its own. It is - # not on Auth either, so PriorAuthAuth (the one concrete descendant) is the ONLY + # not on Auth either, so PermitAuth (the one concrete descendant) is the ONLY # place it can be served. out = _render() - assert '@router.get("/priorauth/{auth_id}/auditors")' in out - assert _gated_body("PriorAuth", "auditors") in out + assert '@router.get("/permit/{auth_id}/auditors")' in out + assert _gated_body("Permit", "auditors") in out assert '@router.get("/{auth_id}/auditors")' not in out assert '@router.get("/bridge/{auth_id}/auditors")' not in out - assert '@router.get("/copay/{auth_id}/auditors")' not in out + assert '@router.get("/coupon/{auth_id}/auditors")' not in out def test_subtype_gate_reuses_the_existing_find_by_id_seam_method() -> None: @@ -383,6 +383,6 @@ def test_polymorphic_and_per_subtype_crud_mounts_still_present() -> None: out = _render() assert 'path="/api/auths"' in out or 'prefix="/api/auths"' in out assert '@router.get("/bridge/{auth_id}")' in out - assert '@router.get("/copay/{auth_id}")' in out - assert '@router.get("/priorauth/{auth_id}")' in out + assert '@router.get("/coupon/{auth_id}")' in out + assert '@router.get("/permit/{auth_id}")' in out assert '@router.get("/{auth_id}")' in out diff --git a/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py b/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py index 07036c3e07..d2924307df 100644 --- a/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py +++ b/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py @@ -59,7 +59,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: # BridgeAuth (subtype) --helpers--> PriorityTicket [SHADOWS the name; TPH # target of the unrelated Ticket hierarchy, so the source-side gate and the # target-discriminator threading stay independent mechanisms] -# CopayAuth (subtype) [inherits, unshadowed] +# CouponAuth (subtype) [inherits, unshadowed] _META = { "metadata.root": { "package": "acme::auth", @@ -79,7 +79,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "helpers", "@cardinality": "many", @@ -101,9 +101,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -184,9 +184,9 @@ def test_every_mount_of_the_shadowed_name_passes_the_threaded_parameter() -> Non assert " rows: list[Any] = render_wire(repo.find_related_helpers(None, auth_id, None), _WIRE_TAG)" in out # Non-shadowing subtype (inherits the base's vanilla target): gated, None literal. assert ( - ' if repo.find_by_id("Copay", auth_id) is None:\n' + ' if repo.find_by_id("Coupon", auth_id) is None:\n' " return []\n" - ' rows: list[Any] = render_wire(repo.find_related_helpers("Copay", auth_id, None), _WIRE_TAG)' + ' rows: list[Any] = render_wire(repo.find_related_helpers("Coupon", auth_id, None), _WIRE_TAG)' ) in out # Shadowing subtype: its OWN target's discriminator literal. assert ( @@ -201,5 +201,5 @@ def test_no_two_argument_call_of_the_shadowed_name_remains() -> None: # name may call the seam without the parameter every other mount passes. out = _render() assert "repo.find_related_helpers(None, auth_id)\n" not in out - assert 'repo.find_related_helpers("Copay", auth_id)\n' not in out + assert 'repo.find_related_helpers("Coupon", auth_id)\n' not in out assert 'repo.find_related_helpers("Bridge", auth_id)\n' not in out diff --git a/server/python/tests/codegen/test_tph_codegen.py b/server/python/tests/codegen/test_tph_codegen.py index 7379fa2305..f5d2705e9d 100644 --- a/server/python/tests/codegen/test_tph_codegen.py +++ b/server/python/tests/codegen/test_tph_codegen.py @@ -71,10 +71,10 @@ def test_plan_detects_base_and_subtypes(entities, index) -> None: assert plan.discriminator_field == "type" assert [(s.entity.name, s.value, s.route_segment) for s in plan.subtypes] == [ ("BridgeAuth", "Bridge", "bridge"), - ("CopayAuth", "Copay", "copay"), - ("PriorAuthAuth", "PriorAuth", "priorauth"), + ("CouponAuth", "Coupon", "coupon"), + ("PermitAuth", "Permit", "permit"), ] - for sub in ("BridgeAuth", "CopayAuth", "PriorAuthAuth"): + for sub in ("BridgeAuth", "CouponAuth", "PermitAuth"): assert is_tph_subtype(entities[sub]) assert not is_tph_subtype(entities["Auth"]) @@ -92,12 +92,12 @@ def test_subtype_pins_discriminator_to_literal(entities, index) -> None: def test_base_entity_model_is_plain_base(entities, index) -> None: # The base is a plain BaseModel; its `type` enum legitimately emits the full - # Literal["Bridge","Copay","PriorAuth"] (the enum values), but it must NOT carry a + # Literal["Bridge","Coupon","Permit"] (the enum values), but it must NOT carry a # single-value discriminator PIN (that's the subtype's job). Python also defers the # discriminated-UNION alias (dict runtime; see the entity_model TPH note). src = render_entity_model(entities["Auth"], index) assert "class Auth(BaseModel):" in src - for val in ("Bridge", "Copay", "PriorAuth"): + for val in ("Bridge", "Coupon", "Permit"): assert f'type: Literal["{val}"] = "{val}"' not in src @@ -117,7 +117,7 @@ def test_base_router_polymorphic_plus_per_subtype(entities, index) -> None: # no polymorphic create (can't create an abstract base) assert '@router.post("", ' not in src # per-subtype CRUD at the lowercased segment, discriminator injected from the URL - for seg, val in (("bridge", "Bridge"), ("copay", "Copay"), ("priorauth", "PriorAuth")): + for seg, val in (("bridge", "Bridge"), ("coupon", "Coupon"), ("permit", "Permit")): assert f'@router.get("/{seg}")' in src assert f'@router.post("/{seg}", status_code=status.HTTP_201_CREATED)' in src assert f'@router.get("/{seg}/{{auth_id}}")' in src @@ -149,5 +149,5 @@ def test_base_allowlist_unions_subtype_fields(entities, index) -> None: assert '"id"' in src and '"type"' in src and '"reference"' in src # subtype-only filterable columns folded into the single-table base allowlist assert '"quantity"' in src # BridgeAuth - assert '"copayAmount"' in src # CopayAuth - assert '"approver"' in src # PriorAuthAuth + assert '"couponAmount"' in src # CouponAuth + assert '"approver"' in src # PermitAuth diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 1ecf6f4ecd..0fc54dd780 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -1,6 +1,19 @@ { "language": "python", - "fixtures": [], + "fixtures": [ + "error-computed-cast-enum-not-int-stored", + "error-origin-function-free-sql", + "error-projection-grain-not-object-array", + "error-projection-union-shape", + "projection-view-vocabulary-rc21" + ], "_comment_fr024": "FR-024 Phase-E validation parity SHIPPED in this port. The full FR-024 loader contract now holds: object.projection registration + per-subtype projection child rules + dotted Entity.child extends-resolution (type-scoped, ERR_EXTENDS_TARGET_MISMATCH), AND the validation passes \u2014 identity names required + projection identity pass-through/key-correspondence (B3), value-purity + projection-licensing subtype rules (B4a), the entity-primary-source-readonly hard cutover (B4b), @via single-hop-unique inference + origin cardinality (B5), and extends/origin agreement + derived-field providability (B6). Every former FR-024 error fixture (error-identity-name-required, error-projection-identity-not-extended, error-identity-key-mismatch, error-projection-extends-entity, error-projection-source-writable, error-value-with-identity-secondary, error-value-with-source, error-origin-via-ambiguous, error-origin-passthrough-to-many, error-origin-aggregate-no-to-many, error-extends-origin-mismatch, error-derived-field-no-read-source, error-entity-primary-source-readonly) now emits its expected code with the byte-identical source envelope and is un-ledgered.", - "notes": "No expected failures remain. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child)." + "notes": "No expected failures remain. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", + "reasons": { + "error-computed-cast-enum-not-int-stored": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", + "error-origin-function-free-sql": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", + "error-projection-grain-not-object-array": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", + "error-projection-union-shape": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", + "projection-view-vocabulary-rc21": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp" + } } diff --git a/server/python/tests/conformance/test_conformance_twin_roundtrip.py b/server/python/tests/conformance/test_conformance_twin_roundtrip.py index 321707e5be..b6a9c99021 100644 --- a/server/python/tests/conformance/test_conformance_twin_roundtrip.py +++ b/server/python/tests/conformance/test_conformance_twin_roundtrip.py @@ -32,6 +32,7 @@ from .conformance_adapter import _resolve_providers from .corpus import corpus_root +from .expected_failures import _ledger from .fixture_discovery import Fixture, discover_fixtures _CORPUS = corpus_root() @@ -111,7 +112,17 @@ def test_yaml_twin(fix: Fixture) -> None: _ROUND_TRIP = [f for f in _FIXTURES if f.has_expected and f.name not in _ROUND_TRIP_EXCLUSIONS] -@pytest.mark.parametrize("fix", _ROUND_TRIP, ids=[f.name for f in _ROUND_TRIP]) +# A fixture on the port's expected-failures ledger is a known gap: strict xfail, so one that +# starts passing fails the build (the ledger's staleness rule). +_LEDGER = _ledger() +_ROUND_TRIP_PARAMS = [ + pytest.param(f, id=f.name, marks=pytest.mark.xfail(strict=True, reason="expected-failures ledger")) + if f.name in _LEDGER else pytest.param(f, id=f.name) + for f in _ROUND_TRIP +] + + +@pytest.mark.parametrize("fix", _ROUND_TRIP_PARAMS) def test_round_trip(fix: Fixture) -> None: text = (fix.dir / "expected.json").read_text(encoding="utf-8") loaded = _load([InMemoryStringSource(text, id="expected.json")], fix) diff --git a/server/python/tests/integration/generated_tph_app.py b/server/python/tests/integration/generated_tph_app.py index 4dc0c4396e..fb855f656c 100644 --- a/server/python/tests/integration/generated_tph_app.py +++ b/server/python/tests/integration/generated_tph_app.py @@ -1,7 +1,7 @@ """FR-017 Tier 4/5 — boot the GENERATED TPH router over HTTP. Peer to ``generated_m2m_app.py`` but for the single-table table-per-hierarchy -model (Auth base + BridgeAuth / CopayAuth / PriorAuthAuth). It runs the REAL +model (Auth base + BridgeAuth / CouponAuth / PermitAuth). It runs the REAL ``router_generator`` (+ the filter-allowlist generator it imports) for the discriminator BASE entity, writes the emitted modules to a temp package, imports the generated router UNMODIFIED, mounts it on a FastAPI app, and fills the diff --git a/server/python/tests/integration/test_api_contract_tph_generated.py b/server/python/tests/integration/test_api_contract_tph_generated.py index 7305eb6b78..b84fb01b84 100644 --- a/server/python/tests/integration/test_api_contract_tph_generated.py +++ b/server/python/tests/integration/test_api_contract_tph_generated.py @@ -55,6 +55,16 @@ def _load_scenarios() -> list[tuple[str, dict[str, Any]]]: _SCENARIOS = _load_scenarios() + +# Scenarios this port's generated routes answer differently, each with its reason. The routes +# validate the body's discriminator against the route's subtype and answer 400 rather than +# dropping it; nothing is stored either way. See codegen/KNOWN_GAPS.md. +_PORT_SKIPS: dict[str, str] = { + "tph-input-foreign-discriminator-dropped": ( + "a body discriminator naming another subtype is a 400 here, not a silent drop " + "(KNOWN_GAPS.md: TPH body discriminator)" + ), +} _APP, _REPO = build_generated_tph_app(_TPH_DIR) _CLIENT = TestClient(_APP) @@ -65,6 +75,8 @@ def _load_scenarios() -> list[tuple[str, dict[str, Any]]]: ids=[name for name, _ in _SCENARIOS], ) def test_api_contract_tph_generated_scenario(scenario_name: str, scenario: dict[str, Any]) -> None: + if scenario_name in _PORT_SKIPS: + pytest.skip(_PORT_SKIPS[scenario_name]) _REPO.reset() _REPO.seed(_SEED["auths"]) for req in scenario.get("requests", []): diff --git a/server/python/tests/integration/test_m2m_target_tph_generated.py b/server/python/tests/integration/test_m2m_target_tph_generated.py index 95c0bef69c..96de59027a 100644 --- a/server/python/tests/integration/test_m2m_target_tph_generated.py +++ b/server/python/tests/integration/test_m2m_target_tph_generated.py @@ -52,7 +52,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], @@ -68,9 +68,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -244,14 +244,14 @@ def _seed(repo: _SponsorRepo) -> None: sponsors=[{"id": 1, "name": "Acme"}], auths=[ {"id": 10, "type": "Bridge", "reference": "b1", "quantity": 3, "pinHash": "bridge-pin"}, - {"id": 11, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 11, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], sponsor_auths=[(1, 10), (1, 11)], ) def test_compliant_repo_filters_target_to_the_resolved_discriminator() -> None: - # The junction links Sponsor 1 to BOTH a Bridge row (10) and a Copay row (11) + # The junction links Sponsor 1 to BOTH a Bridge row (10) and a Coupon row (11) # — the physical FK on SponsorAuth can only address the shared `auths` table, # it cannot itself tell subtypes apart. The router hands the compliant repo # target_subtype="Bridge" (resolved from BridgeAuth's @discriminatorValue at @@ -302,6 +302,6 @@ def spy(id: int, target_subtype: str) -> list[Any]: assert resp.status_code == 200 assert calls == [(1, "Bridge")] - # The hostile repo's own non-compliance leaks the Copay row — expected, and + # The hostile repo's own non-compliance leaks the Coupon row — expected, and # exactly the boundary this test documents rather than papers over. assert {r["id"] for r in resp.json()} == {10, 11} diff --git a/server/python/tests/integration/test_tph_m2m_generated.py b/server/python/tests/integration/test_tph_m2m_generated.py index 3b28ffb84a..4d40e084b5 100644 --- a/server/python/tests/integration/test_tph_m2m_generated.py +++ b/server/python/tests/integration/test_tph_m2m_generated.py @@ -43,7 +43,7 @@ # Auth (base, @discriminator "type") --tags--> Tag [rule a] # BridgeAuth (subtype) --linkedAuths--> BridgeAuth [rule b/c, self-join] -# CopayAuth (subtype) [no own M:N — inherits tags] +# CouponAuth (subtype) [no own M:N — inherits tags] _META = { "metadata.root": { "package": "acme::auth", @@ -63,7 +63,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "tags", "@cardinality": "many", @@ -86,9 +86,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -306,11 +306,11 @@ def _build_app(repo_factory: type[_Repo] = _Repo) -> tuple[FastAPI, _Repo]: @pytest.fixture() def client_and_repo(): app, repo = _build_app() - # id=1 Bridge, id=2 Copay; tag 10 shared, tag 11 Bridge-only; a Bridge->Bridge link. + # id=1 Bridge, id=2 Coupon; tag 10 shared, tag 11 Bridge-only; a Bridge->Bridge link. repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}, {"id": 11, "name": "bridge-only"}], auth_tags=[(1, 10), (1, 11), (2, 10)], @@ -322,7 +322,7 @@ def client_and_repo(): def test_base_level_traversal_ignores_subtype(client_and_repo) -> None: # Rule (a): GET /auths/{id}/tags — every row of the shared table is a legitimate - # source, so both a Bridge id and a Copay id resolve their tags with no gate. + # source, so both a Bridge id and a Coupon id resolve their tags with no gate. client, _ = client_and_repo resp = client.get("/api/auths/1/tags") assert resp.status_code == 200 @@ -343,7 +343,7 @@ def test_subtype_level_traversal_returns_its_own_relations(client_and_repo) -> N def test_subtype_mismatch_returns_200_empty_list_not_404(client_and_repo) -> None: - # Rule (c): GET /auths/bridge/{a Copay id}/tags — the id names no Bridge row, so + # Rule (c): GET /auths/bridge/{a Coupon id}/tags — the id names no Bridge row, so # it has no relations. Must be 200 + [], never 404 and never the sibling's rows # (which the junction FK, addressing only the shared base table, would happily # return without this gate). @@ -352,7 +352,7 @@ def test_subtype_mismatch_returns_200_empty_list_not_404(client_and_repo) -> Non assert resp.status_code == 200 assert resp.json() == [] - resp2 = client.get("/api/auths/copay/1/tags") + resp2 = client.get("/api/auths/coupon/1/tags") assert resp2.status_code == 200 assert resp2.json() == [] @@ -367,7 +367,7 @@ def test_subtype_only_relation_traversal(client_and_repo) -> None: # ...and there is no such route at all on a sibling subtype or the base — the # router never mounted it there (proven at the codegen level too), so FastAPI # itself answers 404 (no matching route), not an application-level empty list. - assert client.get("/api/auths/copay/2/linkedAuths").status_code == 404 + assert client.get("/api/auths/coupon/2/linkedAuths").status_code == 404 assert client.get("/api/auths/1/linkedAuths").status_code == 404 @@ -379,7 +379,7 @@ def hostile_client_and_repo(): repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}, {"id": 11, "name": "bridge-only"}], auth_tags=[(1, 10), (1, 11), (2, 10)], @@ -395,7 +395,7 @@ def test_generated_router_enforces_subtype_gate_even_when_repo_does_not( # THE assertion that distinguishes ENFORCEMENT (in generated code) from # DELEGATION (trusting the consumer): _HostileRepo.find_related_tags does NOT # filter by subtype at all — if the router only ever called it directly (the - # pre-follow-up shape), GET /auths/bridge/2/tags (id=2 is a COPAY row) would + # pre-follow-up shape), GET /auths/bridge/2/tags (id=2 is a COUPON row) would # execute the join over id=2's real auth_tags rows and return tag 10 with a # 200, exactly the silent leak the maintainer flagged. With the composed # find_by_id("Bridge", 2) gate in _emit_tph_m2m_route, the router itself diff --git a/server/python/tests/integration/test_tph_m2m_shadowed_generated.py b/server/python/tests/integration/test_tph_m2m_shadowed_generated.py index 7427d4d9aa..770a605200 100644 --- a/server/python/tests/integration/test_tph_m2m_shadowed_generated.py +++ b/server/python/tests/integration/test_tph_m2m_shadowed_generated.py @@ -38,7 +38,7 @@ # Auth (base, @discriminator "type") --helpers--> Tag [non-TPH target] # BridgeAuth (subtype) --helpers--> PriorityTicket [SHADOWS the name; TPH target] -# CopayAuth (subtype) [inherits, unshadowed] +# CouponAuth (subtype) [inherits, unshadowed] _META = { "metadata.root": { "package": "acme::auth", @@ -58,7 +58,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "helpers", "@cardinality": "many", @@ -80,9 +80,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -284,12 +284,12 @@ def _build_app() -> tuple[FastAPI, _StrictRepo]: @pytest.fixture() def client_and_repo(): app, repo = _build_app() - # id=1 Bridge, id=2 Copay; tag 10; tickets 20 (Priority) and 21 (Standard). + # id=1 Bridge, id=2 Coupon; tag 10; tickets 20 (Priority) and 21 (Standard). # auth 1 has tag 10 AND ticket 20; auth 2 has tag 10 only. repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}], tickets=[ @@ -324,13 +324,13 @@ def test_base_mount_threads_an_explicit_none_and_returns_the_base_targets( def test_non_shadowing_subtype_mount_threads_an_explicit_none( client_and_repo, ) -> None: - # CopayAuth inherits the BASE's helpers→Tag unchanged: same widened arity, + # CouponAuth inherits the BASE's helpers→Tag unchanged: same widened arity, # gated by its own discriminator value, None for the target. client, repo = client_and_repo - resp = client.get("/api/auths/copay/2/helpers") + resp = client.get("/api/auths/coupon/2/helpers") assert resp.status_code == 200 assert [t["id"] for t in resp.json()] == [10] - assert repo.calls[-1] == ("Copay", 2, None) + assert repo.calls[-1] == ("Coupon", 2, None) def test_shadowing_subtype_mount_threads_its_own_target_discriminator( @@ -349,7 +349,7 @@ def test_shadowing_subtype_mount_threads_its_own_target_discriminator( def test_shadowed_subtype_gate_answers_empty_for_a_siblings_id( client_and_repo, ) -> None: - # Rule (c) composes unchanged under the shadow: id=2 is a Copay row, so the + # Rule (c) composes unchanged under the shadow: id=2 is a Coupon row, so the # bridge-segment mount short-circuits to [] before the join is ever reached. client, repo = client_and_repo resp = client.get("/api/auths/bridge/2/helpers") diff --git a/server/python/tests/loader/test_port_scoped_attr.py b/server/python/tests/loader/test_port_scoped_attr.py index 7ae278db2b..5cefed0b92 100644 --- a/server/python/tests/loader/test_port_scoped_attr.py +++ b/server/python/tests/loader/test_port_scoped_attr.py @@ -1,8 +1,6 @@ """``@collectionName`` is shared vocabulary every port implements (Python's REST segment and reverse finders read it). Python registers and type-checks it, so a model that carries it loads -strictly here. The -never-released ``@dbSetName`` it replaced is not vocabulary; an attribute the registry does not -carry still fails, and a wrong value type fails. +strictly here. An attribute the registry does not carry still fails, and a wrong value type fails. """ from __future__ import annotations @@ -33,7 +31,7 @@ def test_it_is_type_checked() -> None: assert _codes({"@collectionName": ["Diagnoses"]}) != [] -def test_the_never_released_db_set_name_is_not_vocabulary() -> None: +def test_db_set_name_is_not_vocabulary() -> None: assert any("UNKNOWN_ATTR" in c for c in _codes({"@dbSetName": "Diagnoses"})) diff --git a/server/python/tests/loader/test_template_payload_target_210.py b/server/python/tests/loader/test_template_payload_target_210.py index ce9fc43c34..b039b79668 100644 --- a/server/python/tests/loader/test_template_payload_target_210.py +++ b/server/python/tests/loader/test_template_payload_target_210.py @@ -82,6 +82,8 @@ def test_assembly_origins_rejected_on_value_host() -> None: "first": {"origin.first": {"@of": "t::ai::Author.name", "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"]}}, + # rc.21 part B (U10). + "function": {"origin.function": {"@function": "f", "@returns": "int"}}, } assert set(origin_by_subtype) == set(ASSEMBLY_ORIGIN_SUBTYPES) for sub, origin in origin_by_subtype.items(): diff --git a/server/python/tests/runtime/test_object_manager_string_value_map.py b/server/python/tests/runtime/test_object_manager_string_value_map.py new file mode 100644 index 0000000000..0c74f3f66c --- /dev/null +++ b/server/python/tests/runtime/test_object_manager_string_value_map.py @@ -0,0 +1,51 @@ +"""rc.21 — a string-stored ``field.enum`` with ``@stringValueMap``: the ObjectManager writes +the member's stored string and reads the member back; an unmapped stored string raises.""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest + +from metaobjects import load_string +from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value + +_META = {"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "Article", "children": [ + {"source.rdb": {"@table": "articles"}}, + {"field.long": {"name": "id"}}, + {"field.enum": {"name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": {"Draft": "draft", "Published": "published"}}}, + {"identity.primary": {"name": "id", "@fields": "id"}}, + ]}}, +]}} + + +def _status() -> Any: + result = load_string(json.dumps(_META)) + assert not result.errors, result.errors + return next(f for f in result.root.children()[0].fields() if f.name == "status") + + +def test_writes_the_stored_string_and_reads_the_member() -> None: + field = _status() + assert _coerce_write_value(field, "Published") == "published" + assert _decode_read_value(field, "published") == "Published" + + +def test_an_unmapped_stored_string_raises() -> None: + with pytest.raises(ValueError, match="no member in @stringValueMap"): + _decode_read_value(_status(), "lost") + + +def test_an_unmapped_member_raises_written_or_filtered() -> None: + # rc.21 part B (N4): a filter on an unmapped member raises, as a write does, in every port — + # passed through, the symbol could equal another member's stored string. + from metaobjects.runtime.object_manager import _coerce_filter_value + field = _status() + with pytest.raises(ValueError, match="cannot write 'Archived': it has no stored string in @stringValueMap"): + _coerce_write_value(field, "Archived") + with pytest.raises(ValueError, match="cannot filter on 'Archived': it has no stored string in @stringValueMap"): + _coerce_filter_value(field, "Archived") + assert _coerce_filter_value(field, "Draft") == "draft" diff --git a/server/python/tests/test_report_read_model.py b/server/python/tests/test_report_read_model.py index cd37a93f81..90c1522120 100644 --- a/server/python/tests/test_report_read_model.py +++ b/server/python/tests/test_report_read_model.py @@ -23,6 +23,7 @@ FIELD_ATTR_PRECISION, FIELD_ATTR_REQUIRED, FIELD_ATTR_SCALE, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_VALUES, ) from metaobjects.meta.core.field.meta_field import MetaField @@ -215,3 +216,20 @@ def test_a_measure_with_default_yields_a_detached_field_with_required_true() -> ("revenueRaw", False), ] assert all(f.get_meta_attr(FIELD_ATTR_DEFAULT) is None for f in fields) + + +def test_string_value_map_is_carried_from_the_type_source() -> None: + """rc.21 part B (N5): a report row over a ``@stringValueMap`` enum carries the map (read + RESOLVING), so the row decodes the stored string to the member, as C# and TypeScript do.""" + model = json.loads(json.dumps(_MODEL)) + sale = model["metadata.root"]["children"][1]["object.entity"] + for child in sale["children"]: + if "field.enum" in child: + child["field.enum"]["@stringValueMap"] = {"OPEN": "open", "PAID": "paid"} + result = MetaDataLoader().load([InMemoryStringSource(json.dumps(model), "meta.shop.json")]) + assert result.errors == [], [e.message for e in result.errors] + report = next(c for c in result.root.children() if c.type == TYPE_OBJECT and c.name == "R") + status = {f.name: f for f in report_read_model(report, result.root).fields()}["status"] + assert status.get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP) == {"OPEN": "open", "PAID": "paid"} + # Without the map on the source, the row carries none. + assert _fields()["status"].get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP) is None diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index 88e4620afe..87a58ca965 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -23,6 +23,7 @@ import { import type { Generator } from "@metaobjectsdev/codegen-ts"; import type { WriteStatus } from "@metaobjectsdev/codegen-ts"; import { packageOfResolutionKey } from "@metaobjectsdev/metadata"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import type { MetaRoot } from "@metaobjectsdev/metadata"; import type { Collection } from "@metaobjectsdev/sdk"; import { describeLoadError, reportLoadError } from "../lib/load-error.js"; @@ -247,6 +248,11 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat : []; for (const w of unknownAttrs) { log.warn(`warning: ${w}`); warnings.push(w); } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. Said before + // the skip, so a skipped run still says it (as `dotnet meta gen` does): the finding is about the + // model, and a warning that stops appearing once nothing changes is one the user never fixes. + warnings.push(...warnWidenedExtenders(metadata, (line) => log.warn(line))); + // ADR-0064 — skip rendering when the loaded model and every generator input match the last // successful run and every file it recorded exists. Nothing renders and nothing is written, // the manifest and the stored key included. `--force` (and every mode that does not write) @@ -338,7 +344,7 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat // the model with a loader of its own (the docs site). sourceRoots: sourceRootsOf(genCollection), // The physical schema `agent/schema.md` describes, built only if `agentDocsFile()` asks. - agentSchema: () => buildAgentSchemaInput( + agentSchema: () => schemaOptions === undefined ? undefined : buildAgentSchemaInput( metadata, forgeConfig.dialect, (m) => { const w = `[agent-docs] ${m}`; log.warn(w); warnings.push(w); }, diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 9806304313..35f378714f 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -85,6 +85,7 @@ import { decimalPrecisionWarnings } from "../lib/decimal-precision-advisory.js"; import { schemaAdvisoryLines } from "../lib/schema-advisories.js"; import { scanForReferentialActionConflicts } from "../lib/referential-action-advisory.js"; import type { MetaData, MetaRoot } from "@metaobjectsdev/metadata"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import { describeError } from "../lib/error-text.js"; /** @@ -829,6 +830,8 @@ export async function migrateCommand( reportLoadError(log, "failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); warnReferentialActionConflicts(metadata, collection, schema); let kysely; @@ -1571,6 +1574,8 @@ export async function runOfflineGenerate( reportLoadError(log, "migrate: failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); const schema = resolveSchemaBuild(collection, offlineGenConfig, fmt); if (typeof schema === "number") return schema; warnReferentialActionConflicts(metadata, collection, schema); @@ -1885,6 +1890,8 @@ async function runD1Migrate( reportLoadError(log, "migrate: failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); const schema = resolveSchemaBuild(collection, d1GenConfig, fmt); if (typeof schema === "number") return schema; warnReferentialActionConflicts(metadata, collection, schema); diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 843d84c2c8..df1b6ade2f 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -68,6 +68,7 @@ import { import type { MetaobjectsGenConfig } from "@metaobjectsdev/codegen-ts"; import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; import { buildKyselyFromUrl, inferDialect, type Dialect } from "../lib/kysely.js"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import { tokensToAllowOptions, describeChange } from "../lib/allow.js"; import { computeDrift, @@ -84,6 +85,8 @@ import { type ReplayEngine, verifyReplay, introspect, + checkDeclaredFunctions, + DECLARED_FUNCTION_CHECK_LIMITS, diff, withoutViewRecreates, readSnapshot, @@ -417,6 +420,8 @@ export async function verifyCommand( }, fmt); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(root, (line) => log.warn(line)); // The project's schema settings, resolved once for every expected-schema build and drift // computation below. A `migrate.conventions` preset this version does not ship is a config @@ -1498,7 +1503,20 @@ export async function verifyCommand( return 1; } - return reportSchemaDrift(driftResult, [...ledgerDrift, ...snapshotDrift], kysely.displayUrl); + // rc.21 part B (N2): a declared origin.function's signature is the database's, or a finding. + let functionDrift: string[] = []; + if (kysely.dialect === "postgres") { + try { + functionDrift = await checkDeclaredFunctions(kysely.db, root); + if (functionDrift.length > 0) log.warn(`verify: ${DECLARED_FUNCTION_CHECK_LIMITS}`); + } catch (err) { + schemaRunError = `failed to read the declared functions from ${kysely.displayUrl}: ${describeError(err)}`; + log.error(`verify: ${schemaRunError}`); + return 1; + } + } + + return reportSchemaDrift(driftResult, [...ledgerDrift, ...snapshotDrift, ...functionDrift], kysely.displayUrl); } finally { await shadow?.close(); try { @@ -1818,7 +1836,7 @@ export async function verifyCommand( try { result = await computeCodegenDrift(config, codegenRoot, genConfigDir, genCollection.inScope, genCollection.ownFiles, { sourceRoots: sourceRootsOf(genCollection), - agentSchema: () => buildAgentSchemaInput( + agentSchema: () => codegenSchema === undefined ? undefined : buildAgentSchemaInput( codegenRoot, config.dialect, (m) => log.warn(`verify --codegen: [agent-docs] ${m}`), diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts index b7666f7194..ed9b85e265 100644 --- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts +++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts @@ -11,7 +11,7 @@ import { resolveCollection, type Collection } from "@metaobjectsdev/sdk"; import { physicalNamingRemovedMessage, registerColumnNamingStrategy, - registerTableNamingRule, + registerTableNamingRule, registerPluralizer, } from "@metaobjectsdev/metadata"; const CONFIG_FILE = "metaobjects.config.ts"; @@ -502,6 +502,7 @@ function registerNamingStrategies(cfg: MetaobjectsGenConfig, fullPath: string): try { for (const [name, fn] of Object.entries(strategies.columns ?? {})) registerColumnNamingStrategy(name, fn); for (const [name, fn] of Object.entries(strategies.tables ?? {})) registerTableNamingRule(name, fn); + for (const [name, fn] of Object.entries(strategies.collections ?? {})) registerPluralizer(name, fn); } catch (err) { throw new Error(`metaobjects.config.ts at ${fullPath}: namingStrategies: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/server/typescript/packages/cli/src/lib/naming-preload.ts b/server/typescript/packages/cli/src/lib/naming-preload.ts index ef249ccb0f..a28915eedd 100644 --- a/server/typescript/packages/cli/src/lib/naming-preload.ts +++ b/server/typescript/packages/cli/src/lib/naming-preload.ts @@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { DEFAULT_METAOBJECTS_DIR, discoverCollectionRoot } from "@metaobjectsdev/sdk"; -import { isRegisteredColumnNamingStrategy, isRegisteredTableNamingRule } from "@metaobjectsdev/metadata"; +import { isRegisteredColumnNamingStrategy, isRegisteredTableNamingRule, isRegisteredPluralizer } from "@metaobjectsdev/metadata"; /** `.metaobjects/config.json`'s basename (the sdk reader's `CONFIG_FILE`). */ const NEUTRAL_CONFIG_FILE = "config.json"; @@ -45,10 +45,11 @@ export async function registerProjectNamingStrategies(cwd: string): Promise n !== undefined); const cause = e instanceof Error ? e.message : String(e); const where = `${join(projectRoot, TS_CONFIG_FILE)}: ${TS_CONFIG_FILE} did not load (${cause})`; diff --git a/server/typescript/packages/cli/src/lib/widened-extenders.ts b/server/typescript/packages/cli/src/lib/widened-extenders.ts new file mode 100644 index 0000000000..ff69bd9367 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/widened-extenders.ts @@ -0,0 +1,13 @@ +// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields read +// a TPH subtype's columns now returns every base row. The loader records that on its warning +// channel, which `loadMemory` does not return, so every command that loads a model to emit or check +// views — gen, migrate, verify — says it here, the same way. + +import { validateExtenderSubtypeScope, type MetaData } from "@metaobjectsdev/metadata"; + +/** Print each widened-extender finding through `warn` and return the findings. */ +export function warnWidenedExtenders(root: MetaData, warn: (line: string) => void): string[] { + const findings = validateExtenderSubtypeScope(root); + for (const w of findings) warn(`warning: ${w}`); + return findings; +} diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index bc76cbef86..a2b26f79b2 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -370,7 +370,7 @@ async function emit( // A documentation generator writes to the `docs` target (ADR-0034 Amendment 9), declared // here at the same directory, so every generator's output is read from one place. const settings = { - outDir, extStyle: "none", dbImport: "../db", dialect: "postgres", targets: { docs: { outDir } }, + outDir, outputLayout: "flat", extStyle: "none", dbImport: "../db", dialect: "postgres", targets: { docs: { outDir } }, } as const; try { await runGen({ diff --git a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts new file mode 100644 index 0000000000..2848372f9b --- /dev/null +++ b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts @@ -0,0 +1,134 @@ +// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields +// read a TPH subtype's columns returns every base row. The loader records that on its warning +// channel, which `loadMemory` does not return; every command that loads a model to emit or check +// views (gen, migrate, verify) prints it, so the change is visible. +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { run } from "../src/index.js"; + +const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures", "__tmp__"); + +function model(scoped: boolean, abstract = false): string { + return JSON.stringify({ + "metadata.root": { + package: "app", + children: [ + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 10 } }, { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + { "object.projection": { name: "TruckRow", extends: "VehicleBase", ...(abstract ? { abstract: true } : {}), ...(scoped ? { "@filter": { kind: "TRUCK" } } : {}), children: [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { name: "payload", extends: "Truck.payloadClass" } } ] } }, + ], + }, + }); +} + +function setupRepo(scoped: boolean, abstract = false, generators = "[]"): string { + mkdirSync(WORKSPACE_TMP, { recursive: true }); + const root = mkdtempSync(join(WORKSPACE_TMP, "gen-extender-scope-")); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.app.json"), model(scoped, abstract), "utf8"); + mkdirSync(join(root, ".metaobjects"), { recursive: true }); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }), "utf8"); + writeFileSync(join(root, "metaobjects.config.ts"), ` +import { defineConfig } from "@metaobjectsdev/codegen-ts"; +export default defineConfig({ + outDir: ${JSON.stringify(join(root, "generated"))}, + dialect: "postgres", + dbImport: "~/db", + extStyle: "none", + generators: ${generators}, +}); +`); + return root; +} + +let out: string[]; +let err: string[]; +let origLog: typeof console.log; +let origErr: typeof console.error; +beforeEach(() => { + out = []; + err = []; + origLog = console.log; + origErr = console.error; + console.log = (...a: unknown[]) => { out.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { err.push(a.map(String).join(" ")); }; +}); +afterEach(() => { + console.log = origLog; + console.error = origErr; +}); + +describe("meta gen — the widened-extender warning is printed", () => { + test("a skipped run still prints it, as dotnet meta gen does", async () => { + // A wired generator, so the first run stores the key the second one skips on. + const root = setupRepo(false, false, `["entity"]`); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + err.length = 0; + out.length = 0; + expect(await run(["gen", "--cwd", root])).toBe(0); + expect([...out, ...err].join("\n")).toContain("nothing changed since the last meta gen"); + expect(err.join("\n")).toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("names the projection, the field and the remedy; exit code unchanged", async () => { + const root = setupRepo(false); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + const stderr = err.join("\n"); + expect(stderr).toContain("object.projection TruckRow"); + expect(stderr).toContain(`"payload" (Truck.payloadClass)`); + expect(stderr).toContain("@filter { kind: }"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("meta verify and meta migrate print it too (fix round 2, N4)", async () => { + const root = setupRepo(false); + try { + await run(["verify", "--cwd", root]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + err.length = 0; + await run(["migrate", "--cwd", root, "--dialect", "sqlite", "--dry-run"]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + err.length = 0; + await run(["migrate", "--cwd", root, "--from-db", "--db", `file:${join(root, "t.db")}`, "--slug", "init", "--dry-run"]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("an abstract extender emits no view: no warning (fix round 2, N4)", async () => { + const root = setupRepo(false, true); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(err.join("\n")).not.toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("a discriminator filter scopes it: no warning", async () => { + const root = setupRepo(true); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(err.join("\n")).not.toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/server/typescript/packages/cli/test/gen-imported-nodes.test.ts b/server/typescript/packages/cli/test/gen-imported-nodes.test.ts index b5b1361c1f..3bb1da55c2 100644 --- a/server/typescript/packages/cli/test/gen-imported-nodes.test.ts +++ b/server/typescript/packages/cli/test/gen-imported-nodes.test.ts @@ -121,6 +121,7 @@ function setupRepo(opts: { scopeInclude?: string[] } = {}): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(genOutDir(root))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/gen-split-tree-single-import.test.ts b/server/typescript/packages/cli/test/gen-split-tree-single-import.test.ts index 0afb0bec66..f62b0dfbe0 100644 --- a/server/typescript/packages/cli/test/gen-split-tree-single-import.test.ts +++ b/server/typescript/packages/cli/test/gen-split-tree-single-import.test.ts @@ -79,6 +79,7 @@ const CONFIG = [ `import { namesFile } from "./codegen/generators/names.js";`, `export default defineConfig({`, ` outDir: "src/generated",`, + ` outputLayout: "flat",`, ` extStyle: "js",`, ` dbImport: "../db",`, ` dialect: "sqlite",`, diff --git a/server/typescript/packages/cli/test/init.test.ts b/server/typescript/packages/cli/test/init.test.ts index 56c45acfcf..3befb26c85 100644 --- a/server/typescript/packages/cli/test/init.test.ts +++ b/server/typescript/packages/cli/test/init.test.ts @@ -779,6 +779,7 @@ describe("init() — no dbImport, no db stub, and routes still works once chosen 'import { routesFile } from "./codegen/generators/routes.js";', "export default defineConfig({", ' outDir: "src/generated",', + ' outputLayout: "flat",', ' dialect: "sqlite",', ' extStyle: "js",', ' dbImport: "../db",', diff --git a/server/typescript/packages/cli/test/integration/eject-owned-runtime.test.ts b/server/typescript/packages/cli/test/integration/eject-owned-runtime.test.ts index 89760eb1fd..a90233dd6c 100644 --- a/server/typescript/packages/cli/test/integration/eject-owned-runtime.test.ts +++ b/server/typescript/packages/cli/test/integration/eject-owned-runtime.test.ts @@ -80,6 +80,7 @@ import { routesFileHono } from "./codegen/generators/routes-hono.js"; export default defineConfig({ outDir: "src/gen", + outputLayout: "flat", dialect: "sqlite", dbImport: "../db", extStyle: "js", diff --git a/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts b/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts index 99e7a2f3d7..d66caa1900 100644 --- a/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts +++ b/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts @@ -105,6 +105,7 @@ function publisherConfig(importFrom: string): string { `import { sharedModelFile } from ${JSON.stringify(importFrom)};`, `export default defineConfig({`, ` outDir: ${JSON.stringify(PUBLISHED)},`, + ` outputLayout: "flat",`, ` dialect: "sqlite",`, ` generators: [sharedModelFile({ name: ${JSON.stringify(DEP_NAME)}, include: ["acme::common::**"], version: "1.0.0" })],`, `});`, diff --git a/server/typescript/packages/cli/test/integration/gen-libraries.test.ts b/server/typescript/packages/cli/test/integration/gen-libraries.test.ts index 3c77bd9580..e36ea44c7e 100644 --- a/server/typescript/packages/cli/test/integration/gen-libraries.test.ts +++ b/server/typescript/packages/cli/test/integration/gen-libraries.test.ts @@ -63,6 +63,7 @@ function setup(libraries: string[] | undefined): { root: string; outDir: string import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(outDir)}, + outputLayout: "flat", dialect: "postgres", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/gen-nested-gen-config.test.ts b/server/typescript/packages/cli/test/integration/gen-nested-gen-config.test.ts index ecc762daa9..fc22c97644 100644 --- a/server/typescript/packages/cli/test/integration/gen-nested-gen-config.test.ts +++ b/server/typescript/packages/cli/test/integration/gen-nested-gen-config.test.ts @@ -31,6 +31,7 @@ function genConfigBody(outDir: string): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(outDir)}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/gen-scope.test.ts b/server/typescript/packages/cli/test/integration/gen-scope.test.ts index 0e85730da6..54c2f1915d 100644 --- a/server/typescript/packages/cli/test/integration/gen-scope.test.ts +++ b/server/typescript/packages/cli/test/integration/gen-scope.test.ts @@ -28,6 +28,7 @@ function setupRepo(): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(genOutDir(root))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/gen-sqlite.test.ts b/server/typescript/packages/cli/test/integration/gen-sqlite.test.ts index c42685d87b..4d62788ff3 100644 --- a/server/typescript/packages/cli/test/integration/gen-sqlite.test.ts +++ b/server/typescript/packages/cli/test/integration/gen-sqlite.test.ts @@ -26,6 +26,7 @@ function setupRepo(): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(genOutDir(root))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/gen-subproject-source-scope.test.ts b/server/typescript/packages/cli/test/integration/gen-subproject-source-scope.test.ts index 84b34c2439..f0c42dabb8 100644 --- a/server/typescript/packages/cli/test/integration/gen-subproject-source-scope.test.ts +++ b/server/typescript/packages/cli/test/integration/gen-subproject-source-scope.test.ts @@ -29,6 +29,7 @@ function genConfigBody(outDir: string): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(outDir)}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts index c43e0b7107..659f769a9e 100644 --- a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts +++ b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts @@ -49,17 +49,17 @@ const META = JSON.stringify({ { "object.value": { name: "PhaseArgs", - children: [{ "field.int": { name: "caseId", "@required": true } }], + children: [{ "field.int": { name: "consignmentId", "@required": true } }], }, }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { name: "src", "@kind": "storedProc", - "@proc": "fn_phase_summary", "@parameterRef": "PhaseArgs", + "@proc": "fn_stage_summary", "@parameterRef": "PhaseArgs", }, }, { "field.long": { name: "phaseId" } }, @@ -130,7 +130,7 @@ describe("meta migrate — proc/matview projection kinds (real sqlite)", () => { expect(byName.get("v_programs")).toBe("view"); // …the matview is NOT silently created as a plain view, and the proc emits nothing. expect(byName.has("mv_program_stats")).toBe(false); - expect([...byName.keys()].some((n) => n.includes("fn_phase_summary"))).toBe(false); + expect([...byName.keys()].some((n) => n.includes("fn_stage_summary"))).toBe(false); // …and the STANDALONE read-model is left alone: hand-authored SQL, so migrate // neither creates nor drops it. The load-bearing assertion is `exit === 0` and // `programs` existing above — before the fix, this projection aborted the entire diff --git a/server/typescript/packages/cli/test/integration/prisma-schema.test.ts b/server/typescript/packages/cli/test/integration/prisma-schema.test.ts index 84e1230f54..ee0f2f1aab 100644 --- a/server/typescript/packages/cli/test/integration/prisma-schema.test.ts +++ b/server/typescript/packages/cli/test/integration/prisma-schema.test.ts @@ -38,6 +38,7 @@ export default defineConfig({ orm: "prisma", dialect: ${JSON.stringify(dialect)}, outDir: ${JSON.stringify(join(root, "src/generated"))}, + outputLayout: "flat", extStyle: "none", targets: { prisma: { outDir: ${JSON.stringify(join(root, "prisma"))} } }, generators: ["entity", prismaSchemaFile({ target: "prisma"${prismaOpts} })], diff --git a/server/typescript/packages/cli/test/integration/quickstart-smoke.test.ts b/server/typescript/packages/cli/test/integration/quickstart-smoke.test.ts index 19d6743d81..8ef4dbb2b4 100644 --- a/server/typescript/packages/cli/test/integration/quickstart-smoke.test.ts +++ b/server/typescript/packages/cli/test/integration/quickstart-smoke.test.ts @@ -77,6 +77,7 @@ export default defineConfig({ dialect: "sqlite", dbImport: "./db", extStyle: "js", + outputLayout: "package", // what meta init scaffolds generators: ["entity", "queries", "routes"], }); `, @@ -109,9 +110,10 @@ describe("quickstart smoke — the documented TS path, gen -> migrate -> boot -> // 3. boot the GENERATED routes plugin on Fastify, as the doc shows const { default: Fastify } = await import("fastify"); + // outputLayout: "package" (what `meta init` writes) puts acme::blog's modules under acme/blog/, as the quickstart says. // The routes module is generated at runtime, so its type isn't knowable at // compile time — register through Fastify's own plugin type. - const { authorRoutes } = (await import(join(outDir, "Author.routes.ts"))) as { + const { authorRoutes } = (await import(join(outDir, "acme", "blog", "Author.routes.ts"))) as { authorRoutes: FastifyPluginAsync; }; const app = Fastify(); diff --git a/server/typescript/packages/cli/test/integration/stock-generators-importable.test.ts b/server/typescript/packages/cli/test/integration/stock-generators-importable.test.ts index 8a52dc3eac..a286c93dde 100644 --- a/server/typescript/packages/cli/test/integration/stock-generators-importable.test.ts +++ b/server/typescript/packages/cli/test/integration/stock-generators-importable.test.ts @@ -40,6 +40,7 @@ function config(imports: string, generators: string): string { imports, `export default defineConfig({`, ` outDir: ${JSON.stringify(OUT)},`, + ` outputLayout: "flat",`, ` dialect: "sqlite",`, ` dbImport: "~/db",`, ` extStyle: "none",`, diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts index b8a822945e..8be02aa874 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts @@ -66,6 +66,7 @@ const CONFIG = [ `import { entityFile } from "./codegen/generators/entity.js";`, `export default defineConfig({`, ` outDir: ${JSON.stringify(OUT)},`, + ` outputLayout: "flat",`, ` dialect: "sqlite",`, ` dbImport: "~/db",`, ` extStyle: "none",`, diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts index fbfbfe8c38..3556d35d8b 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts @@ -50,6 +50,7 @@ function setupRepo(): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(join(root, OUT))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", @@ -207,6 +208,7 @@ import { defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: ${JSON.stringify(join(root, OUT))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts index eb752aff58..8922cea153 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts @@ -45,6 +45,7 @@ function setupRepo(): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(join(root, OUT))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", @@ -64,6 +65,7 @@ function setupRepoWithNames(): string { import { defineConfig } from "@metaobjectsdev/codegen-ts"; export default defineConfig({ outDir: ${JSON.stringify(join(root, OUT))}, + outputLayout: "flat", dialect: "sqlite", dbImport: "~/db", extStyle: "none", diff --git a/server/typescript/packages/cli/test/owned-generator-subpath-import.test.ts b/server/typescript/packages/cli/test/owned-generator-subpath-import.test.ts index 4fc75dc86e..67a6692ac1 100644 --- a/server/typescript/packages/cli/test/owned-generator-subpath-import.test.ts +++ b/server/typescript/packages/cli/test/owned-generator-subpath-import.test.ts @@ -82,6 +82,7 @@ import { probeFile } from "./codegen/generators/probe.js"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", dialect: "sqlite", generators: [probeFile()], }); diff --git a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts index c2d73eceb4..d48e9110bb 100644 --- a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts +++ b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts @@ -36,7 +36,7 @@ const PAYLOAD = { async function load(children: unknown[]): Promise { const r = await new MetaDataLoader().load([ - new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "clinic", children } })), + new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "depot", children } })), ]); expect(r.errors).toEqual([]); return r.root; @@ -157,7 +157,7 @@ describe("genMigrateAdvice", () => { const root = project(); writeFileSync( join(root, "wrangler.toml"), - `name = "app"\n\n[[d1_databases]]\nbinding = "DB"\ndatabase_name = "clinic-db"\ndatabase_id = "x"\n`, + `name = "app"\n\n[[d1_databases]]\nbinding = "DB"\ndatabase_name = "depot-db"\ndatabase_id = "x"\n`, ); return root; }; @@ -166,7 +166,7 @@ describe("genMigrateAdvice", () => { const metadata = await load([PET, PAYLOAD]); const advice = await genMigrateAdvice(input({ metadata, projectRoot: d1Project() })); expect(advice).toContain("meta migrate --dialect d1 --d1 DB --slug "); - expect(advice).toContain("wrangler d1 migrations apply clinic-db --local"); + expect(advice).toContain("wrangler d1 migrations apply depot-db --local"); expect(advice).not.toContain("--dialect sqlite"); }); diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index 19eaf8362d..96564c569b 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -101,6 +101,7 @@ async function emit(metadata: MetaRoot, generators: Generator[]): Promise { const root = mkdtempSync(join(tmpdir(), "reporting-inert-only-")); try { return await runGen({ - config: { outDir: "src/generated", extStyle: "js", dialect: "postgres", dbImport: "../db", generators: allGenerators() }, + config: { outDir: "src/generated", outputLayout: "flat", extStyle: "js", dialect: "postgres", dbImport: "../db", generators: allGenerators() }, metadata: withReporting, projectRoot: root, genStateDir: join(root, GEN_STATE), @@ -491,6 +492,7 @@ describe("FR-044 the documentation generators differ by exactly the report pages import { docsFile, docsSiteFile, requirementsFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", + outputLayout: "flat", extStyle: "js", dialect: "postgres", dbImport: "../db", diff --git a/server/typescript/packages/cli/test/verify-declared-functions.test.ts b/server/typescript/packages/cli/test/verify-declared-functions.test.ts new file mode 100644 index 0000000000..bb85272ff9 --- /dev/null +++ b/server/typescript/packages/cli/test/verify-declared-functions.test.ts @@ -0,0 +1,84 @@ +/** + * rc.21 part B fix round 2 (N2): `meta verify --db` reads every declared `origin.function` from + * pg_proc, so a declaration the database does not have (a `numeric` result declared `int`, which the + * view's cast would round) is a finding and fails the run. Needs a Postgres: set + * METAOBJECTS_TEST_PG_URL; without one the test is skipped (the check itself is covered live in + * integration-tests view-vocabulary-rc21-pg.test.ts). + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { verifyCommand } from "../src/commands/verify.js"; + +const PG_URL = process.env.METAOBJECTS_TEST_PG_URL; +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +function model(returns: string, subType: string): string { + return JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Meter", children: [ + { "source.rdb": { "@table": "meters" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.projection": { name: "MeterRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_meter_row" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { [`field.${subType}`]: { name: "reading", children: [ + { "origin.function": { "@function": "meter_reading", "@schema": "verify_fn", "@args": ["id"], "@params": ["long"], "@returns": returns } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } }, + ] } }, + ] } }); +} + +async function project(returns: string, subType: string): Promise { + const root = await mkdtemp(join(tmpdir(), "verify-declared-functions-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), model(returns, subType), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + return root; +} + +async function capture(fn: () => Promise): Promise<{ code: number; out: string }> { + const lines: string[] = []; + const log = console.log; + const err = console.error; + console.log = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + try { + const code = await fn(); + return { code, out: lines.join("\n") }; + } finally { + console.log = log; + console.error = err; + } +} + +describe("meta verify --db — declared origin.function signatures", () => { + test.skipIf(PG_URL === undefined)("a declared return type the database does not have fails the run, named; a matching one is no finding", async () => { + const k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: PG_URL }) }) }); + try { + await sql.raw("DROP SCHEMA IF EXISTS verify_fn CASCADE").execute(k); + await sql.raw("CREATE SCHEMA verify_fn").execute(k); + await sql.raw("CREATE FUNCTION verify_fn.meter_reading(bigint) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT $1 * 1.5 $$").execute(k); + + const bad = await capture(async () => verifyCommand(["--db", PG_URL!], await project("int", "int"))); + expect(bad.code).toBe(1); + expect(bad.out).toContain("origin.function verify_fn.meter_reading on MeterRow.reading: declared (long) → int, which needs " + + "verify_fn.meter_reading(bigint) → integer; the database has verify_fn.meter_reading(bigint) → numeric."); + // Fix round 3 (M2): the run says what the comparison does not see. + expect(bad.out).toContain("a domain is compared by its own name, not its base type"); + + const good = await capture(async () => verifyCommand(["--db", PG_URL!], await project("decimal", "decimal"))); + expect(good.out).not.toContain("origin.function verify_fn.meter_reading"); + } finally { + await sql.raw("DROP SCHEMA IF EXISTS verify_fn CASCADE").execute(k); + await k.destroy(); + } + }, 60_000); +}); diff --git a/server/typescript/packages/codegen-ts-angular/test/codegen-angular.test.ts b/server/typescript/packages/codegen-ts-angular/test/codegen-angular.test.ts index c585aa8b23..b4233b73c0 100644 --- a/server/typescript/packages/codegen-ts-angular/test/codegen-angular.test.ts +++ b/server/typescript/packages/codegen-ts-angular/test/codegen-angular.test.ts @@ -16,7 +16,7 @@ const FIXTURE = resolve(import.meta.dir, "fixtures", "author-entity.json"); async function ctxFor(filter?: (e: any) => boolean): Promise { const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", @@ -29,7 +29,7 @@ async function ctxFor(filter?: (e: any) => boolean): Promise { entities, loadedRoot: root, matches: filter ?? (() => true), - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; @@ -208,8 +208,8 @@ describe("@emitAngular is retired", () => { entities: root.objects(), loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, - renderContext: makeRenderContext({ + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + renderContext: makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), }), diff --git a/server/typescript/packages/codegen-ts-angular/test/sourceless-objects.test.ts b/server/typescript/packages/codegen-ts-angular/test/sourceless-objects.test.ts index bce827fecf..768bdf5a75 100644 --- a/server/typescript/packages/codegen-ts-angular/test/sourceless-objects.test.ts +++ b/server/typescript/packages/codegen-ts-angular/test/sourceless-objects.test.ts @@ -76,7 +76,7 @@ async function ctxFor(gen: Generator): Promise { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(META)]); expect(errors).toEqual([]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/tmp", @@ -89,7 +89,7 @@ async function ctxFor(gen: Generator): Promise { entities, loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "./db", dialect: "postgres" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "./db", dialect: "postgres" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-react/src/form-file.ts b/server/typescript/packages/codegen-ts-react/src/form-file.ts index ed9a67fd67..77ef09f909 100644 --- a/server/typescript/packages/codegen-ts-react/src/form-file.ts +++ b/server/typescript/packages/codegen-ts-react/src/form-file.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, hasGeneratedForm, withClientDirective, +import { perEntity, type Generator, type GeneratorFactory, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, hasGeneratedForm, withClientDirective, effectivePackage, } from "@metaobjectsdev/codegen-ts"; import { renderFormFile } from "./templates/form-file.js"; @@ -46,7 +46,7 @@ export const formFile = function formFile(opts?: FormFileOpts): Generator { throw new Error("form-file: renderContext is required (provided by runGen)"); } return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.form.tsx`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.form.tsx`), content: withClientDirective( renderFormFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, diff --git a/server/typescript/packages/codegen-ts-react/src/reference/form.ts b/server/typescript/packages/codegen-ts-react/src/reference/form.ts index af02502abe..4e3e1fe825 100644 --- a/server/typescript/packages/codegen-ts-react/src/reference/form.ts +++ b/server/typescript/packages/codegen-ts-react/src/reference/form.ts @@ -22,6 +22,7 @@ import { perEntity, type Generator, type GeneratorFactory, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, hasGeneratedForm, withClientDirective, @@ -78,7 +79,7 @@ export const formFile = function formFile(opts?: FormFileOpts): Generator { ctx.renderContext.clientDirective, ); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.form.tsx`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.form.tsx`), content: body, }; }), diff --git a/server/typescript/packages/codegen-ts-react/test/abstract-projection-skip.test.ts b/server/typescript/packages/codegen-ts-react/test/abstract-projection-skip.test.ts index 4c18014f6d..c978ca43ba 100644 --- a/server/typescript/packages/codegen-ts-react/test/abstract-projection-skip.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/abstract-projection-skip.test.ts @@ -70,7 +70,7 @@ async function loadFixture() { async function ctxFor() { const root = await loadFixture(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -80,7 +80,7 @@ async function ctxFor() { entities: root.objects(), loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-react/test/client-directive.test.ts b/server/typescript/packages/codegen-ts-react/test/client-directive.test.ts index a9fc4c16c2..ef86aa2741 100644 --- a/server/typescript/packages/codegen-ts-react/test/client-directive.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/client-directive.test.ts @@ -39,7 +39,7 @@ async function gen(form: FormFactory, clientDirective: boolean | undefined): Pro try { await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: dir, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", ...(clientDirective === undefined ? {} : { clientDirective }), generators: [entityFile(), form()], }), diff --git a/server/typescript/packages/codegen-ts-react/test/form-blank-optional-tristate.test.ts b/server/typescript/packages/codegen-ts-react/test/form-blank-optional-tristate.test.ts index 287a8b5dde..4601e06235 100644 --- a/server/typescript/packages/codegen-ts-react/test/form-blank-optional-tristate.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/form-blank-optional-tristate.test.ts @@ -48,7 +48,7 @@ async function formFor( const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(json)]); if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("\n")); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -58,7 +58,7 @@ async function formFor( entities: root.objects(), loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-react/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts-react/test/reference-byte-identical.test.ts index 7b586cf207..271387d847 100644 --- a/server/typescript/packages/codegen-ts-react/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/reference-byte-identical.test.ts @@ -73,7 +73,7 @@ async function gen(generators: Generator[], root: Parameters[0][" try { await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators, + outDir: dir, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators, }), metadata: root, }); diff --git a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts index a11e10655f..386ffe7dbd 100644 --- a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts @@ -30,7 +30,7 @@ async function loadTph(withRule = false): Promise<{ root: MetaRoot; base: MetaOb "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -54,11 +54,11 @@ async function loadTph(withRule = false): Promise<{ root: MetaRoot; base: MetaOb }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts-tanstack/test/abstract-skip.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/abstract-skip.test.ts index baad7d6069..b06e515b38 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/abstract-skip.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/abstract-skip.test.ts @@ -60,7 +60,7 @@ async function loadFixture() { async function emit(gen: Generator) { const root = await loadFixture(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -69,7 +69,7 @@ async function emit(gen: Generator) { entities: root.objects(), loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/co-emitted-output-compiles.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/co-emitted-output-compiles.test.ts index 03fddb5611..a00e594077 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/co-emitted-output-compiles.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/co-emitted-output-compiles.test.ts @@ -96,7 +96,7 @@ async function generate(dir: string): Promise { expect(errors).toEqual([]); await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: DB_IMPORT, dialect: "postgres", + outDir: dir, extStyle: "none", dbImport: DB_IMPORT, outputLayout: "flat" as const, dialect: "postgres", generators: [ entityFile(), queriesFile(), routesFile(), tanstackQuery(), tanstackGrid(), tanstackGridHook(), barrel(), diff --git a/server/typescript/packages/codegen-ts-tanstack/test/hooks-pk-type.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/hooks-pk-type.test.ts index 2f84247206..eef371c17d 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/hooks-pk-type.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/hooks-pk-type.test.ts @@ -29,7 +29,7 @@ async function generate(): Promise> { const { root } = await loader.load([ new FileSource(resolve(import.meta.dir, "fixtures", "pk-types.json")), ]); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -37,7 +37,7 @@ async function generate(): Promise> { const ctx: GenContext = { entities: root.objects(), loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/package-layout.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/package-layout.test.ts index 50887aa76a..bb80114b3f 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/package-layout.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/package-layout.test.ts @@ -57,14 +57,14 @@ describe("package-aware output placement — tanstackQuery + tanstackGrid", () = expect(colsContent).toContain('from "./Product"'); }); - test("flat layout (default): hooks and columns land at outDir root", async () => { + test("flat layout (opt-in): hooks and columns land at outDir root", async () => { const { root, errors } = await new MetaDataLoader().load([new FileSource(PACKAGED_GRID)]); expect(errors).toEqual([]); const out = await runGen({ config: defineConfig({ outDir: tmp, - // outputLayout omitted → defaults to "flat" + outputLayout: "flat", extStyle: "none", dbImport: "../db", dialect: "sqlite", @@ -87,6 +87,7 @@ describe("package-aware output placement — tanstackQuery + tanstackGrid", () = const out = await runGen({ config: defineConfig({ outDir: tmp, + outputLayout: "flat", extStyle: "js", dbImport: "../db", dialect: "sqlite", diff --git a/server/typescript/packages/codegen-ts-tanstack/test/projection-grid.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/projection-grid.test.ts index b1a6bb7fd0..0bafb7a87f 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/projection-grid.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/projection-grid.test.ts @@ -53,7 +53,7 @@ async function loadFixture() { async function emit(gen: Generator) { const root = await loadFixture(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -62,7 +62,7 @@ async function emit(gen: Generator) { entities: root.objects(), loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/reference-byte-identical.test.ts index 2dbb1d4862..19c6a01fc1 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/reference-byte-identical.test.ts @@ -53,7 +53,7 @@ async function gen(generators: Generator[], root: Parameters[0][" try { await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators, + outDir: dir, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators, }), metadata: root, }); diff --git a/server/typescript/packages/codegen-ts-tanstack/test/report-ui-tier.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/report-ui-tier.test.ts index f229286813..8dbbecca66 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/report-ui-tier.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/report-ui-tier.test.ts @@ -39,7 +39,7 @@ async function emittedPaths(generators: Generator[]): Promise { const dir = mkdtempSync(join(tmpdir(), "report-no-ui-")); try { const result = await runGen({ - config: defineConfig({ outDir: dir, extStyle: "none", dbImport: "../db", dialect: "postgres", generators }), + config: defineConfig({ outDir: dir, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "postgres", generators }), metadata: await loadWith(), dryRun: true, }); @@ -95,7 +95,7 @@ describe("a served report gets a list hook and no other UI-tier file", () => { const dir = mkdtempSync(join(tmpdir(), "report-hooks-")); try { await runGen({ - config: defineConfig({ outDir: dir, extStyle: "none", dbImport: "../db", dialect: "postgres", generators: [make()] }), + config: defineConfig({ outDir: dir, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "postgres", generators: [make()] }), metadata: await loadWith(), }); const out = readFileSync(join(dir, "StoreTotals.hooks.ts"), "utf8"); @@ -157,7 +157,7 @@ describe("a keyless projection gets a list hook and no detail hook", () => { const obj = root.findObject("TagLabel"); if (!obj) throw new Error("TagLabel not found"); const ctx = makeRenderContext({ - dialect: "sqlite", loadedRoot: root, outDir: "/x", dbImport: "~/db", + outputLayout: "flat" as const, dialect: "sqlite", loadedRoot: root, outDir: "/x", dbImport: "~/db", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), }); return { obj, out: renderHooksFile(obj, ctx) }; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/tanstack-query-m2m.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/tanstack-query-m2m.test.ts index 78957f4ebe..7f9d257e1a 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/tanstack-query-m2m.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/tanstack-query-m2m.test.ts @@ -13,7 +13,7 @@ async function buildCtx(): Promise { const { root, errors } = await loader.load([new FileSource(FIXTURE)]); expect(errors).toEqual([]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/tmp", @@ -27,7 +27,7 @@ async function buildCtx(): Promise { entities, loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "postgres" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "postgres" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts index b9b10a0b9b..2a03fe1a3d 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts @@ -27,7 +27,7 @@ import { renderColumnsFile } from "../src/templates/columns-file.js"; import { makeRenderContext, buildPkMap, buildRelationMap, runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile } from "@metaobjectsdev/test-generators"; -async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject; copay: MetaObject }> { +async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject; coupon: MetaObject }> { const loader = new MetaDataLoader(); const { root, errors } = await loader.load([ new InMemoryStringSource( @@ -41,7 +41,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { "layout.dataGrid": { name: "default", "@columns": ["type", "id"] } }, @@ -58,13 +58,13 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", // Opted IN to a per-subtype grid by the OPT_IN predicate below — no // metadata attribute is involved any more. children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -76,7 +76,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me ]); if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("; ")); const find = (n: string) => root.objects().find((o) => o.name === n)! as MetaObject; - return { root, base: find("Auth"), bridge: find("BridgeAuth"), copay: find("CopayAuth") }; + return { root, base: find("Auth"), bridge: find("BridgeAuth"), coupon: find("CouponAuth") }; } /** Same hierarchy, but the base's grid carries an `@filter` preset — the arm where an @@ -96,7 +96,7 @@ async function loadTphFiltered(): Promise<{ root: MetaRoot }> { "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { @@ -130,11 +130,11 @@ async function loadTphFiltered(): Promise<{ root: MetaRoot }> { /** The per-subtype-grid opt-in, as an adopter would write it in metaobjects.config.ts. * Declared ONCE and passed to BOTH generators, which is the discipline the option * documents: two disagreeing predicates reproduce #287 exactly. */ -const OPT_IN = (e: MetaObject) => e.name === "CopayAuth"; +const OPT_IN = (e: MetaObject) => e.name === "CouponAuth"; function ctxFor(root: MetaRoot) { return makeRenderContext({ - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", loadedRoot: root, outDir: "/x", dbImport: "../db", @@ -155,28 +155,28 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { expect(out).toContain('id: "type"'); expect(out).toContain('id: "id"'); expect(out).toContain('id: "quantity"'); - expect(out).toContain('id: "copayAmount"'); + expect(out).toContain('id: "couponAmount"'); // Discriminator column renders as a badge. expect(out).toMatch(/id: "type"[\s\S]*?renderer: "badge"/); }); test("grid filter: base emits; a subtype emits only when tphSubtypeGrids opts it in", async () => { - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); const gen = tanstackGrid({ tphSubtypeGrids: OPT_IN }); expect(gen.filter!(base)).toBe(true); // polymorphic grid expect(gen.filter!(bridge)).toBe(false); // inherits layout, but not opted in - expect(gen.filter!(copay)).toBe(true); // opted in + expect(gen.filter!(coupon)).toBe(true); // opted in }); test("tphSubtypeGrids defaults OFF — no TPH subtype emits without one", async () => { // The default is what every existing project gets, so it is the arm most worth // pinning: an option that silently defaulted ON would change output for models that // never asked for a per-subtype grid. - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); for (const gen of [tanstackGrid(), tanstackGridHook()]) { expect(gen.filter!(base)).toBe(true); expect(gen.filter!(bridge)).toBe(false); - expect(gen.filter!(copay)).toBe(false); + expect(gen.filter!(coupon)).toBe(false); } }); @@ -187,24 +187,24 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { // missing that clause, so BridgeAuth got a .grid.ts whose sibling .columns.tsx never // exists. With the clause now driven by a caller-supplied predicate, agreement is the // CALLER's discipline — so this asserts it holds when the same predicate is passed. - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); const hook = tanstackGridHook({ tphSubtypeGrids: OPT_IN }); expect(hook.filter!(base)).toBe(true); expect(hook.filter!(bridge)).toBe(false); - expect(hook.filter!(copay)).toBe(true); + expect(hook.filter!(coupon)).toBe(true); }); test("an opted-in subtype gets BOTH artifacts; an opted-out one gets NEITHER", async () => { // The pairing invariant on the OPT-IN path, asserted on a real run's output rather // than on the predicates. `tphSubtypeGrids` is passed to both generators — the - // discipline the option documents — so CopayAuth must get the pair and BridgeAuth + // discipline the option documents — so CouponAuth must get the pair and BridgeAuth // must get nothing. A one-sided wiring shows up here as a file set, not a subtlety. const { root } = await loadTph(); const tmp = mkdtempSync(join(tmpdir(), "tph-grid-optin-")); try { await runGen({ config: defineConfig({ - outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "postgres", + outDir: tmp, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "postgres", generators: [ entityFile(), tanstackGrid({ tphSubtypeGrids: OPT_IN }), @@ -214,8 +214,8 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { metadata: root, }); const files = readdirSync(tmp); - expect(files).toContain("CopayAuth.columns.tsx"); - expect(files).toContain("CopayAuth.grid.ts"); + expect(files).toContain("CouponAuth.columns.tsx"); + expect(files).toContain("CouponAuth.grid.ts"); expect(files).not.toContain("BridgeAuth.columns.tsx"); expect(files).not.toContain("BridgeAuth.grid.ts"); } finally { @@ -233,7 +233,7 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { try { await runGen({ config: defineConfig({ - outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "postgres", + outDir: tmp, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "postgres", generators: [ entityFile(), tanstackGrid({ tphSubtypeGrids: OPT_IN }), diff --git a/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts index a84efcc244..2d18d9d244 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts @@ -30,7 +30,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -46,11 +46,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -107,11 +107,11 @@ describe("FR-017 Tier 3 — TPH TanStack hooks", () => { expect(out).toContain("export function useCreateBridgeAuth("); expect(out).toContain("export function useUpdateBridgeAuth("); expect(out).toContain("export function useDeleteBridgeAuth("); - // Per-subtype CopayAuth too. - expect(out).toContain("export function useCreateCopayAuth("); + // Per-subtype CouponAuth too. + expect(out).toContain("export function useCreateCouponAuth("); // Sub-path derived from the lowercased discriminator value. expect(out).toContain("/bridge"); - expect(out).toContain("/copay"); + expect(out).toContain("/coupon"); // Create input omits the discriminator. expect(out).toContain('Omit'); }); diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index edde17c572..2cfb5e5242 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -38,6 +38,7 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + parseDbColumnType, FIELD_ATTR_LOCAL_TIME, FIELD_ATTR_LENIENT, TYPE_ORIGIN, @@ -47,6 +48,9 @@ import { AGG_ALL, AGG_COLLECT, resolveEnumMaxLength, + storedEnumValue, + stringValueMapOf, + VALIDATOR_ATTR_DB_CHECK, } from "@metaobjectsdev/metadata"; import { columnNameFromField } from "./naming.js"; import { enumValues, intValueMapOf, intValueForMember } from "./enum-meta.js"; @@ -243,6 +247,12 @@ export interface EnumIntCustomType { members: string[]; /** Member symbol -> stored integer. */ intByMember: Record; + /** + * rc.21 — set for a STRING-stored enum with `@stringValueMap` (scalar only; the loader refuses + * it on an array): member symbol -> stored string. The codec then maps member <-> stored string + * over a text/varchar column, and `intByMember` is empty. + */ + storedByMember?: Record; /** * Set only for an `isArray` field. `"native"`: the element codec under Drizzle's * Postgres `.array()` (PgArray maps each element through it), so the column is @@ -359,9 +369,13 @@ function pgColumnTypeOverride( return { fnName: "uuid" }; case DB_COLUMN_TYPE_JSONB: return { fnName: "jsonb" }; - default: - return undefined; } + // rc.21 part B (U2): the text spellings, as `meta migrate` creates them. + const parsed = parseDbColumnType(dbColumnType); + if (parsed?.kind === "text") return { fnName: "text" }; + if (parsed?.kind === "varchar") return parsed.length !== undefined ? { fnName: "varchar", fnOptions: { length: parsed.length } } : { fnName: "varchar" }; + if (parsed?.kind === "char") return { fnName: "char", fnOptions: { length: parsed.length } }; + return undefined; } /** Resolve max length from validator.length child or @maxLength attr. @@ -472,6 +486,28 @@ function buildEnumIntCustomType( }; } +/** rc.21 — the codec descriptor of a `@stringValueMap` enum: member <-> stored string. */ +function buildEnumStoredCustomType( + field: MetaField, + storedByMember: Readonly>, + dataType: string, +): EnumIntCustomType | undefined { + const members = enumValues(field); + if (members === undefined || members.length === 0) return undefined; + const base = field.name.replace(/[^A-Za-z0-9]/g, ""); + const camel = base.charAt(0).toLowerCase() + base.slice(1); + const screaming = screamingSnake(base); + return { + fnConstName: `${camel}StoredEnum`, + toIntConstName: `${screaming}_TO_STORED`, + fromIntConstName: `${screaming}_FROM_STORED`, + members, + intByMember: {}, + storedByMember: Object.fromEntries(members.map((m) => [m, storedByMember[m] ?? m])), + dataType, + }; +} + /** * The Drizzle pg-core column functions that can carry an IDENTITY clause — * i.e. the builders extending `PgIntColumnBaseBuilder`, the only ones declaring @@ -702,7 +738,10 @@ export function mapColumnType( enumIntCustomType = buildEnumIntCustomType(field, im); fnName = enumIntCustomType?.fnConstName ?? "integer"; } else { - fnName = "text"; + const stored = isArray ? undefined : stringValueMapOf(field); + // rc.21: a @stringValueMap enum maps member <-> stored string at the column. + enumIntCustomType = stored === undefined ? undefined : buildEnumStoredCustomType(field, stored, "text"); + fnName = enumIntCustomType?.fnConstName ?? "text"; } } break; @@ -861,7 +900,13 @@ export function mapColumnType( // creates; with none the column is unbounded text, as before. An array enum is // a text[] column, whose elements carry no length (migrate's arrayElementSqlType). const sized = isArray ? undefined : resolveEnumMaxLength(field); - if (sized !== undefined) { + const stored = isArray ? undefined : stringValueMapOf(field); + if (stored !== undefined) { + // rc.21: the column holds each member's @stringValueMap string, so a codec maps + // member <-> stored string at the column, as the int-backed codec does. + enumIntCustomType = buildEnumStoredCustomType(field, stored, sized === undefined ? "text" : `varchar(${sized})`); + fnName = enumIntCustomType?.fnConstName ?? "text"; + } else if (sized !== undefined) { fnName = "varchar"; fnOptions = { length: sized }; } else { @@ -1030,8 +1075,10 @@ export function mapColumnType( if (dollarTypeRef !== undefined) result.dollarTypeRef = dollarTypeRef; if (leadingComment !== undefined) result.leadingComment = leadingComment; - // Enum fields: emit a CHECK constraint listing the valid member values. - if (subType === FIELD_SUBTYPE_ENUM && !isArray) { + // Enum fields: emit a CHECK constraint listing the valid member values — unless the enum opts + // out (`@dbCheck: false`, ADR-0039 resolving), exactly as migrate-ts's buildChecks decides, or + // `drizzle-kit push` would re-add the CHECK `meta migrate` leaves out. + if (subType === FIELD_SUBTYPE_ENUM && !isArray && field.attr(VALIDATOR_ATTR_DB_CHECK) !== false) { const values = enumValues(field); if (values !== undefined && values.length > 0) { const intMap = intValueMapOf(field); @@ -1045,10 +1092,9 @@ export function mapColumnType( .map((v) => String(intValueForMember(intMap, v, `CHECK for column '${dbName}'`))) .join(", "); } else { - // Single-quote escaping is belt-and-suspenders: the loader's - // ENUM_MEMBER_PATTERN already rejects quote-bearing members (members are - // validated to be identifier-safe), so this never fires in practice. - list = values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", "); + // rc.21: a member is stored as its @stringValueMap string, else as itself — exactly + // migrate-ts's buildChecks. A stored string may carry a quote, so it is escaped. + list = values.map((v) => `'${storedEnumValue(field, v).replace(/'/g, "''")}'`).join(", "); } result.checkConstraint = `${dbName} IN (${list})`; result.checkConstraintValues = list; diff --git a/server/typescript/packages/codegen-ts/src/constants.ts b/server/typescript/packages/codegen-ts/src/constants.ts index d16ad395bc..426c94bca6 100644 --- a/server/typescript/packages/codegen-ts/src/constants.ts +++ b/server/typescript/packages/codegen-ts/src/constants.ts @@ -143,7 +143,7 @@ export const RETIRED_CODEGEN_ATTRS: readonly RetiredCodegenAttr[] = [ name: "emitGrid", replacement: 'pass the `tphSubtypeGrids` option — tanstackGrid({ tphSubtypeGrids: (e) => e.name === ' + - '"CopayAuth" }) — and pass the SAME predicate to tanstackGridHook(), or the emitted ' + + '"CouponAuth" }) — and pass the SAME predicate to tanstackGridHook(), or the emitted ' + '.grid.ts has no .columns.tsx to import. This one is an opt-IN, so a `filter` ' + 'cannot express it: a filter is ANDed with the built-in gates and can only narrow', }, diff --git a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts index b39e3b6b09..b6f9dbf018 100644 --- a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts +++ b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts @@ -54,7 +54,7 @@ import { type MetaSegment, type ReportShape, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import type { ColumnNamingStrategy } from "../metaobjects-config.js"; import { hasWritableRdbSource, servedReport } from "../source-detect.js"; import { isTphSubtype, tphDiscriminatorBase, tphDiscriminatorPin } from "../tph.js"; @@ -986,7 +986,7 @@ class CubeModelBuilder { if (field === undefined) throw new Error(`${where}: discriminator field '${pin.fieldName}' is not a field of '${entity.name}'.`); const value = field.subType === FIELD_SUBTYPE_ENUM - ? encodeIntEnumFilterValue(pin.value, FILTER_OP_EQ, intValueMapOf(field), pin.fieldName, where) + ? encodeIntEnumFilterValue(pin.value, FILTER_OP_EQ, enumStorageMapOf(field), pin.fieldName, where) : pin.value; return { kind: "cmp", ref: `${prefix}${sourceColumnNameFor(field, this.mc.extract)}`, op: FILTER_OP_EQ, value }; } diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts index 3273777ead..b3084a723a 100644 --- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts +++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts @@ -42,7 +42,7 @@ import { TYPE_MEASURE, derivedExprFields, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import { sourceColumnNameFor, type ExtractContext } from "../projection/extract-view-spec.js"; import { ratioOperand, resolveAggregate } from "../projection/report-resolve.js"; import { cond, declared, mysqlTupleCount, resolveReportFilter, type SqlRenderer } from "../projection/report-sql.js"; @@ -147,11 +147,12 @@ export function dimensionColumn( const d = mc.dialect; const col = cubeColumn(sourceColumnNameFor(field, mc.extract), d, renderer); if (field.subType === FIELD_SUBTYPE_ENUM) { - const intMap = intValueMapOf(field); + const intMap = enumStorageMapOf(field); if (intMap !== undefined) { - // An int-backed enum stores the integer; the wire carries the member symbol, as every - // port's read does. - const arms = Object.entries(intMap).map(([symbol, n]) => `WHEN ${String(n)} THEN ${renderer.literal(symbol, d)}`); + // An int-backed enum stores the integer (a @stringValueMap one its stored string, rc.21); + // the wire carries the member symbol, as every port's read does. + const arms = Object.entries(intMap).map(([symbol, n]) => + `WHEN ${typeof n === "number" ? String(n) : renderer.literal(n, d)} THEN ${renderer.literal(symbol, d)}`); return { sql: `CASE ${col} ${arms.join(" ")} END`, type: "string" }; } } diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index 179308b287..1dbc8d9fe8 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -50,6 +50,7 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/naming.ts", "codegen-ts/src/naming/name-claims.ts", "codegen-ts/src/owned-runtime.ts", + "codegen-ts/src/pg-identifier.ts", "codegen-ts/src/pk-resolver.ts", "codegen-ts/src/poet.ts", "codegen-ts/src/projection/build-projection-views.ts", diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index f79f498d40..b8e6b0fa6a 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -58,6 +58,7 @@ export * from "./templates/entity-ui-descriptor.js"; export * from "./templates/find-inbound.js"; export * from "./templates/find-templates.js"; export * from "./tph.js"; +export * from "./pg-identifier.js"; export * from "./view-context.js"; export * from "./writer/code-writer.js"; export * from "./writer/ts-writer.js"; diff --git a/server/typescript/packages/codegen-ts/src/enum-meta.ts b/server/typescript/packages/codegen-ts/src/enum-meta.ts index b5fe8ec7cb..95a627eb4d 100644 --- a/server/typescript/packages/codegen-ts/src/enum-meta.ts +++ b/server/typescript/packages/codegen-ts/src/enum-meta.ts @@ -3,7 +3,7 @@ // extraction and the z.enum([...]) expression are derived in exactly one place. import type { MetaField } from "@metaobjectsdev/metadata"; -import { FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP } from "@metaobjectsdev/metadata"; +import { FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, stringValueMapOf } from "@metaobjectsdev/metadata"; /** * Effective enum member values (`@values`) for a field, as strings. @@ -55,3 +55,14 @@ export function intValueForMember( } return n; } + +/** + * rc.21 — member symbol → what the column stores, for an enum whose storage differs from its + * members: the `@intValueMap` integer, or the `@stringValueMap` string. Undefined when every member + * is its own stored string. For the lowerings (a view or report `@filter`, a TPH pin, a Cube + * dimension) that write a member into SQL. + */ +export type EnumStorageMap = Readonly>; +export function enumStorageMapOf(field: MetaField): EnumStorageMap | undefined { + return intValueMapOf(field) ?? stringValueMapOf(field); +} diff --git a/server/typescript/packages/codegen-ts/src/generators/api-model.ts b/server/typescript/packages/codegen-ts/src/generators/api-model.ts index e026e77249..2aee817e79 100644 --- a/server/typescript/packages/codegen-ts/src/generators/api-model.ts +++ b/server/typescript/packages/codegen-ts/src/generators/api-model.ts @@ -143,7 +143,7 @@ import { buildPkMap } from "../pk-resolver.js"; import { buildRelationMap, type RelationEntry, type RelationMap } from "../relation-resolver.js"; import { generatableObjects } from "../source-detect.js"; import { effectivePackage } from "../docs-paths.js"; -import { entityOutputPath, type OutputLayout } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath, type OutputLayout } from "../import-path.js"; import type { RenderContext } from "../render-context.js"; import type { GenContext } from "../generator.js"; import type { PkInfo } from "../pk-resolver.js"; @@ -281,7 +281,7 @@ export interface ApiModelContext { /** The output layout the codegen run uses. The per-symbol `importPath` mirrors * the emitting generator's own path computation under this layout (flat → * `Product.queries`; package → folded under the entity's package path iff the - * generator folds). Defaults to "flat" (today's byte-identical placement). */ + * generator folds). Defaults to `DEFAULT_OUTPUT_LAYOUT` ("package", R63). */ outputLayout?: OutputLayout; /** Whether to ALSO document the OPT-IN Hono CRUD variant (routesFileHono). * Hono is not in the default generator suite — it is an alternative wired by @@ -320,7 +320,7 @@ export function buildApiModel(root: MetaRoot, ctx: ApiModelContext): ApiModel { // getPkInfo wants a RenderContext; it only reads `.pkMap`, so a structural // shim is sufficient (and avoids forcing callers to build a full context). const pkCtx = { pkMap } as RenderContext; - const layout = ctx.outputLayout ?? "flat"; + const layout = ctx.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const apiPrefix = ctx.apiPrefix ?? ""; const relationMap = ctx.relationMap ?? buildRelationMap(root); const includeHono = ctx.includeHonoRoutes ?? false; @@ -1295,7 +1295,7 @@ function templateExample(symbolBase: string, symbols: ApiSymbol[]): UnitExample export function buildApiModelForRun(ctx: GenContext): ApiModel { return buildApiModel(ctx.loadedRoot, { loadedRoot: ctx.loadedRoot, - outputLayout: ctx.config.outputLayout ?? "flat", + outputLayout: ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, includeHonoRoutes: ctx.config.includeHonoRoutes ?? false, ...(ctx.config.includeEntityModule !== undefined && { includeEntityModule: ctx.config.includeEntityModule }), ...(ctx.config.includeQueries !== undefined && { includeQueries: ctx.config.includeQueries }), diff --git a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts index 08a4856e91..f4500bd408 100644 --- a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts @@ -10,7 +10,7 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type Generator, type GeneratorFactory } from "../generator.js"; import { renderCallableFile, isCallableEntity } from "../templates/callable-file.js"; import { formatTs } from "../format.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; export interface CallableFileOpts { @@ -30,7 +30,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene generate: perEntity(async (entity, ctx) => { return { path: entityOutputPath( - ctx.config.outputLayout ?? "flat", + ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.callable.ts`, ), diff --git a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts index 6315b0968c..d6eb4e4eb7 100644 --- a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts @@ -3,7 +3,7 @@ import { perEntity, type EmittedFile, type GenContext, type Generator, type Gene import { renderEntityFile } from "../templates/entity-file.js"; import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; import { formatTs } from "../format.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isAbstract } from "../instance-artifacts.js"; import { effectivePackage } from "../docs-paths.js"; import { claimModuleNames } from "../naming/name-claims.js"; @@ -44,7 +44,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator // objects emitting one name there are refused, naming both. Nothing is renamed. claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), content: await formatTs(renderEntityFile(entity, ctx.renderContext, { allowlists })), }; }); diff --git a/server/typescript/packages/codegen-ts/src/generators/names-file.ts b/server/typescript/packages/codegen-ts/src/generators/names-file.ts index 4829087d18..3dd3d02296 100644 --- a/server/typescript/packages/codegen-ts/src/generators/names-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/names-file.ts @@ -1,6 +1,6 @@ import type { Generator, GenContext, EmittedFile } from "../generator.js"; import { selectedEntities } from "../generator.js"; -import { entityOutputPath, crossEntitySpecifier } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath, crossEntitySpecifier } from "../import-path.js"; import { NAMES_FILE_SUFFIX } from "../constants.js"; import { renderNamesDecl } from "../templates/names-decl.js"; import { namesArtifactSuperOf, resolveObjectNames } from "../names.js"; @@ -50,7 +50,7 @@ export function namesFile(opts?: NamesFileOpts): Generator { // routesFileHono already uses via emitsHonoRoutes/includeHonoRoutes. emitsNames: true, generate: (ctx: GenContext): EmittedFile[] => { - const layout = ctx.config.outputLayout ?? "flat"; + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const extStyle = ctx.config.extStyle ?? "js"; // The strategy lives on the RENDER CONTEXT, not on ResolvedGenConfig — `ctx.config` // carries outDir/extStyle/dbImport/dialect and nothing about naming. diff --git a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts index 8e1a21e142..94debcf794 100644 --- a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts @@ -4,7 +4,7 @@ import { renderQueriesFile } from "../templates/queries-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; import { formatTs } from "../format.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { claimModuleNames } from "../naming/name-claims.js"; @@ -51,7 +51,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat } claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.queries.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), content: await formatTs(renderQueriesFile(entity, ctx.renderContext)), }; }), diff --git a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts index 28e9426220..347504b4cd 100644 --- a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts @@ -1,6 +1,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GenContext, EmittedFile } from "../generator.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { formatTs } from "../format.js"; import { isReport } from "../source-detect.js"; @@ -51,7 +51,7 @@ export function reportExport(opts?: ReportExportOpts): Generator { name: "report-export", emitsReportExport: true, generate: async (ctx: GenContext): Promise => { - const layout = ctx.config.outputLayout ?? "flat"; + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const extStyle = ctx.config.extStyle ?? "js"; const selfTarget = ctx.renderContext?.selfTarget; if (selfTarget === undefined) throw new Error("report-export: no render context (run it through runGen)."); diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts index d752742f32..2c5956e61c 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts @@ -4,7 +4,7 @@ import { renderRoutesFileHono } from "../templates/routes-file-hono.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; import { formatTs } from "../format.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isTphSubtype } from "../tph.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; import { effectivePackage } from "../docs-paths.js"; @@ -116,7 +116,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) claimRouteSegment(ctx, entity); return { path: entityOutputPath( - ctx.config.outputLayout ?? "flat", + ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts index 223f260f63..f0a871f20a 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts @@ -5,7 +5,7 @@ import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; import { formatTs } from "../format.js"; -import { entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; import { effectivePackage } from "../docs-paths.js"; import { claimRouteSegment } from "../naming/name-claims.js"; @@ -62,7 +62,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator } claimRouteSegment(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.routes.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), content: await formatTs(renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), }; }); diff --git a/server/typescript/packages/codegen-ts/src/import-path.ts b/server/typescript/packages/codegen-ts/src/import-path.ts index c31b3e0e90..017b2dbd78 100644 --- a/server/typescript/packages/codegen-ts/src/import-path.ts +++ b/server/typescript/packages/codegen-ts/src/import-path.ts @@ -10,6 +10,11 @@ import { withExt, withExtIfRelative, type ExtStyle, type RenderContext } from ". export type OutputLayout = "flat" | "package"; +/** The layout a target writes in when none is declared: `"flat"`, one directory. Declare + * `outputLayout: "package"` for a directory per metadata package. (Main's shipped default; the + * rc.19 R63 flip to `"package"` was not carried through the merge.) */ +export const DEFAULT_OUTPUT_LAYOUT: OutputLayout = "flat"; + /** "a::b::c" → "a/b/c"; undefined / "" → "". */ export function packageToPath(pkg: string | undefined): string { if (pkg === undefined || pkg === "") return ""; diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 6d8b9c5ec5..85c5a9d9d2 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -122,7 +122,7 @@ export { entityTypeNames, type EntityTypeNames, type EntityTypeNamesOpts } from // owned-composition-imports gate in test/ — it derives the required set from that body rather // than trusting this list to stay complete. -export { packageToPath, entityOutputPath, crossEntitySpecifier, barrelEntrySpecifier, relativeModuleSpecifier, entityModuleSpecifier, siblingSpecifier, barrelModuleSpecifier } from "./import-path.js"; +export { DEFAULT_OUTPUT_LAYOUT, packageToPath, entityOutputPath, crossEntitySpecifier, barrelEntrySpecifier, relativeModuleSpecifier, entityModuleSpecifier, siblingSpecifier, barrelModuleSpecifier } from "./import-path.js"; export type { OutputLayout, ResolvedTarget } from "./import-path.js"; export { docPageOutputPath, diff --git a/server/typescript/packages/codegen-ts/src/metaobjects-config.ts b/server/typescript/packages/codegen-ts/src/metaobjects-config.ts index 1b6f0c31b6..bb4b6ea7c6 100644 --- a/server/typescript/packages/codegen-ts/src/metaobjects-config.ts +++ b/server/typescript/packages/codegen-ts/src/metaobjects-config.ts @@ -4,7 +4,7 @@ import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; import type { RoutesExpose } from "./routes-expose.js"; import type { Generator } from "./generator.js"; import type { ExtStyle } from "./render-context.js"; -import type { OutputLayout, ResolvedTarget } from "./import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, type OutputLayout, type ResolvedTarget } from "./import-path.js"; import { generatorRegistry } from "./generator-registry.js"; import { normalizeTimestampMode } from "./dialect-module.js"; @@ -94,7 +94,7 @@ export interface ResolvedGenConfig { extStyle: ExtStyle; dbImport: string; dialect: Dialect; - /** "flat" (default) — all files in outDir; "package" — files placed in a sub-path derived from each entity's metadata package. */ + /** "package" (default, R63) — files placed in a sub-path derived from each object's metadata package; "flat" — all files in outDir. */ outputLayout?: OutputLayout; /** Whether the OPT-IN Hono routes generator (routesFileHono) is active in the * run — aggregated by the runner from the suite's `emitsHonoRoutes` markers. @@ -172,6 +172,8 @@ export const DEFAULT_EXT_STYLE: ExtStyle = "js"; export interface NamingStrategies { readonly columns?: Readonly>; readonly tables?: Readonly>; + /** rc.19 (R57): pluralizers by name, selected by `naming.collections`. */ + readonly collections?: Readonly>; } export interface MetaobjectsGenConfig extends Omit { @@ -374,7 +376,7 @@ export function defineConfig(config: MetaobjectsGenConfig): MetaobjectsGenConfig * each named target (outputLayout + dbImport fall back to top-level; * importBase does NOT inherit — it is a per-target identity). */ export function resolveTargets(config: MetaobjectsGenConfig): Record { - const layout: OutputLayout = config.outputLayout ?? "flat"; + const layout: OutputLayout = config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; // Under Prisma no target carries Drizzle bindings: Prisma owns the client and the schema. const runtime = resolveOrm(config) !== ORM_PRISMA; const out: Record = { @@ -518,7 +520,7 @@ export function normalizeConfig(config: MetaobjectsGenConfig): NormalizedMetaobj clientDirective: config.clientDirective ?? false, apiPrefix: config.apiPrefix ?? "", emitAbstractShapes: config.emitAbstractShapes ?? true, - outputLayout: config.outputLayout ?? "flat", + outputLayout: config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, targets: resolveTargets(config), }; } diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts index 05f1cb14ac..67bc34a925 100644 --- a/server/typescript/packages/codegen-ts/src/names.ts +++ b/server/typescript/packages/codegen-ts/src/names.ts @@ -15,6 +15,8 @@ import { resolveTableSchema, isMetaObject, isMetaSource, + isWritableSource, + OBJECT_SUBTYPE_ENTITY, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STORAGE, FIELD_SUBTYPE_OBJECT, @@ -34,6 +36,7 @@ import { code, imp, type Code } from "./poet.js"; import { crossEntitySpecifier } from "./import-path.js"; import type { RenderContext } from "./render-context.js"; import { effectivePackage } from "./docs-paths.js"; +import { isWriteThrough } from "./projection/projection-detector.js"; /** * One field's names. @@ -363,12 +366,15 @@ export function resolveObjectNames( // level down from the one this file exists to prevent (a NAME resolved twice). const source = primaryRdbSource(obj); if (source === undefined) return undefined; - const ownFieldList = obj.ownFields(); + // rc.21 (U7): a derived field of an object read from its table has no column, so it has no + // names entry — no `column` naming a column that does not exist. + const columnless = (f: MetaField): boolean => isWritableSource(source) && !isWriteThrough(obj) && f.isDerived(); + const ownFieldList = obj.ownFields().filter((f) => !columnless(f)); const fields: Record = {}; // ADR-0039: fields() is the RESOLVING accessor — inherited fields must appear, and an // inherited @column must resolve, or the constant disagrees with the DDL. - for (const f of obj.fields()) { + for (const f of obj.fields().filter((x) => !columnless(x))) { fields[f.name] = fieldNamesOf(f, strategy); } // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. See ObjectNames. @@ -378,6 +384,14 @@ export function resolveObjectNames( } const superObj = namesArtifactSuperOf(obj); + // rc.21 fix round (M8): an abstract-entity fragment leaves its derived fields out (no column of + // the tables extending it), so an object whose derived fields ARE columns (a write-through + // entity's read view) declares the ones it inherits itself. + if (superObj !== undefined && superObj.subType === OBJECT_SUBTYPE_ENTITY && superObj.isAbstract) { + for (const f of obj.fields()) { + if (f.isDerived() && !columnless(f) && ownFields[f.name] === undefined) ownFields[f.name] = fieldNamesOf(f, strategy); + } + } const superNames: SuperNames | undefined = superObj === undefined ? undefined : { name: superObj.name, package: effectivePackage(superObj) }; @@ -455,10 +469,12 @@ export function resolveSuperFragmentNames( strategy?: ColumnNamingStrategy, ): ObjectNames | undefined { if (!declaresNamesContent(obj)) return undefined; - const ownFieldList = obj.ownFields(); + // rc.21 (U7): an abstract ENTITY's derived field is no column of the tables extending it. + const columnless = (f: MetaField): boolean => obj.subType === OBJECT_SUBTYPE_ENTITY && f.isDerived(); + const ownFieldList = obj.ownFields().filter((f) => !columnless(f)); const fields: Record = {}; - for (const f of obj.fields()) { + for (const f of obj.fields().filter((x) => !columnless(x))) { fields[f.name] = fieldNamesOf(f, strategy); } const ownFields: Record = {}; diff --git a/server/typescript/packages/codegen-ts/src/naming/name-claims.ts b/server/typescript/packages/codegen-ts/src/naming/name-claims.ts index 8c2d067fc9..64f09a9a67 100644 --- a/server/typescript/packages/codegen-ts/src/naming/name-claims.ts +++ b/server/typescript/packages/codegen-ts/src/naming/name-claims.ts @@ -13,7 +13,10 @@ // object's type is its own name. // -import { OBJECT_SUBTYPE_VALUE, collectionSegment, type MetaObject } from "@metaobjectsdev/metadata"; +import { + OBJECT_SUBTYPE_VALUE, OBJECT_ATTR_COLLECTION_NAME, collectionSegment, declaredCollectionName, + type MetaObject, +} from "@metaobjectsdev/metadata"; import type { GenContext } from "../generator.js"; import { collectionPascal } from "../naming.js"; import { emitsInstanceArtifacts } from "../instance-artifacts.js"; diff --git a/server/typescript/packages/codegen-ts/src/pg-identifier.ts b/server/typescript/packages/codegen-ts/src/pg-identifier.ts new file mode 100644 index 0000000000..8e796e2d87 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/pg-identifier.ts @@ -0,0 +1,3 @@ +// rc.21 part B (N2): Postgres's 63-byte identifier fit, re-exported where the generators (and the +// owned template copies, which import only from `@metaobjectsdev/codegen-ts/engine`) can reach it. +export { fitPgIdentifier } from "@metaobjectsdev/migrate-ts/expected"; diff --git a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts index 42533a7a77..79445b9bd5 100644 --- a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts +++ b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts @@ -361,8 +361,10 @@ function collectSqlDependsOn( const t = joinTables[host.resolutionKey()]; if (t !== undefined) tables.add(t); } - // Extends-bound anchor tables (a projection's read-model base). - for (const child of host.ownChildren()) { + // Extends-bound anchor tables (a projection's read-model base). ADR-0039: resolving — a + // projection extending another projection inherits its anchors, and so its dependencies + // (rc.21, U5 audit: an `@sql` extender with no anchor of its own had none). + for (const child of host.children()) { if (child.type !== TYPE_IDENTITY && child.type !== TYPE_FIELD) continue; const owner = refNamedOwner(child, root); if (owner === undefined) continue; @@ -407,17 +409,22 @@ function collectSqlDependsOn( * for custom SQL views and matviews — not a new hole. What changes is only that ONE * such view no longer blocks migration of every other entity in the tree. * - * ADR-0039: own — a projection's derivation is declared locally; an inherited extends or - * origin belongs to the parent's own view. + * ADR-0039: resolving — a projection that extends another projection (G13) inherits its + * anchors and its fields' origins, and its view is derived from them exactly as the base's is + * (`extractViewSpec` reads the effective fields, and `baseEntityFor` falls back to the super's + * anchor). Reading own children here dropped an extender that declares nothing but its own + * source, silently (rc.21, U5). Each field's origin is still read from that field node's own + * children: origin.* never inherits (ADR-0029), and an inherited field IS the parent's node. */ function viewIsDerived(projection: MetaObject): boolean { - const own = projection.ownChildren(); - const anchored = own.some( + const effective = projection.children(); + const anchored = effective.some( (c) => (c.type === TYPE_IDENTITY || c.type === TYPE_FIELD) && c.superRef !== undefined, ); if (anchored) return true; // Origins without an anchor = malformed, not standalone. Let extractViewSpec say so. - return own.some( + return effective.some( + // ADR-0039: own (category 4) — origin.* never inherits (ADR-0029). (f) => f.type === TYPE_FIELD && f.ownChildren().some((c) => c.type === TYPE_ORIGIN), ); } @@ -439,11 +446,12 @@ function collectDependsOn( for (const child of node.children) walk(child); }; for (const j of spec.joinTree.joins) walk(j); - // An origin.first subquery reads its tables, whether it is a column or inlined in an expression or filter. + // origin.first subqueries — a column's, and (rc.19 entity-derived, computed-over-joined) one + // inlined in an expression or a filter — read their tables too. const first = (c: Extract): void => { const t = joinTables[c.childEntity]; if (t) tables.add(t); - // Every table the subquery joins along its @via. + // first-multihop: every table the subquery joins along its @via. for (const j of c.innerJoins ?? []) { const jt = joinTables[j.entity]; if (jt) tables.add(jt); @@ -455,7 +463,12 @@ function collectDependsOn( case "first": first(e.column); return; case "cmp": expr(e.left); expr(e.right); return; case "nullTest": case "not": expr(e.arg); return; - case "logic": case "coalesce": e.args.forEach(expr); return; + case "logic": case "coalesce": case "fn": case "call": e.args.forEach(expr); return; + case "cast": expr(e.arg); return; + case "agg": + if (e.column.kind === "aggregate" && e.column.filter !== undefined) clause(e.column.filter); + if (e.column.kind === "predicateAgg") clause(e.column.pred); + return; case "case": if (e.operand !== undefined) expr(e.operand); for (const w of e.whens) { expr(w.when); expr(w.then); } @@ -475,5 +488,11 @@ function collectDependsOn( else if (c.kind === "predicateAgg") clause(c.pred); } if (spec.where !== undefined) clause(spec.where); + // rc.21 part B (U15): a union reads every member's tables too. + for (const m of spec.union?.members ?? []) { + const t = joinTables[m.joinTree.baseEntity]; + for (const mt of collectDependsOn(m, t ?? baseTableName, joinTables)) tables.add(mt); + } + if (spec.where !== undefined) clause(spec.where); return [...tables]; } diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index ef1c6f6ad9..6f62e3af5c 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -28,6 +28,21 @@ import { ORIGIN_FIRST_ATTR_OF, ORIGIN_FIRST_ATTR_VIA, ORIGIN_FIRST_ATTR_FILTER, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + EXPR_CAST, + EXPR_CAST_AS, + EXPR_CAST_DB_COLUMN_TYPE, + EXPR_FUNCTIONS, + parseDbColumnType, AGG_ANY, AGG_ALL, AGG_COLLECT, @@ -48,6 +63,8 @@ import { FILTER_RELATIVE_START_OF, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, + ORIGIN_ATTR_SEGMENT, + FILTER_OPERAND_FIELD, type RelativeStartOf, SORT_ORDER_DESC, RELATIONSHIP_ATTR_OBJECT_REF, @@ -57,19 +74,19 @@ import { IDENTITY_SUBTYPE_REFERENCE, IDENTITY_REFERENCE_ATTR_REFERENCES, FIELD_ATTR_COLUMN, - effectiveProjectionFilter, - OBJECT_SUBTYPE_PROJECTION, findReferencesBetween, findReverseReferenceHops, - resolveRelationshipReference, - resolveObjectRef, + OBJECT_SUBTYPE_PROJECTION, + resolveFlattenedMember, + resolveFlattenedColumnName, resolveFieldPathColumn, resolveFilterPath, + effectiveProjectionFilter, + type FilterPath, isMetaRoot, isMetaField, - type FilterPath, - ORIGIN_ATTR_SEGMENT, - FILTER_OPERAND_FIELD, + resolveRelationshipReference, + resolveObjectRef, FILTER_OP_IS_DISTINCT_FROM, FILTER_OP_IS_NOT_DISTINCT_FROM, refTarget, @@ -77,7 +94,7 @@ import { type ReferenceLookup, } from "@metaobjectsdev/metadata"; import { type MetaData, type MetaField, type MetaReferenceIdentity, type MetaRoot, type MetaSource, MetaObject } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf, type EnumStorageMap } from "../enum-meta.js"; import { columnNameFromField, viewNameFromProjection, @@ -85,7 +102,9 @@ import { // #213 — a write-through ENTITY (FR-024 §7 read-view) hosts its own view; the base // is the entity itself, not an extends-anchored projection. import { isWriteThrough } from "./projection-detector.js"; -import { tphDiscriminatorBase, tphDiscriminatorPin } from "../tph.js"; +import { tphDiscriminatorBase, tphDiscriminatorPin, tphStorageObject } from "../tph.js"; +// #209 — the SAME NOT-NULL predicate that drives a column's `.notNull()` decides +// whether a belongs-to join is INNER (required FK) vs LEFT OUTER (nullable FK). import type { ColumnNamingStrategy } from "../metaobjects-config.js"; import { fieldSqlType } from "@metaobjectsdev/migrate-ts/expected"; import { segmentClause, temporalOf } from "./report-sql.js"; @@ -93,7 +112,7 @@ import type { RelativeNow } from "./report-spec.js"; import type { ReportTemporal } from "./time-sql.js"; import type { JoinNode, JoinTree, SelectColumn, SelectSpec, ViewSpec, ViewFilterClause, - ViewExprNode, ViewExprLiteral, ViewOrderKey, FirstInnerJoin, TphScope, FirstColumn, ColRef, + ViewExprNode, ViewExprLiteral, ViewOrderKey, FirstInnerJoin, TphScope, FirstColumn, ColRef, CastTarget, } from "./view-spec.js"; /** Compose keys in the attr.filter shape. */ @@ -108,12 +127,14 @@ const FILTER_OR = FILTER_COMPOSE_OR; const EXPR_OP_IS_NOT_NULL = "isNotNull"; const EXPR_OP_NOT = "not"; const EXPR_FN_COALESCE = "coalesce"; -// `case` node keys (mirror meta-attr-expression's case grammar). +// rc.19 `case` and `now` node keys (mirror meta-attr-expression's EXPR_CASE* / EXPR_NOW*). const EXPR_CASE = "case"; const EXPR_CASE_WHEN = "when"; const EXPR_CASE_THEN = "then"; const EXPR_CASE_ELSE = "else"; const EXPR_CASE_OPERAND = "operand"; +const EXPR_NOW = FILTER_RELATIVE_NOW; +const EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF; /** The scalar-reduce @agg values that map to the plain `aggregate` SelectColumn kind. */ const SCALAR_AGG_FUNCTIONS: ReadonlySet = new Set(AGGREGATE_FUNCTIONS); @@ -152,7 +173,7 @@ function resolveAggregateFilter( entity: MetaObject, alias: string, ctx: ExtractContext, - /** The base row a `{ field }` operand names, and its alias (correlated filter). */ + /** rc.19 correlated-filter: the base row a `{ field }` operand names, and its alias. */ outer?: OuterRow, ): ViewFilterClause | undefined { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return undefined; @@ -168,37 +189,43 @@ function resolveAggregateFilter( const field = entity.fields().find((f) => f.name === key); // The loader resolves every key; one that reaches here unresolved would drop a predicate. if (!field) throw new Error(`origin @filter key "${key}" names no field of "${entity.name}".`); - const opObj = desugarClause(val); - const ops = Object.keys(opObj); - if (ops.length === 0) throw new Error(`origin @filter on "${key}" has no operator.`); - // A field clause may carry several operators (a range { gte, lte }); each is its own - // comparison and they compose with AND. Keeping one would widen the aggregated row set. - const fieldClauses: ViewFilterClause[] = ops.map((op) => { - const operand = opObj[op]; - return { - kind: "cmp", - ref: `${alias}.${sourceColumnNameFor(field, ctx)}`, - op, - // Same int-backed-enum encoding as the row-scope @filter below: this scoping - // filter renders as a SQL literal too (FILTER (WHERE …) / CASE WHEN), so a - // member symbol would land unencoded in an integer comparison. A relative date - // and a base-row operand lower here too. - value: lowerFilterValue(operand, op, field, key, `origin @filter over ${entity.name}`, outer, ctx), - }; - }); - clauses.push(fieldClauses.length === 1 ? fieldClauses[0]! : { kind: "and", clauses: fieldClauses }); + const filterOps = Object.entries(desugarClause(val)); + if (filterOps.length === 0) throw new Error(`origin @filter on "${key}" has no operator.`); + // multi-op: a field clause may carry several ops (a range { gte: 1, lte: 5 }); each is its own + // comparison, AND-composed. Keeping only the first widened the row set silently. + const fieldClauses: ViewFilterClause[] = filterOps.map(([op, raw]) => ({ + kind: "cmp", + ref: `${alias}.${sourceColumnNameFor(field, ctx)}`, + op, + // Same int-backed-enum encoding as the row-scope @filter below: this scoping + // filter renders as a SQL literal too (FILTER (WHERE …) / CASE WHEN), so a + // member symbol would land unencoded in an integer comparison. rc.19: a relative date + // (`now`) and a base-row operand (correlated-filter) lower here too. + value: lowerFilterValue(raw, op, field, key, `origin @filter over ${entity.name}`, outer, ctx), + })); + if (fieldClauses.length === 1) clauses.push(fieldClauses[0]!); + else if (fieldClauses.length > 1) clauses.push({ kind: "and", clauses: fieldClauses }); } if (clauses.length === 0) return undefined; return clauses.length === 1 ? clauses[0]! : { kind: "and", clauses }; } -/** The row a `{ field: "" }` filter operand reads, and its alias. */ +/** rc.19 correlated-filter: the row a `{ field: "" }` filter operand reads, and its alias. */ export interface OuterRow { readonly entity: MetaObject; readonly alias: string; + /** rc.21 part B (U4): the to-one paths from the outer row the view joined, by dotted key. */ + readonly paths?: ReadonlyMap; +} + +/** rc.21 part B (U3, U4): a to-one path from the base the view joined (not output): its end's alias and field. */ +export interface PathRef { + readonly alias: string; + readonly field: MetaField; + readonly entity: MetaObject; } -/** A `{ field: "" }` operand, not a relative date. */ +/** A `{ field: "" }` operand (correlated-filter), not a relative date. */ function isFieldOperand(v: unknown): v is { field: string } { return isPlainObject(v) && typeof v[FILTER_OPERAND_FIELD] === "string" && !(FILTER_RELATIVE_NOW in v); } @@ -207,12 +234,7 @@ function isRelativeOperand(v: unknown): v is Record { return isPlainObject(v) && FILTER_RELATIVE_NOW in v; } -/** The relative-date kind of a temporal field; an instant for anything else. */ -function temporalOfField(f: MetaField): ReportTemporal { - return f.subType === FIELD_SUBTYPE_DATE || f.subType === FIELD_SUBTYPE_TIMESTAMP ? temporalOf(f) : "instant"; -} - -/** A relative-date operand on `field`, as the value the emitters render. */ +/** rc.19 `now`: a relative-date operand on `field`, as the value the emitters render. */ function relativeNowOf(v: Record, field: MetaData, key: string, where: string): RelativeNow { if (field.subType !== FIELD_SUBTYPE_DATE && field.subType !== FIELD_SUBTYPE_TIMESTAMP) { throw new Error(`${where}: a relative-date value on "${key}" needs a field.date or field.timestamp.`); @@ -226,8 +248,9 @@ function relativeNowOf(v: Record, field: MetaData, key: string, } /** - * One filter operand for `field`, as the emitters render it: a relative date, a base-row column - * (only where an `outer` row exists), or a literal (an int-backed enum member as its integer). + * One filter operand for `field`, as the emitters render it: a relative date (rc.19 `now`), a + * base-row column (rc.19 correlated-filter, only where an `outer` row exists), or a literal — + * an int-backed enum member as its integer. */ function lowerFilterValue( raw: unknown, op: string, field: MetaData, key: string, where: string, outer: OuterRow | undefined, ctx: ExtractContext, @@ -238,6 +261,17 @@ function lowerFilterValue( } if (isFieldOperand(raw)) { const name = raw[FILTER_OPERAND_FIELD]; + if (name.includes(".")) { + // rc.21 part B (U4): a path operand reads the joined row at its end. + const path = outer?.paths?.get(name); + if (path === undefined) { + throw new Error(`${where}: "${key}" compares with the path "${name}", which the outer row did not join (a path operand is legal only on a projection's own origins).`); + } + if (path.field.isDerived()) { + throw new Error(`${where}: "${key}" compares with the path "${name}", a derived field; a path operand reads a stored column.`); + } + return { kind: "colRef", ref: `${path.alias}.${sourceColumnNameFor(path.field, ctx)}` } satisfies ColRef; + } const other = outer?.entity.fields().find((f) => f.name === name); if (outer === undefined || other === undefined) { throw new Error(`${where}: "${key}" compares with base-row field "${name}", which the base row does not have.`); @@ -248,15 +282,14 @@ function lowerFilterValue( throw new Error(`${where}: "${op}" on "${key}" needs a { field } operand.`); } return encodeIntEnumFilterValue( - raw, op, field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field as MetaField) : undefined, key, where, + raw, op, field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field as MetaField) : undefined, key, where, ); } -/** An origin's `@segment` predicate over `entity` at `alias`, ANDed with its `@filter`. */ +/** rc.19 origin-segment: the origin's `@segment` predicate over `entity` at `alias`, ANDed with its `@filter`. */ function originScope( origin: MetaData, filterAttr: unknown, entity: MetaObject, alias: string, ctx: ExtractContext, outer: OuterRow | undefined, ): ViewFilterClause | undefined { - // ADR-0039: own (category 4) — origin.* never inherits (ADR-0029). const segment = origin.ownAttr(ORIGIN_ATTR_SEGMENT); const seg = typeof segment === "string" ? segmentClause(segment, entity, alias, ctx, `origin.${origin.subType} @segment`) @@ -274,11 +307,12 @@ function originScope( * Own-only at either hop would silently emit the member symbol into an integer column * (ADR-0039). */ -function intEnumMapsOf(projection: MetaObject): ReadonlyMap> { - const out = new Map>(); +function intEnumMapsOf(projection: MetaObject): ReadonlyMap { + // rc.21: a @stringValueMap enum's stored strings take the same lowering. + const out = new Map(); for (const f of projection.fields()) { if (f.subType !== FIELD_SUBTYPE_ENUM) continue; - const map = intValueMapOf(f); + const map = enumStorageMapOf(f); if (map !== undefined) out.set(f.name, map); } return out; @@ -299,7 +333,7 @@ function intEnumMapsOf(projection: MetaObject): ReadonlyMap | undefined, + intMap: EnumStorageMap | undefined, fieldName: string, /** Names the filter being lowered, for the error text: the row-scope view @filter * (`Projection P: view @filter`) or an aggregate's scoping filter @@ -308,7 +342,7 @@ export function encodeIntEnumFilterValue( ): unknown { if (intMap === undefined) return value; if (op === FILTER_OP_IS_NULL) return value; - if (op === FILTER_OP_LIKE) { + if (op === FILTER_OP_LIKE && Object.values(intMap).some((n) => typeof n === "number")) { throw new Error( `${host} uses "like" on "${fieldName}", an ` + `int-backed field.enum (@intValueMap) — it stores as an integer column, so a ` + @@ -318,10 +352,10 @@ export function encodeIntEnumFilterValue( const encode = (v: unknown): unknown => { if (typeof v !== "string") return v; const n = intMap[v]; - if (typeof n !== "number") { + if (typeof n !== "number" && typeof n !== "string") { throw new Error( `${host} value "${v}" for "${fieldName}" has no ` + - `entry in @intValueMap.`, + `entry in @intValueMap / @stringValueMap.`, ); } return n; @@ -348,8 +382,8 @@ function resolveViewFilter( filter: unknown, columnsByField: ReadonlyMap, projectionName: string, - intMapsByField: ReadonlyMap>, - /** The field each key names (a relative date reads its type to lower). */ + intMapsByField: ReadonlyMap, + /** The field each key names (rc.19 `now` reads its type to lower a relative date). */ fieldsByKey: ReadonlyMap = new Map(), ): ViewFilterClause | undefined { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return undefined; @@ -383,6 +417,7 @@ function resolveViewFilter( // path, but view DDL is emitted as literal SQL text and never touches Drizzle. const where = `Projection ${projectionName}: view @filter`; const keyField = fieldsByKey.get(key); + // rc.19 `now`: a relative date lowers to the dialect's "now" shifted, of the field's kind. const value = keyField !== undefined && (isRelativeOperand(rawValue) || (Array.isArray(rawValue) && rawValue.some(isRelativeOperand))) ? Array.isArray(rawValue) @@ -701,6 +736,13 @@ function baseEntityFor( const named = refNamedOwner(identity, root); if (named !== undefined) return named; } + // rc.21 part B (G13): an extender with no identity of its own keeps its super's identity anchor, so its + // own fields (a TPH subtype's columns, say) do not move the base (mirrors the loader's _deriveBaseEntity). + const supAnchor = projection.superResolved; + if (!projection.ownChildren().some((c) => c.type === TYPE_IDENTITY) && supAnchor !== undefined && isMetaObject(supAnchor) + && supAnchor.subType === OBJECT_SUBTYPE_PROJECTION && anchorsByIdentity(supAnchor, root)) { + return baseEntityFor(supAnchor, root); + } const targets = new Set(); // ADR-0039: own — see above; base-entity derivation reads own extends-bound fields. for (const f of projection.ownChildren().filter((c) => c.type === TYPE_FIELD)) { @@ -708,8 +750,8 @@ function baseEntityFor( if (named !== undefined && named !== projection) targets.add(named); } if (targets.size === 1) return [...targets][0]!; - // A projection extending another projection and anchoring nothing of its own has its super's - // base entity (mirrors the loader's _deriveBaseEntity). + // G13: a projection extending another projection, anchoring nothing of its own, has its + // super's base entity (mirrors the loader's _deriveBaseEntity). const sup = projection.superResolved; if (targets.size === 0 && sup !== undefined && isMetaObject(sup) && sup.subType === OBJECT_SUBTYPE_PROJECTION) { return baseEntityFor(sup, root); @@ -721,6 +763,14 @@ function baseEntityFor( ); } +/** rc.21 part B: whether a projection (or a projection it extends) anchors its base with an extended identity. */ +function anchorsByIdentity(projection: MetaObject, root: MetaRoot): boolean { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (projection.ownChildren().some((c) => c.type === TYPE_IDENTITY && refNamedOwner(c, root) !== undefined)) return true; + const sup = projection.superResolved; + return sup !== undefined && isMetaObject(sup) && sup.subType === OBJECT_SUBTYPE_PROJECTION && anchorsByIdentity(sup, root); +} + export function sourceColumnNameFor( entityField: MetaData, ctx: ExtractContext, @@ -770,7 +820,10 @@ function baseColumnNameFor( ): string { const target = field.superData; if (target === undefined) return sourceColumnNameFor(field, ctx); - if (refNamedOwner(field, root) !== base) return sourceColumnNameFor(field, ctx); + const owner = refNamedOwner(field, root); + // rc.21 part B: a field bound to a TPH relative of the base (a subtype's column of a projection over the + // TPH root) is a column of the same shared table, so it reads that column too. + if (owner !== base && (owner === undefined || tphStorageObject(owner) !== tphStorageObject(base))) return sourceColumnNameFor(field, ctx); return sourceColumnNameFor(target, ctx); } @@ -783,8 +836,8 @@ function baseColumnNameFor( export function joinColumnFor(entity: MetaObject, fieldName: string, ctx: ExtractContext): string { const f = entity.fields().find((x) => x.name === fieldName); if (f) return sourceColumnNameFor(f, ctx); - // A reference may name a member of a flattened value object (`address.countryId`): its - // column is on the entity's own table, under the embedding's prefix. + // G6: a reference over a flattened value-object member (`address.countryId`) joins on the + // member's prefixed column of the owning table. return resolveFieldPathColumn(entity, fieldName, ctx.columnNamingStrategy) ?? columnNameFromField(fieldName, ctx.columnNamingStrategy); } @@ -859,10 +912,10 @@ function resolveExprNode( base: MetaObject, baseAlias: string, ctx: ExtractContext, - /** A ref naming one of the projection's own fields, resolved to its column expression (and the - * field, for a `now` beside it); undefined → a field of the base. */ + /** rc.19 computed-over-joined: a ref to one of the projection's own fields, resolved to its + * column expression (and the field, for a `now` beside it); undefined → a base field. */ lookup?: (name: string) => ResolvedRef | undefined, - /** The kind a relative instant takes here: that of the field it is compared with. */ + /** rc.19 `now`: the kind a relative instant takes here — the field it is compared with. */ nowTemporal: ReportTemporal = "instant", ): ViewExprNode | undefined { if (!isPlainObject(raw)) return undefined; @@ -886,14 +939,14 @@ function resolveExprNode( if ("value" in raw) { return { kind: "lit", value: raw.value as ViewExprLiteral }; } - if (FILTER_RELATIVE_NOW in raw) { + if (EXPR_NOW in raw) { return { kind: "now", value: { kind: "relativeNow", - duration: String(raw[FILTER_RELATIVE_NOW]), + duration: String(raw[EXPR_NOW]), temporal: nowTemporal, - ...(FILTER_RELATIVE_START_OF in raw ? { startOf: raw[FILTER_RELATIVE_START_OF] as RelativeStartOf } : {}), + ...(EXPR_NOW_START_OF in raw ? { startOf: raw[EXPR_NOW_START_OF] as RelativeStartOf } : {}), }, }; } @@ -919,11 +972,24 @@ function resolveExprNode( ...(otherwise !== undefined ? { else: otherwise } : {}), }; } + if (EXPR_CAST in raw) { + // rc.21 part B (U12): a cast to a field subtype's column type, optionally a text spelling. + const arg = sub(raw[EXPR_CAST]); + const as = raw[EXPR_CAST_AS]; + if (arg === undefined || typeof as !== "string") return undefined; + const spelling = typeof raw[EXPR_CAST_DB_COLUMN_TYPE] === "string" ? parseDbColumnType(raw[EXPR_CAST_DB_COLUMN_TYPE] as string) : undefined; + const to: CastTarget = spelling !== undefined && spelling.kind !== "uuid" && spelling.kind !== "jsonb" + ? { subType: as, spelling: { kind: spelling.kind, ...("length" in spelling && spelling.length !== undefined ? { length: spelling.length } : {}) } } + : { subType: as }; + return { kind: "cast", arg, to }; + } if ("fn" in raw) { - if (raw.fn !== EXPR_FN_COALESCE || !Array.isArray(raw.args)) return undefined; + if (typeof raw.fn !== "string" || !Object.prototype.hasOwnProperty.call(EXPR_FUNCTIONS, raw.fn) || !Array.isArray(raw.args)) return undefined; const args = raw.args.map((a) => sub(a)); if (args.some((a) => a === undefined)) return undefined; - return { kind: "coalesce", args: args as ViewExprNode[] }; + if (raw.fn === EXPR_FN_COALESCE) return { kind: "coalesce", args: args as ViewExprNode[] }; + // rc.21 part B (U11, U13): the rest of the closed function set. + return { kind: "fn", name: raw.fn, args: args as ViewExprNode[] }; } if ("op" in raw && typeof raw.op === "string") { const op = raw.op; @@ -959,6 +1025,109 @@ interface ResolvedRef { readonly field: MetaField; } +/** The relative-date kind of a temporal field; an instant for anything else. */ +function temporalOfField(f: MetaField): ReportTemporal { + return f.subType === FIELD_SUBTYPE_DATE || f.subType === FIELD_SUBTYPE_TIMESTAMP ? temporalOf(f) : "instant"; +} + +/** + * rc.21 part B (U10): an origin.function's call, each argument resolved by `arg` (undefined if one does + * not), cast to the carrying field's column type (fix round I4: the view column has the field's type + * whatever the function returns). The declared signature is checked here too, for a caller that skipped + * the loader: each argument's subtype is its `@params` entry, and `@returns` is the field's subtype. + */ +function functionCall( + origin: MetaData, field: MetaField, arg: (name: string) => { expr: ViewExprNode; subType: string } | undefined, +): ViewExprNode | undefined { + // ADR-0039: own — origin.* never inherits (ADR-0029). + const name = origin.ownAttr(ORIGIN_FUNCTION_ATTR_FUNCTION); + const schema = origin.ownAttr(ORIGIN_FUNCTION_ATTR_SCHEMA); + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + const rawParams = origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + if (typeof name !== "string") return undefined; + const names = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + const params = rawParams === undefined ? [] : Array.isArray(rawParams) ? rawParams : [rawParams]; + const where = `origin.function "${name}" on "${field.name}"`; + if (returns !== field.subType) { + throw new Error(`${where}: @returns ${String(returns)}, but the field is field.${field.subType}; the declared return type must be the field's type.`); + } + if (params.length !== names.length) { + throw new Error(`${where}: @params declares ${params.length} parameter type(s) for ${names.length} argument(s).`); + } + const args: ViewExprNode[] = []; + for (const [i, n] of names.entries()) { + const a = typeof n === "string" ? arg(n) : undefined; + if (a === undefined) return undefined; + if (a.subType !== params[i]) { + throw new Error(`${where}: argument ${i + 1} "${String(n)}" is a field.${a.subType}, but parameter ${i + 1} is declared ${String(params[i])}; cast it through an origin.computed field.`); + } + args.push(a.expr); + } + const call: ViewExprNode = { kind: "call", name, ...(typeof schema === "string" ? { schema } : {}), args }; + // N1: the call is cast to the field's full column type — length, @dbColumnType spelling, + // precision and scale, local or zoned timestamp — the type `meta migrate` gives its column. + return { kind: "cast", arg: call, to: { subType: field.subType, column: fieldSqlType(field) } }; +} + +/** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ +function grainValueObject(projection: MetaObject, base: MetaObject): MetaObject | undefined { + if (projection === base) return undefined; + const grain = projection.attr(OBJECT_PROJECTION_ATTR_GRAIN); + if (typeof grain !== "string") return undefined; + const field = base.fields().find((f) => f.name === grain); + const vo = field === undefined ? undefined : refTarget(field, FIELD_ATTR_OBJECT_REF); + return vo !== undefined && isMetaObject(vo) ? vo : undefined; +} + +/** Every `{ field }` name an expression tree reads, through every node kind. */ +function exprFieldNames(node: unknown, out: string[] = []): string[] { + if (!isPlainObject(node)) return out; + if (typeof node.field === "string") out.push(node.field); + for (const key of ["left", "right", "arg", EXPR_CAST, EXPR_CASE_OPERAND, EXPR_CASE_ELSE]) exprFieldNames(node[key], out); + if (Array.isArray(node.args)) for (const a of node.args) exprFieldNames(a, out); + if (Array.isArray(node[EXPR_CASE])) { + for (const arm of node[EXPR_CASE] as unknown[]) { + if (isPlainObject(arm)) { exprFieldNames(arm[EXPR_CASE_WHEN], out); exprFieldNames(arm[EXPR_CASE_THEN], out); } + } + } + return out; +} + +/** Every `{ field: "" }` operand of a filter, through and/or. */ +function filterOperandNames(filter: unknown, out: string[] = []): string[] { + if (!isPlainObject(filter)) return out; + for (const [key, val] of Object.entries(filter)) { + if (key === FILTER_AND || key === FILTER_OR) { + if (Array.isArray(val)) for (const sub of val) filterOperandNames(sub, out); + continue; + } + if (!isPlainObject(val)) continue; + for (const operand of Object.values(val)) if (isFieldOperand(operand)) out.push(operand[FILTER_OPERAND_FIELD]); + } + return out; +} + +/** + * rc.21 part B (U3, U4): the dotted names a projection's own origins read that are not its fields — + * an origin.computed expression's path refs, and an origin.first / origin.aggregate @filter's path + * operands. Each is a to-one path from the base the view joins without outputting it. + */ +function originPathKeys(projection: MetaObject): string[] { + const keys: string[] = []; + // G13: effective fields; ADR-0039: own — origin.* never inherits (ADR-0029). + for (const f of projection.fields()) { + for (const origin of f.ownChildren()) { + if (origin.type !== TYPE_ORIGIN) continue; + if (origin.subType === ORIGIN_SUBTYPE_COMPUTED) keys.push(...exprFieldNames(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))); + if (origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_AGGREGATE) { + keys.push(...filterOperandNames(origin.ownAttr(ORIGIN_FIRST_ATTR_FILTER))); + } + } + } + return keys.filter((k) => k.includes(".")); +} + export function shortAliasFor(entityName: string, used: Set): string { // Derive from the SHORT name — an entity ref may now be a resolutionKey ("pkg::Name", // #244); the alias must stay the first letter of the entity, so existing single-package @@ -986,22 +1155,23 @@ export interface PathStep { fkColumn: string; pkColumn: string; referenceHolder: "source" | "target"; - /** Always `left`: a generated view join never drops a base row. */ + /** #209 — derived join type: `inner` for a required belongs-to FK, else `left`. */ joinType: "left"; targetEntity: string; - /** The target is a TPH level: the discriminator values that scope the join to its rows. */ + /** TPH-scope: the target subtype's discriminator pin, when the target is a TPH subtype. */ tphScope?: TphScope; } export type Path = PathStep[]; /** - * A TPH level's rows on its base's shared table: the discriminator column and the values stored - * for it (an int-backed discriminator enum stores its integers) - a concrete subtype's own value - * and those of every concrete subtype beneath it; an abstract intermediate level has only the - * latter. Undefined for the discriminator base and anything outside a TPH hierarchy. + * TPH-scope: a TPH level's rows on its base's shared table — the discriminator column and the + * values stored for it (an int-backed discriminator enum stores its integers): a concrete + * subtype's own value and those of every concrete subtype beneath it; an abstract intermediate + * level has only the latter. Undefined for the discriminator base and anything outside a TPH. */ export function tphScopeOf(entity: MetaObject, ctx: ExtractContext): TphScope | undefined { + // The discriminator base itself (or anything outside a hierarchy) reads every row. const base = tphDiscriminatorBase(entity); if (base === undefined || base === entity) return undefined; const root = entity.root(); @@ -1012,6 +1182,7 @@ export function tphScopeOf(entity: MetaObject, ctx: ExtractContext): TphScope | } return false; }; + // Its own rows, then every concrete level beneath it (an abstract level has only those). const levels = [entity, ...objects.filter((o) => o !== entity && descends(o))]; const values: (string | number)[] = []; let column: string | undefined; @@ -1020,7 +1191,7 @@ export function tphScopeOf(entity: MetaObject, ctx: ExtractContext): TphScope | if (pin === undefined) continue; const field = level.fields().find((f) => f.name === pin.fieldName); if (field === undefined) continue; - const map = field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field) : undefined; + const map = field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field) : undefined; column = sourceColumnNameFor(field, ctx); values.push(map?.[pin.value] ?? pin.value); } @@ -1137,10 +1308,12 @@ export function walkViaPath(via: string, root: MetaRoot, referrerPkg: string, ct const fkHolder = referenceHolder === "source" ? currentObj : target; const pkHolder = referenceHolder === "source" ? target : currentObj; - // Every generated view join is LEFT OUTER, so a join never drops a base row (an INNER join over a - // required key would drop one whose reference names no row: an unenforced reference, or a TPH - // subtype target). A view that must require the related row says so in its @filter, e.g. - // `{ ".id": { isNull: false } }`. A report dimension's `required` reads the model. + // rc.19 R62 (review item 9): every generated view join is LEFT OUTER. #209 made a belongs-to + // hop over a NOT NULL key INNER, which silently dropped a base row whose reference names no + // row — an `@enforce: false` reference, or a TPH-subtype target whose discriminator the join + // carries. A view that must require the related row says so: `@filter: { ".id": + // { isNull: false } }`. A report dimension's `required` reads the model (report-shape.ts + // `viaAlwaysMatches`), never the join type. const joinType = "left" as const; path.push({ @@ -1203,7 +1376,7 @@ function buildJoinTree( ctx: ExtractContext, extraPaths: readonly Path[] = [], ): JoinTree { - // The to-one paths a view @filter walks join like any origin's @via. + // G7 (joined): the to-one paths a view @filter walks join like any origin's @via. const allPaths: Path[] = [...extraPaths]; // Referrer package for resolving a bare @via head: the origins are authored on the // projection, so bare refs bind package-locally to it (FQN refs ignore this). @@ -1213,8 +1386,8 @@ function buildJoinTree( // ADR-0028, inclusive + fail-closed); iterate the projection's own fields and // each field's own origin. origin.* NEVER inherits (ADR-0029), so origin reads // below are own by policy (category 4). - // The EFFECTIVE fields: a projection extending another projection inherits its fields and - // their origins (base first), so its view joins what they need. + // G13: the EFFECTIVE fields — a projection that extends another projection inherits its + // fields and their origins (base first), so its view joins what they need. for (const field of projection.fields()) { for (const origin of field.ownChildren()) { if (origin.type !== TYPE_ORIGIN) continue; @@ -1250,6 +1423,31 @@ function buildJoinTree( // Helpers for SelectSpec building // --------------------------------------------------------------------------- +/** + * The alias an origin reads its `@via`'s terminal entity from. With a `@via`, it is the join the + * hop chain itself built (two references onto one target are two joins with two aliases); the + * entity-name lookup below is only the fallback for an origin with no `@via` (the base, or a join + * the tree reaches by entity alone). + */ +function originSourceAlias( + joinTree: JoinTree, + via: string | undefined, + entityName: string, + root: MetaRoot, + projPkg: string, + ctx: ExtractContext, +): string | undefined { + if (via !== undefined && via.length > 0) { + const path = walkViaPath(via, root, projPkg, ctx); + // Only when the hop chain ends on the entity the origin reads (an aggregate's @of names it). + if (path.length > 0 && path[path.length - 1]!.targetEntity === entityName) { + const alias = aliasForHops(joinTree, path.map((step) => step.relationship)); + if (alias !== undefined) return alias; + } + } + return findAliasInTree(joinTree, entityName); +} + function findAliasInTree( joinTree: JoinTree, entityName: string, @@ -1322,8 +1520,14 @@ function buildSelectSpec( root: MetaRoot, ctx: ExtractContext, usedAliases: Set, + /** rc.21 part B (U3, U4): the joined to-one paths an expression or an operand reads. */ + pathRefs: ReadonlyMap = new Map(), ): SelectSpec { const columns: SelectColumn[] = []; + const outerRow: OuterRow = { entity: base, alias: joinTree.baseAlias, paths: pathRefs }; + // rc.21 part B (U14): a @grain view's rows are the elements of the base's array field. + const grainVo = grainValueObject(projection, base); + const grainOrdinal = grainVo === undefined ? undefined : projection.attr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); // Referrer package for resolving bare @from/@of/@via entity refs (FQN refs ignore it). const projPkg = packageOf(projection); @@ -1345,16 +1549,23 @@ function buildSelectSpec( const isReadViewHost = base === projection; const declaredFields: MetaField[] = isReadViewHost ? base.fields() + // G13: effective — an extending projection's view carries the inherited fields, base first. : projection.fields(); const pendingComputed = new Map(); for (const field of declaredFields) { const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); const dbCol = sourceColumnNameFor(field, ctx); + if (!origin && grainVo !== undefined && field.name === grainOrdinal) { + // rc.21 part B (U14): the element's 1-based position. + columns.push({ kind: "element", fieldName: field.name, dbColAlias: dbCol, castTo: fieldSqlType(field) }); + continue; + } if (!origin) { - // A field bound to a DERIVED base field has no base column: its derivation is inlined on the base row. + // rc.19 entity-derived: a field bound to a DERIVED base field has no base column; its + // derivation is inlined on the base row. const bound = isReadViewHost ? undefined : field.superData; - if (bound !== undefined && isMetaField(bound) && isDerivedField(bound) && refNamedOwner(field, root) === base) { + if (bound !== undefined && isMetaField(bound) && bound.isDerived() && refNamedOwner(field, root) === base) { const expr = inlineEntityDerived(bound, base, joinTree.baseAlias, root, usedAliases, ctx, `Projection ${projection.name}: "${field.name}"`); columns.push({ kind: "computed", fieldName: field.name, dbColAlias: dbCol, expr }); continue; @@ -1384,26 +1595,25 @@ function buildSelectSpec( // key the alias lookup on the SAME resolutionKey() the joinTree stored (#244). const fieldName = from.slice(dotIdx + 1); const targetEntity = resolveEntityRef(root, from.slice(0, dotIdx), projPkg); - if (!targetEntity) cannotLower(projection, field, "its @of/@from names no entity"); - // The alias of the join this origin's own @via walked: two references onto one target - // join it twice, and the entity alone cannot say which join a field reads. - // ADR-0039: own (category 4) — origin.* never inherits (ADR-0029). - const via = origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) as string | undefined; - const sourceAlias = via !== undefined - ? aliasForVia(joinTree, walkViaPath(via, root, projPkg, ctx), targetEntity.resolutionKey()) - : findAliasInTree(joinTree, targetEntity.resolutionKey()); - if (sourceAlias === undefined) cannotLower(projection, field, "the entity it reads is not joined into the view"); + if (!targetEntity) continue; + if (grainVo !== undefined && targetEntity === grainVo) { + // rc.21 part B (U14): a member of the array element, cast to the field's column type. + columns.push({ kind: "element", fieldName: field.name, dbColAlias: dbCol, member: fieldName, castTo: fieldSqlType(field) }); + continue; + } + const passthroughVia = origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) as string | undefined; + const sourceAlias = originSourceAlias(joinTree, passthroughVia, targetEntity.resolutionKey(), root, projPkg, ctx); + if (sourceAlias === undefined) continue; // EFFECTIVE fields — the source column may be inherited via `extends` // (e.g. created_at/updated_at/created_by from an audited base), which // ownChildren() would miss. A member of a flattened value object (`address.city`) is a // column of the entity's own table. const targetField = targetEntity.fields().find((f) => f.name === fieldName); - const sourceColumn = targetField !== undefined - ? sourceColumnNameFor(targetField, ctx) - : resolveFieldPathColumn(targetEntity, fieldName, ctx.columnNamingStrategy); - if (sourceColumn === undefined) cannotLower(projection, field, "its @of/@from names no field of that entity"); - // A derived field of the entity has no column on its table; its origin is inlined where reached. - if (targetField !== undefined && isDerivedField(targetField)) { + // G6: a member of a flattened value object reads the owning table's prefixed column. + const flattened = targetField === undefined ? resolveFlattenedMember(targetEntity, fieldName) : undefined; + if (!targetField && !flattened) continue; + // rc.19 entity-derived: a derived field of the reached entity has no column; it is inlined. + if (targetField !== undefined && targetField.isDerived()) { const expr = inlineEntityDerived(targetField, targetEntity, sourceAlias, root, usedAliases, ctx, `Projection ${projection.name}: "${field.name}" @from`); columns.push({ kind: "computed", fieldName: field.name, dbColAlias: dbCol, expr }); continue; @@ -1413,9 +1623,11 @@ function buildSelectSpec( fieldName: field.name, dbColAlias: dbCol, sourceAlias, - sourceColumn, - // @convert acknowledges the declared type differs from the source's; the view yields the declared one. - // ADR-0039: own — origin.* never inherits (ADR-0029). + sourceColumn: targetField !== undefined + ? sourceColumnNameFor(targetField, ctx) + : resolveFlattenedColumnName(flattened!.embedding, flattened!.member, ctx.columnNamingStrategy), + // bug `cast`: @convert acknowledges the declared type differs from the source's; the view + // must yield the declared one. ADR-0039: own — origin.* never inherits (ADR-0029). ...(origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_CONVERT) === true ? { castTo: fieldSqlType(field) } : {}), }); } else if (origin.subType === ORIGIN_SUBTYPE_AGGREGATE) { @@ -1430,13 +1642,13 @@ function buildSelectSpec( const via = origin.ownAttr(ORIGIN_AGGREGATE_ATTR_VIA) as string | undefined; if (!via) cannotLower(projection, field, "it declares no @via"); const relatedEntity = viaTerminalEntity(via, root, projPkg); - if (!relatedEntity) cannotLower(projection, field, "its @via does not resolve"); - const sourceAlias = aliasForVia(joinTree, walkViaPath(via, root, projPkg, ctx), relatedEntity.resolutionKey()); - if (sourceAlias === undefined) cannotLower(projection, field, "the entity it reads is not joined into the view"); + if (!relatedEntity) continue; + const sourceAlias = originSourceAlias(joinTree, via, relatedEntity.resolutionKey(), root, projPkg, ctx); + if (sourceAlias === undefined) continue; const joinedPk = primaryKeyColumn(relatedEntity, ctx); - if (joinedPk === undefined) cannotLower(projection, field, "the related entity has no primary key"); - const pred = originFilterFor(fail, origin, filterAttr, relatedEntity, sourceAlias, ctx, outer); - if (pred === undefined) cannotLower(projection, field, "its @filter does not resolve"); + if (joinedPk === undefined) continue; + const pred = originScope(origin, filterAttr, relatedEntity, sourceAlias, ctx, outerRow); + if (pred === undefined) continue; // loader requires @filter on any/all columns.push({ kind: "predicateAgg", fieldName: field.name, @@ -1465,9 +1677,9 @@ function buildSelectSpec( const via = origin.ownAttr(ORIGIN_AGGREGATE_ATTR_VIA) as string | undefined; if (!via) cannotLower(projection, field, "it declares no @via"); const relatedEntity = viaTerminalEntity(via, root, projPkg); - if (!relatedEntity) cannotLower(projection, field, "its @via does not resolve"); - const sourceAlias = aliasForVia(joinTree, walkViaPath(via, root, projPkg, ctx), relatedEntity.resolutionKey()); - if (sourceAlias === undefined) cannotLower(projection, field, "the entity it reads is not joined into the view"); + if (!relatedEntity) continue; + const sourceAlias = originSourceAlias(joinTree, via, relatedEntity.resolutionKey(), root, projPkg, ctx); + if (sourceAlias === undefined) continue; const joinedPk = primaryKeyColumn(relatedEntity, ctx); if (joinedPk === undefined) cannotLower(projection, field, "the related entity has no primary key"); // ADR-0059 R7 — the VO the loader bound for @objectRef, resolved where it was declared. @@ -1505,13 +1717,9 @@ function buildSelectSpec( if (dotIdx < 1) cannotLower(projection, field, 'its @of/@from is not "Entity.field"'); const fieldName = of_.slice(dotIdx + 1); const targetEntity = resolveEntityRef(root, of_.slice(0, dotIdx), projPkg); - if (!targetEntity) cannotLower(projection, field, "its @of/@from names no entity"); - // The join its own @via walked (see the passthrough branch). ADR-0039: own (category 4). - const aggVia = origin.ownAttr(ORIGIN_AGGREGATE_ATTR_VIA) as string | undefined; - const sourceAlias = aggVia !== undefined - ? aliasForVia(joinTree, walkViaPath(aggVia, root, projPkg, ctx), targetEntity.resolutionKey()) - : findAliasInTree(joinTree, targetEntity.resolutionKey()); - if (sourceAlias === undefined) cannotLower(projection, field, "the entity it reads is not joined into the view"); + if (!targetEntity) continue; + const sourceAlias = originSourceAlias(joinTree, origin.ownAttr(ORIGIN_AGGREGATE_ATTR_VIA) as string | undefined, targetEntity.resolutionKey(), root, projPkg, ctx); + if (sourceAlias === undefined) continue; const targetField = targetEntity.fields().find((f) => f.name === fieldName); if (!targetField) cannotLower(projection, field, "its @of/@from names no field of that entity"); @@ -1538,7 +1746,7 @@ function buildSelectSpec( if (SCALAR_AGG_FUNCTIONS.has(agg)) { // Optional scoping filter — resolved against the aggregated entity (the @of // entity, reached at `sourceAlias`), e.g. max(version) over only active rows. - const filter = originFilterFor(fail, origin, filterAttr, targetEntity, sourceAlias, ctx, outer); + const filter = originScope(origin, filterAttr, targetEntity, sourceAlias, ctx, outerRow); columns.push({ kind: "aggregate", fieldName: field.name, @@ -1552,34 +1760,47 @@ function buildSelectSpec( cannotLower(projection, field, `@agg "${agg}" has no view lowering`); } } else if (origin.subType === ORIGIN_SUBTYPE_COMPUTED) { - // #195 row-level computed value (@expr tree, no @via). Its refs may name other projection - // fields, so it resolves after every column exists (the second pass below), in this place. + // #195 row-level computed value from the base entity's own fields (@expr tree, + // no @via). ADR-0039: own — origin.* never inherits (ADR-0029). + // rc.19 computed-over-joined: its refs may name other projection fields, so it resolves + // after every column exists (the second pass below), in this column's place. pendingComputed.set(field.name, { index: columns.length, origin, field }); columns.push({ kind: "computed", fieldName: field.name, dbColAlias: dbCol, expr: { kind: "lit", value: null } }); } else if (origin.subType === ORIGIN_SUBTYPE_FIRST) { // #195 correlated latest-row — argmax-then-project. Resolves to a correlated // subquery (NOT a join). ADR-0039: own — origin.* never inherits (ADR-0029). - const first = buildFirstColumn(field, origin, base, joinTree.baseAlias, root, projPkg, usedAliases, ctx, fail); - columns.push(first); - } else { - cannotLower(projection, field, `origin.${origin.subType} has no view lowering`); + const first = buildFirstColumn(field, origin, base, joinTree.baseAlias, root, projPkg, usedAliases, ctx, pathRefs); + if (first !== undefined) columns.push(first); + } else if (origin.subType === ORIGIN_SUBTYPE_FUNCTION) { + // rc.21 part B (U10): a call of a database function; its arguments may name other + // projection fields, so it resolves with the computed columns, in this column's place. + pendingComputed.set(field.name, { index: columns.length, origin, field }); + columns.push({ kind: "computed", fieldName: field.name, dbColAlias: dbCol, expr: { kind: "lit", value: null } }); } } - // Resolve every origin.computed now that the columns it may name exist: a ref to a projection - // field reads that column (a passthrough's source, an origin.first's subquery, another - // computed's expression); anything else is a base field. An aggregate is not readable. + // rc.19 computed-over-joined — resolve every origin.computed now that the columns it may name + // exist: a ref to a projection field reads that column (a passthrough's source column, an + // origin.first's subquery, another computed's expression); anything else is a base field. const byName = new Map(columns.map((c) => [c.fieldName, c] as const)); const fieldByName = new Map(declaredFields.map((f) => [f.name, f] as const)); const resolving = new Set(); const resolveComputed = (name: string): ViewExprNode | undefined => { const pending = pendingComputed.get(name)!; if (resolving.has(name)) { - throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to itself through ${[...resolving].join(" -> ")}.`); + throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to itself through ${[...resolving].join(" → ")}.`); } resolving.add(name); const lookup = (ref: string): ResolvedRef | undefined => { if (ref === name) return undefined; // its own name is the base field's + // rc.21 part B (U3): a path of to-one hops from the base, joined but not output. + const path = ref.includes(".") && !fieldByName.has(ref) ? pathRefs.get(ref) : undefined; + if (path !== undefined) { + const expr: ViewExprNode = path.field.isDerived() + ? inlineEntityDerived(path.field, path.entity, path.alias, root, usedAliases, ctx, `Projection ${projection.name}: "${name}" path "${ref}"`) + : { kind: "col", ref: `${path.alias}.${sourceColumnNameFor(path.field, ctx)}` }; + return { expr, field: path.field }; + } const f = fieldByName.get(ref); const c = byName.get(ref); if (f === undefined || c === undefined) return undefined; @@ -1589,34 +1810,42 @@ function buildSelectSpec( } if (c.kind === "passthrough") return { expr: { kind: "col", ref: `${c.sourceAlias}.${c.sourceColumn}` }, field: f }; if (c.kind === "computed") return { expr: c.expr, field: f }; - if (c.kind === "first") return { expr: { kind: "first", column: { ...c, outerAlias: joinTree.baseAlias } }, field: f }; - throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to "${ref}", an aggregate; a computed value cannot read one.`); + if (c.kind === "first") return { expr: { kind: "first", column: c }, field: f }; + // rc.21 part B (U13): a scalar aggregate (or any/all) is read on the grouped row. + if (c.kind === "aggregate" || c.kind === "predicateAgg") return { expr: { kind: "agg", column: c }, field: f }; + throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to "${ref}", a collect; a computed value cannot read an array.`); + }; + const argOf = (arg: string): { expr: ViewExprNode; subType: string } | undefined => { + const e = resolveExprNode({ field: arg }, base, joinTree.baseAlias, ctx, lookup); + const f = lookup(arg)?.field ?? base.fields().find((x) => x.name === arg); + return e === undefined || f === undefined ? undefined : { expr: e, subType: f.subType }; }; - // ADR-0039: own — origin.* never inherits (ADR-0029). - const expr = resolveExprNode(pending.origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), base, joinTree.baseAlias, ctx, lookup); + const expr = pending.origin.subType === ORIGIN_SUBTYPE_FUNCTION + ? functionCall(pending.origin, pending.field, argOf) + : resolveExprNode(pending.origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), base, joinTree.baseAlias, ctx, lookup); resolving.delete(name); pendingComputed.delete(name); - if (expr === undefined) cannotLower(projection, pending.field, "its @expr uses a node the view lowering does not support yet"); - // A bare NULL in a view is text, so any other declared type needs the cast. + if (expr === undefined) return undefined; + // bug `cast`: a bare NULL in a view is text, so any other declared type needs the cast. const declared = fieldSqlType(pending.field); const castNull = expr.kind === "lit" && expr.value === null && !(declared.kind === "text" && declared.maxLength === undefined); - const resolved: SelectColumn = { - kind: "computed", fieldName: name, dbColAlias: sourceColumnNameFor(pending.field, ctx), expr, - ...(castNull ? { castTo: declared } : {}), - }; + const resolved: SelectColumn = { kind: "computed", fieldName: name, dbColAlias: sourceColumnNameFor(pending.field, ctx), expr, ...(castNull ? { castTo: declared } : {}) }; columns[pending.index] = resolved; byName.set(name, resolved); return expr; }; + const dropped: number[] = []; for (const name of [...pendingComputed.keys()]) { - if (pendingComputed.has(name)) resolveComputed(name); // else resolved through another + if (!pendingComputed.has(name)) continue; // resolved through another + const index = pendingComputed.get(name)!.index; + if (resolveComputed(name) === undefined) dropped.push(index); } - return { columns }; + return { columns: columns.filter((_, i) => !dropped.includes(i)) }; } -/** origin.first's column: the selected related row's @of, correlated to `base`'s row at `baseAlias` (#195). */ +/** origin.first's column: the selected related row's @of, correlated to `base`'s row (#195). */ function buildFirstColumn( - field: MetaData, + field: MetaField, origin: MetaData, base: MetaObject, baseAlias: string, @@ -1624,18 +1853,18 @@ function buildFirstColumn( projPkg: string, usedAliases: Set, ctx: ExtractContext, - fail: Refuse, -): FirstColumn { + paths?: ReadonlyMap, +): FirstColumn | undefined { const dbCol = sourceColumnNameFor(field, ctx); const of_ = origin.ownAttr(ORIGIN_FIRST_ATTR_OF) as string | undefined; - if (!of_) fail("it declares no @of"); + if (!of_) return undefined; const dotIdx = of_.indexOf("."); - if (dotIdx < 1) fail('its @of/@from is not "Entity.field"'); + if (dotIdx < 1) return undefined; const ofFieldName = of_.slice(dotIdx + 1); const childEntity = resolveEntityRef(root, of_.slice(0, dotIdx), projPkg); - if (!childEntity) fail("its @of names no entity"); + if (!childEntity) return undefined; const ofField = childEntity.fields().find((f) => f.name === ofFieldName); - if (!ofField) fail("its @of names no field of that entity"); + if (!ofField) return undefined; // The base↔child correlation FK — resolved exactly as buildJoinTree resolves a // single hop (the identity.reference is the FK-direction SSOT). Single-hop @via; // a multi-hop @via on origin.first is not lowered here (rare, and validated away). @@ -1649,12 +1878,12 @@ function buildFirstColumn( // a separate, larger change (wiring @via/single-hop-unique inference into this // branch to match _validateViaPath/_inferViaSingleHop) — out of scope for #368's // silent-first-match fix; the message below reflects the real, narrower remedy. - // A @via of two or more hops is lowered along that path — the first hop correlated to the - // base, the rest INNER-joined inside the subquery. One hop (or none) keeps the direct - // correlation below, so its SQL is unchanged. + // first-multihop: a @via of two or more hops is lowered along that path — the first hop + // correlated to the base, the rest INNER-joined inside the subquery. One hop (or none) + // keeps the direct correlation below, so its SQL is unchanged. const firstVia = origin.ownAttr(ORIGIN_FIRST_ATTR_VIA); if (typeof firstVia === "string" && firstVia.split(".").length > 2) { - return firstAlongPath(field.name, dbCol, firstVia, ofField, childEntity, origin, root, projPkg, usedAliases, ctx, { entity: base, alias: baseAlias }); + return firstAlongPath(field.name, dbCol, firstVia, ofField, childEntity, origin, root, projPkg, usedAliases, ctx, { entity: base, alias: baseAlias, ...(paths !== undefined ? { paths } : {}) }) as FirstColumn; } const refs = findReferencesBetween(base, childEntity); // findReferencesBetween walks BOTH directions ([base,child] then [child,base]), @@ -1680,16 +1909,16 @@ function buildFirstColumn( ); } const ref = refs[0]; - if (!ref) fail("no identity.reference correlates the base with the @of entity"); + if (!ref) return undefined; const fkField = ref.referenceIdentity.fields[0]; - if (!fkField) fail("its correlating reference names no field"); + if (!fkField) return undefined; const pkField = ref.referenceIdentity.resolvedTargetPkField(root) ?? "id"; const referenceHolder: "source" | "target" = ref.holder.name === base.name ? "source" : "target"; const fkHolder = referenceHolder === "source" ? base : childEntity; const pkHolder = referenceHolder === "source" ? childEntity : base; const childPk = primaryKeyColumn(childEntity, ctx); - if (childPk === undefined) fail("the @of entity has no primary key"); + if (childPk === undefined) return undefined; // A FRESH alias — the subquery is an independent correlated scope, never the // JOIN-tree alias (reserved against usedAliases so it can never collide). const childAlias = shortAliasFor(childEntity.name, usedAliases); @@ -1697,7 +1926,7 @@ function buildFirstColumn( const filterAttr = origin.ownAttr(ORIGIN_FIRST_ATTR_FILTER); const childScope = tphScopeOf(childEntity, ctx); const filter = andClauses( - originFilterFor(fail, origin, filterAttr, childEntity, childAlias, ctx, { entity: base, alias: baseAlias }), + originScope(origin, filterAttr, childEntity, childAlias, ctx, { entity: base, alias: baseAlias, ...(paths !== undefined ? { paths } : {}) }), childScope !== undefined ? tphScopeClause(childScope, childAlias) : undefined, ); return { @@ -1715,14 +1944,13 @@ function buildFirstColumn( orderBy, ...(filter !== undefined ? { filter } : {}), }; - } /** - * An `origin.first` whose `@via` has two or more hops. The first hop is the correlation to the - * base row; every later hop is an INNER JOIN inside the subquery, and the selected row, its - * ordering, filter and tie-breaker are the last hop's (the `@of` entity). A path that does not - * walk to the `@of` entity is refused here rather than dropped. + * first-multihop: an `origin.first` whose `@via` has two or more hops. The first hop is the + * correlation to the base row; every later hop is an INNER JOIN inside the subquery, and the + * selected row, its ordering, filter and tie-breaker are the last hop's (the `@of` entity). A + * path that does not walk to the `@of` entity is refused here rather than dropped. */ function firstAlongPath( fieldName: string, @@ -1736,7 +1964,7 @@ function firstAlongPath( usedAliases: Set, ctx: ExtractContext, outer: OuterRow, -): FirstColumn { +): SelectColumn { const path = walkViaPath(via, root, projPkg, ctx); const hops = via.split(".").length - 1; const last = path[path.length - 1]; @@ -1796,63 +2024,78 @@ function filterKeysOf(filter: unknown, out: string[] = []): string[] { return out; } -/** A field with an origin child (origin.first / origin.computed on an entity): derived, with no column of its own. */ -function isDerivedField(field: MetaData): boolean { - // ADR-0039: own — origin.* never inherits (ADR-0029). - return field.ownChildren().some((c) => c.type === TYPE_ORIGIN); +/** The join alias the hop chain `hops` (relationship names from the base) landed on. */ +function aliasForHops(joinTree: JoinTree, hops: readonly string[]): string | undefined { + let nodes = joinTree.joins; + let alias: string | undefined; + for (const hop of hops) { + const node = nodes.find((n) => n.relationship === hop); + if (node === undefined) return undefined; + alias = node.alias; + nodes = node.children; + } + return alias; } /** - * A derived field of `entity`, inlined where a projection reaches the entity at `alias`: an - * origin.computed becomes its expression over that alias, an origin.first its correlated - * subquery keyed on it. An aggregate (or anything else) has no row-level form and is refused. + * The column a view @filter compares for a field of `entity` read on `alias` (the base, or the + * end of a to-one path): its stored column, or — entity-derived — its derivation inlined there. */ -export function inlineEntityDerived( - field: MetaData, +function filterColumnFor( + key: string, + field: MetaField, entity: MetaObject, alias: string, root: MetaRoot, usedAliases: Set, ctx: ExtractContext, - where: string, -): ViewExprNode { - // ADR-0039: own — origin.* never inherits (ADR-0029). - const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); - const refuse: Refuse = (why) => { - throw new Error(`${where}: "${entity.name}.${field.name}" is derived and cannot be inlined where it is reached: ${why}.`); - }; - if (origin?.subType === ORIGIN_SUBTYPE_COMPUTED) { - // ADR-0039: own — origin.* never inherits (ADR-0029). - const expr = resolveExprNode(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), entity, alias, ctx); - if (expr !== undefined) return expr; - return refuse("its @expr uses a node the view lowering does not support yet"); - } - if (origin?.subType === ORIGIN_SUBTYPE_FIRST) { - const first = buildFirstColumn(field, origin, entity, alias, root, packageOf(entity), usedAliases, ctx, refuse); - return { kind: "first", column: { ...first, outerAlias: alias } }; + projectionName: string, +): SelectColumn { + if (!field.isDerived()) { + return { kind: "passthrough", fieldName: key, dbColAlias: key, sourceAlias: alias, sourceColumn: sourceColumnNameFor(field, ctx) }; } - return refuse(`origin.${origin?.subType ?? "?"} has no row-level form`); + const expr = inlineEntityDerived(field, entity, alias, root, usedAliases, ctx, `Projection ${projectionName}: view @filter "${key}"`); + return { kind: "computed", fieldName: key, dbColAlias: key, expr }; } /** - * The column a view @filter compares for a field read on `alias` (the base, or the end of a - * to-one path). A derived field has no column there: it is inlined at that alias. + * entity-derived: a derived field declared on an ENTITY, lowered where a projection reaches it + * (its base row, or the end of a to-one path, at `alias`) — an origin.computed as its expression + * over that alias, an origin.first as its correlated subquery keyed on that alias. Aggregates are + * refused: they would need the reached rows grouped. */ -function filterColumnFor( - key: string, - field: MetaData, +export function inlineEntityDerived( + field: MetaField, entity: MetaObject, alias: string, root: MetaRoot, usedAliases: Set, ctx: ExtractContext, - projectionName: string, -): SelectColumn { - if (isDerivedField(field)) { - const expr = inlineEntityDerived(field, entity, alias, root, usedAliases, ctx, `Projection ${projectionName}: view @filter "${key}"`); - return { kind: "computed", fieldName: key, dbColAlias: key, expr }; + where: string, +): ViewExprNode { + // ADR-0039: own — origin.* never inherits (ADR-0029). + const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (origin?.subType === ORIGIN_SUBTYPE_COMPUTED) { + const expr = resolveExprNode(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), entity, alias, ctx); + if (expr !== undefined) return expr; + } else if (origin?.subType === ORIGIN_SUBTYPE_FIRST) { + const first = buildFirstColumn(field, origin, entity, alias, root, packageOf(entity), usedAliases, ctx); + if (first !== undefined) return { kind: "first", column: { ...first, outerAlias: alias } }; + } else if (origin !== undefined && origin.subType === ORIGIN_SUBTYPE_FUNCTION) { + // rc.21 part B (U10): the call, its arguments read on the reached row. + const call = functionCall(origin, field, (arg) => { + const f = entity.fields().find((x) => x.name === arg); + if (f === undefined) return undefined; + // An argument that is itself derived (an origin.computed cast, say) inlines on the same row. + const e = f.isDerived() ? inlineEntityDerived(f, entity, alias, root, usedAliases, ctx, where) : resolveExprNode({ field: arg }, entity, alias, ctx); + return e === undefined ? undefined : { expr: e, subType: f.subType }; + }); + if (call !== undefined) return call; } - return { kind: "passthrough", fieldName: key, dbColAlias: key, sourceAlias: alias, sourceColumn: sourceColumnNameFor(field, ctx) }; + throw new Error( + `${where}: "${entity.name}.${field.name}" is derived by ${origin === undefined ? "nothing" : `origin.${origin.subType}`}, ` + + `which a view cannot inline where it reaches the entity; only origin.computed, origin.first and origin.function can be.`, + ); } /** The inflation-sensitive aggregate kinds: a non-distinct row multiplication corrupts @@ -1875,7 +2118,7 @@ function countManyBranches(joinTree: JoinTree): number { return joinTree.joins.filter(hasMany).length; } -function buildGroupBy(spec: SelectSpec): string[] { +function buildGroupBy(spec: SelectSpec, baseAlias: string): string[] { // predicateAgg (bool_or/bool_and), collectAgg (array_agg) and collectObjectAgg // (jsonb_agg) are real aggregates and force GROUP BY too; computed/first are // scalar-per-row and never grouped. @@ -1884,9 +2127,54 @@ function buildGroupBy(spec: SelectSpec): string[] { || c.kind === "collectAgg" || c.kind === "collectObjectAgg", ); if (!hasAgg) return []; - return spec.columns + const keys = spec.columns .filter((c) => c.kind === "passthrough") .map((c) => `${c.sourceAlias}.${c.sourceColumn}`); + // rc.21 part B (U3, U13): every column a non-aggregate expression reads must be grouped, or + // depend on a grouped key. The base row's do (its primary key is grouped); a JOINED row's need + // not, now that an expression may read a joined column the view does not output (a path) or sit + // over an aggregate. So each joined column a computed expression or an origin.first's correlation + // reads outside an aggregate is grouped too, once. A base-only expression is unchanged. + const add = (ref: string): void => { + if (!ref.startsWith(`${baseAlias}.`) && !keys.includes(ref)) keys.push(ref); + }; + const firstRefs = (f: FirstColumn): void => { + const outer = f.outerAlias ?? baseAlias; + add(`${outer}.${f.referenceHolder === "source" ? f.fkColumn : f.pkColumn}`); + for (const v of filterColRefs(f.filter)) add(v); + }; + const walk = (e: ViewExprNode): void => { + if (e.kind === "col") add(e.ref); + else if (e.kind === "first") firstRefs(e.column); + else if (e.kind !== "agg") exprChildren(e).forEach(walk); + }; + for (const c of spec.columns) { + if (c.kind === "computed") walk(c.expr); + else if (c.kind === "first") firstRefs(c); + } + return keys; +} + +/** The outer-row columns (correlated operands) a filter compares with. */ +function filterColRefs(f: ViewFilterClause | undefined, out: string[] = []): string[] { + if (f === undefined) return out; + if (f.kind === "and" || f.kind === "or") for (const c of f.clauses) filterColRefs(c, out); + else if (f.kind === "cmp" && isPlainObject(f.value) && (f.value as { kind?: unknown }).kind === "colRef") { + out.push((f.value as unknown as ColRef).ref); + } + return out; +} + +/** A resolved expression node's sub-expressions. */ +function exprChildren(e: ViewExprNode): ViewExprNode[] { + switch (e.kind) { + case "cmp": return [e.left, e.right]; + case "nullTest": case "not": return [e.arg]; + case "logic": case "coalesce": case "fn": case "call": return [...e.args]; + case "cast": return [e.arg]; + case "case": return [...(e.operand !== undefined ? [e.operand] : []), ...e.whens.flatMap((w) => [w.when, w.then]), ...(e.else !== undefined ? [e.else] : [])]; + default: return []; + } } // --------------------------------------------------------------------------- @@ -1907,6 +2195,8 @@ export function extractViewSpec( projection: MetaObject, root: MetaRoot, ctx: ExtractContext, + /** rc.21 part B (U15): `member` — a union member's body, which needs no view of its own. */ + options: { readonly member?: boolean } = {}, ): ViewSpec { // #213 — a write-through entity (FR-024 §7) IS its own base: stored fields SELECT // from the base alias (o.*), derived (origin.*) fields from the joins. A plain @@ -1915,27 +2205,40 @@ export function extractViewSpec( const base = writeThrough ? projection : baseEntityFor(projection, root); const usedAliases = new Set(); const baseAlias = shortAliasFor(base.name, usedAliases); - // The effective @filter (every level of an extends chain, supers first, ANDed). A write-through - // entity read-view is never filtered: a filtered replica breaks read-your-writes totality. + // C1: the EFFECTIVE @filter — every level of an extends chain, supers first, ANDed — so a + // projection extending a gated projection keeps the gate. const rawFilter = writeThrough ? undefined : effectiveProjectionFilter(projection); - // A filter key that is not a field of the projection may be a path of to-one hops from the base - // then a field of the entity they reach; the view joins along it (sharing an origin's join). + // G7 (joined) / entity-derived: the @filter keys that are paths of to-one hops from the base. const ownFieldNames = new Set(projection.fields().map((f) => f.name)); - const filterPaths = new Map(); + const filterPaths = new Map(); for (const key of filterKeysOf(rawFilter)) { if (ownFieldNames.has(key)) continue; - const reached = resolveFilterPath(base, key); - if (reached === undefined || typeof reached === "string") continue; - const joins = walkViaPath(`${base.resolutionKey()}.${reached.hops.join(".")}`, root, packageOf(projection), ctx); - if (joins.length > 0) filterPaths.set(key, { reached, joins }); + const path = resolveFilterPath(base, key); + if (path !== undefined && typeof path !== "string") filterPaths.set(key, path); } - const joinTree = buildJoinTree( - projection, base, root, usedAliases, baseAlias, ctx, [...filterPaths.values()].map((p) => p.joins), - ); - const selectSpec = buildSelectSpec(projection, base, joinTree, root, ctx, usedAliases); - const groupBy = buildGroupBy(selectSpec); + // rc.21 part B (U3, U4): an expression's path refs and an origin filter's path operands join too. + const refPaths = new Map(); + if (!writeThrough) { + for (const key of originPathKeys(projection)) { + if (ownFieldNames.has(key) || refPaths.has(key)) continue; + const path = resolveFilterPath(base, key); + if (path !== undefined && typeof path !== "string") refPaths.set(key, path); + } + } + const filterJoinPaths = [...filterPaths.values(), ...refPaths.values()] + .map((p) => walkViaPath(`${base.resolutionKey()}.${p.hops.join(".")}`, root, packageOf(projection), ctx)) + .filter((p) => p.length > 0); + const joinTree = buildJoinTree(projection, base, root, usedAliases, baseAlias, ctx, filterJoinPaths); + const pathRefs = new Map(); + for (const [key, path] of refPaths) { + const alias = aliasForHops(joinTree, path.hops); + if (alias === undefined) throw new Error(`Projection ${projection.name}: the path "${key}" did not join.`); + pathRefs.set(key, { alias, field: path.field as MetaField, entity: path.entity }); + } + const selectSpec = buildSelectSpec(projection, base, joinTree, root, ctx, usedAliases, pathRefs); + const groupBy = buildGroupBy(selectSpec, joinTree.baseAlias); - const view = viewName(projection, ctx); + const view = options.member === true ? projection.name : viewName(projection, ctx); warnOnJoinInflation(projection, view, joinTree, selectSpec); // #207 — a projection's OWN row-scope @filter lowers to the view's outer WHERE. @@ -1950,44 +2253,68 @@ export function extractViewSpec( const columnsByField = new Map( selectSpec.columns.map((c) => [c.fieldName, c] as const), ); + // G7: a base-entity field the view does not output is filtered on its base column; a + // projection field of the same name wins. Its int-backed enum map comes from the base field. const intMaps = new Map(intEnumMapsOf(projection)); const fieldsByKey = new Map(projection.fields().map((f) => [f.name, f] as const)); const reached = (key: string, f: MetaField, entity: MetaObject, alias: string): void => { columnsByField.set(key, filterColumnFor(key, f, entity, alias, root, usedAliases, ctx, projection.name)); fieldsByKey.set(key, f); - const map = f.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(f) : undefined; + const map = f.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(f) : undefined; if (map !== undefined) intMaps.set(key, map); }; - // A base-entity field the view does not output is filtered on its base column; a projection - // field of the same name wins. Only the keys the filter names are reached. + // I1: lazily — only the keys the filter names. Reaching every base field would inline (and + // refuse) a derived field the filter never mentions, and reserve aliases nobody reads. const baseFields = new Map(base.fields().map((f) => [f.name, f] as const)); for (const key of new Set(filterKeysOf(rawFilter))) { if (columnsByField.has(key) || filterPaths.has(key)) continue; const f = baseFields.get(key); if (f !== undefined) reached(key, f, base, joinTree.baseAlias); } - // A path key reads the reached entity's column on the alias its joins gave it. - for (const [key, { reached: target, joins }] of filterPaths) { - const alias = aliasForVia(joinTree, joins, target.entity.resolutionKey()); + // G7 (joined): a path key reads the reached entity's column on the alias its joins gave it. + for (const [key, path] of filterPaths) { + const alias = aliasForHops(joinTree, path.hops); if (alias === undefined) { throw new Error(`Projection ${projection.name}: view @filter path "${key}" did not join.`); } - reached(key, target.field as MetaField, target.entity, alias); + reached(key, path.field as MetaField, path.entity, alias); } where = resolveViewFilter(rawFilter, columnsByField, projection.name, intMaps, fieldsByKey); } } - // A subtype base reads only its rows of the shared table. + // TPH-scope: a subtype base reads only its rows of the shared table. const baseScope = writeThrough ? undefined : tphScopeOf(base, ctx); if (baseScope !== undefined) where = andClauses(where, tphScopeClause(baseScope, joinTree.baseAlias)); + // rc.21 part B (U14): one row per element of the base's jsonb array field. + const grainName = writeThrough ? undefined : projection.attr(OBJECT_PROJECTION_ATTR_GRAIN); + const grainField = typeof grainName === "string" ? base.fields().find((f) => f.name === grainName) : undefined; + if (typeof grainName === "string" && grainField === undefined) { + throw new Error(`Projection ${projection.name}: @grain "${grainName}" is not a field of "${base.name}".`); + } + // rc.21 part B (U15): the member bodies, each its own SELECT. ADR-0039: own — a union is ITS view. + const unionNames = writeThrough || options.member === true ? undefined : projection.ownAttr(OBJECT_PROJECTION_ATTR_UNION); + const members = unionNames === undefined ? [] : (Array.isArray(unionNames) ? unionNames : [unionNames]).map((name) => { + const member = resolveEntityRef(root, String(name), packageOf(projection)); + if (member === undefined) throw new Error(`Projection ${projection.name}: @union member "${String(name)}" does not resolve.`); + const spec = extractViewSpec(member, root, ctx, { member: true }); + const mine = selectSpec.columns.map((c) => c.dbColAlias).join(", "); + const theirs = spec.selectSpec.columns.map((c) => c.dbColAlias).join(", "); + if (mine !== theirs) { + throw new Error(`Projection ${projection.name}: @union member "${member.name}" has columns (${theirs}), not (${mine}).`); + } + return spec; + }); + return { viewName: view, joinTree, selectSpec, groupBy, ...(where !== undefined ? { where } : {}), + ...(grainField !== undefined ? { grain: { column: sourceColumnNameFor(grainField, ctx), alias: "mo_el" } } : {}), + ...(members.length > 0 ? { union: { all: projection.ownAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) === true, members } } : {}), }; } diff --git a/server/typescript/packages/codegen-ts/src/projection/report-sql.ts b/server/typescript/packages/codegen-ts/src/projection/report-sql.ts index 8a230e867d..a5300409ca 100644 --- a/server/typescript/packages/codegen-ts/src/projection/report-sql.ts +++ b/server/typescript/packages/codegen-ts/src/projection/report-sql.ts @@ -27,7 +27,7 @@ import { type MetaSegment, type RelativeStartOf, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import { desugarClause, encodeIntEnumFilterValue, @@ -183,7 +183,7 @@ function lowerFilterValue(raw: unknown, op: string, field: MetaField, key: strin return encodeIntEnumFilterValue( raw, op, - field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field) : undefined, + field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field) : undefined, key, where, ); diff --git a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts index 1db79acf6c..1e3ad93240 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts @@ -1,6 +1,7 @@ +import { DEFAULT_DB_SCHEMA_POSTGRES } from "@metaobjectsdev/metadata"; import { pgType, type SqlType } from "@metaobjectsdev/migrate-ts/expected"; import type { - JoinNode, ViewSpec, ViewFilterClause, ViewExprNode, ViewOrderKey, SelectColumn, ColRef, + JoinNode, ViewSpec, ViewFilterClause, ViewExprNode, ViewOrderKey, SelectColumn, ColRef, CastTarget, AggregateColumn, GrainColumn, } from "./view-spec.js"; import { isRelativeNow } from "./report-spec.js"; import { relativeNowSql } from "./time-sql.js"; @@ -54,7 +55,6 @@ export function viewRelation(entity: string, table: string, options: EmitOptions /** SQL literal for a filter value, dialect-aware for booleans. */ function sqlLiteral(value: unknown, dialect: EmitOptions["dialect"]): string { if (value === null || value === undefined) return "NULL"; - // A relative date is the dialect's shifted "now"; a base-row operand is its column. if (isRelativeNow(value)) return relativeNowSql(value.duration, value.temporal, dialect, value.startOf); if (isColRef(value)) return quoteRef(value.ref); if (typeof value === "number") return String(value); @@ -68,7 +68,7 @@ const FILTER_OP_SQL: Readonly> = { eq: "=", ne: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE", }; -/** The null-safe comparisons of a correlated origin `@filter`, per dialect (SQLite's IS / IS NOT are null-safe). */ +/** rc.19 correlated-filter's null-safe comparisons, per dialect (SQLite's IS / IS NOT are null-safe). */ function nullSafeOpSql(op: string, dialect: EmitOptions["dialect"]): string | undefined { if (op === "isDistinctFrom") return dialect === "sqlite" ? "IS NOT" : "IS DISTINCT FROM"; if (op === "isNotDistinctFrom") return dialect === "sqlite" ? "IS" : "IS NOT DISTINCT FROM"; @@ -116,7 +116,18 @@ function renderOrderKeys(keys: readonly ViewOrderKey[], alias: string): string { } /** Lower a resolved computed expression tree (#195 origin.computed) to a SQL scalar expression. */ +/** An inlined `first` correlates with the row it sits in; without that alias the subquery + * would compare against `.fk` and the view would fail only when it is applied. */ +function requireOuterAlias(column: Extract): string { + const outer = column.outerAlias; + if (outer === undefined || outer.length === 0) { + throw new Error(`view-ddl-emit: an inlined origin.first for "${column.fieldName}" has no outer alias to correlate with.`); + } + return outer; +} + function renderExpr(node: ViewExprNode, options: EmitOptions): string { + const dialect = options.dialect; switch (node.kind) { case "col": return quoteRef(node.ref); @@ -137,24 +148,118 @@ function renderExpr(node: ViewExprNode, options: EmitOptions): string { } case "coalesce": return `COALESCE(${node.args.map((a) => renderExpr(a, options)).join(", ")})`; - case "first": { - // An inlined `first` correlates with the row it sits in; without that alias the subquery - // would compare against `.fk` and the view would fail only when it is applied. - const outer = node.column.outerAlias; - if (outer === undefined || outer.length === 0) { - throw new Error(`view-ddl-emit: an inlined origin.first for "${node.column.fieldName}" has no outer alias to correlate with.`); - } - return firstSubquery(node.column, options, outer); - } + case "first": + return firstSubquery(node.column, options, requireOuterAlias(node.column)); case "now": - return relativeNowSql(node.value.duration, node.value.temporal, options.dialect, node.value.startOf); + return relativeNowSql(node.value.duration, node.value.temporal, dialect, node.value.startOf); case "case": { const arms = node.whens.map((w) => ` WHEN ${renderExpr(w.when, options)} THEN ${renderExpr(w.then, options)}`).join(""); const head = node.operand !== undefined ? `CASE ${renderExpr(node.operand, options)}` : "CASE"; const otherwise = node.else !== undefined ? ` ELSE ${renderExpr(node.else, options)}` : ""; return `(${head}${arms}${otherwise} END)`; } + case "fn": + return renderFn(node.name, node.args.map((a) => renderExpr(a, options)), node.args, dialect); + case "cast": + return `CAST(${renderExpr(node.arg, options)} AS ${castTypeSql(node.to, dialect)})`; + case "agg": + return aggregateSql(node.column, options); + case "call": { + if (dialect !== "postgres") { + throw new Error(`view-ddl-emit: origin.function "${node.name}" calls a database function, which SQLite does not have.`); + } + const fn = `${quoteIfNeeded(node.schema ?? DEFAULT_DB_SCHEMA_POSTGRES)}.${quoteIfNeeded(node.name)}`; + return `${fn}(${node.args.map((a) => renderExpr(a, options)).join(", ")})`; + } + } +} + +/** + * rc.21 part B (U11, U13): one function of the closed set, in the dialect's spelling. Where SQLite + * has no function of the same meaning it is spelled from ones it has; where it cannot be, the + * emitter refuses rather than write SQL that means something else. + */ +function renderFn(name: string, args: readonly string[], nodes: readonly ViewExprNode[], dialect: EmitOptions["dialect"]): string { + const pg = dialect === "postgres"; + const list = args.join(", "); + switch (name) { + case "lower": return `LOWER(${list})`; + case "upper": return `UPPER(${list})`; + case "btrim": return pg ? `BTRIM(${list})` : `TRIM(${list})`; + case "replace": return `REPLACE(${list})`; + case "nullif": return `NULLIF(${list})`; + case "length": return pg ? `CHAR_LENGTH(${list})` : `LENGTH(${list})`; + // fix round M9: SQLite's substr counts a non-positive start from the end, and has no left/right; + // these spellings give Postgres's meaning for every count (a negative one included). + case "substring": { + if (pg) return `SUBSTR(${list})`; + const [str, start, len] = args; + const from1 = len === undefined ? `SUBSTR(${str}, 1)` : `SUBSTR(${str}, 1, MAX((${len}) + (${start}) - 1, 0))`; + return `(CASE WHEN ${start} >= 1 THEN SUBSTR(${list}) ELSE ${from1} END)`; + } + case "left": + return pg ? `LEFT(${list})` + : `(CASE WHEN ${args[1]} >= 0 THEN SUBSTR(${args[0]}, 1, ${args[1]}) ELSE SUBSTR(${args[0]}, 1, MAX(LENGTH(${args[0]}) + (${args[1]}), 0)) END)`; + case "right": + return pg ? `RIGHT(${list})` + : `(CASE WHEN ${args[1]} > 0 THEN SUBSTR(${args[0]}, -(${args[1]})) WHEN ${args[1]} = 0 THEN '' ELSE SUBSTR(${args[0]}, 1 - (${args[1]})) END)`; + case "concat": + return pg ? `CONCAT(${list})` : `(${args.map((a) => `COALESCE(CAST(${a} AS TEXT), '')`).join(" || ")})`; + case "concatWs": { + if (pg) return `CONCAT_WS(${list})`; + // Each non-null value is prefixed with the separator, and the first separator dropped. + const [sep, ...rest] = args; + const joined = rest.map((a) => `COALESCE(${sep} || CAST(${a} AS TEXT), '')`).join(" || "); + return `(CASE WHEN ${sep} IS NULL THEN NULL ELSE SUBSTR(${joined}, LENGTH(${sep}) + 1) END)`; + } + case "splitPart": { + if (pg) return `SPLIT_PART(${list})`; + // SQLite has no split_part. The first part is spelled with instr/substr; any other is refused. + const n = nodes[2]; + if (n?.kind !== "lit" || n.value !== 1) { + throw new Error("view-ddl-emit: splitPart on SQLite is lowered only for the first part (a literal 1); SQLite has no split_part."); + } + const [str, delim] = args; + return `(CASE WHEN INSTR(${str}, ${delim}) = 0 THEN ${str} ELSE SUBSTR(${str}, 1, INSTR(${str}, ${delim}) - 1) END)`; + } + case "greatest": + case "least": { + if (pg) return `${name.toUpperCase()}(${list})`; + if (args.length === 1) return args[0]!; + // SQLite's scalar max/min return NULL if any argument is; Postgres's skip NULLs. Each slot + // falls back to the others, so the result is the max (min) of the non-null values, NULL + // only when every one is. + const slots = args.map((a, i) => `COALESCE(${[a, ...args.filter((_, j) => j !== i)].join(", ")})`); + return `${name === "greatest" ? "MAX" : "MIN"}(${slots.join(", ")})`; + } + } + throw new Error(`view-ddl-emit: unknown expression function "${name}".`); +} + +/** rc.21 part B (U12): the column type a cast names, in the dialect's spelling. */ +function castTypeSql(to: CastTarget, dialect: EmitOptions["dialect"]): string { + const pg = dialect === "postgres"; + // N1: a field's own column type is spelled by the table DDL's own function. + if (pg && to.column !== undefined) return pgType(to.column); + switch (to.subType) { + case "string": { + if (!pg) return "TEXT"; + const sp = to.spelling; + if (sp?.kind === "char") return `CHARACTER(${sp.length ?? 1})`; + if (sp?.kind === "varchar") return sp.length !== undefined ? `VARCHAR(${sp.length})` : "VARCHAR"; + return "TEXT"; + } + case "int": return pg ? "INTEGER" : "INTEGER"; + case "long": return pg ? "BIGINT" : "INTEGER"; + case "double": return pg ? "DOUBLE PRECISION" : "REAL"; + case "float": return pg ? "REAL" : "REAL"; + case "decimal": return "NUMERIC"; + case "boolean": return pg ? "BOOLEAN" : "INTEGER"; + case "date": return pg ? "DATE" : "TEXT"; + case "timestamp": return pg ? "TIMESTAMPTZ" : "TEXT"; + case "uuid": return pg ? "UUID" : "TEXT"; } + throw new Error(`view-ddl-emit: a cast to "${to.subType}" has no column type.`); } /** @@ -168,10 +273,11 @@ function renderFirst( options: EmitOptions, baseAlias: string, ): string { - return `${firstSubquery(c, options, baseAlias)} AS ${quoteIfNeeded(c.dbColAlias)}`; + return `${firstSubquery(c, options, c.outerAlias ?? baseAlias)} AS ${quoteIfNeeded(c.dbColAlias)}`; } -/** The correlated scalar subquery of an `origin.first`, keyed on the row at `baseAlias`. */ +/** origin.first's correlated scalar subquery, keyed on `baseAlias` (the view's base, or the + * alias an entity-derived field is reached on). */ function firstSubquery( c: Extract, options: EmitOptions, @@ -309,7 +415,7 @@ function sqliteCollectOuter(c: CollectColumn): string { const isCollect = (c: SelectColumn): c is CollectColumn => c.kind === "collectAgg" || c.kind === "collectObjectAgg"; -/** A column the declared type must win over, cast to it on Postgres (SQLite views are untyped). */ +/** bug `cast`: a column the declared type must win over, cast to it on Postgres (SQLite views are untyped). */ function cast(sql: string, to: SqlType | undefined, dialect: EmitOptions["dialect"]): string { return to === undefined || dialect !== "postgres" ? sql : `CAST(${sql} AS ${pgType(to)})`; } @@ -322,39 +428,12 @@ function renderColumn(c: SelectColumn, options: EmitOptions, baseAlias: string): return `${cast(`${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`, c.castTo, dialect)} AS ${alias}`; } - if (c.kind === "aggregate") { - const src = `${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`; - // aggregate — use DISTINCT for count() over joined PKs to avoid join inflation. - // A scoping @filter renders as postgres `FILTER (WHERE …)`; sqlite (no aggregate - // FILTER pre-3.30) uses the portable `CASE WHEN … END` argument form. - const cond = c.filter ? renderFilterCond(c.filter, options) : undefined; - if (c.agg === "count") { - if (cond && dialect === "sqlite") return `COUNT(DISTINCT CASE WHEN ${cond} THEN ${src} END) AS ${alias}`; - if (cond) return `COUNT(DISTINCT ${src}) FILTER (WHERE ${cond}) AS ${alias}`; - return `COUNT(DISTINCT ${src}) AS ${alias}`; - } - const fn = c.agg.toUpperCase(); - if (cond && dialect === "sqlite") return `${fn}(CASE WHEN ${cond} THEN ${src} END) AS ${alias}`; - if (cond) return `${fn}(${src}) FILTER (WHERE ${cond}) AS ${alias}`; - return `${fn}(${src}) AS ${alias}`; + if (c.kind === "aggregate" || c.kind === "predicateAgg") { + return `${aggregateSql(c, options)} AS ${alias}`; } - if (c.kind === "predicateAgg") { - // #195 any/all. The phantom-row guard (joined.pk IS NOT NULL) EXCLUDES null-extended - // LEFT-JOIN non-matches, so the empty-related-set pins hold: any=false / all=true. - const pred = renderFilterCond(c.pred, options); - const guard = `${c.sourceAlias}.${quoteIfNeeded(c.joinedPkColumn)} IS NOT NULL`; - if (dialect === "sqlite") { - // No boolean aggregates: MAX≡bool_or, MIN≡bool_and over 1/0. The outer CASE yields - // NULL (not 0) for phantom rows so MIN/MAX ignore them — the COALESCE default then - // supplies the empty-set pin (0 for any, 1 for all). - const fn = c.quant === "any" ? "MAX" : "MIN"; - const empty = c.quant === "any" ? "0" : "1"; - return `COALESCE(${fn}(CASE WHEN ${guard} THEN (CASE WHEN ${pred} THEN 1 ELSE 0 END) END), ${empty}) AS ${alias}`; - } - const fn = c.quant === "any" ? "bool_or" : "bool_and"; - const empty = c.quant === "any" ? "FALSE" : "TRUE"; - return `COALESCE(${fn}(${pred}) FILTER (WHERE ${guard}), ${empty}) AS ${alias}`; + if (c.kind === "element") { + return `${grainElementSql(c, options)} AS ${alias}`; } if (c.kind === "collectAgg") { @@ -411,6 +490,60 @@ function renderColumn(c: SelectColumn, options: EmitOptions, baseAlias: string): return renderFirst(c, options, baseAlias); } +/** A scalar aggregate or an any/all column's expression (no alias): a column, or (U13) read by a computed. */ +function aggregateSql(c: AggregateColumn, options: EmitOptions): string { + const dialect = options.dialect; + if (c.kind === "aggregate") { + const src = `${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`; + // aggregate — use DISTINCT for count() over joined PKs to avoid join inflation. + // A scoping @filter renders as postgres `FILTER (WHERE …)`; sqlite (no aggregate + // FILTER pre-3.30) uses the portable `CASE WHEN … END` argument form. + const cond = c.filter ? renderFilterCond(c.filter, options) : undefined; + if (c.agg === "count") { + if (cond && dialect === "sqlite") return `COUNT(DISTINCT CASE WHEN ${cond} THEN ${src} END)`; + if (cond) return `COUNT(DISTINCT ${src}) FILTER (WHERE ${cond})`; + return `COUNT(DISTINCT ${src})`; + } + const fn = c.agg.toUpperCase(); + if (cond && dialect === "sqlite") return `${fn}(CASE WHEN ${cond} THEN ${src} END)`; + if (cond) return `${fn}(${src}) FILTER (WHERE ${cond})`; + return `${fn}(${src})`; + } + // #195 any/all. The phantom-row guard (joined.pk IS NOT NULL) EXCLUDES null-extended + // LEFT-JOIN non-matches, so the empty-related-set pins hold: any=false / all=true. + const pred = renderFilterCond(c.pred, options); + const guard = `${c.sourceAlias}.${quoteIfNeeded(c.joinedPkColumn)} IS NOT NULL`; + if (dialect === "sqlite") { + // No boolean aggregates: MAX≡bool_or, MIN≡bool_and over 1/0. The outer CASE yields + // NULL (not 0) for phantom rows so MIN/MAX ignore them — the COALESCE default then + // supplies the empty-set pin (0 for any, 1 for all). + const fn = c.quant === "any" ? "MAX" : "MIN"; + const empty = c.quant === "any" ? "0" : "1"; + return `COALESCE(${fn}(CASE WHEN ${guard} THEN (CASE WHEN ${pred} THEN 1 ELSE 0 END) END), ${empty})`; + } + const fn = c.quant === "any" ? "bool_or" : "bool_and"; + const empty = c.quant === "any" ? "FALSE" : "TRUE"; + return `COALESCE(${fn}(${pred}) FILTER (WHERE ${guard}), ${empty})`; +} + +/** The alias of a `@grain` view's element relation (its `value` and position). */ +const GRAIN_ALIAS = "mo_el"; + +/** rc.21 part B (U14): a grain element member, or the element's 1-based position. */ +function grainElementSql(c: GrainColumn, options: EmitOptions): string { + const pg = options.dialect === "postgres"; + if (c.member === undefined) { + // WITH ORDINALITY is a bigint; a field.int position is cast to it. + if (!pg) return `(${GRAIN_ALIAS}.key + 1)`; + return c.castTo.kind === "integer" && c.castTo.bits === 64 ? `${GRAIN_ALIAS}.ordinality` : `CAST(${GRAIN_ALIAS}.ordinality AS ${pgType(c.castTo)})`; + } + const key = c.member.replace(/'/g, "''"); + if (!pg) return `json_extract(${GRAIN_ALIAS}.value, '$.${key.replace(/"/g, '""')}')`; + const text = `(${GRAIN_ALIAS}.value ->> '${key}')`; + return c.castTo.kind === "text" && c.castTo.maxLength === undefined && c.castTo.variant === undefined + ? text : `CAST(${text} AS ${pgType(c.castTo)})`; +} + /** A TPH scope's comparison after its column: ` = v` for one value, ` IN (a, b)` for several. */ export function tphScopeSql(values: readonly (string | number)[], literal: (v: string | number) => string): string { return values.length === 1 ? ` = ${literal(values[0]!)}` : ` IN (${values.map(literal).join(", ")})`; @@ -452,10 +585,37 @@ function renderJoin( } export function emitViewDdl(spec: ViewSpec, options: EmitOptions): string { + // rc.21 part B (U15): the member bodies follow this one, UNIONed. Each reads its own base. + const members = (spec.union?.members ?? []).map((m) => { + const table = options.joinTables[m.joinTree.baseEntity]; + if (table === undefined) throw new Error(`view-ddl-emit: no table name registered for union member base "${m.joinTree.baseEntity}".`); + return emitViewBody(m, { ...options, baseTableName: table }); + }); + const joiner = spec.union?.all === true ? "\n UNION ALL\n" : "\n UNION\n"; + const body = [emitViewBody(spec, options), ...members].join(joiner); + if (options.bodyOnly) return body; + return `CREATE VIEW ${quoteIfNeeded(spec.viewName)} AS +${body};`; +} + +/** A @grain view's array column on its base row. */ +function grainCol(spec: ViewSpec): string { + return `${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain!.column)}`; +} + +/** One SELECT of a view: its columns, base, grain, joins, WHERE and GROUP BY. */ +function emitViewBody(spec: ViewSpec, options: EmitOptions): string { const cols = spec.selectSpec.columns .map((c) => " " + renderColumn(c, options, spec.joinTree.baseAlias)) .join(",\n"); - const fromClause = ` FROM ${viewRelation(spec.joinTree.baseEntity, options.baseTableName, options)} ${spec.joinTree.baseAlias}`; + // rc.21 part B (U14): a @grain view reads one row per element of the base row's jsonb array. + const grain = spec.grain === undefined ? "" + : options.dialect === "postgres" + // fix round M3: a row whose value is JSON null, an object or a scalar has no element (rather than + // failing the whole query on Postgres, or iterating an object's keys on SQLite). + ? ` CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(${grainCol(spec)}) = 'array' THEN ${grainCol(spec)} END) WITH ORDINALITY AS ${GRAIN_ALIAS}(value, ordinality)` + : ` CROSS JOIN json_each(CASE WHEN json_type(${grainCol(spec)}) = 'array' THEN ${grainCol(spec)} END) ${GRAIN_ALIAS}`; + const fromClause = ` FROM ${viewRelation(spec.joinTree.baseEntity, options.baseTableName, options)} ${spec.joinTree.baseAlias}${grain}`; const joinsClause = spec.joinTree.joins .map((j) => renderJoin(j, spec.joinTree.baseAlias, options)) .join("\n"); @@ -487,8 +647,5 @@ ${spec.selectSpec.columns FROM ( ${grouped} ) ${GROUPED_ALIAS}`; - - if (options.bodyOnly) return body; - return `CREATE VIEW ${quoteIfNeeded(spec.viewName)} AS -${body};`; + return body; } diff --git a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts index 598c2736d6..c86b01c0c0 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts @@ -18,18 +18,19 @@ export interface JoinNode { readonly pkColumn: string; /** Which side of this hop physically holds the FK: the parent (source) or the child (target). */ readonly referenceHolder: "source" | "target"; - /** Always `left`: a generated view join never drops a base row. A view that requires the - * related row filters on it (`@filter: { ".id": { isNull: false } }`). */ + /** rc.19 R62 — always `left`: a generated view join never drops a base row. A view that + * requires the related row filters on it (`@filter: { ".id": { isNull: false } }`). */ readonly joinType: "left"; - /** The target is a TPH subtype (or an abstract level) sharing its base's table, so the join - * keeps only its rows (`AND . = `, or `IN (…)` for several). */ + /** TPH-scope: the target is a TPH subtype sharing its base's table, so the join keeps only + * its rows (`AND . = ` on the ON clause). */ readonly tphScope?: TphScope; /** Child joins. */ readonly children: readonly JoinNode[]; } -/** The rows of a TPH level on its base's shared table: the discriminator column and the values it - * stores for the level (one for a concrete leaf; every concrete subtype beneath an abstract one). */ +/** A TPH level's rows of the shared table: the discriminator column and the values stored for + * it — a concrete subtype's own and those of every concrete subtype beneath it (an abstract + * intermediate level has only the latter). */ export interface TphScope { readonly column: string; readonly values: readonly (string | number)[]; @@ -79,20 +80,41 @@ export type ViewExprNode = | { readonly kind: "not"; readonly arg: ViewExprNode } | { readonly kind: "logic"; readonly op: "and" | "or"; readonly args: readonly ViewExprNode[] } | { readonly kind: "coalesce"; readonly args: readonly ViewExprNode[] } - // An entity's origin.first, inlined where a projection reaches the entity: its correlated - // scalar subquery, keyed on `column.outerAlias`. + // entity-derived: an entity's origin.first, inlined where a projection reaches the entity — + // its correlated scalar subquery, keyed on `column.outerAlias`. | { readonly kind: "first"; readonly column: FirstColumn } - // The current instant shifted by an ISO duration, of the kind of the field it is compared with. + // rc.19 `now`: the current instant shifted, of the kind of the field it is compared with. | { readonly kind: "now"; readonly value: RelativeNow } - // Searched (each `when` a predicate) or, with `operand`, simple (each `when` a value) CASE. + // rc.19 `case`: searched (each `when` a predicate) or, with `operand`, simple (each `when` a value). | { readonly kind: "case"; readonly operand?: ViewExprNode; readonly whens: readonly { readonly when: ViewExprNode; readonly then: ViewExprNode }[]; readonly else?: ViewExprNode; - }; + } + // rc.21 part B (U11, U13): one of the closed function set beside coalesce (lower, upper, btrim, + // splitPart, concat, concatWs, substring, replace, left, right, length, nullif, greatest, least). + | { readonly kind: "fn"; readonly name: string; readonly args: readonly ViewExprNode[] } + // rc.21 part B (U12): a cast to a field subtype's column type (`spelling`: a text @dbColumnType). + | { readonly kind: "cast"; readonly arg: ViewExprNode; readonly to: CastTarget } + // rc.21 part B (U13): a scalar origin.aggregate of the projection, read on the grouped row. + | { readonly kind: "agg"; readonly column: AggregateColumn } + // rc.21 part B (U10): a call of a database function the project owns (origin.function). + | { readonly kind: "call"; readonly schema?: string; readonly name: string; readonly args: readonly ViewExprNode[] }; + +/** A cast's target: a field subtype, and (for a string) a text @dbColumnType spelling. */ +export interface CastTarget { + readonly subType: string; + readonly spelling?: { readonly kind: "text" | "varchar" | "char"; readonly length?: number }; + /** rc.21 part B (N1): the full column type, when the cast is to a field's own column (an + * `origin.function` call): the SqlType `meta migrate` gives that field's table column. */ + readonly column?: SqlType; +} -/** A filter operand that is a column of the base row (`alias.column`), for a correlated origin `@filter`. */ +/** An aggregate column a computed expression may read (U13): a scalar reduce or an any/all. */ +export type AggregateColumn = Extract; + +/** rc.19 correlated-filter: a filter operand that is a column of the base row (`alias.column`). */ export interface ColRef { readonly kind: "colRef"; readonly ref: string; @@ -106,13 +128,14 @@ export interface ViewOrderKey { /** One column of the SELECT list. */ export type SelectColumn = + | GrainColumn | { readonly kind: "passthrough"; readonly fieldName: string; // projection field name readonly dbColAlias: string; // SQL output column name readonly sourceAlias: string; // join alias of the source readonly sourceColumn: string; // source table's column name (already strategy-applied) - /** The declared field's column type when it differs from the source's (`@convert`). Postgres casts to it. */ + /** bug `cast`: the declared field's column type when it differs from the source's (`@convert`). Postgres casts to it. */ readonly castTo?: SqlType; } | { @@ -186,7 +209,7 @@ export type SelectColumn = readonly fieldName: string; readonly dbColAlias: string; readonly expr: ViewExprNode; - /** The declared field's column type, for a bare NULL that would otherwise read as text. Postgres casts to it. */ + /** bug `cast`: the declared field's column type, for a bare NULL that would otherwise read as text. Postgres casts to it. */ readonly castTo?: SqlType; } | { @@ -208,20 +231,30 @@ export type SelectColumn = /** Optional scoping filter over the child entity (refs use `childAlias`). */ readonly filter?: ViewFilterClause; /** - * The hops of a multi-hop `@via` after the first, INNER-joined inside the subquery (the - * selected row must exist along the whole path). `childEntity`/`childAlias` are then the - * FIRST hop's (the one correlated to the base), and `sourceColumn`, `childPkColumn`, - * `orderBy` and `filter` are over the LAST join's alias. Absent for one hop. + * first-multihop: the hops of a multi-hop `@via` after the first, INNER-joined inside the + * subquery (the selected row must exist along the whole path). `childEntity`/`childAlias` + * are then the FIRST hop's (the one correlated to the base), and `sourceColumn`, + * `childPkColumn`, `orderBy` and `filter` are over the LAST join's alias. Absent for one hop. */ readonly innerJoins?: readonly FirstInnerJoin[]; - /** - * Set when the subquery is inlined in an expression or filter rather than selected as a - * column: the alias of the row it correlates to (a reached entity, not the view's base). - */ + /** entity-derived: the alias the correlation keys on, when it is not the view's base alias. */ readonly outerAlias?: string; }; -/** The `origin.first` column of a select list. */ +/** + * rc.21 part B (U14): a member of the array element a `@grain` projection's row is, read from the + * element (`->>` on Postgres, `json_extract` on SQLite) and cast to the member's column type; or, + * with `member` undefined, the element's 1-based position (`@grainOrdinal`). + */ +export interface GrainColumn { + readonly kind: "element"; + readonly fieldName: string; + readonly dbColAlias: string; + readonly member?: string; + readonly castTo: SqlType; +} + +/** An `origin.first` column. */ export type FirstColumn = Extract; /** One inner join of a multi-hop `origin.first` subquery, from the alias before it. */ @@ -254,4 +287,15 @@ export interface ViewSpec { * `@filter`, which scopes the rows a single aggregate spans. Undefined = no filter. */ readonly where?: ViewFilterClause; + /** + * rc.21 part B (U14): one row per element of the base row's jsonb array column `column` + * (`CROSS JOIN LATERAL jsonb_array_elements(...) WITH ORDINALITY` / `json_each`), its element + * and position under `alias`. A row with no element is not returned. + */ + readonly grain?: { readonly column: string; readonly alias: string }; + /** + * rc.21 part B (U15): the bodies UNIONed after this one, each the same shape; `all` keeps + * duplicate rows (UNION ALL), else they are removed (UNION). + */ + readonly union?: { readonly all: boolean; readonly members: readonly ViewSpec[] }; } diff --git a/server/typescript/packages/codegen-ts/src/reference/callable.ts b/server/typescript/packages/codegen-ts/src/reference/callable.ts index 70311ab7c3..2faeaf9c8a 100644 --- a/server/typescript/packages/codegen-ts/src/reference/callable.ts +++ b/server/typescript/packages/codegen-ts/src/reference/callable.ts @@ -32,6 +32,7 @@ import { type Generator, type GeneratorFactory, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, } from "@metaobjectsdev/codegen-ts/engine"; @@ -56,7 +57,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene generate: perEntity(async (entity, ctx) => { return { path: entityOutputPath( - ctx.config.outputLayout ?? "flat", + ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.callable.ts`, ), diff --git a/server/typescript/packages/codegen-ts/src/reference/entity.ts b/server/typescript/packages/codegen-ts/src/reference/entity.ts index ced0ea9be7..6d3c2234c6 100644 --- a/server/typescript/packages/codegen-ts/src/reference/entity.ts +++ b/server/typescript/packages/codegen-ts/src/reference/entity.ts @@ -56,6 +56,7 @@ import { hasWritableRdbSource, formatTs, ownedRuntimeImport, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, namesRef, namesConstArg, @@ -186,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), content: await formatTs(renderEntity(entity, renderContext, { allowlists })), }; }); diff --git a/server/typescript/packages/codegen-ts/src/reference/names.ts b/server/typescript/packages/codegen-ts/src/reference/names.ts index a5fada496d..a0a6ec6fad 100644 --- a/server/typescript/packages/codegen-ts/src/reference/names.ts +++ b/server/typescript/packages/codegen-ts/src/reference/names.ts @@ -32,6 +32,7 @@ // same functionality. import { crossEntitySpecifier, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, namesArtifactSuperOf, resolveObjectNames, @@ -66,7 +67,7 @@ export function namesFile(opts?: NamesFileOpts): Generator { // routesFileHono already uses via emitsHonoRoutes/includeHonoRoutes. emitsNames: true, generate: (ctx: GenContext): EmittedFile[] => { - const layout = ctx.config.outputLayout ?? "flat"; + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const extStyle = ctx.config.extStyle ?? "js"; // The strategy lives on the RENDER CONTEXT, not on ResolvedGenConfig — `ctx.config` // carries outDir/extStyle/dbImport/dialect and nothing about naming. diff --git a/server/typescript/packages/codegen-ts/src/reference/queries.ts b/server/typescript/packages/codegen-ts/src/reference/queries.ts index 6933c4c227..8d03e08142 100644 --- a/server/typescript/packages/codegen-ts/src/reference/queries.ts +++ b/server/typescript/packages/codegen-ts/src/reference/queries.ts @@ -44,6 +44,7 @@ import { isWriteThrough, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, GENERATED_EDIT_NOTE, @@ -171,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat } claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.queries.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), content: await formatTs(renderQueries(entity, ctx.renderContext)), }; }), diff --git a/server/typescript/packages/codegen-ts/src/reference/report-export.ts b/server/typescript/packages/codegen-ts/src/reference/report-export.ts index a192742d34..77ec25579c 100644 --- a/server/typescript/packages/codegen-ts/src/reference/report-export.ts +++ b/server/typescript/packages/codegen-ts/src/reference/report-export.ts @@ -27,6 +27,7 @@ import { GENERATED_EDIT_NOTE, GENERATED_HEADER, effectivePackage, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, formatTs, isCredentialField, @@ -239,7 +240,7 @@ export function reportExport(opts?: ReportExportOpts): Generator { name: "report-export", emitsReportExport: true, generate: async (ctx: GenContext): Promise => { - const layout = ctx.config.outputLayout ?? "flat"; + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const extStyle = ctx.config.extStyle ?? "js"; const selfTarget = ctx.renderContext?.selfTarget; if (selfTarget === undefined) throw new Error("report-export: no render context (run it through runGen)."); diff --git a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts index cede0f74a2..10910a4297 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts @@ -64,6 +64,7 @@ import { knownFieldsLine, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, entityModuleSpecifier, @@ -353,7 +354,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) }; return { path: entityOutputPath( - ctx.config.outputLayout ?? "flat", + ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), diff --git a/server/typescript/packages/codegen-ts/src/reference/routes.ts b/server/typescript/packages/codegen-ts/src/reference/routes.ts index 1cd10a6824..16837743da 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes.ts @@ -74,6 +74,7 @@ import { knownFieldsLine, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, crossEntitySpecifier, @@ -666,7 +667,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, @@ -768,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.routes.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), }; }); diff --git a/server/typescript/packages/codegen-ts/src/render-context.ts b/server/typescript/packages/codegen-ts/src/render-context.ts index 45aef1f778..db5bf1a00c 100644 --- a/server/typescript/packages/codegen-ts/src/render-context.ts +++ b/server/typescript/packages/codegen-ts/src/render-context.ts @@ -8,7 +8,7 @@ import { normalizeTimestampMode } from "./dialect-module.js"; import type { PkInfo } from "./pk-resolver.js"; import type { RelationMap } from "./relation-resolver.js"; import type { ColumnNamingStrategy } from "./metaobjects-config.js"; -import type { OutputLayout, ResolvedTarget } from "./import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, type OutputLayout, type ResolvedTarget } from "./import-path.js"; import { toCamelCase, variableNameFromEntity } from "./naming.js"; /** @@ -117,7 +117,7 @@ export interface RenderContext { apiPrefix: string; /** Whether abstract entities emit their shape artifact (type-only interface / value-object file). Defaults to true. Instance/write artifacts are never emitted for abstract entities regardless. */ emitAbstractShapes: boolean; - /** Output layout mode: "flat" (default) — all files in outDir; "package" — sub-paths from entity metadata package. */ + /** Output layout mode: "package" (default, R63) — sub-paths from entity metadata package; "flat" — all files in outDir. */ outputLayout: OutputLayout; /** * §A6 — whether the run emits the `Names` artifact (the runner aggregates the @@ -225,7 +225,7 @@ export function withExtIfRelative(spec: string, style: ExtStyle): string { /** Thin factory; applies sensible defaults for fields the caller may omit. */ export function makeRenderContext(opts: RenderContextInput): RenderContext { - const outputLayout = opts.outputLayout ?? "flat"; + const outputLayout = opts.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const defaultTarget: ResolvedTarget = opts.selfTarget ?? { name: "default", outDir: opts.outDir, diff --git a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts index 84bb19b238..30359d489b 100644 --- a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts @@ -3,17 +3,17 @@ // // import { sql } from "drizzle-orm"; // import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -// import type { PhaseSummaryArgs } from "./PhaseSummaryArgs.js"; -// import { PhaseSummarySchema, type PhaseSummary } from "./PhaseSummary.js"; +// import type { StageSummaryArgs } from "./StageSummaryArgs.js"; +// import { StageSummarySchema, type StageSummary } from "./StageSummary.js"; // -// export async function callPhaseSummary( +// export async function callStageSummary( // db: PgDatabase>, -// args: PhaseSummaryArgs, -// ): Promise { +// args: StageSummaryArgs, +// ): Promise { // const r = await db.execute( -// sql`SELECT * FROM fn_phase_summary(${args.caseId}, ${args.asOfDate})`, +// sql`SELECT * FROM fn_stage_summary(${args.consignmentId}, ${args.asOfDate})`, // ); -// return r.rows.map((row) => PhaseSummarySchema.parse(row)); +// return r.rows.map((row) => StageSummarySchema.parse(row)); // } // // Zero-argument procs (no @parameterRef) emit a no-args version that drops the diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 8d8d90116a..42b830eebc 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -26,17 +26,22 @@ import { dialectModule } from "../dialect-module.js"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "../names.js"; -import { resolveTableSchema, resolveIndexName } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, resolveIndexName, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "../pg-identifier.js"; +import { intValueMapOf } from "../enum-meta.js"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "../tph.js"; import { flattenedMembersOf } from "../flattened.js"; import { effectivePackage } from "../docs-paths.js"; import { foreignKeyIndexesOf, storedIndexName } from "../foreign-key-indexes.js"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -186,7 +191,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -200,16 +205,31 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -218,6 +238,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -303,8 +325,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -443,6 +469,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -812,6 +854,60 @@ function renderColumn( : columnLine; } +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): CheckEntry[] | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: CheckEntry[] = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + const name = typeof declared === "string" && declared.length > 0 + ? declared + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); + }); + return out; +} + /** * Drizzle's identity options for what the model declares, the same two meta migrate writes * (`SEQUENCE NAME … START WITH n`): `{ name: "Old_Id_seq", startWith: 1000 }`, or nothing. diff --git a/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts b/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts index c80396cd8d..a8a6f03a45 100644 --- a/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts +++ b/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts @@ -140,8 +140,9 @@ export interface EntityUiDescriptor { * when you specifically want an object's own pluralized name, never to build an address. */ export function resourcePath(entity: MetaData): string { - // One rule, every object kind: its declared @collectionName or the configured pluralizer's - // output, snake_cased; with neither, snake_case then pluralize, as every port serves it. + // One rule, every object kind and every port (collection-segments.json): a declared + // @collectionName, else a configured pluralizer, snake_cased; with neither, rc.18's + // snake_case-then-pluralize, byte-identical (rc.19 R57, fix round I3). return `/${collectionSegment(entity)}`; } diff --git a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts index 94de947410..343fe8c76f 100644 --- a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "../column-mapper.js"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,37 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts b/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts index 57708d764a..99c6eee937 100644 --- a/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts +++ b/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts @@ -23,6 +23,7 @@ import { enumValues } from "../enum-meta.js"; import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "../render-context.js"; import { httpRuntimeSpecifier } from "../owned-runtime.js"; +import { DEFAULT_OUTPUT_LAYOUT } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; /** @@ -31,7 +32,7 @@ import { effectivePackage } from "../docs-paths.js"; * (`owned-runtime.ts`). Absent `ctx`, or with no `httpRuntimeImport`, the package: the * byte-identical default. */ -const PACKAGE_DEFAULT = { outputLayout: "flat", extStyle: "none" } as const; +const PACKAGE_DEFAULT = { outputLayout: DEFAULT_OUTPUT_LAYOUT, extStyle: "none" } as const; function allowlistTypesFrom(entity: MetaObject, ctx: RenderContext | undefined): string { return httpRuntimeSpecifier("allowlists", ctx ?? PACKAGE_DEFAULT, effectivePackage(entity)); diff --git a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts index 5a23a808aa..c5dfad7e02 100644 --- a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts @@ -25,6 +25,10 @@ import { type FieldNames, type KeyNames, type ObjectNames, type SourceNames, } from "../names.js"; +/** The JSDoc on a flattened field's own `column`, which names no column of the table. */ +export const FLATTENED_COLUMN_DEPRECATION = + "/** @deprecated a flattened field has no column of its own; use members..column */"; + /** The physical-name alias keys, in the metamodel's own order. */ const PHYSICAL_NAME_ALIASES = [...PHYSICAL_NAME_ATTR_BY_KIND.values()] as const; diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-file.ts b/server/typescript/packages/codegen-ts/src/templates/routes-file.ts index c2948805ee..973ccca11c 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-file.ts @@ -592,7 +592,7 @@ function renderTphRoutesFile( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: "/" + segment, diff --git a/server/typescript/packages/codegen-ts/src/templates/value-object-import.ts b/server/typescript/packages/codegen-ts/src/templates/value-object-import.ts index 2d417d38f6..a065fc97a4 100644 --- a/server/typescript/packages/codegen-ts/src/templates/value-object-import.ts +++ b/server/typescript/packages/codegen-ts/src/templates/value-object-import.ts @@ -12,7 +12,7 @@ import { posix } from "node:path"; import type { MetaData } from "@metaobjectsdev/metadata"; import { effectivePackage } from "../docs-paths.js"; -import { entityModuleSpecifier, entityOutputPath } from "../import-path.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityModuleSpecifier, entityOutputPath } from "../import-path.js"; import { localTypeName, withExt, type ExtStyle, type RenderContext } from "../render-context.js"; /** A value object's type as a file imports it: `name`, the local binding the file uses; @@ -59,7 +59,8 @@ export function valueObjectImport( if (ctx && ctx.selfTarget.name !== ctx.entityModuleTarget.name) { return { name, exported, specifier: entityModuleSpecifier(ctx.selfTarget, ctx.entityModuleTarget, pkg, exported, extStyle) }; } - const layout = ctx ? ctx.entityModuleTarget.outputLayout : "flat"; + // rc.19 fix round 2 (N2): a ctx-less call uses the default layout, as every other fallback does. + const layout = ctx ? ctx.entityModuleTarget.outputLayout : DEFAULT_OUTPUT_LAYOUT; const modulePath = entityOutputPath(layout, pkg, exported); // extension-less let rel = posix.relative(posix.dirname(fromPath), modulePath); if (!rel.startsWith(".")) rel = `./${rel}`; diff --git a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts index 8b1c6b400c..9afe663e0d 100644 --- a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts +++ b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts @@ -712,6 +712,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); diff --git a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts index 34adfe33f2..8c29f20f87 100644 --- a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts +++ b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts @@ -41,7 +41,7 @@ async function gen(opts: { baseline?: BaselineMode; dryRun?: boolean } = {}) { outDir: outDir(), extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts b/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts index dcb98f7c21..d131e5927d 100644 --- a/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts @@ -50,7 +50,7 @@ describe("ai LlmCall codegen — abstract base + concrete entity", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: loaded.root, diff --git a/server/typescript/packages/codegen-ts/test/api-model.test.ts b/server/typescript/packages/codegen-ts/test/api-model.test.ts index 157e4a09c5..0e3984954e 100644 --- a/server/typescript/packages/codegen-ts/test/api-model.test.ts +++ b/server/typescript/packages/codegen-ts/test/api-model.test.ts @@ -36,7 +36,7 @@ const AUTH_TPH = [ "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], diff --git a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts index 17ae3d42d7..da6c7fdbe8 100644 --- a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts @@ -82,7 +82,7 @@ async function genAndCompile(dialect: Dialect): Promise true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts index a0ea791134..5569dae961 100644 --- a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts @@ -86,7 +86,7 @@ async function genAndCompile( const root = await loadRoot(pkField, identity); const dir = mkdtempSync(join(import.meta.dir, "tmp-assigned-pk-")); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -99,7 +99,7 @@ async function genAndCompile( loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts b/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts new file mode 100644 index 0000000000..fd5f0fe80b --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts @@ -0,0 +1,110 @@ +// The default outputLayout is "flat"; "package" is the opt-in that places modules under +// //. Imports through the generated barrel (index.ts) are unaffected: the +// barrel exports the same names in both layouts, and a consumer importing from it type-checks +// against either. Pinned here because the CHANGELOG's upgrade note says so. + +import { describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import ts from "typescript"; +import { InMemoryStringSource, MetaDataLoader, type MetaObject } from "@metaobjectsdev/metadata"; +import { entityFile } from "../src/generators/entity-file.js"; +import { queriesFile } from "../src/generators/queries-file.js"; +import { barrel } from "../src/generators/barrel.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import { resolveTargets } from "../src/metaobjects-config.js"; +import type { EmittedFile, GenContext } from "../src/generator.js"; +import type { OutputLayout } from "../src/import-path.js"; + +const pk = { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }; +const MODEL = { "metadata.root": { package: "acme::blog", children: [ + { "object.entity": { name: "Author", children: [ + { "source.rdb": { "@table": "authors" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "name", "@required": true } }, + pk, + ] } }, + { "object.entity": { name: "Post", children: [ + { "source.rdb": { "@table": "posts" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "authorId", "@required": true } }, + { "field.string": { name: "title", "@required": true } }, + pk, + { "identity.reference": { name: "author", "@fields": "authorId", "@references": "Author" } }, + ] } }, +] } }; + +async function generate(layout: OutputLayout | undefined): Promise { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + // The layout a project gets when it declares none is what resolveTargets resolves. + const outputLayout = resolveTargets({ outDir: "/x", dbImport: "~/db", dialect: "sqlite", generators: [], + ...(layout !== undefined ? { outputLayout: layout } : {}) } as never).default!.outputLayout; + const renderContext = makeRenderContext({ outputLayout, + dialect: "sqlite", loadedRoot: root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(root), relationMap: buildRelationMap(root), + }); + const genCtx = (g: { filter?: (e: MetaObject) => boolean }): GenContext => ({ + entities: root.objects(), loadedRoot: root, matches: (e) => g.filter?.(e) ?? true, projectRoot: "/x", + config: { outputLayout, outDir: "/x", extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, + renderContext, warn: () => {}, + }); + const generators = [entityFile({ allowlists: false }), queriesFile(), barrel()]; + return (await Promise.all(generators.map((g) => g.generate(genCtx(g))))).flat(); +} + +const CONSUMER = ` +import { type Author, type Post, authors, posts } from "./generated"; +export const tables = [authors, posts]; +export function title(p: Post, a: Author): string { return p.title + " by " + a.name; } +`; + +function compile(files: EmittedFile[]): string[] { + const dir = mkdtempSync(join(import.meta.dir, "tmp-barrel-layout-")); + try { + for (const f of files) { + mkdirSync(dirname(join(dir, "generated", f.path)), { recursive: true }); + writeFileSync(join(dir, "generated", f.path), f.content); + } + writeFileSync(join(dir, "db.ts"), "export type Db = any;\nexport const db: Db = undefined;\n"); + writeFileSync(join(dir, "consumer.ts"), CONSUMER); + const program = ts.createProgram([join(dir, "consumer.ts")], { + strict: true, noEmit: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, skipLibCheck: true, + baseUrl: dir, paths: { "~/db": ["./db.ts"] }, + }); + return ts.getPreEmitDiagnostics(program).map((d) => + `${d.file?.fileName.slice(dir.length + 1) ?? ""} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +describe("the flat layout is the default, the package layout is opt-in, and the barrel hides the difference", () => { + test("with no outputLayout declared, modules sit flat in the output directory", async () => { + const paths = (await generate(undefined)).map((f) => f.path).sort(); + expect(paths).toContain("Post.ts"); + expect(paths).toContain("index.ts"); + expect(paths.some((p) => p.startsWith("acme/"))).toBe(false); + }); + + test("outputLayout: package places modules under their package directory", async () => { + const paths = (await generate("package")).map((f) => f.path).sort(); + expect(paths).toContain("acme/blog/Post.ts"); + expect(paths).toContain("index.ts"); + expect(paths.filter((p) => p !== "index.ts").every((p) => p.startsWith("acme/blog/"))).toBe(true); + }); + + test("the barrel exports the same names in both layouts", async () => { + const names = (files: EmittedFile[]) => [...files.find((f) => f.path === "index.ts")!.content + .matchAll(/export \* from "([^"]+)"/g)].map((m) => m[1]!.split("/").pop()).sort(); + expect(names(await generate("package"))).toEqual(names(await generate("flat"))); + }); + + test("a consumer importing through the barrel type-checks against either layout", async () => { + expect(compile(await generate("flat"))).toEqual([]); + expect(compile(await generate("package"))).toEqual([]); + }, 60_000); +}); diff --git a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts index ed27f36123..a28c5cfc31 100644 --- a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts +++ b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts @@ -37,7 +37,7 @@ async function gen(baseline?: BaselineMode) { outDir: outDir(), extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts b/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts index 357bdea74b..e62497d47a 100644 --- a/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts +++ b/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts @@ -84,16 +84,16 @@ describe("renderCallableFile — divergent primary sources", () => { const root = await loadClean([ { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { name: "procSrc", "@kind": "storedProc", "@proc": "phase_summary" } }, + { "source.rdb": { name: "procSrc", "@kind": "storedProc", "@proc": "stage_summary" } }, { "field.long": { name: "id" } }, ], }, }, ]); - const proj = root.children().find((c) => c.name === "PhaseSummary")! as MetaObject; + const proj = root.children().find((c) => c.name === "StageSummary")! as MetaObject; expect(isCallableEntity(proj)).toBe(true); - expect(renderCallableFile(proj)).toContain("phase_summary"); + expect(renderCallableFile(proj)).toContain("stage_summary"); }); }); diff --git a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts index 0cc2519e10..33238de5f3 100644 --- a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts @@ -137,7 +137,7 @@ describe("codegen-compile conformance — the shared fitness corpus", () => { const root = await loadCorpus(); const dir = mkdtempSync(join(import.meta.dir, `tmp-codegen-compile-${dialect}-`)); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -162,7 +162,7 @@ describe("codegen-compile conformance — the shared fitness corpus", () => { // extStyle "js" — the runner's default, and the only style NodeNext resolution // (the `tsc --init` profile) accepts. It must agree with the render context's // (also "js" by default): a mismatch emits half the tree extension-less. - config: { outDir: dir, extStyle: "js", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "js", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }); diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index f715b76907..fe5742c441 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -265,14 +265,14 @@ describe("the three shapes", () => { const c = corpusCase("tph-shared-marks"); const tree = await contractTree(c); const keysOf = (path: string): string[] => Object.keys(jsonAt(tree, path)["properties"] as JsonDoc); - const copay = "schemas/acme/auth/CopayAuth"; + const coupon = "schemas/acme/auth/CouponAuth"; const bridge = "schemas/acme/auth/BridgeAuth"; - const row = { id: 1, type: "Copay", reference: "R-1", auditRef: "A-1" }; - expect(validatorOf(tree, `${copay}.schema.json`)(row)).toBe(true); - expect(keysOf(`${copay}.schema.json`)).not.toContain("token"); + const row = { id: 1, type: "Coupon", reference: "R-1", auditRef: "A-1" }; + expect(validatorOf(tree, `${coupon}.schema.json`)(row)).toBe(true); + expect(keysOf(`${coupon}.schema.json`)).not.toContain("token"); expect(keysOf(`${bridge}.schema.json`)).not.toContain("token"); for (const shape of ["create", "update"]) { - expect(keysOf(`${copay}.${shape}.schema.json`)).toEqual(["reference"]); + expect(keysOf(`${coupon}.${shape}.schema.json`)).toEqual(["reference"]); expect(keysOf(`${bridge}.${shape}.schema.json`)).toEqual(["reference"]); } diff --git a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts index 2aa37d6a30..fbd18466fa 100644 --- a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts @@ -170,7 +170,7 @@ describe("Table A — what becomes a cube", () => { [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, pk, ], { "@discriminator": "type" }, @@ -1501,7 +1501,7 @@ describe("Table H — the canonical model", () => { // The other canonical entities (Node, Session, Measurement, the Auth family, AllTypes) and the // join-path cubes carry no report of Table H's; only their presence is asserted here. expect(model.cubes.map((c) => c.name)).toEqual([ - "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth", + "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth", "AllTypes", "Gadget", "GadgetEvent", "Entry", "Node_fkParent", "ProgramRosterFacts", "ProgramLongWeeksFacts", "ProgramFlagRosterFacts", "ProgramSessionsFacts", "ProgramSessions_fkWeek", ]); diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts index f541f5c459..c2a5e29c65 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts @@ -18,14 +18,14 @@ describe("the cube-model canonical golden", () => { "model/cubes/Asset.yml", "model/cubes/Auth.yml", "model/cubes/BridgeAuth.yml", - "model/cubes/CopayAuth.yml", + "model/cubes/CouponAuth.yml", "model/cubes/Entry.yml", "model/cubes/Gadget.yml", "model/cubes/GadgetEvent.yml", "model/cubes/Measurement.yml", "model/cubes/Node.yml", "model/cubes/Node_fkParent.yml", - "model/cubes/PriorAuthAuth.yml", + "model/cubes/PermitAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", "model/cubes/ProgramLongWeeksFacts.yml", diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts index 6e793ea834..300be13b7b 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts @@ -1154,7 +1154,7 @@ describe("parse oracle", () => { test("the canonical cubes parse to the model's values", async () => { const model = await canonicalModel(); expect(model.cubes.map((c) => c.name)).toEqual([ - "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth", + "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth", "AllTypes", "Gadget", "GadgetEvent", "Entry", "Node_fkParent", "ProgramRosterFacts", "ProgramLongWeeksFacts", "ProgramFlagRosterFacts", "ProgramSessionsFacts", "ProgramSessions_fkWeek", ]); diff --git a/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts b/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts index 229ebaf4a7..3bc606a3b1 100644 --- a/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts @@ -519,7 +519,7 @@ describe("selection — a report writes into its @from cube whenever that cube i [ { "source.rdb": { "@table": "auths" } }, longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "status" } }, pk, ], diff --git a/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts b/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts index 81c4df6054..aca7d50cc8 100644 --- a/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts @@ -470,7 +470,7 @@ describe("other spine shapes", () => { entity("Auth", [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "reference" } }, pk, ], { "@discriminator": "type" }), @@ -508,7 +508,7 @@ describe("other spine shapes", () => { entity("Auth", [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "programId" } }, { "field.int": { name: "quantity" } }, pk, diff --git a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts index bbcd9aee59..a64b5fb2ab 100644 --- a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts @@ -132,7 +132,7 @@ async function genAndCompile(dialect: Dialect, withSchema: boolean): Promise true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts new file mode 100644 index 0000000000..8144528335 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts @@ -0,0 +1,57 @@ +// rc.20 @dbCheck: an enum with `@dbCheck: false` gets no membership CHECK in the Drizzle table, as +// `meta migrate` creates none — else `drizzle-kit push` would re-add the CHECK the model opted out +// of. A sibling enum keeps its own, and the enum's values still type the column. +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderDrizzleSchema } from "../src/templates/drizzle-schema.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts/expected"; +import type { Dialect } from "../src/metaobjects-config.js"; + +async function load() { + const json = JSON.stringify({ "metadata.root": { children: [ + { "object.entity": { name: "Provider", children: [ + { "source.rdb": { name: "src", "@table": "providers" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.enum": { name: "kind", "@values": ["DEPOT", "LAB"] } }, + { "field.enum": { name: "tier", "@values": ["GOLD", "SILVER"], "@constraintName": "CK_Providers_Tier" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + return res.root; +} + +async function emit(dialect: Dialect) { + const root = await load(); + const ctx = makeRenderContext({ + dialect, loadedRoot: root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(root), relationMap: buildRelationMap(root), + }); + return renderDrizzleSchema(root.findObject("Provider")!, ctx).toString(); +} + +describe("Drizzle: @dbCheck: false on a field.enum", () => { + for (const dialect of ["postgres", "sqlite"] as const) { + test(`${dialect}: the opted-out enum declares no CHECK; its sibling keeps one`, async () => { + const out = await emit(dialect); + expect(out).not.toContain("providers_state_chk"); + expect(out).toContain("providers_kind_chk"); + // A declared @constraintName names the CHECK, as meta migrate names it. + expect(out).toContain('"CK_Providers_Tier"'); + expect(out).not.toContain("providers_tier_chk"); + // The column is still the enum's: only the database CHECK is left out. + expect(out).toContain('"OPEN"'); + }); + + test(`${dialect}: the Drizzle CHECKs are the ones meta migrate creates`, async () => { + const root = await load(); + const migrate = buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === "providers")!; + expect(migrate.checks.map((c) => c.name)).toEqual(["providers_kind_chk", "CK_Providers_Tier"]); + }); + } +}); diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts new file mode 100644 index 0000000000..ccd97b68f1 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts @@ -0,0 +1,124 @@ +// rc.21 — a string-stored field.enum with @stringValueMap: its member<->stored-string codec lives +// in the COLUMN, as the int-backed codec does (drizzle-enum-intvaluemap.test.ts), and its CHECK +// lists the stored strings, as `meta migrate` does. +// +// (The int-backed note follows.) Task 5 — an int-backed field.enum's symbol<->int codec lives in the COLUMN +// definition, as a generated Drizzle customType. Nothing downstream changes: +// db.insert().values() encodes on bind, a selected row decodes on read, and a +// filter comparison encodes because Drizzle binds through the column type. +// +// Chosen over a Zod write-transform + generated read-decode because TS's +// generated queries return raw Drizzle rows and have NO decode seam — that route +// meant inventing one and wrapping every generated read. This is also the direct +// analogue of the other four ports' codec seams (EF Core HasConversion, OMDB +// JdbcFieldCodec, Exposed customEnumeration, Python ObjectManager coercion). + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderDrizzleSchema } from "../src/templates/drizzle-schema.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import type { Dialect } from "../src/metaobjects-config.js"; + +const VALUES = ["Draft", "Published"]; +const STORED = { Draft: "draft", Published: "published" }; + +async function emit(statusDecl: Record, extraRoots: unknown[] = [], dialect: Dialect = "postgres") { + const json = JSON.stringify({ + "metadata.root": { + children: [ + ...extraRoots, + { + "object.entity": { + name: "Order", + children: [ + { "field.long": { name: "id" } }, + { "field.enum": statusDecl }, + { "source.rdb": { name: "src", "@table": "orders" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, + }, + ], + }, + }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ + dialect, loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root), + }); + return renderDrizzleSchema(res.root.findObject("Order")!, ctx).toString(); +} + +describe("Drizzle codegen — @stringValueMap field.enum customType", () => { + for (const dialect of ["postgres", "sqlite"] as const) { + test(`maps member <-> stored string at the column, and the CHECK lists the stored strings (${dialect})`, async () => { + const out = await emit({ name: "status", "@values": VALUES, "@stringValueMap": STORED }, [], dialect); + expect(out).toContain('const STATUS_TO_STORED = { "Draft": "draft", "Published": "published" }'); + expect(out).toContain('const STATUS_FROM_STORED: Record = { "draft": "Draft", "published": "Published" }'); + expect(out).toContain('dataType: () => "text"'); + expect(out).toContain('statusStoredEnum("status")'); + expect(out).toContain("IN ('draft', 'published')"); + }); + } + + test("a sized column is the varchar(n) meta migrate creates", async () => { + const out = await emit({ name: "status", "@values": VALUES, "@stringValueMap": STORED, "@maxLength": 12 }); + expect(out).toContain('dataType: () => "varchar(12)"'); + }); +}); + +// rc.21 fix round (I1): sibling TPH subtypes declaring one column with different @values each +// get their own enum CHECK, guarded by their discriminator value, as `meta migrate` derives it. +describe("Drizzle codegen — TPH siblings sharing a column with different @values", () => { + test("each owner's CHECK is guarded by its discriminator value", async () => { + const json = JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Device", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "devices" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "kind", "@values": ["METER", "SWITCH"] } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "Meter", extends: "Device", "@discriminatorValue": "METER", children: [ + { "field.enum": { name: "grade", "@values": ["A", "B"] } } ] } }, + { "object.entity": { name: "Switch", extends: "Device", "@discriminatorValue": "SWITCH", children: [ + { "field.enum": { name: "grade", "@values": ["X", "Y"] } } ] } } ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ + dialect: "postgres", loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root), + }); + const out = renderDrizzleSchema(res.root.findObject("Device")!, ctx).toString(); + expect(out).toContain(`"devices_meter_grade_chk"`); + expect(out).toContain(`("kind" <> 'METER') OR (grade IN ('A', 'B'))`); + expect(out).toContain(`"devices_switch_grade_chk"`); + expect(out).not.toContain(`"devices_grade_chk"`); + }); +}); + +// rc.21 part B (N1): two different CHECKs under one name are refused on Postgres, which requires +// unique constraint names, as `meta migrate` refuses them; SQLite accepts and enforces both. +describe("Drizzle codegen — two CHECKs under one name", () => { + async function render(dialect: Dialect) { + const json = JSON.stringify({ "metadata.root": { children: [ { "object.entity": { name: "Order", children: [ + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["A", "B"], "@constraintName": "orders_state_chk" } }, + { "field.enum": { name: "phase", "@values": ["X", "Y"], "@constraintName": "orders_state_chk" } }, + { "source.rdb": { name: "src", "@table": "orders" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } } ] } } ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ dialect, loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root) }); + return () => renderDrizzleSchema(res.root.findObject("Order")!, ctx).toString(); + } + test("refused on Postgres", async () => { + expect(await render("postgres")).toThrow(/both named 'orders_state_chk'.*Postgres requires/); + }); + test("both kept on SQLite", async () => { + const out = (await render("sqlite"))(); + expect(out.match(/"orders_state_chk"/g)?.length).toBe(2); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts b/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts index 5b7db831f2..e1180bdfa8 100644 --- a/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts +++ b/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts @@ -54,7 +54,7 @@ async function gen(root: string, dryRun: boolean) { return runGen({ config: defineConfig({ outDir: join(root, "generated"), - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", dbImport: "../db", extStyle: "js", generators: [entityFile()], diff --git a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts index 4d4100f29d..145cd36cbd 100644 --- a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts @@ -108,7 +108,7 @@ async function generateAndCompile( const root = loaded.root; const dir = mkdtempSync(join(import.meta.dir, "tmp-exact-optional-")); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -122,7 +122,7 @@ async function generateAndCompile( loadedRoot: root, matches: (e) => generator.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }); diff --git a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts index 3fc58a160c..ad6eb186c7 100644 --- a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts @@ -12,8 +12,8 @@ import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { join } from "node:path"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { renderOutputParser } from "../src/templates/output-parser.js"; @@ -52,6 +52,7 @@ async function writeEntityModules( warn: () => {}, }; for (const f of await entityFile().generate(ctx)) { + mkdirSync(dirname(join(dir, f.path)), { recursive: true }); writeFileSync(join(dir, f.path), f.content); } } diff --git a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts index 4f5af92488..59acada456 100644 --- a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts @@ -93,7 +93,7 @@ describe("Filter types an enum filter value as the enum's member union", const root = loaded.root; const dir = mkdtempSync(join(import.meta.dir, "tmp-filter-enum-")); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: dir, @@ -107,7 +107,7 @@ describe("Filter types an enum filter value as the enum's member union", loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json b/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json index 91ba472b73..17c0607b62 100644 --- a/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json +++ b/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json @@ -30,18 +30,18 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "coupon_cents" } } ] } } diff --git a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts index f19643acd1..ba3c7c8e82 100644 --- a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts +++ b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts @@ -93,8 +93,8 @@ function genContext(root: Awaited>): GenContext { loadedRoot: root, matches: () => true, projectRoot: "/tmp", - config: { outDir: "/tmp", extStyle: "js", dbImport: "~/db", dialect: "sqlite" } as never, - renderContext: makeRenderContext({ + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "js", dbImport: "~/db", dialect: "sqlite" } as never, + renderContext: makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", diff --git a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts index 81c8364fa9..7e6afadacd 100644 --- a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts +++ b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts @@ -38,7 +38,7 @@ async function gen(opts: { baselineFresh?: boolean } = {}) { outDir: join(projectRoot, "generated"), extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts b/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts index ce3a01f8e7..6c6f6b9b86 100644 --- a/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts @@ -122,14 +122,14 @@ describe('runGen — string selection produces identical output to the factory', const byString = await runGen({ config: defineConfig({ - outDir: join(tmp, "s"), extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: join(tmp, "s"), extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators: ["entity"], }), metadata: root, }); const byFactory = await runGen({ config: defineConfig({ - outDir: join(tmp, "f"), extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: join(tmp, "f"), extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile()], }), metadata: root, @@ -152,7 +152,7 @@ describe('runGen — string selection produces identical output to the factory', const root = await loadRoot(); const result = await runGen({ config: defineConfig({ - outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: tmp, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators: ["entity", routesFile()], }), metadata: root, @@ -168,7 +168,7 @@ describe('runGen — string selection produces identical output to the factory', const root = await loadRoot(); await expect(runGen({ config: defineConfig({ - outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: tmp, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators: ["bogus"], }), metadata: root, @@ -179,7 +179,7 @@ describe('runGen — string selection produces identical output to the factory', const root = await loadRoot(); await expect(runGen({ config: defineConfig({ - outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "sqlite", + outDir: tmp, extStyle: "none", dbImport: "../db", outputLayout: "flat" as const, dialect: "sqlite", generators: ["docs"], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/generators/entity-file.test.ts b/server/typescript/packages/codegen-ts/test/generators/entity-file.test.ts index e967ec54ae..c590c31b61 100644 --- a/server/typescript/packages/codegen-ts/test/generators/entity-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/entity-file.test.ts @@ -23,7 +23,7 @@ describe("entityFile() factory", () => { const { root } = await loader.load([new FileSource(FIXTURE)]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -31,7 +31,7 @@ describe("entityFile() factory", () => { const ctx: GenContext = { entities, loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; @@ -53,7 +53,7 @@ describe("entityFile() factory", () => { const { root } = await loader.load([new FileSource(FIXTURE)]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -61,7 +61,7 @@ describe("entityFile() factory", () => { const ctx: GenContext = { entities, loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; @@ -83,7 +83,7 @@ describe("entityFile() factory", () => { const { root } = await loader.load([new FileSource(FIXTURE)]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -93,7 +93,7 @@ describe("entityFile() factory", () => { const ctx: GenContext = { entities, loadedRoot: root, matches: (e) => gen.filter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; @@ -137,7 +137,7 @@ describe("entityFile() — emitAbstractShapes knob", () => { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(model)]); if (errors.length > 0) throw new Error(errors.map((e: { message: string }) => e.message).join("\n")); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", emitAbstractShapes, pkMap: buildPkMap(root), relationMap: buildRelationMap(root), @@ -145,7 +145,7 @@ describe("entityFile() — emitAbstractShapes knob", () => { const ctx: GenContext = { entities, loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; @@ -237,13 +237,13 @@ describe("entityFile() — emitAbstractShapes knob", () => { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(MODEL)]); expect(errors).toEqual([]); const entities = root.objects(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", dbImport: "../db", extStyle: "none", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), }); const ctx: GenContext = { entities, loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; const files = await entityFile().generate(ctx); diff --git a/server/typescript/packages/codegen-ts/test/generators/factories.test.ts b/server/typescript/packages/codegen-ts/test/generators/factories.test.ts index fcdef0f7b2..74b8fb043d 100644 --- a/server/typescript/packages/codegen-ts/test/generators/factories.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/factories.test.ts @@ -22,7 +22,7 @@ async function buildCtx(genFilter?: (e: MetaObject) => boolean): Promise boolean): Promise genFilter?.(e) ?? true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts b/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts index 4d1e560459..9247d10054 100644 --- a/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts @@ -71,6 +71,7 @@ function genConfig(outDir: string) { outDir, extStyle: "none", dbImport: "~/server/db", + outputLayout: "flat", dialect: "postgres", generators: [namesFile()], }); diff --git a/server/typescript/packages/codegen-ts/test/generators/prompt-render-file.test.ts b/server/typescript/packages/codegen-ts/test/generators/prompt-render-file.test.ts index 83bc1f32e2..3c971fe169 100644 --- a/server/typescript/packages/codegen-ts/test/generators/prompt-render-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/prompt-render-file.test.ts @@ -60,6 +60,7 @@ describe("promptRender() factory", () => { expect(out[0]!.path).toBe("prompts.ts"); // The payload type is the value object's OWN interface, declared by entityFile() in its // module — imported, never re-declared here. + // No render context: the default (flat) layout places the module beside the file. expect(out[0]!.content).toContain('import type { NpcPromptPayload } from "./NpcPromptPayload.js";'); expect(out[0]!.content).not.toContain("export interface"); expect(out[0]!.content).toContain( diff --git a/server/typescript/packages/codegen-ts/test/golden/api-doc-render.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-doc-render.test.ts index 85f2e1a5f9..c37d40a255 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-doc-render.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-doc-render.test.ts @@ -70,7 +70,7 @@ async function loadModel(): Promise<{ model: ApiModel; root: Awaited { ), ]); expect(res.errors).toEqual([]); - return buildApiModel(res.root, { loadedRoot: res.root }); + return buildApiModel(res.root, { outputLayout: "flat", loadedRoot: res.root }); } describe("worked example chains via the entity's REAL primary key (not a literal `id`)", () => { diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts index d4a320e9e5..c47e29961c 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts @@ -97,7 +97,7 @@ const FIXTURE = JSON.stringify({ "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -184,7 +184,7 @@ async function runGenerator( root: Awaited>, projectRoot: string, ): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", @@ -198,7 +198,7 @@ async function runGenerator( // Replicates runner.ts:169 — the per-entity filter the generator declares. matches: (e: MetaObject) => gen.filter?.(e) ?? true, projectRoot, - config: { + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "~/db", @@ -359,7 +359,7 @@ describe("api-docs ACCURACY gate — documented symbols == real generated output extractorAll = joinContent(extractorFiles); renderAll = joinContent(renderFiles); - model = buildApiModel(root, { loadedRoot: root }); + model = buildApiModel(root, { outputLayout: "flat", loadedRoot: root }); // Sanity: the generators actually produced output for the rich fixture. expect(entityFiles.length).toBeGreaterThan(0); @@ -872,24 +872,24 @@ const T5_FIXTURE = JSON.stringify({ ], }, }, - // PhaseSummaryArgs — the @parameterRef value-object for the callable. + // StageSummaryArgs — the @parameterRef value-object for the callable. { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ - { "field.long": { name: "caseId", "@required": true } }, + { "field.long": { name: "consignmentId", "@required": true } }, { "field.string": { name: "asOfDate", "@required": true } }, ], }, }, - // PhaseSummary — a projection entity backed by a stored procedure → the - // callable generator emits callPhaseSummary(db, args): Promise. + // StageSummary — a projection entity backed by a stored procedure → the + // callable generator emits callStageSummary(db, args): Promise. { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseSummaryArgs" } }, - { "field.long": { name: "caseId" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "StageSummaryArgs" } }, + { "field.long": { name: "consignmentId" } }, { "field.string": { name: "phase" } }, ], }, @@ -941,10 +941,10 @@ describe("api-docs ACCURACY gate (T5) — relations / callable / prompt / Hono", honoFiles = await runGenerator(routesFileHono(), root, projectRoot); // Hono is the opt-in variant → the builder documents it only when asked. - model = buildApiModel(root, { loadedRoot: root, includeHonoRoutes: true }); + model = buildApiModel(root, { outputLayout: "flat", loadedRoot: root, includeHonoRoutes: true }); expect(entityFiles.length).toBeGreaterThan(0); - // Exactly one callable entity in the fixture (PhaseSummary). + // Exactly one callable entity in the fixture (StageSummary). expect(callableFiles.length).toBe(1); // One aggregated prompts.ts. expect(promptFiles.length).toBe(1); @@ -1014,21 +1014,21 @@ describe("api-docs ACCURACY gate (T5) — relations / callable / prompt / Hono", // ----------------------------------------------------------------------- // CALLABLE: call in .callable.ts at the documented path. // ----------------------------------------------------------------------- - test("CALLABLE: callPhaseSummary documented + emitted at PhaseSummary.callable", () => { - const unit = model.units.find((u) => u.node === "PhaseSummary")!; + test("CALLABLE: callStageSummary documented + emitted at StageSummary.callable", () => { + const unit = model.units.find((u) => u.node === "StageSummary")!; const callable = unit.symbols.find((s) => s.kind === "callable"); - expect(callable, "PhaseSummary carries a callable symbol").toBeDefined(); - expect(callable!.name).toBe("callPhaseSummary"); + expect(callable, "StageSummary carries a callable symbol").toBeDefined(); + expect(callable!.name).toBe("callStageSummary"); - const f = fileFor(callableFiles, "PhaseSummary.callable.ts")!; + const f = fileFor(callableFiles, "StageSummary.callable.ts")!; expect(f, "callable file emitted").toBeDefined(); - expect(hasExportedFn(f.content, "callPhaseSummary")).toBe(true); - expect(callable!.importPath).toBe("PhaseSummary.callable"); + expect(hasExportedFn(f.content, "callStageSummary")).toBe(true); + expect(callable!.importPath).toBe("StageSummary.callable"); expect(`${callable!.importPath}.ts`).toBe(f.path); // Signature: takes the @parameterRef args VO + returns the projection array. - expect(callable!.signature).toContain("PhaseSummaryArgs"); - expect(callable!.returns).toBe("PhaseSummary[]"); + expect(callable!.signature).toContain("StageSummaryArgs"); + expect(callable!.returns).toBe("StageSummary[]"); }); test("CALLABLE inverse: a non-callable entity carries no callable symbol", () => { @@ -1083,7 +1083,7 @@ describe("api-docs ACCURACY gate (T5) — relations / callable / prompt / Hono", }); test("HONO inverse: when includeHonoRoutes is NOT set, no Hono symbols are documented", () => { - const noHono = buildApiModel(root, { loadedRoot: root }); + const noHono = buildApiModel(root, { outputLayout: "flat", loadedRoot: root }); for (const u of noHono.units) { expect(u.symbols.some((s) => s.kind === "rest-hono")).toBe(false); } @@ -1176,7 +1176,7 @@ describe("api-docs ACCURACY gate — writes are documented only where the genera queriesFiles = await runGenerator(queriesFile(), res.root, projectRoot); routesFiles = await runGenerator(routesFile(), res.root, projectRoot); honoFiles = await runGenerator(routesFileHono(), res.root, projectRoot); - model = buildApiModel(res.root, { loadedRoot: res.root, includeHonoRoutes: true }); + model = buildApiModel(res.root, { outputLayout: "flat", loadedRoot: res.root, includeHonoRoutes: true }); }); for (const name of ["CustomerCard", "RegionTotal", "Order", "Customer"]) { diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts index 0b651a4a61..4f9f281d7b 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts @@ -75,7 +75,7 @@ async function loadRoot() { async function loadModel(opts?: { includeHonoRoutes?: boolean }): Promise { const root = await loadRoot(); - return buildApiModel(root, { loadedRoot: root, ...(opts ?? {}) }); + return buildApiModel(root, { outputLayout: "flat", loadedRoot: root, ...(opts ?? {}) }); } // --------------------------------------------------------------------------- @@ -176,6 +176,7 @@ async function runGenerator( configExtra?: Record, ): Promise { const renderContext = makeRenderContext({ + outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", @@ -192,6 +193,7 @@ async function runGenerator( outDir: "/tmp", extStyle: "none", dbImport: "~/db", + outputLayout: "flat", dialect: "sqlite", ...(configExtra ?? {}), } as never, @@ -282,7 +284,7 @@ describe("Fix 1: a CRUD consumer from AGENT-API.md COMPILES against the REAL gen const queriesFiles = await runGenerator(queriesFile(), root, projectRoot); // 2. Build the api-docs agent form for the SAME model. - const model = buildApiModel(root, { loadedRoot: root }); + const model = buildApiModel(root, { outputLayout: "flat", loadedRoot: root }); const agent = renderAgentApi(model, provider); // 3. Lay out a temp output dir exactly as a consumer's generated dir: the @@ -401,6 +403,7 @@ describe("Fix 2: api-docs documents Hono routes when the Hono generator is in th outDir, extStyle: "none", dbImport: "~/db", + outputLayout: "flat", dialect: "sqlite", targets: { docs: { outDir: docsDir } }, generators: [entityFile(), queriesFile(), routesFile(), routesFileHono(), apiDocsFile()], diff --git a/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts index 90db3b9863..ec89daab22 100644 --- a/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts @@ -44,7 +44,7 @@ async function gen(root: MetaRoot): Promise> { outDir: tmp, extStyle: "none", dbImport: "~/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts index cc37b17e95..8185804949 100644 --- a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts @@ -236,7 +236,7 @@ describe("extractor/render payload import resolves against the REAL generated VO expect(extractorSrc).toContain('from "./Line.js"'); // 3. Lay the real generated VO modules + the extractor/render files into a - // temp dir exactly as `meta gen` would (flat, co-located). + // temp dir exactly as `meta gen` would (the default package layout, R63). const dir = mkdtempSync(join(tmpdir(), "extractor-render-payload-")); TEMP_DIRS.push(dir); const write = (rel: string, body: string) => { @@ -285,15 +285,15 @@ describe("the render helper honours extStyle and marks itself generated", () => test('extStyle "none" drops the extension from the payload import', async () => { const root = await loadRoot(MODEL); const src = renderRenderHelper(root, "OrderDoc", PROVIDER, "none"); - expect(src).toMatch(/from "\.\/[A-Za-z0-9_]+";/); - expect(src).not.toMatch(/from "\.\/[A-Za-z0-9_]+\.js";/); + expect(src).toMatch(/from "\.\/[A-Za-z0-9_/]+";/); + expect(src).not.toMatch(/from "\.\/[A-Za-z0-9_/]+\.js";/); }); test('extStyle "js" keeps it — and is the default, so an existing caller is unchanged', async () => { const root = await loadRoot(MODEL); const explicit = renderRenderHelper(root, "OrderDoc", PROVIDER, "js"); const defaulted = renderRenderHelper(root, "OrderDoc", PROVIDER); - expect(explicit).toMatch(/from "\.\/[A-Za-z0-9_]+\.js";/); + expect(explicit).toMatch(/from "\.\/[A-Za-z0-9_/]+\.js";/); expect(defaulted).toBe(explicit); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts index 4c693db87e..44fc81c8c6 100644 --- a/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts @@ -62,7 +62,7 @@ async function gen( outDir: tmp, extStyle: "none", dbImport: "~/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: only !== undefined ? [entityFile({ filter: only })] : [entityFile(), queriesFile(), barrel()], ...(providedEnumModule !== undefined && { providedEnumModule }), diff --git a/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts b/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts index 344b8f0564..0683060dc9 100644 --- a/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts @@ -44,7 +44,7 @@ describe("golden output — byte-identical port gate", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect, + dialect, outputLayout: "flat", generators: [entityFile(), queriesFile(), routesFile(), formFile(), barrel()], }), metadata: metadataRoot, diff --git a/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts index 46f787e4e8..b91649a523 100644 --- a/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts @@ -42,7 +42,7 @@ async function gen(root: MetaRoot): Promise> { outDir: tmp, extStyle: "none", dbImport: "~/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/golden/routes-file-hono-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/routes-file-hono-conformance.test.ts index 00e848f99e..f5da216f57 100644 --- a/server/typescript/packages/codegen-ts/test/golden/routes-file-hono-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/routes-file-hono-conformance.test.ts @@ -29,7 +29,7 @@ const CORPUS = resolve(import.meta.dir, "../../../../../../fixtures/conformance" const UPDATE = process.env.UPDATE_GOLDEN === "1"; function makeCtx(root: Awaited>["root"]): GenContext { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/tmp", @@ -44,7 +44,7 @@ function makeCtx(root: Awaited>["root"]): Gen entities: root.objects(), loadedRoot: root, matches: () => true, - config: { outDir: "/tmp", extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, + config: { outputLayout: "flat", outDir: "/tmp", extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/integration.test.ts b/server/typescript/packages/codegen-ts/test/integration.test.ts index 68af37aa3b..d27312ab37 100644 --- a/server/typescript/packages/codegen-ts/test/integration.test.ts +++ b/server/typescript/packages/codegen-ts/test/integration.test.ts @@ -53,7 +53,7 @@ describe("trainer-website-shape integration — 9 entities, SQLite", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -98,7 +98,7 @@ describe("trainer-website-shape integration — 9 entities, SQLite", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -197,7 +197,7 @@ describe("trainer-website-shape integration — 9 entities, SQLite", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -236,7 +236,7 @@ describe("trainer-website-shape integration — 9 entities, SQLite", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -274,7 +274,7 @@ describe("trainer-website-shape integration — 9 entities, Postgres", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -316,7 +316,7 @@ describe("trainer-website-shape integration — 9 entities, Postgres", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, diff --git a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts index ecb2b1f003..7cac3179f0 100644 --- a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts @@ -58,7 +58,7 @@ async function loadModel(): Promise { } async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -71,7 +71,7 @@ async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise< loadedRoot: root, matches: (e) => generator.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, renderContext, warn: () => {}, }); diff --git a/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts new file mode 100644 index 0000000000..0aa12da32a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts @@ -0,0 +1,57 @@ +// rc.21 (U7): a derived (origin-bearing) field of a table-backed entity has no column — it is +// lowered where a projection reads it — so its names entry would name a column that does not +// exist. The artifact carries no entry for it. A projection's derived field IS a column of its +// view and keeps its entry. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; +import { resolveObjectNames } from "../src/names.js"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Account", children: [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { name: "id" } }, + { "field.int": { name: "score" } }, + { "field.boolean": { name: "isHigh", children: [ { "origin.computed": { "@expr": { + op: "gte", left: { field: "score" }, right: { value: 4 } } } } ] } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "AccountView", "@filter": { isHigh: true }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { name: "id", extends: "Account.id" } }, + { "field.int": { name: "doubled", children: [ { "origin.computed": { "@expr": { + fn: "coalesce", args: [ { field: "score" }, { value: 0 } ] } } } ] } }, + { "identity.primary": { name: "id", extends: "Account.id" } } ] } } ] } }; + +describe("names of a derived field", () => { + test("a table entity's derived field has no names entry; a projection's keeps its column", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const obj = (name: string) => root.objects().find((o) => o.name === name && isMetaObject(o)) as MetaObject; + const account = resolveObjectNames(obj("Account"))!; + expect(Object.keys(account.fields).sort()).toEqual(["id", "score"]); + expect(Object.keys(account.ownFields).sort()).toEqual(["id", "score"]); + expect(resolveObjectNames(obj("AccountView"))!.fields["doubled"]?.column).toBe("doubled"); + }); +}); + +// rc.21 fix round (M8): a write-through extender declares the derived column its fragment drops. +test("a write-through extender of an abstract entity keeps its inherited derived column", async () => { + const model = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Tracked", abstract: true, children: [ + { "field.int": { name: "score" } }, + { "field.boolean": { name: "isHigh", children: [ { "origin.computed": { "@expr": { + op: "gte", left: { field: "score" }, right: { value: 4 } } } } ] } } ] } }, + { "object.entity": { name: "Account", extends: "Tracked", children: [ + { "source.rdb": { "@table": "accounts" } }, + { "source.rdb": { name: "read", "@kind": "view", "@view": "v_accounts", "@role": "replica" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "HighAccounts", "@filter": { isHigh: true }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { name: "id", extends: "Account.id" } }, + { "identity.primary": { name: "id", extends: "Account.id" } } ] } } ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(errors).toEqual([]); + const account = root.objects().find((o) => o.name === "Account" && isMetaObject(o)) as MetaObject; + expect(resolveObjectNames(account)!.ownFields["isHigh"]?.column).toBe("is_high"); +}); diff --git a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts index 109a544397..af8dd55500 100644 --- a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts @@ -58,17 +58,17 @@ const MODEL = { children: [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "kind", "@values": ["Copay"] } }, + { "field.enum": { name: "kind", "@values": ["Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.long": { name: "copayAmount", "@column": "zz_copay_cents" } }], + "@discriminatorValue": "Coupon", + children: [{ "field.long": { name: "couponAmount", "@column": "zz_coupon_cents" } }], }, }, ], @@ -87,7 +87,7 @@ async function generate( const dir = mkdtempSync(join(import.meta.dir, "tmp-names-extends-")); await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", + outDir: dir, extStyle: "none", dbImport: "~/server/db", outputLayout: "flat" as const, dialect: "sqlite", generators: [namesFile(namesOpts), entityFile()], }), metadata: root, @@ -153,15 +153,15 @@ describe("names artifacts extend rather than restate", () => { test("a TPH subtype spreads the WHOLE base — the shared table is named once", async () => { const { tree, dir } = await generate(); try { - const sub = tree["CopayAuth.names.ts"]; + const sub = tree["CouponAuth.names.ts"]; expect(sub).toContain('import { AuthNames } from "./Auth.names"'); // A TPH subtype spreads the base's SOURCES — the shared table is named once, on the // base — rather than the whole artifact. Spreading the whole thing would carry the // base's `name`/`subType` onto the child, which are the child's own now. expect(sub).toContain("...AuthNames.sources,"); - expect(sub).toContain('name: "CopayAuth"'); + expect(sub).toContain('name: "CouponAuth"'); expect(sub).toContain("...AuthNames.fields,"); - expect(sub).toContain('copayAmount: { name: "copayAmount", column: "zz_copay_cents" }'); + expect(sub).toContain('couponAmount: { name: "couponAmount", column: "zz_coupon_cents" }'); // The whole point: the subtype used to restate the base's table name and every one // of its columns. expect(sub).not.toContain("zz_auths"); @@ -181,12 +181,12 @@ describe("names artifacts extend rather than restate", () => { const { writeFileSync } = await import("node:fs"); writeFileSync(probe, [ `import { AuthorNames } from "./Author.names";`, - `import { CopayAuthNames } from "./CopayAuth.names";`, + `import { CouponAuthNames } from "./CouponAuth.names";`, // An INHERITED column, reached through the spread. `const a: "zz_made_at" = AuthorNames.fields.createdAt.column;`, // An inherited TOP-LEVEL member, reached through the whole-base spread. - `const b: "zz_auths" = CopayAuthNames.sources.primary.table;`, - `const c: "zz_copay_cents" = CopayAuthNames.fields.copayAmount.column;`, + `const b: "zz_auths" = CouponAuthNames.sources.primary.table;`, + `const c: "zz_coupon_cents" = CouponAuthNames.fields.couponAmount.column;`, `export const probe = [a, b, c];`, ].join("\n"), "utf8"); @@ -309,12 +309,12 @@ describe("a key-only abstract is a link in the chain, not a node to walk past", describe("a scoped run still names the shared table", () => { test("generating only the TPH subtype emits a base its sources actually reach", async () => { - // `meta gen --entities CopayAuth`. Pass 1 emits the subtype; pass 2 walks up to `Auth` + // `meta gen --entities CouponAuth`. Pass 1 emits the subtype; pass 2 walks up to `Auth` // and used to render it as a FRAGMENT unconditionally — and a fragment declares no // source, by design, because it has no physical name. But `Auth` DOES have one: it is // the TPH base, and the shared table is named on it. So the base came out with // `sources: {}` while the subtype emitted `...AuthNames.sources`, and the entity module - // referenced `CopayAuthNames.sources.primary.table` — a member that resolved to + // referenced `CouponAuthNames.sources.primary.table` — a member that resolved to // nothing. "Fragment" means "declares no source", so it is DERIVED from the source now // rather than asserted by the caller. const { root, errors } = await new MetaDataLoader().load([ @@ -326,11 +326,11 @@ describe("a scoped run still names the shared table", () => { try { await runGen({ config: defineConfig({ - outDir: dir, extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", + outDir: dir, extStyle: "none", dbImport: "~/server/db", outputLayout: "flat" as const, dialect: "sqlite", generators: [namesFile(), entityFile()], }), metadata: root, - entityFilter: ["CopayAuth"], + entityFilter: ["CouponAuth"], }); const tree: Record = {}; const walk = (d: string): void => { @@ -351,8 +351,8 @@ describe("a scoped run still names the shared table", () => { const probe = join(dir, "zz-probe.ts"); const { writeFileSync } = await import("node:fs"); writeFileSync(probe, [ - `import { CopayAuthNames } from "./CopayAuth.names";`, - `const t: "zz_auths" = CopayAuthNames.sources.primary.table;`, + `import { CouponAuthNames } from "./CouponAuth.names";`, + `const t: "zz_auths" = CouponAuthNames.sources.primary.table;`, `export const probe = [t];`, ].join("\n"), "utf8"); @@ -396,7 +396,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch expect(names).toEqual(["Author.names.ts", "BaseEntity.names.ts"]); // The TPH pair belongs to another tier here and must be gone. expect(tree["Auth.names.ts"]).toBeUndefined(); - expect(tree["CopayAuth.names.ts"]).toBeUndefined(); + expect(tree["CouponAuth.names.ts"]).toBeUndefined(); // And the surviving artifact still really extends the base it kept. expect(tree["Author.names.ts"]).toContain("BaseEntityNames"); } finally { @@ -409,7 +409,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch try { const names = Object.keys(tree).filter((f) => f.endsWith(".names.ts")).sort(); expect(names).toEqual([ - "Auth.names.ts", "Author.names.ts", "BaseEntity.names.ts", "CopayAuth.names.ts", + "Auth.names.ts", "Author.names.ts", "BaseEntity.names.ts", "CouponAuth.names.ts", ]); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts index 87c73b2e77..0abfa75d4b 100644 --- a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts @@ -100,7 +100,7 @@ async function genAndCompile( const dir = mkdtempSync(join(import.meta.dir, "tmp-names-ref-")); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -117,7 +117,7 @@ async function genAndCompile( loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/names.test.ts b/server/typescript/packages/codegen-ts/test/names.test.ts index 439513a281..472f5b9e89 100644 --- a/server/typescript/packages/codegen-ts/test/names.test.ts +++ b/server/typescript/packages/codegen-ts/test/names.test.ts @@ -354,25 +354,25 @@ describe("resolveObjectNames — extends chain", () => { children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Copay"] } }, + { "field.enum": { name: "type", "@values": ["Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.long": { name: "copayAmount", "@column": "copay_cents" } }], + "@discriminatorValue": "Coupon", + children: [{ "field.long": { name: "couponAmount", "@column": "coupon_cents" } }], }, }, ]); - const n = resolveObjectNames(obj(root, "CopayAuth"), "snake_case"); + const n = resolveObjectNames(obj(root, "CouponAuth"), "snake_case"); expect(n?.superNames?.name).toBe("Auth"); // The whole point of the TPH case: the subtype restated `auths` and every base column. expect(n?.inheritsSource).toBe(true); - expect(Object.keys(n?.ownFields ?? {})).toEqual(["copayAmount"]); + expect(Object.keys(n?.ownFields ?? {})).toEqual(["couponAmount"]); }); test("a base with no own fields and no source is NOT an artifact — there is nothing to extend", async () => { diff --git a/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts new file mode 100644 index 0000000000..36afb5684a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts @@ -0,0 +1,172 @@ +// rc.19 (R57) — @collectionName names an object's collection everywhere a port derives one: the +// REST segment, the TS list/finder exports and the Drizzle collection variable, and the reverse +// @via hop other objects walk. Absent, the project's pluralizer (`naming.collections`) derives +// it. + +import { describe, test, expect, afterEach } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative } from "node:path"; +import { + MetaDataLoader, InMemoryStringSource, collectionNameOf, pluralizer, registerPluralizer, + resetNamingStrategiesForTesting, reverseHopName, type MetaRoot, +} from "@metaobjectsdev/metadata"; +import { runGen } from "../../src/runner.js"; +import { defineConfig } from "../../src/metaobjects-config.js"; +import { entityFile } from "../../src/generators/entity-file.js"; +import { queriesFile } from "../../src/generators/queries-file.js"; +import { routesFile } from "../../src/generators/routes-file.js"; +import { resourcePath } from "../../src/templates/entity-ui-descriptor.js"; + +type Json = Record; + +const model = (historyAttrs: Json): Json => ({ + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Consignment", children: [ + { "source.rdb": { "@table": "consignments" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } }, + ] } }, + { "object.entity": { name: "ConsignmentHistory", ...historyAttrs, children: [ + { "source.rdb": { "@table": "consignment_history" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "consignmentId" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { name: "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } }, + ] } }, + ], + }, +}); + +async function load(historyAttrs: Json = {}): Promise { + const res = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model(historyAttrs)), { id: "m.json", format: "json" })]); + expect(res.errors).toEqual([]); + return res.root; +} + +async function gen(root: MetaRoot): Promise<{ files: Map; warnings: string[] }> { + const tmp = mkdtempSync(join(tmpdir(), "mo-collection-")); + try { + const { warnings } = await runGen({ + config: defineConfig({ + outDir: join(tmp, "src"), extStyle: "js", dbImport: "../db", dialect: "sqlite", outputLayout: "flat", + generators: [entityFile(), queriesFile(), routesFile()], + }), + metadata: root, projectRoot: tmp, + }); + const files = new Map(); + const src = join(tmp, "src"); + if (existsSync(src)) { + for (const e of readdirSync(src, { recursive: true, withFileTypes: true })) { + if (e.isFile()) files.set(relative(src, join(e.parentPath, e.name)), readFileSync(join(e.parentPath, e.name), "utf8")); + } + } + return { files, warnings }; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +} + +const history = (root: MetaRoot) => root.objects().find((o) => o.name === "ConsignmentHistory")!; + +afterEach(() => resetNamingStrategiesForTesting()); + +describe("@collectionName", () => { + test("absent, the standard pluralizer derives it", async () => { + const root = await load(); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistories"); + expect(reverseHopName(history(root))).toBe("consignmentHistories"); + }); + + test("names the REST segment, the list and finder exports, the collection variable and the reverse hop", async () => { + const root = await load({ "@collectionName": "ConsignmentHistory" }); + expect(reverseHopName(history(root))).toBe("consignmentHistory"); + const { files, warnings } = await gen(root); + const queries = files.get("ConsignmentHistory.queries.ts")!; + expect(queries).toContain("export async function listConsignmentHistory("); + expect(queries).toContain("export async function findConsignmentHistoryByConsignment("); + expect(queries).toContain(".from(consignmentHistory)"); + expect(files.get("ConsignmentHistory.ts")!).toContain("export const consignmentHistory = "); + expect([...files.values()].join("\n")).toContain('"/consignment_history"'); + expect(warnings.filter((w) => w.includes("deprecated"))).toEqual([]); + }); +}); + +// rc.19 fix round (I3): a project that configures nothing serves every object at its rc.18 +// segment — snake_case, then pluralize — so an acronym-ending name keeps `faqs`, never `fa_qs`. +const acronyms = (attrs: Record = {}): Json => ({ + "metadata.root": { + package: "acme", + children: ["FAQ", "TaxID", "PDF"].map((name) => ({ "object.entity": { name, ...(attrs[name] ?? {}), children: [ + { "source.rdb": { "@table": name.toLowerCase() } }, + { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } }, + ] } })), + }, +}); + +async function loadAcronyms(attrs: Record = {}): Promise { + const res = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(acronyms(attrs)), { id: "a.json", format: "json" })]); + expect(res.errors).toEqual([]); + return res.root; +} + +describe("REST segments of a project that configures nothing (byte-identical to rc.18)", () => { + test("an acronym-ending name is snake_cased before it is pluralized", async () => { + const root = await loadAcronyms(); + expect(root.objects().map((o) => resourcePath(o))).toEqual(["/faqs", "/tax_ids", "/pdfs"]); + const { files } = await gen(root); + const out = [...files.values()].join("\n"); + for (const segment of ["faqs", "tax_ids", "pdfs"]) expect(out).toContain(`"/${segment}"`); + for (const broken of ["fa_qs", "tax_i_ds", "pd_fs"]) expect(out).not.toContain(broken); + }); + + test("a declared @collectionName is snake_cased with its plural suffix kept on the acronym", async () => { + const root = await loadAcronyms({ FAQ: { "@collectionName": "FAQs" }, TaxID: { "@collectionName": "TaxIDs" } }); + expect(root.objects().map((o) => resourcePath(o))).toEqual(["/faqs", "/tax_ids", "/pdfs"]); + }); + + test("a configured pluralizer applies, and is snake_cased the same way", async () => { + const root = await loadAcronyms(); + Object.assign(root, { physicalNaming: { ...root.physicalNaming, collections: "none" } }); + expect(root.objects().map((o) => resourcePath(o))).toEqual(["/faq", "/tax_id", "/pdf"]); + }); +}); + +describe("the pluggable pluralizer (naming.collections)", () => { + test("the built-ins: standard and none", () => { + expect(pluralizer("standard")("Category")).toBe("Categories"); + expect(pluralizer("none")("Category")).toBe("Category"); + }); + + test("the project's pluralizer names every object without @collectionName", async () => { + const root = await load(); + Object.assign(root, { physicalNaming: { ...root.physicalNaming, collections: "none" } }); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistory"); + const { files } = await gen(root); + expect(files.get("Consignment.queries.ts")!).toContain("export async function listConsignment("); + }); + + test("an application registers its own, and every artifact follows it", async () => { + // Distinguishable from `standard` (ConsignmentHistories) on purpose: a test whose pluralizer agrees + // with the default cannot tell the two apart. + registerPluralizer("latin", (n) => (n.endsWith("History") ? n.slice(0, -1) + "ae" : n + "a")); + const root = await load(); + Object.assign(root, { physicalNaming: { ...root.physicalNaming, collections: "latin" } }); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistorae"); + expect(reverseHopName(history(root))).toBe("consignmentHistorae"); + const { files } = await gen(root); + expect(files.get("ConsignmentHistory.queries.ts")!).toContain("export async function listConsignmentHistorae("); + expect([...files.values()].join("\n")).toContain('"/consignment_historae"'); + }); + + test("an unknown name fails loudly, naming the built-ins", () => { + expect(() => pluralizer("klingon")).toThrow(/"naming.collections" names "klingon".*built in: standard, none/); + }); + + test("a built-in cannot be replaced", () => { + expect(() => registerPluralizer("standard", (n) => n)).toThrow(/built in/); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts b/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts index 6f5bc833e3..ac18e66834 100644 --- a/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts +++ b/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts @@ -37,7 +37,7 @@ async function gen(opts: { dryRun?: boolean } = {}) { outDir: outDir(), extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts index 81f69eca31..28576645fd 100644 --- a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts @@ -63,7 +63,7 @@ async function genTo(dir: string, extStyle: "js" | "none" = "js"): Promise config: defineConfig({ outDir: dir, dbImport: "../db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", extStyle, // The list must stay equal to `meta init`'s SCAFFOLDED_GENERATOR_NAMES — this gate's // whole claim is about the output a stock scaffold produces, so a generator that diff --git a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts index 86d9f0d3a2..3c2bd6dfd5 100644 --- a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts @@ -40,7 +40,7 @@ async function genInto(outDir: string) { outDir, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts index f77563e311..76d2cc5649 100644 --- a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts +++ b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts @@ -119,7 +119,7 @@ describe("`.extra.ts` is a convention, not a mechanism", () => { outDir: tmp, extStyle: "js", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), barrel()], }); await runGen({ config, metadata: root, projectRoot: tmp }); @@ -183,7 +183,7 @@ describe("regenerating a hand-written requirement stub", () => { const config = defineConfig({ outDir: tmp, extStyle: "js", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [requirementTests()], }); @@ -230,7 +230,7 @@ describe("regenerating a hand-written requirement stub", () => { const config = defineConfig({ outDir: tmp, extStyle: "js", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [requirementTests()], }); diff --git a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts index e0d786b2a0..ed5978befe 100644 --- a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts @@ -56,14 +56,14 @@ const MODEL: unknown[] = [ { "object.value": { name: "PhaseArgs", - children: [{ "field.int": { name: "caseId", "@required": true } }], + children: [{ "field.int": { name: "consignmentId", "@required": true } }], }, }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseArgs" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "PhaseArgs" } }, { "field.long": { name: "phaseId" } }, { "field.string": { name: "phaseName" } }, ], diff --git a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts index a1ee9330c7..fbdfd832c0 100644 --- a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts @@ -105,7 +105,7 @@ describe("projection codegen compiles (TS2724 regression guard)", () => { // Temp dir UNDER the package so node_modules (drizzle/zod) resolves. const dir = mkdtempSync(join(import.meta.dir, "tmp-proj-compile-")); try { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: dir, @@ -118,7 +118,7 @@ describe("projection codegen compiles (TS2724 regression guard)", () => { loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "sqlite" } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/projection/flattened-member-path.test.ts b/server/typescript/packages/codegen-ts/test/projection/flattened-member-path.test.ts new file mode 100644 index 0000000000..ef93574a79 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/flattened-member-path.test.ts @@ -0,0 +1,66 @@ +// Phase 5, bug G6: an origin @from may name a member of a FLATTENED value object +// (`Plan.address.city`), whose column lives on the owning table under the embedding field's +// prefix (`address_city`; `@flattenedColumnPrefix: ""` gives the bare member column). The +// loader refused the path ("no such field") and codegen could not lower it. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +const model = (from: string) => ({ + "metadata.root": { + package: "acme", + children: [ + { "object.value": { name: "Address", children: [{ "field.string": { name: "city" } }] } }, + { "object.value": { name: "ReferenceIds", children: [{ "field.string": { name: "externalReferenceId" } }] } }, + { + "object.entity": { + name: "Plan", + children: [ + { "source.rdb": { "@table": "plans" } }, + { "field.long": { name: "id" } }, + { "field.object": { name: "address", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { name: "referenceIds", "@objectRef": "ReferenceIds", "@storage": "flattened", "@flattenedColumnPrefix": "" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ], + }, + }, + { + "object.projection": { + name: "PlanExtract", + children: [ + { "source.rdb": { "@kind": "view", "@table": "v_plan_extract" } }, + { "field.long": { name: "id", extends: "Plan.id" } }, + { "field.string": { name: "picked", children: [{ "origin.passthrough": { "@from": from } }] } }, + { "identity.primary": { name: "id", extends: "Plan.id" } }, + ], + }, + }, + ], + }, +}); + +async function load(from: string) { + return new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model(from)))]); +} + +describe("G6 — a passthrough from a flattened value-object member", () => { + test("Plan.address.city reads the prefixed column of the owning table", async () => { + const { root, errors } = await load("Plan.address.city"); + expect(errors).toEqual([]); + const [v] = buildProjectionViews(root, { dialect: "postgres" }); + expect(v!.sql).toContain("p.address_city AS picked"); + }); + + test("an empty @flattenedColumnPrefix reads the bare member column", async () => { + const { root, errors } = await load("Plan.referenceIds.externalReferenceId"); + expect(errors).toEqual([]); + const [v] = buildProjectionViews(root, { dialect: "postgres" }); + expect(v!.sql).toContain("p.external_reference_id AS picked"); + }); + + test("a member the value object does not declare is refused", async () => { + const { errors } = await load("Plan.address.zip"); + expect(errors.map((e) => (e as { code?: string }).code)).toEqual(["ERR_INVALID_ORIGIN"]); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts index 923d3c8f93..59eb6401d7 100644 --- a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts @@ -60,7 +60,7 @@ describe("write-through entity: table + replica view in one module", () => { const dir = mkdtempSync(join(import.meta.dir, `tmp-replica-dup-${dialect}-`)); try { const root = await loadRoot(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -73,7 +73,7 @@ describe("write-through entity: table + replica view in one module", () => { loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts index 7f42bbc592..ec52a62163 100644 --- a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts @@ -106,7 +106,7 @@ function compile(dir: string, files: string[]): readonly ts.Diagnostic[] { async function generate(dialect: "sqlite" | "postgres", dir: string) { const root = await loadRoot(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -119,7 +119,7 @@ async function generate(dialect: "sqlite" | "postgres", dir: string) { loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts b/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts new file mode 100644 index 0000000000..5cdd7291aa --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts @@ -0,0 +1,143 @@ +// rc.19 Phase 6 — the league-gate shape end to end: a segment.filter on Contract that uses `now` +// (rc.19 `now`), a derived boolean declared ONCE on Player as origin.first over that segment +// (origin-segment) along the reverse of Contract.playerId (R-walk), and other projections that +// filter on it without outputting it — through a to-one path (entity-derived + G7 joined) or on +// their base. The SQL is built, then run on SQLite against rows that exercise the reset point. + +import { describe, test, expect } from "bun:test"; +import { Database } from "bun:sqlite"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +const MODEL = { + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Player", children: [ + { "source.rdb": { "@table": "players" } }, + { "field.long": { name: "id" } }, + { "field.boolean": { name: "hasActiveLeagueContract", children: [ + { "origin.first": { + "@via": "Player.contracts", "@of": "Contract.contractIsOnFile", + "@orderBy": ["id:desc"], "@segment": "leagueDecisive", + } }, + ] } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.entity": { name: "Contract", children: [ + { "source.rdb": { "@table": "contracts" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "playerId", "@required": true } }, + { "field.int": { name: "contractTypeId" } }, + { "field.boolean": { name: "contractIsOnFile" } }, + { "field.boolean": { name: "playerContract" } }, + { "field.date": { name: "dateReceived" } }, + { "field.date": { name: "effectiveEndDate" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "playerId", "@fields": "playerId", "@references": "Player" } }, + { "segment.filter": { name: "leagueDecisive", "@filter": { + contractTypeId: 1, + or: [ + { contractIsOnFile: false }, + { and: [ + { contractIsOnFile: true }, + { or: [{ playerContract: null }, { playerContract: true }] }, + { dateReceived: { lte: { now: "P0D" } } }, + { or: [{ effectiveEndDate: null }, { effectiveEndDate: { gte: { now: "P0D" } } }] }, + ] }, + ], + } } }, + ] } }, + { "object.entity": { name: "Camp", children: [ + { "source.rdb": { "@table": "camps" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "playerId", "@required": true } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "playerId", "@fields": "playerId", "@references": "Player" } }, + ] } }, + { "object.entity": { name: "Authorization", children: [ + { "source.rdb": { "@table": "authorizations" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "campId", "@required": true } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "campId", "@fields": "campId", "@references": "Camp" } }, + ] } }, + { "object.projection": { name: "AuthorizationExtract", "@filter": { "campId.playerId.hasActiveLeagueContract": true }, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_authorization_extract" } }, + { "field.long": { name: "id", extends: "Authorization.id" } }, + { "field.string": { name: "code", extends: "Authorization.code" } }, + { "identity.primary": { name: "id", extends: "Authorization.id" } }, + ] } }, + { "object.projection": { name: "PlayerExtract", "@filter": { hasActiveLeagueContract: true }, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_player_extract" } }, + { "field.long": { name: "id", extends: "Player.id" } }, + { "identity.primary": { name: "id", extends: "Player.id" } }, + ] } }, + ], + }, +}; + +async function load() { + const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(result.errors).toEqual([]); + return result.root; +} + +describe("the league gate: an entity-derived boolean over a segment, used in other projections' @filter", () => { + test("loads: Player needs no read source for a derived field projections reach", async () => { + await load(); + }); + + test("the path filter inlines the player's correlated subquery on the joined player", async () => { + const views = buildProjectionViews(await load(), { dialect: "postgres" }); + const auth = views.find((v) => v.name === "v_authorization_extract")!; + expect(auth.sql).toContain("LEFT OUTER JOIN camps c ON c.id = a.camp_id"); + expect(auth.sql).toContain("LEFT OUTER JOIN players p ON p.id = c.player_id"); + // The segment's predicate (with `now` of the date kind) scopes the subquery; it is ordered id:desc. + expect(auth.sql).toMatch(/WHERE \(\(SELECT (\w+)\.contract_is_on_file FROM contracts \1 WHERE \1\.player_id = p\.id AND \(\1\.contract_type_id = 1 AND/); + expect(auth.sql).toContain(".date_received <= CAST(((now() AT TIME ZONE 'UTC') + INTERVAL 'P0D') AS DATE)"); + expect(auth.sql).toMatch(/ORDER BY \w+\.id DESC NULLS LAST, \w+\.id ASC LIMIT 1\)\) = TRUE/); + expect(auth.sql).not.toContain("has_active_league_contract"); + expect(auth.dependsOn).toEqual(expect.arrayContaining(["authorizations", "camps", "players", "contracts"])); + }); + + test("on the base row, the same predicate filters the players", async () => { + const views = buildProjectionViews(await load(), { dialect: "postgres" }); + const pat = views.find((v) => v.name === "v_player_extract")!; + expect(pat.sql).toMatch(/WHERE \(\(SELECT \w+\.contract_is_on_file FROM contracts \w+ WHERE \w+\.player_id = p\.id/); + }); + + test("runs: the latest decisive row decides, an opt-out resets, future and expired rows do not count", async () => { + const views = buildProjectionViews(await load(), { dialect: "sqlite" }); + const db = new Database(":memory:"); + db.exec(` + CREATE TABLE players (id INTEGER PRIMARY KEY); + CREATE TABLE contracts (id INTEGER PRIMARY KEY, player_id INTEGER, contract_type_id INTEGER, contract_is_on_file INTEGER, + player_contract INTEGER, date_received TEXT, effective_end_date TEXT); + CREATE TABLE camps (id INTEGER PRIMARY KEY, player_id INTEGER); + CREATE TABLE authorizations (id INTEGER PRIMARY KEY, camp_id INTEGER, code TEXT); + `); + for (const v of views) db.exec(`CREATE VIEW ${v.name} AS ${v.sql}`); + // 1: live contract. 2: contract, then an opt-out after it. 3: opt-out, then a contract after it. + // 4: only a future-dated contract. 5: only an expired contract. 6: a live non-league contract. + // 7: live contract with playerContract = false (refused). + db.exec(` + INSERT INTO players (id) VALUES (1), (2), (3), (4), (5), (6), (7); + INSERT INTO contracts VALUES + (10, 1, 1, 1, NULL, '2020-01-01', NULL), + (20, 2, 1, 1, 1, '2020-01-01', NULL), (21, 2, 1, 0, NULL, NULL, NULL), + (30, 3, 1, 0, NULL, NULL, NULL), (31, 3, 1, 1, 1, '2020-01-01', '2999-01-01'), + (40, 4, 1, 1, 1, '2999-01-01', NULL), + (50, 5, 1, 1, 1, '2020-01-01', '2020-06-01'), + (60, 6, 2, 1, 1, '2020-01-01', NULL), + (70, 7, 1, 1, 0, '2020-01-01', NULL); + INSERT INTO camps (id, player_id) VALUES (100, 1), (200, 2), (300, 3), (400, 4), (500, 5), (600, 6), (700, 7); + INSERT INTO authorizations (id, camp_id, code) VALUES (1000, 100, 'a'), (2000, 200, 'b'), (3000, 300, 'c'), + (4000, 400, 'd'), (5000, 500, 'e'), (6000, 600, 'f'), (7000, 700, 'g'); + `); + const ids = (sql: string) => (db.query(sql).all() as { id: number }[]).map((r) => r.id); + expect(ids("SELECT id FROM v_player_extract ORDER BY id")).toEqual([1, 3]); + expect(ids("SELECT id FROM v_authorization_extract ORDER BY id")).toEqual([1000, 3000]); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts new file mode 100644 index 0000000000..952eaf9bd4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts @@ -0,0 +1,68 @@ +// rc.21 part B: the shared model of the view-vocabulary tests (golden SQL and live Postgres). +export const RC21B_ENTITIES: unknown[] = [ + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, + { "field.string": { name: "value" } }, + { "field.boolean": { name: "preferred" } }, + { "field.int": { name: "rank" } }, + ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "firstName" } }, + { "field.string": { name: "lastName" } }, + { "field.string": { name: "zip" } }, + { "field.long": { name: "regionId" } }, + { "field.long": { name: "defaultWarehouseId" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, + { "field.string": { name: "loyaltyTier", children: [ + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } }, + ] } }, + { "object.entity": { name: "Address", children: [ + { "source.rdb": { "@table": "addresses" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.string": { name: "street" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } }, + ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.int": { name: "stage" } }, + { "field.string": { name: "externalRef" } }, + { "field.timestamp": { name: "updatedAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } }, + ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId", "@required": true } }, + { "field.long": { name: "customerId" } }, + { "field.int": { name: "stage" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } }, + ] } }, +]; + +/** The same model without the origin.function field (SQLite has no stored functions). */ +export function withoutFunction(entities: unknown[]): unknown[] { + const clone = JSON.parse(JSON.stringify(entities)) as Record[] }>[]; + for (const e of clone) { + const ent = e["object.entity"]; + if (ent?.children) ent.children = ent.children.filter((c) => c["field.string"]?.name !== "loyaltyTier"); + } + return clone; +} diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts new file mode 100644 index 0000000000..8d3e901cbd --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -0,0 +1,320 @@ +// rc.21 part B — the view vocabulary, golden SQL per construct on Postgres and SQLite, and the +// SQLite spellings run on a real SQLite (the live Postgres run is integration-tests' +// view-vocabulary-rc21-pg.test.ts). + +import { describe, test, expect } from "bun:test"; +import { Database } from "bun:sqlite"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; +import { RC21B_ENTITIES, withoutFunction } from "./rc21b-view-vocabulary.fixture.js"; + +const orderRow = (fields: unknown[]) => ({ "object.projection": { name: "OrderRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_order_row" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + ...fields, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }); +const computed = (name: string, subType: string, expr: unknown) => + ({ [`field.${subType}`]: { name, children: [ { "origin.computed": { "@expr": expr } } ] } }); + +async function views(dialect: "postgres" | "sqlite", ...projections: unknown[]): Promise> { + // The origin.function field must be reached (an entity has no read source for it), so only the + // tests that read it keep it. + const reachesFunction = JSON.stringify(projections).includes("loyaltyTier"); + const entities = reachesFunction ? RC21B_ENTITIES : withoutFunction(RC21B_ENTITIES); + const doc = { "metadata.root": { package: "acme", children: [...entities, ...projections] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toEqual([]); + return new Map(buildProjectionViews(root, { dialect }).map((v) => [v.name, v.sql])); +} +const one = async (dialect: "postgres" | "sqlite", projection: unknown) => [...(await views(dialect, projection)).values()][0]!; + +describe("U12 cast and U2 a typed NULL of an unbounded varchar", () => { + const p = orderRow([ + computed("ref", "string", { fn: "coalesce", args: [{ field: "externalRef" }, { cast: { field: "id" }, as: "string" }] }), + computed("nothing", "string", { cast: { value: null }, as: "string", dbColumnType: "varchar" }), + computed("code", "string", { cast: { field: "externalRef" }, as: "string", dbColumnType: "character(3)" }), + ]); + test("postgres", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("COALESCE(o.external_ref, CAST(o.id AS TEXT)) AS ref"); + expect(sql).toContain("CAST(NULL AS VARCHAR) AS nothing"); + expect(sql).toContain("CAST(o.external_ref AS CHARACTER(3)) AS code"); + }); + test("sqlite", async () => { + const sql = await one("sqlite", p); + expect(sql).toContain("COALESCE(o.external_ref, CAST(o.id AS TEXT)) AS ref"); + expect(sql).toContain("CAST(NULL AS TEXT) AS nothing"); + }); +}); + +describe("U8 an int-stored enum and an int in one case, through the cast", () => { + test("postgres", async () => { + const sql = await one("postgres", orderRow([computed("outcome", "int", { + case: [{ when: { op: "eq", left: { field: "stage" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], + else: { field: "stage" } })])); + expect(sql).toContain("(CASE WHEN o.stage = 0 THEN CAST(o.status AS INTEGER) ELSE o.stage END) AS outcome"); + }); +}); + +describe("U11 string functions, and U3 a path the view does not output", () => { + const p = orderRow([ + computed("zip5", "string", { fn: "splitPart", args: [{ field: "customerId.zip" }, { value: "-" }, { value: 1 }] }), + computed("fullName", "string", { fn: "btrim", args: [{ fn: "concatWs", args: [{ value: " " }, { field: "customerId.firstName" }, { field: "customerId.lastName" }] }] }), + computed("tag", "string", { fn: "concat", args: [{ fn: "lower", args: [{ field: "externalRef" }] }, { value: "#" }, { field: "id" }] }), + computed("mid", "string", { fn: "replace", args: [{ fn: "substring", args: [{ field: "externalRef" }, { value: 2 }, { value: 3 }] }, { value: "X" }, { value: "" }] }), + computed("ends", "string", { fn: "concat", args: [{ fn: "left", args: [{ field: "externalRef" }, { value: 1 }] }, { fn: "right", args: [{ field: "externalRef" }, { value: 1 }] }] }), + computed("len", "int", { fn: "length", args: [{ fn: "upper", args: [{ field: "externalRef" }] }] }), + computed("noRef", "string", { fn: "nullif", args: [{ field: "externalRef" }, { value: "NONE" }] }), + ]); + test("postgres: each function by its own name, and the path joined, not output", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("SPLIT_PART(c.zip, '-', 1) AS zip5"); + expect(sql).toContain("BTRIM(CONCAT_WS(' ', c.first_name, c.last_name)) AS full_name"); + expect(sql).toContain("CONCAT(LOWER(o.external_ref), '#', o.id) AS tag"); + expect(sql).toContain("REPLACE(SUBSTR(o.external_ref, 2, 3), 'X', '') AS mid"); + expect(sql).toContain("CONCAT(LEFT(o.external_ref, 1), RIGHT(o.external_ref, 1)) AS ends"); + expect(sql).toContain("CHAR_LENGTH(UPPER(o.external_ref)) AS len"); + expect(sql).toContain("NULLIF(o.external_ref, 'NONE') AS no_ref"); + expect(sql).toContain("LEFT OUTER JOIN customers c ON c.id = o.customer_id"); + expect(sql).not.toMatch(/AS zip\b/); + }); + test("sqlite: the same values from SQLite's own functions", async () => { + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("INSERT INTO customers (id, first_name, last_name, zip) VALUES (10, 'Ada', 'Lovelace', '02139-4307'), (11, NULL, 'Hopper', '12345')"); + db.run("INSERT INTO orders (id, customer_id, external_ref) VALUES (1, 10, 'AXXBCD'), (2, 11, 'NONE'), (3, NULL, NULL)"); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT id, zip5, full_name, tag, mid, ends, len, no_ref FROM v ORDER BY id").all()).toEqual([ + { id: 1, zip5: "02139", full_name: "Ada Lovelace", tag: "axxbcd#1", mid: "B", ends: "AD", len: 6, no_ref: "AXXBCD" }, + { id: 2, zip5: "12345", full_name: "Hopper", tag: "none#2", mid: "ONE", ends: "NE", len: 4, no_ref: null }, + { id: 3, zip5: null, full_name: "", tag: "#3", mid: null, ends: "", len: null, no_ref: null }, + ]); + }); + test("sqlite: splitPart beyond the first part is refused, not mis-spelled", async () => { + await expect(one("sqlite", orderRow([computed("p2", "string", { fn: "splitPart", args: [{ field: "externalRef" }, { value: "-" }, { value: 2 }] })]))) + .rejects.toThrow(/splitPart on SQLite is lowered only for the first part/); + }); +}); + +describe("U13 greatest / least over an aggregate, and U4 a correlated path operand", () => { + const p = orderRow([ + { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + computed("touched", "timestamp", { fn: "greatest", args: [{ field: "updatedAt" }, { field: "lastEvent" }] }), + computed("earliest", "timestamp", { fn: "least", args: [{ field: "updatedAt" }, { field: "lastEvent" }] }), + { "field.long": { name: "eventByCustomer", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + ]); + test("postgres", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("GREATEST(o.updated_at, MAX(o0.created_at)) AS touched"); + expect(sql).toContain("LEAST(o.updated_at, MAX(o0.created_at)) AS earliest"); + expect(sql).toContain("WHERE o1.order_id = o.id AND o1.customer_id = c.id ORDER BY"); + expect(sql).toContain("GROUP BY o.id, c.id"); + }); + test("sqlite: greatest / least skip NULLs as Postgres does", async () => { + const sql = await one("sqlite", p); + expect(sql).toContain("MAX(COALESCE(o.updated_at, MAX(o0.created_at)), COALESCE(MAX(o0.created_at), o.updated_at)) AS touched"); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("CREATE TABLE order_events (id INTEGER PRIMARY KEY, order_id INTEGER, customer_id INTEGER, stage INTEGER, created_at TEXT)"); + db.run("INSERT INTO customers (id) VALUES (10)"); + db.run("INSERT INTO orders (id, customer_id, updated_at) VALUES (1, 10, '2026-01-05'), (2, 10, NULL), (3, 10, '2026-01-01')"); + db.run("INSERT INTO order_events (id, order_id, customer_id, created_at) VALUES (100, 1, 10, '2026-02-01'), (101, 2, 9, '2026-03-01'), (102, 2, 10, '2026-03-02')"); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT id, touched, earliest, event_by_customer FROM v ORDER BY id").all()).toEqual([ + { id: 1, touched: "2026-02-01", earliest: "2026-01-05", event_by_customer: 100 }, + { id: 2, touched: "2026-03-02", earliest: "2026-03-02", event_by_customer: 102 }, + { id: 3, touched: "2026-01-01", earliest: "2026-01-01", event_by_customer: null }, + ]); + }); +}); + +describe("U10 origin.function", () => { + test("postgres: the declared call, its arguments read on the reached row", async () => { + const sql = await one("postgres", orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])); + // fix round I4: the call is cast to the field's column type, so the column has it. + expect(sql).toContain("CAST(app.loyalty_tier(c.id, c.zip) AS TEXT) AS tier"); + }); + test("codegen refuses a signature the loader would refuse (a caller that skipped it)", async () => { + const bad = JSON.parse(JSON.stringify(RC21B_ENTITIES).replace('"@params":["long","string"]', '"@params":["int","string"]')); + const doc = { "metadata.root": { package: "acme", children: [...bad, orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])] } }; + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(() => buildProjectionViews(root, { dialect: "postgres" })).toThrow(/argument 1 "id" is a field.long, but parameter 1 is declared int/); + }); + test("a SQLite view refuses it: SQLite has no stored functions", async () => { + const doc = { "metadata.root": { package: "acme", children: [...RC21B_ENTITIES, orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])] } }; + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(() => buildProjectionViews(root, { dialect: "sqlite" })).toThrow(/calls a database function, which SQLite does not have/); + }); +}); + +describe("U14 @grain — one row per array element", () => { + const p = { "object.projection": { name: "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_customer_contact" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + { "field.int": { name: "position" } }, + { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }, + { "field.int": { name: "rank", children: [ { "origin.passthrough": { "@from": "Contact.rank" } } ] } } ] } }; + test("postgres", async () => { + const sql = await one("postgres", p); + // fix round M3: a non-array value (JSON null, an object, a scalar) has no element. + expect(sql).toContain("FROM customers c CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(c.contacts) = 'array' THEN c.contacts END) WITH ORDINALITY AS mo_el(value, ordinality)"); + expect(sql).toContain("CAST(mo_el.ordinality AS INTEGER) AS position"); + expect(sql).toContain("(mo_el.value ->> 'kind') AS kind"); + expect(sql).toContain("CAST((mo_el.value ->> 'rank') AS INTEGER) AS rank"); + }); + test("sqlite", async () => { + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run(`INSERT INTO customers (id, contacts) VALUES (1, '[{"kind":"email","rank":1},{"kind":"phone","rank":2}]'), (2, '[]'), (3, NULL), (4, '{"kind":"x"}'), (5, 'null'), (6, '7')`); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT customer_id, position, kind, rank FROM v ORDER BY customer_id, position").all()).toEqual([ + { customer_id: 1, position: 1, kind: "email", rank: 1 }, + { customer_id: 1, position: 2, kind: "phone", rank: 2 }, + ]); + }); +}); + +describe("U15 @union", () => { + const branches = [ + { "object.projection": { name: "PersonBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Customer.id" } }, + computed("label", "string", { fn: "lower", args: [{ field: "lastName" }] }) ] } }, + { "object.projection": { name: "AddressBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Address.customerId" } }, + computed("label", "string", { fn: "lower", args: [{ field: "street" }] }) ] } }, + ]; + const union = (all: boolean) => ({ "object.projection": { name: "People", extends: "PersonBranch", "@union": ["AddressBranch"], + ...(all ? { "@unionAll": true } : {}), children: [ { "source.rdb": { "@kind": "view", "@table": "v_people" } } ] } }); + test("postgres: UNION by default, UNION ALL on request, and each branch reads its own base", async () => { + const sql = (await views("postgres", ...branches, union(false))).get("v_people")!; + expect(sql).toBe([ + " SELECT\n c.id AS person_id,\n LOWER(c.last_name) AS label\n FROM customers c", + " UNION", + " SELECT\n a.customer_id AS person_id,\n LOWER(a.street) AS label\n FROM addresses a", + ].join("\n")); + expect((await views("postgres", ...branches, union(true))).get("v_people")).toContain("\n UNION ALL\n"); + }); + test("sqlite: removes duplicates, or keeps them", async () => { + for (const all of [false, true]) { + const sql = (await views("sqlite", ...branches, union(all))).get("v_people")!; + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE addresses (id INTEGER PRIMARY KEY, customer_id INTEGER, street TEXT)"); + db.run("INSERT INTO customers (id, last_name) VALUES (1, 'Main')"); + db.run("INSERT INTO addresses (id, customer_id, street) VALUES (9, 1, 'main'), (10, 2, 'Elm')"); + db.run(`CREATE VIEW v AS ${sql}`); + expect((db.query("SELECT count(*) AS n FROM v").get() as { n: number }).n).toBe(all ? 3 : 2); + } + }); +}); + +// rc.21 part B: two fixes the vocabulary needed to build its motivating views. +describe("a projection over a TPH root reads its subtypes' columns; a unique reverse hop is to-one", () => { + const tph = [ + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 10 } }, + { "field.long": { name: "lockerId" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.entity": { name: "Locker", children: [ + { "source.rdb": { "@table": "lockers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "number" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "LockerKey", children: [ + { "source.rdb": { "@table": "locker_keys" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "lockerId" } }, + { "field.string": { name: "note" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { name: "lockerId", "@fields": "lockerId", "@references": "Locker" } } ] } }, + ]; + async function load(extra: unknown[]) { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...tph, ...extra] } }))]); + return { root, errors: errors.map((e) => e.message) }; + } + test("an extender with no identity keeps the super's anchor, and a subtype column reads the shared table", async () => { + const { root, errors } = await load([ + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + { "object.projection": { name: "VehicleRow", extends: "VehicleBase", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_vehicles" } }, + { "field.string": { name: "externalKey", extends: "Truck.payloadClass" } } ] } }, + ]); + expect(errors).toEqual([]); + const sql = buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; + expect(sql).toContain("v.id AS vehicle_id"); + expect(sql).toContain("v.payload_class AS external_key"); + expect(sql).toContain("FROM vehicles v"); + expect(sql).not.toContain("'TRUCK'"); + }); + const viaCard = (unique: boolean | "partial") => [ + { "object.entity": { name: "LockerKey", children: [ + { "source.rdb": { "@table": "locker_keys" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "lockerId" } }, + { "field.string": { name: "note" } }, + { "identity.primary": { "@fields": "id" } }, + ...(unique ? [{ "identity.secondary": { name: "locker_keys_locker_uq", "@fields": "lockerId", + ...(unique === "partial" ? { "@where": "\"note\" IS NOT NULL" } : {}) } }] : []), + { "identity.reference": { name: "lockerId", "@fields": "lockerId", "@references": "Locker" } } ] } }, + ]; + test("a passthrough over a reverse hop loads when the holder's reference fields are a unique identity, and only then", async () => { + const projection = { "object.projection": { name: "LockerRow", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_lockers" } }, + { "field.long": { name: "id", extends: "Locker.id" } }, + { "field.string": { name: "note", children: [ { "origin.passthrough": { "@from": "LockerKey.note", "@via": "Locker.lockerKeys" } } ] } }, + { "identity.primary": { name: "id", extends: "Locker.primary" } } ] } }; + const withUnique = async (unique: boolean | "partial") => { + const doc = { "metadata.root": { package: "acme", children: [...tph.slice(0, 3), ...viaCard(unique), projection] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + return { root, errors: errors.map((e) => e.message) }; + }; + const ok = await withUnique(true); + expect(ok.errors).toEqual([]); + expect(buildProjectionViews(ok.root, { dialect: "postgres" })[0]!.sql).toContain("LEFT OUTER JOIN locker_keys l0 ON l0.locker_id = l.id"); + expect((await withUnique(false)).errors.some((m) => /is to-many/.test(m))).toBe(true); + // A partial unique index is unique only over its subset, so the hop stays to-many. + expect((await withUnique("partial")).errors.some((m) => /is to-many/.test(m))).toBe(true); + }); +}); + +// rc.21 part B fix round (M9): SQLite's left / right / substring give Postgres's meaning for every count. +describe("SQLite left, right and substring over non-positive counts", () => { + test("match Postgres", async () => { + const p = orderRow([ + computed("l2", "string", { fn: "left", args: [{ field: "externalRef" }, { value: 2 }] }), + computed("lm2", "string", { fn: "left", args: [{ field: "externalRef" }, { value: -2 }] }), + computed("lm9", "string", { fn: "left", args: [{ field: "externalRef" }, { value: -9 }] }), + computed("r2", "string", { fn: "right", args: [{ field: "externalRef" }, { value: 2 }] }), + computed("rm2", "string", { fn: "right", args: [{ field: "externalRef" }, { value: -2 }] }), + computed("r0", "string", { fn: "right", args: [{ field: "externalRef" }, { value: 0 }] }), + computed("s23", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: 2 }, { value: 3 }] }), + computed("s03", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: 0 }, { value: 3 }] }), + computed("sm13", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: -1 }, { value: 3 }] }), + computed("sm1", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: -1 }] }), + ]); + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("INSERT INTO orders (id, external_ref) VALUES (1, 'abcdef')"); + db.run(`CREATE VIEW v AS ${sql}`); + // Postgres: left('abcdef',2)='ab', left(-2)='abcd', left(-9)='', right(2)='ef', right(-2)='cdef', right(0)='', + // substr(s,2,3)='bcd', substr(s,0,3)='ab', substr(s,-1,3)='a', substr(s,-1)='abcdef'. + expect(db.query("SELECT l2, lm2, lm9, r2, rm2, r0, s23, s03, sm13, sm1 FROM v").get()).toEqual({ + l2: "ab", lm2: "abcd", lm9: "", r2: "ef", rm2: "cdef", r0: "", s23: "bcd", s03: "ab", sm13: "a", sm1: "abcdef", + }); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/reference-flattened-member.test.ts b/server/typescript/packages/codegen-ts/test/projection/reference-flattened-member.test.ts new file mode 100644 index 0000000000..defab3ee51 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/reference-flattened-member.test.ts @@ -0,0 +1,87 @@ +// Phase 5, bug G6 (reference half): an identity.reference whose @fields names a member of a +// FLATTENED value object (`address.countryId`). The member's column lives on the owning table +// under the embedding's prefix (`address_country_id`), so a @via hop over the reference must +// join on that column, and `meta migrate` must put the foreign key on it. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts/expected"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +const model = { + "metadata.root": { + package: "acme", + children: [ + { + "object.entity": { + name: "Country", + children: [ + { "source.rdb": { "@table": "countries" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "name" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ], + }, + }, + { + "object.value": { + name: "Address", + children: [{ "field.string": { name: "city" } }, { "field.long": { name: "countryId" } }], + }, + }, + { + "object.entity": { + name: "Plan", + children: [ + { "source.rdb": { "@table": "plans" } }, + { "field.long": { name: "id" } }, + { "field.object": { name: "address", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "countryId", "@fields": "address.countryId", "@references": "Country" } }, + ], + }, + }, + { + "object.projection": { + name: "PlanExtract", + children: [ + { "source.rdb": { "@kind": "view", "@table": "v_plan_extract" } }, + { "field.long": { name: "id", extends: "Plan.id" } }, + { + "field.string": { + name: "countryName", + children: [{ "origin.passthrough": { "@from": "Country.name", "@via": "Plan.countryId" } }], + }, + }, + { "identity.primary": { name: "id", extends: "Plan.id" } }, + ], + }, + }, + ], + }, +}; + +async function load() { + return new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); +} + +describe("G6 — an identity.reference over a flattened value-object member", () => { + test("loads", async () => { + const { errors } = await load(); + expect(errors).toEqual([]); + }); + + test("a @via hop over it joins on the member's prefixed column", async () => { + const { root } = await load(); + const [v] = buildProjectionViews(root, { dialect: "postgres" }); + expect(v!.sql).toContain("countries c ON c.id = p.address_country_id"); + }); + + test("meta migrate puts the foreign key on the member's column", async () => { + const { root } = await load(); + const plans = buildExpectedSchema(root).tables.find((t) => t.name === "plans")!; + expect(plans.foreignKeys.map((fk) => [fk.columns, fk.refTable, fk.refColumns])).toEqual([ + [["address_country_id"], "countries", ["id"]], + ]); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts new file mode 100644 index 0000000000..b93a4b5fa2 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts @@ -0,0 +1,108 @@ +// Phase 5, bug R-walk: an origin's @via may walk the REVERSE of an identity.reference the +// far entity declares, with no relationship declared for it. The hop is named after the +// referencing entity's collection name (lowerFirst(pluralize()), `Player.contracts` +// for Contract.player). The loader used to refuse it ("no such relationship or reference"), +// though codegen's correlations walk references both ways. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +const MODEL = { + "metadata.root": { + "package": "acme::league", + "children": [ + { + "object.entity": { + "name": "Player", + "children": [ + { "source.rdb": { "@table": "players" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + }, + { + "object.entity": { + "name": "Contract", + "children": [ + { "source.rdb": { "@table": "contracts" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "playerId" } }, + { "field.boolean": { "name": "onFile" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "player", "@fields": "playerId", "@references": "acme::league::Player" } } + ] + } + }, + { + "object.projection": { + "name": "PlayerContractSummary", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_player_contract_summary" } }, + { "field.long": { "name": "id", "extends": "acme::league::Player.id" } }, + { "field.int": { "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::league::Contract.id", "@via": "acme::league::Player.contracts" } } ] } }, + { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::league::Contract.onFile", "@via": "acme::league::Player.contracts", "@orderBy": ["id:desc"] } } ] } }, + { "identity.primary": { "name": "id", "extends": "acme::league::Player.id" } } + ] + } + } + ] + } +}; + +async function load(model: unknown) { + return new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); +} + +/** The model with a second reference from Contract to Player: the reverse hop is ambiguous. */ +function twoReferences(): unknown { + const m = JSON.parse(JSON.stringify(MODEL)); + const contract = m["metadata.root"].children[1]["object.entity"].children; + contract.push({ "field.long": { name: "witnessId" } }); + contract.push({ "identity.reference": { name: "witness", "@fields": "witnessId", "@references": "acme::league::Player" } }); + return m; +} + +describe("R-walk — a @via hop over the reverse of an identity.reference", () => { + test("loads with no relationship declared", async () => { + const { errors } = await load(MODEL); + expect(errors).toEqual([]); + }); + + test("the aggregate joins the referencing table, and the first correlates on its FK", async () => { + const { root, errors } = await load(MODEL); + expect(errors).toEqual([]); + const [v] = buildProjectionViews(root, { dialect: "postgres" }); + expect(v!.sql).toContain("COUNT(DISTINCT c.id) AS contract_count"); + expect(v!.sql).toContain("LEFT OUTER JOIN contracts c ON c.player_id = p.id"); + expect(v!.sql).toMatch(/\(SELECT c0\.on_file FROM contracts c0 WHERE c0\.player_id = p\.id ORDER BY c0\.id DESC NULLS LAST, c0\.id ASC LIMIT 1\) AS latest_on_file/); + }); + + test("two references from the holder make the reverse hop ambiguous, named", async () => { + const { errors } = await load(twoReferences()); + expect(errors.length).toBeGreaterThan(0); + expect((errors[0] as { code?: string }).code).toBe("ERR_AMBIGUOUS_PATH"); + expect(String(errors[0]!.message)).toContain('"player", "witness"'); + }); +}); + +// rc.21 (U9): the first hop from the base entity already walks a reference backwards; what an +// author who guesses the name (the reference's own name, a plural a @collectionName overrides) +// lacked was the name the rule gives. The refusal now lists the reverse hops onto the entity. +describe("a reverse hop under a guessed name", () => { + test("the refusal names the reverse hops onto the entity", async () => { + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::league::Player.contracts", "acme::league::Player.player")); + const { errors } = await load(m); + const msg = errors.map((e) => String(e.message)).join("\n"); + expect(msg).toContain(`no such relationship or reference "player" on Player`); + expect(msg).toContain(`The reverse hops from Player are: "contracts" (walks Contract.player backwards)`); + }); + + test("a @collectionName renames the hop, and the refusal says so", async () => { + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::league::Player.contracts", "acme::league::Player.contracts2")); + m["metadata.root"].children[1]["object.entity"]["@collectionName"] = "ContractLog"; + const { errors } = await load(m); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`"contractLog" (walks Contract.player backwards)`); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/routes-file.test.ts b/server/typescript/packages/codegen-ts/test/projection/routes-file.test.ts index 0fccd76a57..2a1b76953e 100644 --- a/server/typescript/packages/codegen-ts/test/projection/routes-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/routes-file.test.ts @@ -16,11 +16,12 @@ import { servedReport } from "../../src/source-detect.js"; import { hasUiSurface } from "../../src/generators/agent-ui-page.js"; import { runGen } from "../../src/runner.js"; import { routesFile } from "../../src/generators/routes-file.js"; -import { ERR_COLLECTION_NAME_COLLISION } from "../../src/naming/collection-name-collision.js"; +import { ERR_NAME_COLLISION } from "../../src/naming/name-claims.js"; import { makeRenderContext } from "../../src/render-context.js"; import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import { GENERATED_HEADER } from "../../src/constants.js"; +import { ERR_COLLECTION_NAME_COLLISION } from "../../src/naming/collection-name-collision.js"; // --------------------------------------------------------------------------- // Shared fixture loader diff --git a/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts b/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts new file mode 100644 index 0000000000..380145f138 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts @@ -0,0 +1,22 @@ +// rc.21 — a projection's @filter on a @stringValueMap enum compares the member's stored string. + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +test("a view @filter on a @stringValueMap enum binds the stored string", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Upload", children: [ + { "source.rdb": { "@table": "uploads" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "PendingUploads", "@filter": { status: "Pending" }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_pending_uploads" } }, + { "field.long": { name: "id", extends: "Upload.id" } }, + { "identity.primary": { name: "id", extends: "Upload.id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + const sql = buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; + expect(sql).toContain("'pending'"); + expect(sql).not.toContain("'Pending'"); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts index 99158cc52d..86947e8cef 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts @@ -80,12 +80,18 @@ describe("computed-over-joined — an expression reads other projection fields", expect(sql).toContain("NOT (s.name IS NOT NULL) AS unnamed"); }); - test("an aggregate is not readable from an expression", async () => { - const errors = await errorsOf(view("Agg", [ + // rc.21 part B (U13, kept from the 1.2.x line): a scalar aggregate is readable (on the grouped row); a collect is not. + test("a scalar aggregate is readable from an expression; a collect is not", async () => { + const sql = await sqlOf(view("Agg", [ { "field.long": { name: "entries", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "gt", left: { field: "entries" }, right: { value: 3 } } } }] } }, ])); - expect(errors.some((e) => e.includes("entries"))).toBe(true); + expect(sql).toContain("COUNT(DISTINCT c0.id) > 3 AS busy"); + const errors = await errorsOf(view("Collect", [ + { "field.long": { name: "ids", isArray: true, children: [{ "origin.aggregate": { "@agg": "collect", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, + { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "isNull", arg: { field: "ids" } } } }] } }, + ])); + expect(errors.some((e) => e.includes("ids"))).toBe(true); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/tph-abstract-level.test.ts b/server/typescript/packages/codegen-ts/test/projection/tph-abstract-level.test.ts index e0dba4d98c..2afd920786 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tph-abstract-level.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tph-abstract-level.test.ts @@ -9,13 +9,13 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "object.entity": { name: "Authorization", "@discriminator": "type", children: [ { "source.rdb": { "@table": "authorizations" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@required": true, "@values": ["Copay", "Prior", "Appeal"], "@intValueMap": { Copay: 1, Prior: 2, Appeal: 3 } } }, + { "field.enum": { name: "type", "@required": true, "@values": ["Coupon", "Permit", "Appeal"], "@intValueMap": { Coupon: 1, Permit: 2, Appeal: 3 } } }, { "field.string": { name: "code" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, { "object.entity": { name: "CardAuthorization", extends: "Authorization", abstract: true, children: [] } }, - { "object.entity": { name: "CopayAuthorization", extends: "CardAuthorization", "@discriminatorValue": "Copay", children: [] } }, - { "object.entity": { name: "PriorAuthorization", extends: "CardAuthorization", "@discriminatorValue": "Prior", children: [] } }, + { "object.entity": { name: "CouponAuthorization", extends: "CardAuthorization", "@discriminatorValue": "Coupon", children: [] } }, + { "object.entity": { name: "PermitAuthorization", extends: "CardAuthorization", "@discriminatorValue": "Permit", children: [] } }, { "object.entity": { name: "AppealAuthorization", extends: "Authorization", "@discriminatorValue": "Appeal", children: [] } }, { "object.projection": { name: "CardAuthView", children: [ { "source.rdb": { "@kind": "view", "@table": "v_card_auth" } }, diff --git a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts index 76cf5cd12a..b9691fb314 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts @@ -7,21 +7,21 @@ import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; const ENTITIES = [ - { "object.entity": { name: "CopayCard", children: [ - { "source.rdb": { "@table": "copay_cards" } }, + { "object.entity": { name: "CouponCard", children: [ + { "source.rdb": { "@table": "coupon_cards" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, { "object.entity": { name: "Authorization", "@discriminator": "type", children: [ { "source.rdb": { "@table": "authorizations" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@required": true, "@values": ["Copay", "Prior"], "@intValueMap": { Copay: 1, Prior: 2 } } }, + { "field.enum": { name: "type", "@required": true, "@values": ["Coupon", "Permit"], "@intValueMap": { Coupon: 1, Permit: 2 } } }, { "field.string": { name: "code" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.entity": { name: "CopayAuthorization", extends: "Authorization", "@discriminatorValue": "Copay", children: [ - { "field.long": { name: "copayCardId" } }, - { "identity.reference": { name: "copayCard", "@fields": "copayCardId", "@references": "CopayCard" } }, + { "object.entity": { name: "CouponAuthorization", extends: "Authorization", "@discriminatorValue": "Coupon", children: [ + { "field.long": { name: "couponCardId" } }, + { "identity.reference": { name: "couponCard", "@fields": "couponCardId", "@references": "CouponCard" } }, ] } }, ]; @@ -35,11 +35,11 @@ async function viewSql(projections: unknown[]): Promise { describe("a view over a TPH subtype carries its discriminator", () => { test("a subtype base filters the shared table to its rows", async () => { - const sql = await viewSql([{ "object.projection": { name: "CopayAuthView", children: [ - { "source.rdb": { "@kind": "view", "@table": "v_copay_auth" } }, - { "field.long": { name: "id", extends: "CopayAuthorization.id" } }, - { "field.string": { name: "code", extends: "CopayAuthorization.code" } }, - { "identity.primary": { name: "id", extends: "CopayAuthorization.id" } }, + const sql = await viewSql([{ "object.projection": { name: "CouponAuthView", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_coupon_auth" } }, + { "field.long": { name: "id", extends: "CouponAuthorization.id" } }, + { "field.string": { name: "code", extends: "CouponAuthorization.code" } }, + { "identity.primary": { name: "id", extends: "CouponAuthorization.id" } }, ] } }]); expect(sql).toContain("FROM authorizations c"); expect(sql).toContain("WHERE c.type = 1"); @@ -48,13 +48,13 @@ describe("a view over a TPH subtype carries its discriminator", () => { test("a join onto a subtype scopes the join, not the base rows", async () => { const sql = await viewSql([{ "object.projection": { name: "CardAuthCount", children: [ { "source.rdb": { "@kind": "view", "@table": "v_card_auth_count" } }, - { "field.long": { name: "id", extends: "CopayCard.id" } }, - { "field.int": { name: "auths", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CopayAuthorization.id", "@via": "CopayCard.copayAuthorizations" } }] } }, - { "field.string": { name: "latestCode", children: [{ "origin.first": { "@of": "CopayAuthorization.code", "@via": "CopayCard.copayAuthorizations", "@orderBy": ["id:desc"] } }] } }, - { "identity.primary": { name: "id", extends: "CopayCard.id" } }, + { "field.long": { name: "id", extends: "CouponCard.id" } }, + { "field.int": { name: "auths", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CouponAuthorization.id", "@via": "CouponCard.couponAuthorizations" } }] } }, + { "field.string": { name: "latestCode", children: [{ "origin.first": { "@of": "CouponAuthorization.code", "@via": "CouponCard.couponAuthorizations", "@orderBy": ["id:desc"] } }] } }, + { "identity.primary": { name: "id", extends: "CouponCard.id" } }, ] } }]); - expect(sql).toMatch(/LEFT OUTER JOIN authorizations (\w+) ON \1\.copay_card_id = c\.id AND \1\.type = 1/); - expect(sql).toMatch(/FROM authorizations (\w+) WHERE \1\.copay_card_id = c\.id AND \1\.type = 1 ORDER BY/); + expect(sql).toMatch(/LEFT OUTER JOIN authorizations (\w+) ON \1\.coupon_card_id = c\.id AND \1\.type = 1/); + expect(sql).toMatch(/FROM authorizations (\w+) WHERE \1\.coupon_card_id = c\.id AND \1\.type = 1 ORDER BY/); expect(sql).not.toContain("WHERE c.type"); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/view-ddl-emit.test.ts b/server/typescript/packages/codegen-ts/test/projection/view-ddl-emit.test.ts index 32d3383888..71946723f8 100644 --- a/server/typescript/packages/codegen-ts/test/projection/view-ddl-emit.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/view-ddl-emit.test.ts @@ -69,7 +69,9 @@ describe("emitViewDdl — postgres", () => { joinTables: { Week: "weeks", Workout: "workouts" }, }); expect(sql).toContain("CREATE VIEW v_program_summary AS"); + // Ruling R54: Postgres qualifies every relation (`public` when no @schema is declared). expect(sql).toMatch(/FROM programs p\b/); + expect(sql).toMatch(/LEFT OUTER JOIN weeks w ON/); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/view-schema-qualify.test.ts b/server/typescript/packages/codegen-ts/test/projection/view-schema-qualify.test.ts new file mode 100644 index 0000000000..4f9a951153 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/view-schema-qualify.test.ts @@ -0,0 +1,96 @@ +// Ruling R54 (rc.19 item 10): on Postgres every relation a generated view reads is +// schema-qualified — its declared `@schema`, else `public`. A bare name binds through the +// `search_path` current when the view is created, so a view in `reporting` over a bare +// `programs` is one `search_path` away from reading itself. SQLite/D1 have no schemas and +// stay bare. Applies to the FROM, every JOIN, an origin.first subquery and a report view. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +async function load(children: unknown[]) { + const json = JSON.stringify({ "metadata.root": { package: "acme", children } }); + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(errors).toEqual([]); + return root; +} + +const model = (schemas: boolean) => [ + { + "object.entity": { + name: "Program", + children: [ + { "source.rdb": { "@table": "programs", ...(schemas ? { "@schema": "crm" } : {}) } }, + { "field.int": { name: "id" } }, + { "field.int": { name: "ownerId" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "owner", "@fields": "ownerId", "@references": "Owner" } }, + { "relationship.association": { name: "weeks", "@objectRef": "Week", "@cardinality": "many" } }, + ], + }, + }, + { + "object.entity": { + name: "Owner", + children: [ + { "source.rdb": { "@table": "owners" } }, + { "field.int": { name: "id" } }, + { "field.string": { name: "label" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ], + }, + }, + { + "object.entity": { + name: "Week", + children: [ + { "source.rdb": { "@table": "weeks" } }, + { "field.int": { name: "id" } }, + { "field.int": { name: "programId" } }, + { "field.int": { name: "ordinal" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "ref_program", "@fields": "programId", "@references": "Program" } }, + ], + }, + }, + { + "object.projection": { + name: "ProgramSummary", + children: [ + { "source.rdb": { "@kind": "view", "@table": "v_program_summary", ...(schemas ? { "@schema": "reporting" } : {}) } }, + { "field.int": { name: "id", extends: "Program.id" } }, + { "field.string": { name: "ownerLabel", children: [{ "origin.passthrough": { "@from": "Owner.label", "@via": "Program.owner" } }] } }, + { "field.int": { name: "weekCount", children: [{ "origin.aggregate": { "@agg": "count", "@of": "Week.id", "@via": "Program.weeks" } }] } }, + { + "field.int": { + name: "latestOrdinal", + children: [{ "origin.first": { "@of": "Week.ordinal", "@via": "Program.weeks", "@orderBy": ["ordinal:desc"] } }], + }, + }, + { "identity.primary": { name: "id", extends: "Program.id" } }, + ], + }, + }, +]; + +describe("ruling R54 — generated views qualify every relation on Postgres", () => { + test("postgres: the base, every join and the first subquery carry @schema, else stay bare", async () => { + const root = await load(model(true)); + const [v] = buildProjectionViews(root, { dialect: "postgres" }); + expect(v!.schema).toBe("reporting"); + expect(v!.sql).toMatch(/FROM crm\.programs [a-z0-9]+/); + expect(v!.sql).toMatch(/LEFT OUTER JOIN weeks [a-z0-9]+/); + expect(v!.sql).toMatch(/JOIN owners [a-z0-9]+/); + expect(v!.sql).toMatch(/\(SELECT [a-z0-9]+\.ordinal FROM weeks [a-z0-9]+ WHERE/); + // The base declares @schema, so it is never left bare. + expect(v!.sql).not.toMatch(/FROM programs /); + }); + + test("sqlite: relations stay bare", async () => { + const root = await load(model(false)); + const [v] = buildProjectionViews(root, { dialect: "sqlite" }); + expect(v!.sql).toMatch(/FROM programs [a-z0-9]+/); + expect(v!.sql).toMatch(/LEFT OUTER JOIN weeks [a-z0-9]+/); + expect(v!.sql).not.toContain("public."); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts index fd8b2e071e..3aaa353af0 100644 --- a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts @@ -95,13 +95,13 @@ async function generate(): Promise<{ root: MetaRoot; files: EmittedFile[] }> { ]); expect(result.errors.map((e) => e.message)).toEqual([]); const root = result.root; - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/x", dbImport: "./db", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), includeNames: true, }); const genCtx = (g: { filter?: (e: MetaObject) => boolean }): GenContext => ({ entities: root.objects(), loadedRoot: root, matches: (e) => g.filter?.(e) ?? true, projectRoot: "/x", - config: { outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, + config: { outputLayout: "flat", outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, renderContext, warn: () => {}, }); const generators = [entityFile(), namesFile(), queriesFile(), routesFile(), barrel()]; diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 39029d8741..fbb5ecab01 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -128,7 +128,7 @@ async function gen( ) { await runGen({ // The documentation generators write to the `docs` target, which a run must declare. - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", generators, targets: { docs: { outDir: join(dir, "_docs") } }, }), @@ -598,7 +598,7 @@ describe("ADR-0034 — the requirement-tests reference over a ledger that declar const dir = mkdtempSync(join(tmpdir(), "codegen-req-")); try { const result = await runGen({ - config: defineConfig({ outDir: join(dir, "out"), extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", generators: [generator] }), + config: defineConfig({ outputLayout: "flat", outDir: join(dir, "out"), extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", generators: [generator] }), metadata: loaded.root, projectRoot: dir, }); @@ -846,11 +846,11 @@ describe("ADR-0034 — the cube-model reference is byte-identical to the built-i // facts cube; ProgramSessions reaches its facts through the Session -> Week reference. expect("tree" in a ? a.tree.map(([p]) => p) : a).toEqual([ "model/cubes/AllTypes.yml", "model/cubes/Asset.yml", "model/cubes/Auth.yml", "model/cubes/BridgeAuth.yml", - "model/cubes/CopayAuth.yml", + "model/cubes/CouponAuth.yml", "model/cubes/Entry.yml", "model/cubes/Gadget.yml", "model/cubes/GadgetEvent.yml", "model/cubes/Measurement.yml", "model/cubes/Node.yml", "model/cubes/Node_fkParent.yml", - "model/cubes/PriorAuthAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", + "model/cubes/PermitAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", "model/cubes/ProgramLongWeeksFacts.yml", "model/cubes/ProgramRosterFacts.yml", "model/cubes/ProgramSessionsFacts.yml", "model/cubes/ProgramSessions_fkWeek.yml", "model/cubes/ReferralAuth.yml", "model/cubes/Session.yml", "model/cubes/Week.yml", "model/views/ProgramFlagRoster.yml", "model/views/ProgramLongWeeks.yml", @@ -897,7 +897,7 @@ describe("ADR-0034 — the cube-model reference is byte-identical to the built-i const dir = mkdtempSync(join(tmpdir(), "cube-ref-run-")); try { await runGen({ - config: defineConfig({ outDir: join(dir, "out"), dialect: config.dialect, generators: [make()] }), + config: defineConfig({ outputLayout: "flat", outDir: join(dir, "out"), dialect: config.dialect, generators: [make()] }), metadata: root, projectRoot: dir, ...extra, @@ -992,9 +992,9 @@ const CALLABLE_MODEL = { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, @@ -1002,9 +1002,9 @@ const CALLABLE_MODEL = { { // A stored procedure taking typed arguments. "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseSummaryArgs" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "StageSummaryArgs" } }, { "field.long": { name: "phaseId" } }, { "field.string": { name: "phaseName" } }, ], @@ -1015,18 +1015,18 @@ const CALLABLE_MODEL = { "object.projection": { name: "OpenCase", children: [ - { "source.rdb": { "@kind": "tableFunction", "@function": "fn_open_cases" } }, - { "field.long": { name: "caseId" } }, + { "source.rdb": { "@kind": "tableFunction", "@function": "fn_open_consignments" } }, + { "field.long": { name: "consignmentId" } }, ], }, }, { // An ordinary table: must emit no wrapper on either side. "object.entity": { - name: "Case", + name: "Consignment", children: [ { "field.long": { name: "id" } }, - { "source.rdb": { "@table": "cases" } }, + { "source.rdb": { "@table": "consignments" } }, { "identity.primary": { name: "pk", "@fields": ["id"] } }, ], }, @@ -1155,7 +1155,7 @@ describe("ADR-0034 Amendment 7 — the shared-model reference publishes the same const root = await loadFiles([run.model]); return await outcomeOf(async () => { await runGen({ - config: defineConfig({ outDir, extStyle: "none", dbImport: "~/db", dialect: "sqlite", generators: [make(opts)] }), + config: defineConfig({ outputLayout: "flat", outDir, extStyle: "none", dbImport: "~/db", dialect: "sqlite", generators: [make(opts)] }), metadata: root, projectRoot: project, ...(run.sourceFiles !== undefined ? { sourceFiles: run.sourceFiles } : {}), diff --git a/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts b/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts index ded98e96ff..df61cfb6c2 100644 --- a/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts @@ -92,7 +92,7 @@ describe("src/reference/entity.ts — ctx.select call site, end to end via runGe outDir: dir, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [refEntity()], }), metadata: root, @@ -115,7 +115,7 @@ describe("src/reference/entity.ts — ctx.select call site, end to end via runGe outDir: dir, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [refEntity()], }), metadata: root, diff --git a/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts b/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts index 0dde01b860..1ef5812c5c 100644 --- a/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts +++ b/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts @@ -32,7 +32,7 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "relationship.association": { name: "bridgeTags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, diff --git a/server/typescript/packages/codegen-ts/test/report-credential.test.ts b/server/typescript/packages/codegen-ts/test/report-credential.test.ts index 2a2e28ff62..aa6aee72d9 100644 --- a/server/typescript/packages/codegen-ts/test/report-credential.test.ts +++ b/server/typescript/packages/codegen-ts/test/report-credential.test.ts @@ -47,14 +47,14 @@ async function load(): Promise { } async function generate(gen: Generator, root: MetaRoot): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/x", dbImport: "./db", pkMap: buildPkMap(root), relationMap: buildRelationMap(root), includeNames: true, }); const ctx: GenContext = { // runGen hands a generator the served reports as their read models. entities: generatableObjects(root.objects(), root), loadedRoot: root, matches: (e: MetaObject) => gen.filter?.(e) ?? true, - projectRoot: "/x", config: { outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, + projectRoot: "/x", config: { outputLayout: "flat", outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, renderContext, warn: () => {}, }; return await gen.generate(ctx); diff --git a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts index da04e331f0..53d6c99db5 100644 --- a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts @@ -29,7 +29,7 @@ const META = JSON.stringify({ // TPH base + subtype: the polymorphic mount is read-only BY CONSTRUCTION. { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts b/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts index a0b6a1fd0b..4f1e71347f 100644 --- a/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts @@ -32,7 +32,7 @@ const META = JSON.stringify({ // TPH base + two subtypes. { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts b/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts index 6ac40f5294..284124ea7a 100644 --- a/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts @@ -103,7 +103,7 @@ describe("knownFieldNames on a single-table hierarchy", () => { const bridge = res.root.objects().find((o) => o.name === "BridgeAuth") as MetaObject; expect(knownFieldNames(tphHierarchy(bridge, res.root))).toEqual([ "id", "type", "reference", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "quantity", "copayAmount", "approver", + "quantity", "couponAmount", "approver", ]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts b/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts index aaa6105259..9ed1ed116b 100644 --- a/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts @@ -28,7 +28,7 @@ const META = JSON.stringify({ // TPH: the base is registered, the subtype is not (its routes live in the base's file). { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/run-gen.test.ts b/server/typescript/packages/codegen-ts/test/run-gen.test.ts index aa2388c350..31bf582e45 100644 --- a/server/typescript/packages/codegen-ts/test/run-gen.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-gen.test.ts @@ -40,7 +40,7 @@ describe("runGen — single entity, SQLite", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -87,7 +87,7 @@ describe("runGen — two entities with FK, Postgres", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -130,7 +130,7 @@ describe("runGen — first-time regen on a pre-existing file", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), routesFile(), barrel()], }), metadata: result.root, @@ -187,7 +187,7 @@ describe("runGen — path-traversal guard (security)", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), barrel()], }), metadata: root, @@ -223,7 +223,7 @@ describe("runGen — mergeStrategy: 'skip-existing'", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), barrel()], }); @@ -330,7 +330,7 @@ describe("runGen — entityFilter", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: result.root, @@ -357,7 +357,7 @@ describe("runGen — scope", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: result.root, @@ -395,7 +395,7 @@ describe("runGen — scope", () => { const baseConfig = { extStyle: "none" as const, dbImport: "~/server/db", - dialect: "postgres" as const, + outputLayout: "flat" as const, dialect: "postgres" as const, generators: [entityFile(), queriesFile(), routesFile(), barrel()], }; @@ -440,7 +440,7 @@ describe("runGen — scope", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: result.root, @@ -466,7 +466,7 @@ describe("runGen — scope", () => { outDir: tmp, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), barrel()], }), metadata: result.root, diff --git a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts index 3b56ee3c5b..310f37a7e6 100644 --- a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts @@ -48,7 +48,7 @@ async function gen( extra: { generators?: Generator[]; entityFilter?: string[]; generatorNames?: string[]; dryRun?: boolean } = {}, ) { return runGen({ - config: { outDir: OUT, extStyle: "js", generators: extra.generators ?? [entityFile()] }, + config: { outDir: OUT, extStyle: "js", outputLayout: "flat", generators: extra.generators ?? [entityFile()] }, metadata: await model(...names), projectRoot, ...(extra.entityFilter !== undefined && { entityFilter: extra.entityFilter }), @@ -58,6 +58,19 @@ async function gen( } describe("run-wide orphan sweep", () => { + // A project that opted into the package layout and then drops the opt-in gets the default flat + // layout on its next `meta gen`: the modules move to the output root and the package copies are swept. + test("a package layout's modules are swept when the default flat layout takes over", async () => { + const root = await model("Telemetry"); + await runGen({ config: { outDir: OUT, extStyle: "js", outputLayout: "package", generators: [entityFile()] }, metadata: root, projectRoot }); + expect(existsSync(abs(`${OUT}/acme/Telemetry.ts`))).toBe(true); + + const result = await runGen({ config: { outDir: OUT, extStyle: "js", generators: [entityFile()] }, metadata: root, projectRoot }); + expect(existsSync(abs(`${OUT}/Telemetry.ts`))).toBe(true); + expect(existsSync(abs(`${OUT}/acme/Telemetry.ts`))).toBe(false); + expect(result.files).toContainEqual({ path: abs(`${OUT}/acme/Telemetry.ts`), status: "removed" }); + }); + test("a renamed value object's old module is deleted and forgotten", async () => { await gen(["Telemetry"]); expect(existsSync(abs(`${OUT}/Telemetry.ts`))).toBe(true); @@ -177,7 +190,7 @@ describe("nested output directories", () => { async function nested(generators: Generator[]) { return runGen({ config: { - outDir: OUT, + outDir: OUT, outputLayout: "flat", extStyle: "js", targets: { inner: { outDir: `${OUT}/inner` } }, generators, diff --git a/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts b/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts index fc30d166f6..6efb719e37 100644 --- a/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts +++ b/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts @@ -7,8 +7,8 @@ // holds the drifted text; the clean text the helpers are generated from is the parent corpus's // `templates/`. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { FileSystemProvider } from "../src/render-engine/framework-provider.js"; import { renderRenderHelper } from "../src/templates/render-helper.js"; @@ -80,7 +80,9 @@ describe("runtime drift — a variable not on the payload raises at render time" TEMP_DIRS.push(dir); // The handle imports the payload from the value object's own module. const imp = /from "(\.[^"]+)"/.exec(out[0]!.content)?.[1] ?? "./Welcome.js"; - writeFileSync(join(dir, imp.replace(/\.js$/, "") + ".ts"), PAYLOADS); + const payloadFile = join(dir, imp.replace(/\.js$/, "") + ".ts"); + mkdirSync(dirname(payloadFile), { recursive: true }); + writeFileSync(payloadFile, PAYLOADS); writeFileSync(join(dir, "prompts.ts"), out[0]!.content); const mod = await import(join(dir, "prompts.ts")); expect(mod.renderWelcomePrompt({ name: "Ada" }, clean())).toBe("Hello Ada"); diff --git a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts index 8468dbac8d..008439e3d5 100644 --- a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts @@ -73,7 +73,7 @@ async function loadRoot() { async function generate(dir: string): Promise> { const root = await loadRoot(); - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: dir, @@ -86,7 +86,7 @@ async function generate(dir: string): Promise> { loadedRoot: root, matches: () => true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "postgres" } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect: "postgres" } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts index 6e3ca1fdca..8476fa1ea1 100644 --- a/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts +++ b/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts @@ -86,7 +86,7 @@ function genConfig(outDir: string) { outDir, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), queriesFile(), routesFile(), routesFileHono()], }); } @@ -116,7 +116,7 @@ function refGenConfig(outDir: string) { outDir, extStyle: "none", dbImport: "~/server/db", - dialect: "postgres", + outputLayout: "flat" as const, dialect: "postgres", generators: [entityFile(), refQueriesFile(), refRoutesFile()], }); } diff --git a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts index effe9c35ff..1388b89c7d 100644 --- a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts @@ -15,7 +15,7 @@ async function loadFirstEntity(doc: unknown) { new InMemoryStringSource(JSON.stringify(doc), { id: "demo.json" }), ]); if (errors.length > 0) throw new Error(`load errors: ${errors.map((e) => e.message).join("; ")}`); - const procEntity = root.objects().find((o) => o.name === "PhaseSummary")!; + const procEntity = root.objects().find((o) => o.name === "StageSummary")!; return { root, procEntity }; } @@ -27,22 +27,22 @@ describe("renderCallableFile", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_phase_summary", - "@parameterRef": "PhaseSummaryArgs", + "@proc": "fn_stage_summary", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "phaseId" } }, @@ -55,12 +55,12 @@ describe("renderCallableFile", () => { }); const out = renderCallableFile(procEntity); - expect(out).toContain("export async function callPhaseSummary"); - expect(out).toContain("args: PhaseSummaryArgs"); - expect(out).toContain("fn_phase_summary"); - expect(out).toContain("args.caseId"); + expect(out).toContain("export async function callStageSummary"); + expect(out).toContain("args: StageSummaryArgs"); + expect(out).toContain("fn_stage_summary"); + expect(out).toContain("args.consignmentId"); expect(out).toContain("args.asOfDate"); - expect(out).toContain("Promise"); + expect(out).toContain("Promise"); }); test("tableFunction with @parameterRef emits the same shape with the @function name", async () => { @@ -70,19 +70,19 @@ describe("renderCallableFile", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [{ "field.int": { name: "id" } }], }, }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "tableFunction", "@function": "fn_phase_listing", - "@parameterRef": "PhaseSummaryArgs", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "id" } }, @@ -104,7 +104,7 @@ describe("renderCallableFile", () => { children: [ { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { @@ -120,7 +120,7 @@ describe("renderCallableFile", () => { }, }); const out = renderCallableFile(procEntity); - expect(out).toContain("callPhaseSummary(db"); + expect(out).toContain("callStageSummary(db"); expect(out).not.toContain("args:"); expect(out).toContain("fn_ping()"); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts index 3006d48b63..39441f9667 100644 --- a/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts @@ -341,6 +341,22 @@ describe("renderDocsFile — Identity section", () => { expect(out).toContain("**Secondary index:** `visitorId`"); expect(out).toContain("**Reference:** `authorId` → [`Author`](./Author.md)"); }); + + test("a reference whose target the tree does not hold stays plain text (rc.20 G4)", () => { + const root = metaRoot(); + const post = metaObject(OBJECT_SUBTYPE_ENTITY, "Post"); + attachRdbSource(post, "posts"); + post.addChild(metaField(FIELD_SUBTYPE_LONG, "id")); + post.addChild(metaField(FIELD_SUBTYPE_LONG, "ghostId")); + const reference = meta(new TypeId(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE), "ghost"); + reference.setAttr("fields", ["ghostId"]); + reference.setAttr("references", "Ghost"); + post.addChild(reference); + root.addChild(post); + const out = renderDocsFile(post, { dialect: "sqlite", loadedRoot: root }); + const bullet = out.split("\n").find((l) => l.startsWith("- **Reference:**")); + expect(bullet).toBe("- **Reference:** `ghostId` → `Ghost`"); + }); }); describe("renderDocsFile — Constraints", () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/entity-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/entity-file.test.ts index 29a2aafe6a..400c646271 100644 --- a/server/typescript/packages/codegen-ts/test/templates/entity-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/entity-file.test.ts @@ -25,7 +25,7 @@ describe("renderEntityFile", () => { order.addChild(primary); root.addChild(order); - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -61,7 +61,7 @@ describe("renderEntityFile", () => { const root = result.root; const order = root.objects()[0]!; - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -107,7 +107,7 @@ describe("renderEntityFile", () => { const root = result.root; const order = root.objects()[0]!; - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -142,7 +142,7 @@ describe("renderEntityFile", () => { order.addChild(primary); root.addChild(order); - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -181,7 +181,7 @@ describe("renderEntityFile", () => { const root = result.root; const order = root.objects()[0]!; - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -220,7 +220,7 @@ describe("renderEntityFile", () => { const root = result.root; const user = root.objects()[0]!; - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -257,7 +257,7 @@ describe("renderEntityFile", () => { const root = result.root; const user = root.objects()[0]!; - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -290,7 +290,7 @@ describe("renderEntityFile", () => { post.addChild(primary); root.addChild(post); - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -330,7 +330,7 @@ describe("renderEntityFile", () => { post.addChild(primary); root.addChild(post); - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", @@ -360,7 +360,7 @@ describe("renderEntityFile", () => { post.addChild(primary); root.addChild(post); - const ctx = makeRenderContext({ + const ctx = makeRenderContext({ outputLayout: "flat", dialect: "sqlite", loadedRoot: root, outDir: "/x", diff --git a/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts b/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts index bd78ee438e..33b78a4913 100644 --- a/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts @@ -38,7 +38,7 @@ async function gen(root: MetaRoot, providedEnumModule?: string): Promise outDir: tmp, extStyle: "none", dbImport: "~/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), queriesFile(), barrel()], ...(providedEnumModule !== undefined && { providedEnumModule }), }), @@ -135,7 +135,7 @@ describe("#266 shared enums across multiple entityFile() instances", () => { outDir: tmp, extStyle: "none", dbImport: "~/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [ entityFile({ filter: (e) => e.name === "Order" }), entityFile({ filter: (e) => e.name === "Article" }), diff --git a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts index 1daddff266..d8a0055456 100644 --- a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts @@ -46,7 +46,7 @@ async function renderEntityWithGenerators(active: boolean, extStyle: ExtStyle = outDir: tmp, extStyle, dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: active ? [entityFile(), namesFile()] : [entityFile()], }), metadata: metadataRoot, @@ -121,7 +121,7 @@ describe("§A6 — the entity file consumes the names artifact", () => { outDir: join(tmp, "names"), extStyle: "js", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", targets: { db: { outDir: join(tmp, "db") } }, generators: [entityFile({ target: "db" }), namesFile()], }), @@ -152,7 +152,7 @@ describe("§A6 — the entity file consumes the names artifact", () => { outDir: dir, extStyle: "js", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile({ allowlists: false }), queriesFile(), namesFile()], }), metadata: metadataRoot, @@ -228,7 +228,7 @@ describe("§A6 — the entity file consumes the names artifact", () => { outDir: tmp, extStyle: "js", dbImport: "~/server/db", - dialect: "sqlite", + outputLayout: "flat" as const, dialect: "sqlite", generators: [entityFile(), namesFile()], }), metadata: loadResult.root, diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts index 0733e2f934..392ab717b9 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts @@ -2,7 +2,7 @@ // // For an entity with @discriminator + concrete subtypes carrying // @discriminatorValue, entityFile additionally emits: -// - The union type `Auth = BridgeAuth | CopayAuth | ...` +// - The union type `Auth = BridgeAuth | CouponAuth | ...` // - Type guards `isBridgeAuth(a): a is BridgeAuth` // - The `parseAuth(row)` dispatcher // @@ -36,7 +36,7 @@ async function loadTph() { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -54,13 +54,13 @@ async function loadTph() { }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ { "field.decimal": { - name: "copayAmount", + name: "couponAmount", "@precision": 10, "@scale": 2, }, @@ -77,8 +77,8 @@ async function loadTph() { if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("; ")); const base = root.objects().find((o) => o.name === "Auth")! as MetaObject; const bridge = root.objects().find((o) => o.name === "BridgeAuth")! as MetaObject; - const copay = root.objects().find((o) => o.name === "CopayAuth")! as MetaObject; - return { root, base, bridge, copay }; + const coupon = root.objects().find((o) => o.name === "CouponAuth")! as MetaObject; + return { root, base, bridge, coupon }; } describe("FR-017 Tier 1 — renderTphDiscriminatorUnion", () => { @@ -87,19 +87,19 @@ describe("FR-017 Tier 1 — renderTphDiscriminatorUnion", () => { const out = renderTphDiscriminatorUnion(base, root)!.toString(); // Union type spans every concrete subtype, base does not appear in members. - expect(out).toContain("export type Auth = BridgeAuth | CopayAuth"); + expect(out).toContain("export type Auth = BridgeAuth | CouponAuth"); // Type guards per subtype. expect(out).toContain("export function isBridgeAuth(value: Auth)"); - expect(out).toContain("export function isCopayAuth(value: Auth)"); + expect(out).toContain("export function isCouponAuth(value: Auth)"); expect(out).toContain('value.type === "Bridge"'); - expect(out).toContain('value.type === "Copay"'); + expect(out).toContain('value.type === "Coupon"'); // Dispatcher function reads the discriminator without committing to a // subtype yet, then dispatches via switch. expect(out).toContain("export function parseAuth(row: unknown): Auth"); expect(out).toContain('case "Bridge":'); - expect(out).toContain('case "Copay":'); + expect(out).toContain('case "Coupon":'); }); test("returns null for an entity that has no @discriminator", async () => { @@ -116,10 +116,10 @@ describe("FR-017 Tier 1 — subtype Zod pins discriminator via z.literal", () => expect(out).toContain('z.literal("Bridge")'); }); - test("CopayAuth's Zod schema pins type to z.literal(\"Copay\")", async () => { - const { copay } = await loadTph(); - const out = renderZodValidators(copay).toString(); - expect(out).toContain('z.literal("Copay")'); + test("CouponAuth's Zod schema pins type to z.literal(\"Coupon\")", async () => { + const { coupon } = await loadTph(); + const out = renderZodValidators(coupon).toString(); + expect(out).toContain('z.literal("Coupon")'); }); test("BridgeAuth's schema still emits the subtype-only field", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts index b1f2db3478..e9c939ea78 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" }, @@ -47,19 +47,19 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me extends: "Auth", "@discriminatorValue": "Bridge", // @required on a subtype-only column — must STILL be nullable in - // the single TPH table (Copay rows store NULL here). + // the single TPH table (Coupon rows store NULL here). children: [{ "field.int": { name: "quantity", "@required": true } }], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ { "field.decimal": { - name: "copayAmount", + name: "couponAmount", "@precision": 10, "@scale": 2, }, @@ -101,7 +101,7 @@ describe("FR-017 Tier 2 — Drizzle TPH single-table", () => { expect(out).toContain("type:"); // Subtype-only columns folded into the single table. expect(out).toContain("quantity:"); - expect(out).toContain("copay_amount"); + expect(out).toContain("coupon_amount"); }); test("subtype-only columns are nullable even when the field is @required", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts index 3741a9dfa2..9780eed677 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts @@ -37,7 +37,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -53,11 +53,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts index 4c809bbf9c..afe6964cad 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, // increment generation → InsertSchema OMITS id, read schema KEEPS it. { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, @@ -50,11 +50,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -122,7 +122,7 @@ describe("FR-017 Tier 2 — per-subtype full read schema", () => { // Exactly one `export type Auth =` — the discriminated union. const count = (out.match(/export type Auth =/g) ?? []).length; expect(count).toBe(1); - expect(out).toContain("export type Auth = BridgeAuth | CopayAuth"); + expect(out).toContain("export type Auth = BridgeAuth | CouponAuth"); // The raw single-table row type is emitted under the non-colliding `AuthRow`. expect(out).toContain("export type AuthRow ="); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts index a1dd540566..0184cafa3e 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -49,11 +49,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -94,7 +94,7 @@ describe("FR-017 Tier 2 — TPH routes file", () => { const out = renderRoutesFile(base, ctxFor(root)); // Segment is the lowercased discriminator value. expect(out).toContain('Auth.$path + "/bridge"'); - expect(out).toContain('Auth.$path + "/copay"'); + expect(out).toContain('Auth.$path + "/coupon"'); // Scoped via the runtime discriminator option. expect(out).toContain('discriminator: { column: "type", value: "Bridge" }'); // Create body OMITS the discriminator. @@ -104,10 +104,10 @@ describe("FR-017 Tier 2 — TPH routes file", () => { test("the polymorphic mount sends a decimal only a subtype declares as its canonical string", async () => { const { root, base } = await loadTph(); const out = renderRoutesFile(base, ctxFor(root)); - // The base declares no decimal, but its list/get serve CopayAuth rows, so the polymorphic - // mount must rewrite `copayAmount` too (ADR-0019 Amendment 1; Postgres returns "12.50"). + // The base declares no decimal, but its list/get serve CouponAuth rows, so the polymorphic + // mount must rewrite `couponAmount` too (ADR-0019 Amendment 1; Postgres returns "12.50"). const polymorphic = out.slice(out.indexOf("path: Auth.$path,"), out.indexOf('Auth.$path + "/')); - expect(polymorphic).toContain('decimalColumns: ["copayAmount"]'); + expect(polymorphic).toContain('decimalColumns: ["couponAmount"]'); }); test("routesFile generator skips TPH subtypes", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts index 70ef660e6e..23ee673db1 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts @@ -34,7 +34,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me children: [ { "source.rdb": { "@table": "auths" } }, // Discriminator is filterable on the base (polymorphic GET). - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -50,11 +50,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts/test/templates/value-object-import-default-layout.test.ts b/server/typescript/packages/codegen-ts/test/templates/value-object-import-default-layout.test.ts new file mode 100644 index 0000000000..1462039226 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/templates/value-object-import-default-layout.test.ts @@ -0,0 +1,20 @@ +// rc.19 fix round 2 (N2): a ctx-less valueObjectImport resolves under the default layout +// (DEFAULT_OUTPUT_LAYOUT, "flat"), like every other fallback. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { valueObjectImport } from "../../src/templates/value-object-import.js"; + +describe("valueObjectImport without a render context", () => { + test("names the value object's module in the flat output directory", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ + "metadata.root": { package: "acme::blog", children: [ + { "object.value": { name: "Address", children: [{ "field.string": { name: "street" } }] } }, + ] }, + }))]); + expect(errors).toEqual([]); + const vo = root.children().find((c) => c.name === "Address")!; + // A file at the root of outDir importing acme::blog's Address. + expect(valueObjectImport(undefined, vo, "index.ts").specifier).toBe("./Address.js"); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts b/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts index b9c501e622..c02401a483 100644 --- a/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts @@ -23,14 +23,14 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ]}}, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.string": { name: "pinHash", children: [{ "view.password": {} }] } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ]}}, { "object.entity": { name: "PayerAuth", children: [ { "source.rdb": { "@table": "payer_auths" } }, @@ -76,7 +76,7 @@ async function loadModel(model: object = MODEL): Promise { } async function generate(root: MetaRoot): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/x", @@ -91,7 +91,7 @@ async function generate(root: MetaRoot): Promise { loadedRoot: root, matches: (e: MetaObject) => gen.filter?.(e) ?? true, projectRoot: "/x", - config: { outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, + config: { outputLayout: "flat", outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts b/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts index 9c697d76d3..d6c912afeb 100644 --- a/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts @@ -44,7 +44,7 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, // Declared on the BASE: legitimate for every row of the table. { "relationship.association": { name: "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -55,15 +55,15 @@ const MODEL = { // Declared on a SUBTYPE, and a directed self-join onto that same subtype. { "relationship.association": { name: "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ]}}, // An ABSTRACT intermediate level that declares an M:N. It is neither the base nor // a concrete subtype, so it is the level an own-only filter loses entirely. { "object.entity": { name: "ScopedAuth", extends: "Auth", abstract: true, children: [ { "relationship.association": { name: "auditors", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthAudit" } }, ]}}, - { "object.entity": { name: "PriorAuthAuth", extends: "ScopedAuth", "@discriminatorValue": "PriorAuth", children: [ + { "object.entity": { name: "PermitAuth", extends: "ScopedAuth", "@discriminatorValue": "Permit", children: [ { "field.string": { name: "approver", "@maxLength": 80 } }, ]}}, // The junction references the CONCRETE subtype, not the base. That is the supported @@ -76,7 +76,7 @@ const MODEL = { { "field.long": { name: "auditAuthId", "@required": true } }, { "field.long": { name: "auditTagId", "@required": true } }, { "identity.primary": { name: "pk", "@fields": ["auditAuthId", "auditTagId"] } }, - { "identity.reference": { name: "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth" } }, + { "identity.reference": { name: "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth" } }, { "identity.reference": { name: "fkAuditTag", "@fields": "auditTagId", "@references": "Tag" } }, ]}}, { "object.entity": { name: "AuthTag", children: [ @@ -124,7 +124,7 @@ async function loadModel(): Promise { } async function generate(root: MetaRoot): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect: "postgres", loadedRoot: root, outDir: "/x", @@ -139,7 +139,7 @@ async function generate(root: MetaRoot): Promise { loadedRoot: root, matches: (e: MetaObject) => gen.filter?.(e) ?? true, projectRoot: "/x", - config: { outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, + config: { outputLayout: "flat", outDir: "/x", extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, renderContext, warn: () => {}, }; @@ -193,13 +193,13 @@ describe("M:N traversal in a TPH hierarchy", () => { // `tags` is declared on Auth, so every subtype resolves it. A subtype resource is a // resource: it carries the same sub-resources as any other. The overlap is not // redundancy — the subtype segment is a type assertion, and only the subtype mount - // gates the source id, so /auths/bridge/{a Copay id}/tags is [] where /auths/{that + // gates the source id, so /auths/bridge/{a Coupon id}/tags is [] where /auths/{that // id}/tags is not. This is the independent oracle's rule (expectedRoutes), which // walks every SERVED object's RESOLVED relationships. const tagMounts = routes.match(/relationName: "tags"/g) ?? []; - expect(tagMounts.length).toBe(4); // the base, plus /bridge, /copay and /priorauth - const copayTags = m2mMount(routes.slice(routes.indexOf('Auth.$path + "/copay"')), "tags"); - expect(copayTags).toMatch(/sourceDiscriminator: \{ table: auths, pkColumn: \S+, column: \S+, value: "Copay",? \}/); + expect(tagMounts.length).toBe(4); // the base, plus /bridge, /coupon and /permit + const couponTags = m2mMount(routes.slice(routes.indexOf('Auth.$path + "/coupon"')), "tags"); + expect(couponTags).toMatch(/sourceDiscriminator: \{ table: auths, pkColumn: \S+, column: \S+, value: "Coupon",? \}/); }); test("an M:N from a NON-subtype onto a subtype filters the target, not the source", async () => { @@ -219,11 +219,11 @@ describe("M:N traversal in a TPH hierarchy", () => { // own. It is not on the base either, so the ONLY place it can be served is beneath // each concrete subtype under that level. const mount = m2mMount(routes, "auditors"); - expect(mount).toContain('path: Auth.$path + "/priorauth",'); + expect(mount).toContain('path: Auth.$path + "/permit",'); expect(mount).toContain("junctionTable: authAudits,"); expect(mount).toContain("targetTable: tags,"); expect(mount).toMatch( - /sourceDiscriminator: \{ table: auths, pkColumn: AuthNames\.fields\.id\.column, column: AuthNames\.fields\.type\.column, value: "PriorAuth",? \}/, + /sourceDiscriminator: \{ table: auths, pkColumn: AuthNames\.fields\.id\.column, column: AuthNames\.fields\.type\.column, value: "Permit",? \}/, ); // It is NOT mounted at the base path: Auth does not resolve `auditors`, and // ScopedAuth is abstract, so it is served nowhere else. Matches the oracle, whose @@ -235,6 +235,6 @@ describe("M:N traversal in a TPH hierarchy", () => { const routes = fileNamed(await generate(await loadModel()), "Auth.routes.ts"); expect(routes).toContain("mountCrudRoutes({ fastify: fastify, path: Auth.$path, db: db,"); expect(routes).toContain('path: Auth.$path + "/bridge",'); - expect(routes).toContain('path: Auth.$path + "/copay",'); + expect(routes).toContain('path: Auth.$path + "/coupon",'); }); }); diff --git a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts index 0b4aed9155..02792d1153 100644 --- a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts @@ -70,7 +70,7 @@ async function loadModel(model: object = MODEL): Promise { } async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -85,7 +85,7 @@ async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise< loadedRoot: root, matches: (e) => generator.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, renderContext, warn: () => {}, }); @@ -269,7 +269,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { test("the emitted read schema parses a raw base-table row with no derived key", async () => { const root = await loadModel(DERIVED_MODEL); const carrier = root.objects().find((o) => o.name === "Carrier")!; - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: "/x", diff --git a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts index 1ad356f36e..f74bab8bf3 100644 --- a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts @@ -92,7 +92,7 @@ async function loadModel(): Promise { } async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -108,7 +108,7 @@ async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise< loadedRoot: root, matches: (e) => generator.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, renderContext, warn: () => {}, }); diff --git a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts index a997b0a855..a62fd4176a 100644 --- a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts @@ -61,7 +61,7 @@ async function loadModel(): Promise { } async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise { - const renderContext = makeRenderContext({ + const renderContext = makeRenderContext({ outputLayout: "flat", dialect, loadedRoot: root, outDir: dir, @@ -74,7 +74,7 @@ async function generate(root: MetaRoot, dialect: Dialect, dir: string): Promise< loadedRoot: root, matches: (e) => generator.filter?.(e) ?? true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "./db", dialect } as never, renderContext, warn: () => {}, }); diff --git a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts index cac127ae11..490227b179 100644 --- a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts @@ -125,7 +125,7 @@ async function genAndCompile(dialect: Dialect): Promise true, projectRoot: dir, - config: { outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "~/db", dialect } as never, renderContext, warn: () => {}, }; diff --git a/server/typescript/packages/docs-site/src/builders/object-data.ts b/server/typescript/packages/docs-site/src/builders/object-data.ts index 0ebe0d6b45..412f348dc0 100644 --- a/server/typescript/packages/docs-site/src/builders/object-data.ts +++ b/server/typescript/packages/docs-site/src/builders/object-data.ts @@ -259,8 +259,11 @@ export function buildObjectPage(fqn: string, g: LinkGraph, cov: CoverageTracker) else if (v.subType === "presentIff") rule = `${esc(String(at("field") ?? ""))} present iff ${esc(String(at("when") ?? ""))} = ${esc(String(at("equals") ?? ""))}`; else if (v.subType === "atLeastOne" || v.subType === "exactlyOne") { const fs = at("fields"); + const max = at("max"); const list = esc(Array.isArray(fs) ? fs.map(String).join(", ") : String(fs ?? "")); - rule = `${v.subType === "exactlyOne" ? "exactly one" : "at least one"} of ${list}`; + rule = v.subType === "exactlyOne" || max === 1 + ? `exactly one of ${list}` + : typeof max === "number" ? `between 1 and ${max} of ${list}` : `at least one of ${list}`; } else rule = esc(v.subType); const condition = at("condition"); diff --git a/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts b/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts index ad47113826..77bfbc4f20 100644 --- a/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts +++ b/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts @@ -53,7 +53,7 @@ INSERT INTO matches (id, home_team_id, away_team_id) VALUES (1, 1, 2), (2, 1, 2), (3, 2, 1), (4, 3, 1), (5, 3, 2); CREATE TABLE auths (id BIGINT PRIMARY KEY, type TEXT NOT NULL); -INSERT INTO auths (id, type) VALUES (1, 'Bridge'), (2, 'Copay'), (3, 'Bridge'), (4, 'Copay'), (5, 'Copay'), (6, 'Bridge'), (7, 'Bridge'); +INSERT INTO auths (id, type) VALUES (1, 'Bridge'), (2, 'Coupon'), (3, 'Bridge'), (4, 'Coupon'), (5, 'Coupon'), (6, 'Bridge'), (7, 'Bridge'); -- programs: 1 and 3 have a profile, 2 has none; program 4 has sessions through no week (spine row, no facts). CREATE TABLE programs (id BIGINT PRIMARY KEY, title TEXT); diff --git a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts index c24de2f4ca..ab17b0595c 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts @@ -109,7 +109,7 @@ export async function startGeneratedCorpusServer( // spelling the committed schema artifact uses, so the emitted tables read it unmodified. const root = await loadMetadataFile(metaPath); const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts index 7cb755bb9b..55592f741f 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts @@ -83,7 +83,7 @@ export async function startGeneratedServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts index 798546652c..8f89e407c0 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts @@ -52,7 +52,7 @@ export async function startGeneratedJsonbServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts index be641ddec9..5a9af4aaa4 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts @@ -74,7 +74,7 @@ export async function startGeneratedM2mServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts index d63c7c951b..f43b643f3c 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts @@ -64,7 +64,7 @@ export async function startGeneratedProjectionServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts index 4c00cc097d..52f385d79d 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts @@ -211,7 +211,7 @@ export async function startGeneratedReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts index c7c80333a0..2461ba83c9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts @@ -102,7 +102,7 @@ export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts index 1f826ce509..f992eba6b6 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts @@ -125,7 +125,7 @@ export async function startSqliteReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts index bf43ee4cc6..533134cf44 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts @@ -44,14 +44,14 @@ const READ_PATHS = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.string": { name: "pinHash", "@maxLength": 100, children: [{ "view.password": {} }] } }, ] } }, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ] } }, { "object.entity": { name: "PayerAuth", children: [ { "source.rdb": { "@table": "payer_auths" } }, @@ -93,7 +93,7 @@ export async function startGeneratedSecretFieldsServer( // The lane provisions its table below in the generated Drizzle table's default spelling. root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, @@ -137,7 +137,7 @@ export const db = drizzle(pool); "id" bigserial PRIMARY KEY, "type" varchar(16) NOT NULL, "pin_hash" varchar(100), - "copay_cents" integer + "coupon_cents" integer ); CREATE TABLE IF NOT EXISTS "payer_auths" ( "payer_id" bigint NOT NULL, @@ -145,7 +145,7 @@ export const db = drizzle(pool); PRIMARY KEY ("payer_id", "auth_id") ); INSERT INTO "payers" ("id") VALUES (1); - INSERT INTO "auths" ("id", "type", "pin_hash", "copay_cents") VALUES (1, 'Bridge', 'auth-pin-1', NULL), (2, 'Copay', NULL, 500); + INSERT INTO "auths" ("id", "type", "pin_hash", "coupon_cents") VALUES (1, 'Bridge', 'auth-pin-1', NULL), (2, 'Coupon', NULL, 500); INSERT INTO "payer_auths" ("payer_id", "auth_id") VALUES (1, 1), (1, 2);`, ); diff --git a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts index 3e5f778501..e9826ad2ed 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts @@ -2,7 +2,7 @@ // deployed artifact) over HTTP and drives them against the FR-017 TPH corpus. // // Mirrors api-contract-m2m-generated-server.ts but for the single-table -// table-per-hierarchy model (Auth + BridgeAuth / CopayAuth / PriorAuthAuth). It: +// table-per-hierarchy model (Auth + BridgeAuth / CouponAuth / PermitAuth). It: // 1. runs the real codegen (runGen from @metaobjectsdev/codegen-ts) over the // TPH meta into a temp dir, emitting the single Drizzle `auths` table + // per-subtype Zod/allowlists AND Auth.routes.ts — which mounts the @@ -33,7 +33,7 @@ export interface TphSeed { type: string; reference: string; quantity: number | null; - copayAmount: string | null; + couponAmount: string | null; approver: string | null; // FR-037 R1 — the @mutability "writeOnce" column, declared on the TPH BASE so // every subtype inherits it (which also exercises the resolving-accessor rule: @@ -70,7 +70,7 @@ export async function startGeneratedTphServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", outputLayout, @@ -98,7 +98,7 @@ export const db = drizzle(pool); writeFileSync(join(tmp, "db.ts"), dbModule, "utf8"); // 3. Provision the SINGLE TPH table to match the EMITTED Drizzle table. - // Subtype-only columns (quantity / copay_amount / approver) are nullable. + // Subtype-only columns (quantity / coupon_amount / approver) are nullable. // #203 / ADR-0045 — auto_created_at/auto_updated_at mirror the emitted // Auth.ts columns (physical snake_case naming). Plain `timestamp` here // (not `timestamptz`) matches the precedent in api-contract-generated-server.ts @@ -110,7 +110,7 @@ export const db = drizzle(pool); "type" text, "reference" varchar(80) NOT NULL, "quantity" integer, - "copay_amount" numeric(10,2), + "coupon_amount" numeric(10,2), "approver" varchar(80), "issued_currency" varchar(3), "auto_created_at" timestamp, @@ -156,8 +156,8 @@ export async function seedTph(connectionUri: string, seed: TphSeed): Promise [check("chk_auths_type", sql`type IN ('Bridge', 'Copay', 'PriorAuth')`)], + () => [check("chk_auths_type", sql`type IN ('Bridge', 'Coupon', 'Permit')`)], ); // Base entity: polymorphic read surface only (no polymorphic create). const AuthInsertSchema = z.object({ - type: z.enum(["Bridge", "Copay", "PriorAuth"]).optional(), + type: z.enum(["Bridge", "Coupon", "Permit"]).optional(), reference: z.string().min(1).max(80), }); const AuthUpdateSchema = AuthInsertSchema.partial(); @@ -92,10 +92,10 @@ const writeOnceInsertShape = { issuedCurrency: z.string().max(3).nullable().optional(), }; -// CopayAuth.copayAmount is decimal(10,2): a string or a JSON number in, its canonical string +// CouponAuth.couponAmount is decimal(10,2): a string or a JSON number in, its canonical string // stored, and a value the column would round or overflow refused (ADR-0019 Amendment 1, W2/W3), // as the generated write schema does it. -const copayAmount = z +const couponAmount = z .union([z.string(), z.number()]) .transform((v, ctx) => { const c = parseDecimalInput(v); @@ -108,23 +108,23 @@ const copayAmount = z }) .nullable() .optional(); -const DECIMAL_COLUMNS = ["copayAmount"] as const; +const DECIMAL_COLUMNS = ["couponAmount"] as const; // The decimal output form is the corpus's own `wire` setting (ADR-0019 Amendment 2), read from // its .metaobjects/config.json like the generated lanes, never a literal here. const DECIMAL_WIRE = nearestWireFormat(API_CONTRACT_TPH_DIR).decimals; // Per-subtype insert schemas (discriminator pinned, omitted at the route boundary). const BridgeInsert = z.object({ reference: z.string().min(1).max(80), quantity: z.number().int(), ...writeOnceInsertShape, ...autoSetInsertShape }); -const CopayInsert = z.object({ reference: z.string().min(1).max(80), copayAmount, ...writeOnceInsertShape, ...autoSetInsertShape }); -const PriorAuthInsert = z.object({ reference: z.string().min(1).max(80), approver: z.string().max(80).nullable().optional(), ...writeOnceInsertShape, ...autoSetInsertShape }); +const CouponInsert = z.object({ reference: z.string().min(1).max(80), couponAmount, ...writeOnceInsertShape, ...autoSetInsertShape }); +const PermitInsert = z.object({ reference: z.string().min(1).max(80), approver: z.string().max(80).nullable().optional(), ...writeOnceInsertShape, ...autoSetInsertShape }); // Per-subtype update schemas — NOT derived via `.partial()` (that would // carry autoCreatedAt's stamping transform into every PATCH, re-writing the // creation timestamp on every update — the exact lost-update bug this gate // exists to catch). Declared explicitly instead, omitting autoCreatedAt. const BridgeUpdate = z.object({ reference: z.string().min(1).max(80).optional(), quantity: z.number().int().optional(), ...autoSetUpdateShape }); -const CopayUpdate = z.object({ reference: z.string().min(1).max(80).optional(), copayAmount, ...autoSetUpdateShape }); -const PriorAuthUpdate = z.object({ reference: z.string().min(1).max(80).optional(), approver: z.string().max(80).nullable().optional(), ...autoSetUpdateShape }); +const CouponUpdate = z.object({ reference: z.string().min(1).max(80).optional(), couponAmount, ...autoSetUpdateShape }); +const PermitUpdate = z.object({ reference: z.string().min(1).max(80).optional(), approver: z.string().max(80).nullable().optional(), ...autoSetUpdateShape }); const numberOps = ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"] as const; const stringOps = ["eq", "ne", "in", "like", "isNull"] as const; @@ -133,26 +133,26 @@ const BridgeFilterAllowlist = { reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, quantity: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, } as const satisfies FilterAllowlist; -const CopayFilterAllowlist = { +const CouponFilterAllowlist = { id: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, - copayAmount: { ops: numberOps, subType: "number" as const, leadingWildcard: false, format: "decimal" as const }, + couponAmount: { ops: numberOps, subType: "number" as const, leadingWildcard: false, format: "decimal" as const }, } as const satisfies FilterAllowlist; -const PriorAuthFilterAllowlist = { +const PermitFilterAllowlist = { id: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, approver: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, } as const satisfies FilterAllowlist; const BridgeSortAllowlist = { id: {}, reference: {}, quantity: {} } as const satisfies SortAllowlist; -const PriorAuthSortAllowlist = { id: {}, reference: {}, approver: {} } as const satisfies SortAllowlist; -const CopaySortAllowlist = { id: {}, reference: {} } as const satisfies SortAllowlist; +const PermitSortAllowlist = { id: {}, reference: {}, approver: {} } as const satisfies SortAllowlist; +const CouponSortAllowlist = { id: {}, reference: {} } as const satisfies SortAllowlist; // `api.unknownFields` at its default, `reject`, which this corpus does not change: every // field the hierarchy declares, so a sibling subtype's column is dropped on another subtype's // route rather than refused, as the generated per-subtype mounts have it. const KNOWN_FIELDS = [ "id", "type", "reference", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "quantity", "copayAmount", "approver", + "quantity", "couponAmount", "approver", ] as const; export async function startTphServer(connectionUri: string): Promise { @@ -165,7 +165,7 @@ export async function startTphServer(connectionUri: string): Promise [r.id, r.type]).sort()).toEqual([[1, "Bridge"], [2, "Copay"]]); + expect(auths.map((r) => [r.id, r.type]).sort()).toEqual([[1, "Bridge"], [2, "Coupon"]]); for (const row of auths) expect(Object.keys(row)).not.toContain("pinHash"); } finally { if (server) await server.close(); diff --git a/server/typescript/packages/integration-tests/test/contract-oasdiff.test.ts b/server/typescript/packages/integration-tests/test/contract-oasdiff.test.ts index f74f27235f..077510dcdf 100644 --- a/server/typescript/packages/integration-tests/test/contract-oasdiff.test.ts +++ b/server/typescript/packages/integration-tests/test/contract-oasdiff.test.ts @@ -74,7 +74,7 @@ async function emitDocument(meta: unknown, dir: string, name: string): Promise { "metadata.root": { "package": "demo", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"], - "@intValueMap": { "Bridge": 1, "Copay": 2 } } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"], + "@intValueMap": { "Bridge": 1, "Coupon": 2 } } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, { "field.enum": { "name": "status", "@values": ["OPEN", "SHUT"], @@ -487,8 +487,8 @@ describe("int-backed field.enum under TPH — real Postgres", () => { { "object.entity": { "name": "BridgeAuth", "extends": "demo::Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", "children": [ + { "object.entity": { "name": "CouponAuth", "extends": "demo::Auth", + "@discriminatorValue": "Coupon", "children": [ { "field.int": { "name": "amount" } } ] } } ] } }`; @@ -505,7 +505,7 @@ describe("int-backed field.enum under TPH — real Postgres", () => { const root = (await new MetaDataLoader().load([new InMemoryStringSource(TPH_META)])).root; const lr = await runGen({ - config: defineConfig({ + config: defineConfig({ outputLayout: "flat", outDir: tphTmp, extStyle: "none", dbImport: "./db", dialect: "postgres", generators: [entityFile(), queriesFile()], }), @@ -545,7 +545,7 @@ describe("int-backed field.enum under TPH — real Postgres", () => { SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conname = 'auths_type_chk' `.execute(k); - // Unquoted integers, not 'Bridge'/'Copay' — the discriminator's CHECK is + // Unquoted integers, not 'Bridge'/'Coupon' — the discriminator's CHECK is // subject to the same int-backing as any other enum column. expect(chk.rows[0]?.def).toContain("1"); expect(chk.rows[0]?.def).toContain("2"); @@ -586,8 +586,8 @@ describe("int-backed field.enum under TPH — real Postgres", () => { ).execute(k); const bridges = await q.listBridgeAuths(tphDb); expect(bridges.map((r: any) => r.title).sort()).toEqual(["b", "d"]); - const copays = await q.listCopayAuths(tphDb); - expect(copays.map((r: any) => r.title)).toEqual(["c"]); + const coupons = await q.listCouponAuths(tphDb); + expect(coupons.map((r: any) => r.title)).toEqual(["c"]); }, 120_000); test("the polymorphic read dispatches on the DECODED discriminator", async () => { @@ -596,9 +596,9 @@ describe("int-backed field.enum under TPH — real Postgres", () => { ).execute(k); const all = await q.listAuths(tphDb); expect(all).toHaveLength(1); - // parseAuth read `type` as "Copay" and dispatched to CopayAuthSchema — a raw 2 + // parseAuth read `type` as "Coupon" and dispatched to CouponAuthSchema — a raw 2 // would have thrown on the z.enum head parse. - expect(all[0].type).toBe("Copay"); + expect(all[0].type).toBe("Coupon"); expect(all[0].amount).toBe(42); }, 120_000); @@ -607,9 +607,9 @@ describe("int-backed field.enum under TPH — real Postgres", () => { `INSERT INTO "auths" ("type", "title", "status") VALUES (2, 'c', 7);`, ).execute(k); const [{ id }] = (await sql<{ id: string }>`SELECT "id" FROM "auths"`.execute(k)).rows as any; - // The row IS a Copay, so asking for it as a Bridge must miss — proving the AND'd + // The row IS a Coupon, so asking for it as a Bridge must miss — proving the AND'd // discriminator predicate encoded to 1 rather than binding 'Bridge'. expect(await q.findBridgeAuthById(tphDb, Number(id))).toBeNull(); - expect((await q.findCopayAuthById(tphDb, Number(id)))?.title).toBe("c"); + expect((await q.findCouponAuthById(tphDb, Number(id)))?.title).toBe("c"); }, 120_000); }); diff --git a/server/typescript/packages/integration-tests/test/load-project-model.test.ts b/server/typescript/packages/integration-tests/test/load-project-model.test.ts index 14ad1d7a25..72f1c13acd 100644 --- a/server/typescript/packages/integration-tests/test/load-project-model.test.ts +++ b/server/typescript/packages/integration-tests/test/load-project-model.test.ts @@ -26,7 +26,7 @@ const CONFIG = [ ` });`, ` },`, `};`, - `export default defineConfig({ outDir: "out", dialect: "postgres", generators: [], providers: [geoProvider] });`, + `export default defineConfig({ outputLayout: "flat", outDir: "out", dialect: "postgres", generators: [], providers: [geoProvider] });`, ].join("\n"); const META = { diff --git a/server/typescript/packages/integration-tests/test/mysql-object-manager.test.ts b/server/typescript/packages/integration-tests/test/mysql-object-manager.test.ts index 667f13c40d..a52e4d37dc 100644 --- a/server/typescript/packages/integration-tests/test/mysql-object-manager.test.ts +++ b/server/typescript/packages/integration-tests/test/mysql-object-manager.test.ts @@ -103,7 +103,7 @@ beforeAll(async () => { // The Drizzle driver's schema is the generated `dialect: "mysql"` tables. await runGen({ - config: defineConfig({ outDir: tmp, extStyle: "none", dialect: "mysql", generators: [entityFile({ allowlists: false })] }), + config: defineConfig({ outputLayout: "flat", outDir: tmp, extStyle: "none", dialect: "mysql", generators: [entityFile({ allowlists: false })] }), metadata, }); schema = { diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts new file mode 100644 index 0000000000..36184a6ace --- /dev/null +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -0,0 +1,281 @@ +// rc.21 part B — the view vocabulary on a real Postgres: a cast (with a text @dbColumnType +// spelling), the closed function set, a path ref, a correlated path operand, an expression over an +// aggregate, an origin.function, a @grain view, and a @union. Each view is created by the +// production pipeline (build → diff → emit → apply), queried, and a second migrate is a no-op. + +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { buildExpectedSchema, checkDeclaredFunctions, diff, emit, introspectPostgres, postgresViewReplaceProbe, splitSqlStatements } from "@metaobjectsdev/migrate-ts"; +import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { startPostgres, type RunningPg } from "../src/postgres-container.ts"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code", "@dbColumnType": "character(3)" } }, + { "field.string": { name: "label", "@dbColumnType": "varchar" } }, + { "field.string": { name: "note", "@dbColumnType": "varchar(20)" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, + { "field.boolean": { name: "preferred" } }, + { "field.int": { name: "rank" } } ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "firstName" } }, + { "field.string": { name: "lastName" } }, + { "field.string": { name: "zip" } }, + { "field.long": { name: "regionId" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, + { "field.string": { name: "loyaltyTier", children: [ + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } }, + // Fix round 2 (N1): the call is cast to the field's full column type. + { "field.timestamp": { name: "memberSince", "@localTime": true, children: [ + { "origin.function": { "@function": "member_since", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" } } ] } }, + { "field.string": { name: "regionCode", "@maxLength": 8, children: [ + { "origin.function": { "@function": "region_code", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "string" } } ] } }, + { "field.decimal": { name: "creditLimit", "@precision": 10, "@scale": 2, children: [ + { "origin.function": { "@function": "credit_limit", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "decimal" } } ] } } ] } }, + { "object.entity": { name: "Address", children: [ + { "source.rdb": { "@table": "addresses" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.string": { name: "street" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.int": { name: "stage" } }, + { "field.string": { name: "externalRef" } }, + { "field.timestamp": { name: "updatedAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId", "@required": true } }, + { "field.long": { name: "customerId" } }, + { "field.int": { name: "stage" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { name: "OrderRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_order_row" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "field.string": { name: "ref", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "externalRef" }, { cast: { field: "id" }, as: "string" } ] } } } ] } }, + { "field.string": { name: "nothing", children: [ { "origin.computed": { "@expr": { cast: { value: null }, as: "string", dbColumnType: "varchar" } } } ] } }, + { "field.int": { name: "outcome", children: [ { "origin.computed": { "@expr": { case: [ { when: { op: "eq", left: { field: "stage" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } } ], else: { field: "stage" } } } } ] } }, + { "field.string": { name: "zip5", children: [ { "origin.computed": { "@expr": { fn: "splitPart", args: [ { field: "customerId.zip" }, { value: "-" }, { value: 1 } ] } } } ] } }, + { "field.string": { name: "fullName", children: [ { "origin.computed": { "@expr": { fn: "btrim", args: [ { fn: "concatWs", args: [ { value: " " }, { field: "customerId.firstName" }, { field: "customerId.lastName" } ] } ] } } } ] } }, + { "field.string": { name: "initials", children: [ { "origin.computed": { "@expr": { fn: "upper", args: [ { fn: "concat", args: [ { fn: "left", args: [ { field: "customerId.firstName" }, { value: 1 } ] }, { fn: "right", args: [ { fn: "lower", args: [ { field: "customerId.lastName" } ] }, { value: 1 } ] } ] } ] } } } ] } }, + { "field.int": { name: "refLength", children: [ { "origin.computed": { "@expr": { fn: "length", args: [ { fn: "replace", args: [ { fn: "substring", args: [ { field: "externalRef" }, { value: 2 }, { value: 3 } ] }, { value: "X" }, { value: "" } ] } ] } } } ] } }, + { "field.string": { name: "noRef", children: [ { "origin.computed": { "@expr": { fn: "nullif", args: [ { field: "externalRef" }, { value: "NONE" } ] } } } ] } }, + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { name: "memberSince", "@localTime": true, children: [ { "origin.passthrough": { "@from": "Customer.memberSince", "@via": "Order.customerId" } } ] } }, + { "field.string": { name: "regionCode", "@maxLength": 8, children: [ { "origin.passthrough": { "@from": "Customer.regionCode", "@via": "Order.customerId" } } ] } }, + { "field.decimal": { name: "creditLimit", "@precision": 10, "@scale": 2, children: [ { "origin.passthrough": { "@from": "Customer.creditLimit", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + { "field.timestamp": { name: "firstAtStatus", children: [ { "origin.aggregate": { "@agg": "min", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents", "@filter": { stage: { eq: { field: "stage" } } } } } ] } }, + { "field.timestamp": { name: "touched", children: [ { "origin.computed": { "@expr": { fn: "greatest", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, + { "field.timestamp": { name: "earliest", children: [ { "origin.computed": { "@expr": { fn: "least", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, + { "field.long": { name: "eventByCustomer", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }, + { "object.projection": { name: "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_customer_contact" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + { "field.int": { name: "position" } }, + { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }, + { "field.boolean": { name: "preferred", children: [ { "origin.passthrough": { "@from": "Contact.preferred" } } ] } }, + { "field.int": { name: "rank", children: [ { "origin.passthrough": { "@from": "Contact.rank" } } ] } } ] } }, + { "object.projection": { name: "PersonBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Customer.id" } }, + { "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [ { field: "lastName" } ] } } } ] } } ] } }, + { "object.projection": { name: "AddressBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Address.customerId" } }, + { "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [ { field: "street" } ] } } } ] } } ] } }, + { "object.projection": { name: "People", extends: "PersonBranch", "@union": ["AddressBranch"], children: [ + { "source.rdb": { "@kind": "view", "@table": "v_people" } } ] } }, + { "object.projection": { name: "PeopleAll", extends: "PersonBranch", "@union": ["AddressBranch"], "@unionAll": true, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_people_all" } } ] } }, +] } }; + +let pg: RunningPg; +let k: Kysely>; + +beforeAll(async () => { + pg = await startPostgres(); + k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: pg.connectionUri }) }) }); +}, 120_000); + +afterAll(async () => { + await k.destroy(); + await pg.stop(); +}, 60_000); + +async function migrate() { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const expected = buildExpectedSchema(root, { views: buildProjectionViews(root, { dialect: "postgres" }) }); + const run = async () => diff({ expected, actual: await introspectPostgres(k), dialect: "postgres", viewReplaceProbe: postgresViewReplaceProbe(k) }); + const first = await run(); + expect(first.blocked).toEqual([]); + const { up } = emit(first.changes, { dialect: "postgres" }); + for (const stmt of splitSqlStatements(up)) await sql.raw(stmt.endsWith(";") ? stmt : `${stmt};`).execute(k); + return run; +} + +const rows = async (q: string) => (await sql.raw(q).execute(k)).rows as Record[]; + +describe("rc.21 part B view vocabulary — live Postgres", () => { + test("every construct creates, reads the expected rows, and a second migrate is a no-op", async () => { + await sql.raw("DROP SCHEMA IF EXISTS app CASCADE").execute(k); + await sql.raw("CREATE SCHEMA app").execute(k); + // The function the project owns: owned SQL, created before the view that calls it. + await sql.raw(`CREATE FUNCTION app.loyalty_tier(bigint, text) RETURNS text LANGUAGE sql IMMUTABLE + AS $$ SELECT CASE WHEN $1 % 2 = 0 THEN 'gold' ELSE 'silver' END || ':' || left($2, 2) $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.member_since(bigint) RETURNS timestamp LANGUAGE sql IMMUTABLE + AS $$ SELECT timestamp '2026-01-01 08:30:00' + ($1 || ' days')::interval $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.region_code(bigint) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT 'R-' || $1 $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.credit_limit(bigint) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT $1 * 100.5 $$`).execute(k); + const again = await migrate(); + + // U2: the text spellings are the column types. + const types = await rows(`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns + WHERE table_name = 'regions' AND column_name IN ('code', 'label', 'note') ORDER BY column_name`); + expect(types).toEqual([ + { column_name: "code", data_type: "character", character_maximum_length: 3 }, + { column_name: "label", data_type: "character varying", character_maximum_length: null }, + { column_name: "note", data_type: "character varying", character_maximum_length: 20 }, + ]); + const nothingType = await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'nothing'`); + expect(nothingType).toEqual([{ data_type: "character varying" }]); + // I4: the function's call is cast to the carrying field's column type. + expect(await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'tier'`)) + .toEqual([{ data_type: "text" }]); + // N1: a local timestamp stays without a zone, a sized string keeps its length, a decimal its precision and scale. + expect(await rows(`SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale + FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name IN ('member_since', 'region_code', 'credit_limit') + ORDER BY column_name`)).toEqual([ + { column_name: "credit_limit", data_type: "numeric", character_maximum_length: null, numeric_precision: 10, numeric_scale: 2 }, + { column_name: "member_since", data_type: "timestamp without time zone", character_maximum_length: null, numeric_precision: null, numeric_scale: null }, + { column_name: "region_code", data_type: "character varying", character_maximum_length: 8, numeric_precision: null, numeric_scale: null }, + ]); + + await sql.raw(` + INSERT INTO regions (id, code, label, note) VALUES (1, 'NE', 'north east', 'n'); + INSERT INTO customers (id, first_name, last_name, zip, region_id, contacts) VALUES + (10, 'Ada', 'Lovelace', '02139-4307', 1, '[{"kind":"email","preferred":true,"rank":1},{"kind":"phone","preferred":false,"rank":2}]'), + (11, ' Alan', 'Turing ', '12345', 1, '{"kind":"not an array"}'), + (12, NULL, 'Hopper', NULL, NULL, 'null'); + INSERT INTO addresses (id, customer_id, street) VALUES (100, 10, 'Lovelace'), (101, 11, 'Main St'); + INSERT INTO orders (id, customer_id, status, stage, external_ref, updated_at) VALUES + (1, 10, 1, 0, NULL, '2026-01-05T00:00:00Z'), + (2, 11, 0, 7, 'AXXBCD', '2026-03-01T00:00:00Z'), + (3, 12, 0, 0, 'NONE', NULL); + INSERT INTO order_events (id, order_id, customer_id, stage, created_at) VALUES + (1000, 1, 10, 0, '2026-01-01T00:00:00Z'), + (1001, 1, 10, 0, '2026-02-01T00:00:00Z'), + (1002, 1, 99, 3, '2026-01-02T00:00:00Z'), + (1003, 2, 11, 7, '2026-02-15T00:00:00Z'); + `).execute(k); + + const order = await rows(`SELECT id, ref, nothing, outcome, zip5, full_name, initials, ref_length, no_ref, tier, + (last_event AT TIME ZONE 'UTC')::text AS last_event, (first_at_status AT TIME ZONE 'UTC')::text AS first_at_status, + (touched AT TIME ZONE 'UTC')::text AS touched, (earliest AT TIME ZONE 'UTC')::text AS earliest, event_by_customer FROM v_order_row ORDER BY id`); + expect(order).toEqual([ + { id: "1", ref: "1", nothing: null, outcome: 1, zip5: "02139", full_name: "Ada Lovelace", initials: "AE", ref_length: null, no_ref: null, + tier: "gold:02", last_event: "2026-02-01 00:00:00", first_at_status: "2026-01-01 00:00:00", + touched: "2026-02-01 00:00:00", earliest: "2026-01-05 00:00:00", event_by_customer: "1000" }, + { id: "2", ref: "AXXBCD", nothing: null, outcome: 7, zip5: "12345", full_name: "Alan Turing", initials: " ", ref_length: 1, no_ref: "AXXBCD", + tier: "silver:12", last_event: "2026-02-15 00:00:00", first_at_status: "2026-02-15 00:00:00", + touched: "2026-03-01 00:00:00", earliest: "2026-02-15 00:00:00", event_by_customer: "1003" }, + { id: "3", ref: "NONE", nothing: null, outcome: 0, zip5: null, full_name: "Hopper", initials: "R", ref_length: 3, no_ref: null, + tier: null, last_event: null, first_at_status: null, touched: null, earliest: null, event_by_customer: null }, + ]); + + // N1: the local timestamp reads the same in any session zone (a TIMESTAMPTZ cast would have moved it). + // One connection: SET LOCAL holds for the transaction only. + const zoned = await k.transaction().execute(async (trx) => { + await sql.raw(`SET LOCAL TIME ZONE 'America/New_York'`).execute(trx); + return (await sql.raw(`SELECT current_setting('TimeZone') AS tz, id, member_since::text AS member_since, region_code, + credit_limit::text AS credit_limit FROM v_order_row ORDER BY id`).execute(trx)).rows; + }); + expect(zoned).toEqual([ + { tz: "America/New_York", id: "1", member_since: "2026-01-11 08:30:00", region_code: "R-10", credit_limit: "1005.00" }, + { tz: "America/New_York", id: "2", member_since: "2026-01-12 08:30:00", region_code: "R-11", credit_limit: "1105.50" }, + { tz: "America/New_York", id: "3", member_since: "2026-01-13 08:30:00", region_code: "R-12", credit_limit: "1206.00" }, + ]); + + // U14: one row per element; a customer whose value is an object or JSON null has none (fix round M3). + expect(await rows(`SELECT customer_id, position, kind, preferred, rank FROM v_customer_contact ORDER BY customer_id, position`)).toEqual([ + { customer_id: "10", position: 1, kind: "email", preferred: true, rank: 1 }, + { customer_id: "10", position: 2, kind: "phone", preferred: false, rank: 2 }, + ]); + + // U15: UNION removes the duplicate ('lovelace' as a customer and as a street); UNION ALL keeps it. + expect(await rows(`SELECT person_id, label FROM v_people ORDER BY person_id, label`)).toEqual([ + { person_id: "10", label: "lovelace" }, { person_id: "11", label: "main st" }, + { person_id: "11", label: "turing " }, { person_id: "12", label: "hopper" }, + ]); + expect((await rows(`SELECT count(*)::int AS n FROM v_people_all`))[0]).toEqual({ n: 5 }); + + const followup = await again(); + expect(followup.changes).toEqual([]); + + // N2: every declared function is the database's, with the declared types. + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(await checkDeclaredFunctions(k, root)).toEqual([]); + }, 120_000); + + // N2: `meta verify --db` reads each declared function from pg_proc; a declaration the database + // does not have is a finding, never hidden by the view's cast. Runs after the test above, which + // created the functions. + test("a declared function signature the database does not have is a finding", async () => { + const fn = (field: Record, origin: Record) => ({ ...field, children: [ { "origin.function": { "@schema": "app", ...origin } } ] }); + const findings = async (...fields: { [k: string]: Record }[]) => { + const model = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Account", children: [ + { "source.rdb": { "@table": "accounts" } }, { "field.long": { name: "id" } }, { "field.int": { name: "pin" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "AccountRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_account_row" } }, + { "field.long": { name: "id", extends: "Account.id" } }, { "field.int": { name: "pin", extends: "Account.pin" } }, + { "identity.primary": { name: "id", extends: "Account.id" } }, ...fields ] } } ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(errors).toEqual([]); + return checkDeclaredFunctions(k, root); + }; + // Matching declarations: none. + expect(await findings( + { "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["id"], "@params": ["long"], "@returns": "decimal" }) }, + { "field.timestamp": fn({ name: "since", "@localTime": true }, { "@function": "member_since", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" }) }, + )).toEqual([]); + // A numeric result declared int: the cast would round it. + const [rounded] = await findings({ "field.int": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["id"], "@params": ["long"], "@returns": "int" }) }); + expect(rounded).toBe("origin.function app.credit_limit on AccountRow.limit: declared (long) → int, which needs app.credit_limit(bigint) → integer; " + + "the database has app.credit_limit(bigint) → numeric."); + // A local timestamp result on a zoned field: the cast would read it in the session's zone. + const [zoned] = await findings({ "field.timestamp": fn({ name: "since" }, { "@function": "member_since", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" }) }); + expect(zoned).toMatch(/needs app\.member_since\(bigint\) → timestamp with time zone; the database has app\.member_since\(bigint\) → timestamp without time zone\.$/); + // A parameter of another type, and a function that does not exist. + const [param] = await findings({ "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["pin"], "@params": ["int"], "@returns": "decimal" }) }); + expect(param).toMatch(/needs app\.credit_limit\(integer\) → numeric; the database has app\.credit_limit\(bigint\) → numeric\.$/); + // Fix round 3 (M1): a trailing defaulted parameter may be left out; fewer than the required ones is a finding. + await sql.raw(`CREATE FUNCTION app.tier_label(bigint, as_of date DEFAULT current_date) RETURNS text LANGUAGE sql STABLE + AS $$ SELECT 'tier-' || $1 || '@' || $2 $$`).execute(k); + expect(await findings({ "field.string": fn({ name: "tierLabel" }, { "@function": "tier_label", "@args": ["id"], "@params": ["long"], "@returns": "string" }) })).toEqual([]); + const [tooFew] = await findings({ "field.string": fn({ name: "tierLabel" }, { "@function": "tier_label", "@args": [], "@params": [], "@returns": "string" }) }); + expect(tooFew).toMatch(/needs app\.tier_label\(\) → text \| character varying \| character; the database has app\.tier_label\(bigint, date\) → text\.$/); + const [missing] = await findings({ "field.int": fn({ name: "score" }, { "@function": "no_such_fn", "@args": [], "@params": [], "@returns": "int" }) }); + expect(missing).toBe("origin.function app.no_such_fn on AccountRow.score: no such function in the database (declared () → int)."); + }, 60_000); +}); diff --git a/server/typescript/packages/metadata/src/attr-schema-validate.ts b/server/typescript/packages/metadata/src/attr-schema-validate.ts index 9be7c41f44..dac1f2c8bc 100644 --- a/server/typescript/packages/metadata/src/attr-schema-validate.ts +++ b/server/typescript/packages/metadata/src/attr-schema-validate.ts @@ -56,14 +56,18 @@ import { FIELD_ATTR_COERCE_DEFAULT, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, ENUM_MEMBER_PATTERN, + FIELD_ATTR_MAX_LENGTH, + FIELD_SUBTYPE_STRING, } from "./core/field/field-constants.js"; import { isSharedEnumDeclaration } from "./core/field/shared-enum.js"; import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_VALUES, - DB_COLUMN_TYPE_LEGAL_SUBTYPES, - type DbColumnTypeValue, + DB_COLUMN_TYPE_SIZED_SPELLINGS, + dbColumnTypeLegalSubtypes, + parseDbColumnType, } from "./persistence/db/db-constants.js"; export interface AttrSchemaValidationResult { @@ -498,6 +502,52 @@ function validateNode( } } } + // --- Check 5c (rc.21): field.enum @stringValueMap content rules --- + // + // The string twin of Check 5b, with its policies: own-only (an inherited map is validated + // on its declaring node), a shared enum's backing owned by the shared declaration. Keys must + // exactly match @values; values are unique non-empty strings. An enum that is not + // string-stored refuses it: an @intValueMap enum stores integers, and an array enum stores + // its members as text[] elements, which no port maps through it. + const rawStringValueMap = node.ownAttrs().get(FIELD_ATTR_STRING_VALUE_MAP); + if (rawStringValueMap !== undefined) { + const bad = (message: string, code: "ERR_BAD_ATTR_VALUE" | "ERR_ENUM_EXTENDS_VALUES_CONFLICT" = "ERR_BAD_ATTR_VALUE") => + errors.push(new ParseError(`${nodeLabel(node)} attribute '@${FIELD_ATTR_STRING_VALUE_MAP}' ${message}`, { code, source: node.source })); + if (sharedSuper !== undefined) { + bad(`is declared on a field extending shared abstract enum '${nodeLabel(sharedSuper)}' — a shared enum's ` + + `stored strings are owned by the shared declaration; move it onto '${nodeLabel(sharedSuper)}' to inherit it.`, + "ERR_ENUM_EXTENDS_VALUES_CONFLICT"); + } else if (node.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined) { + bad(`is refused beside '@${FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one.`); + } else if ((node as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true) { + bad(`is refused on an array enum: its column holds the members as text[] elements, which no port maps through @${FIELD_ATTR_STRING_VALUE_MAP}.`); + } else if (typeof rawStringValueMap !== "object" || rawStringValueMap === null || Array.isArray(rawStringValueMap)) { + bad(`must be an object of { member: storedString }.`); + } else { + const map = rawStringValueMap as Record; + const effectiveValues = node.attrs().get(FIELD_ATTR_VALUES); + const declaredMembers: string[] = Array.isArray(effectiveValues) ? effectiveValues : []; + const memberSet = new Set(declaredMembers); + const keySet = new Set(Object.keys(map)); + const missing = declaredMembers.filter((m) => !keySet.has(m)); + const extra = Object.keys(map).filter((k) => !memberSet.has(k)); + if (missing.length > 0 || extra.length > 0) { + bad(`keys must exactly match '@${FIELD_ATTR_VALUES}' members` + + (missing.length > 0 ? ` (missing: ${missing.join(", ")})` : "") + + (extra.length > 0 ? ` (unknown: ${extra.join(", ")})` : "") + "."); + } + const seen = new Map(); + for (const [member, value] of Object.entries(map)) { + if (typeof value !== "string" || value.length === 0) { + bad(`member '${member}' must map to a non-empty string.`); + continue; + } + const owner = seen.get(value); + if (owner !== undefined) bad(`members '${owner}' and '${member}' share the stored string '${value}'; every member must have a unique one.`); + else seen.set(value, member); + } + } + } } // --- Check 6 (R6 Plan 2b): @dbColumnType (logical subtype × value) pairing --- @@ -514,21 +564,33 @@ function validateNode( // one was pairing-checked on its declaring node; own-attrs-only policy). const ownValue = node.ownAttrs().get(FIELD_ATTR_DB_COLUMN_TYPE); if (typeof ownValue === "string") { - const legalSubtypes = (DB_COLUMN_TYPE_VALUES as readonly string[]).includes(ownValue) - ? DB_COLUMN_TYPE_LEGAL_SUBTYPES[ownValue as DbColumnTypeValue] - : undefined; + const legalSubtypes = dbColumnTypeLegalSubtypes(ownValue); if (legalSubtypes === undefined || !legalSubtypes.includes(node.subType)) { errors.push( new ParseError( `${nodeLabel(node)} attribute '@${FIELD_ATTR_DB_COLUMN_TYPE}' value ` + `'${ownValue}' is not legal on field.${node.subType}. ` + `Legal @${FIELD_ATTR_DB_COLUMN_TYPE} pairings: ` + - `${DB_COLUMN_TYPE_VALUES.map( - (v) => `${v} (field.${DB_COLUMN_TYPE_LEGAL_SUBTYPES[v].join("/field.")})`, + `${[...DB_COLUMN_TYPE_VALUES, ...DB_COLUMN_TYPE_SIZED_SPELLINGS].map( + (v) => `${v} (field.${FIELD_SUBTYPE_STRING})`, ).join(", ")}.`, { code: "ERR_BAD_ATTR_VALUE", source: node.source }, ), ); + } else { + // rc.21 part B (U2): a sized spelling holds n characters, so a longer @maxLength would let + // the app accept a value the column refuses. ADR-0039: resolving — @maxLength may be inherited. + const parsed = parseDbColumnType(ownValue); + const max = node.attr(FIELD_ATTR_MAX_LENGTH); + if (parsed !== undefined && "length" in parsed && parsed.length !== undefined && typeof max === "number" && max > parsed.length) { + errors.push( + new ParseError( + `${nodeLabel(node)} declares @${FIELD_ATTR_MAX_LENGTH}: ${max} over '@${FIELD_ATTR_DB_COLUMN_TYPE}: ${ownValue}', ` + + `which holds ${parsed.length}; a value the field accepts would not fit the column.`, + { code: "ERR_BAD_ATTR_VALUE", source: node.source }, + ), + ); + } } } } diff --git a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts index bdd5f3e675..a5522146ee 100644 --- a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts @@ -73,7 +73,7 @@ export const ATTR_DEFINITION: ProviderDefinition = { "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] }; diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index 9f04e4a97c..e48b9bd0bf 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -34,6 +34,8 @@ import { registerAttrClass } from "../../attr-class-map.js"; import { FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF, ISO_DURATION_RE, RELATIVE_START_OF_UNITS, } from "../reporting/reporting-constants.js"; +import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_ENUM } from "../field/field-constants.js"; +import { parseDbColumnType } from "../../persistence/db/db-constants.js"; // --- Expression-only op/fn names (the comparison + and/or/isNull names are the // --- shared filter vocabulary above; these three are new). --- @@ -49,6 +51,119 @@ export const EXPR_CASE_OPERAND = "operand"; // `now`: { now: "", startOf? } — the relative-date value, as a leaf. export const EXPR_NOW = FILTER_RELATIVE_NOW; export const EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF; +// rc.21 part B (U12): { cast: , as: "", dbColumnType?: "" }. +export const EXPR_CAST = "cast"; +export const EXPR_CAST_AS = "as"; +export const EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType"; +// rc.21 part B (U11, U13): the closed, typed function set beside coalesce. +export const EXPR_FN_GREATEST = "greatest"; +export const EXPR_FN_LEAST = "least"; +export const EXPR_FN_NULLIF = "nullif"; +export const EXPR_FN_LOWER = "lower"; +export const EXPR_FN_UPPER = "upper"; +export const EXPR_FN_BTRIM = "btrim"; +export const EXPR_FN_SPLIT_PART = "splitPart"; +export const EXPR_FN_CONCAT = "concat"; +export const EXPR_FN_CONCAT_WS = "concatWs"; +export const EXPR_FN_SUBSTRING = "substring"; +export const EXPR_FN_REPLACE = "replace"; +export const EXPR_FN_LEFT = "left"; +export const EXPR_FN_RIGHT = "right"; +export const EXPR_FN_LENGTH = "length"; + +/** A function parameter's kind: a string, an integer, any scalar, or the type the "same" ones share. */ +type ParamKind = "string" | "int" | "scalar" | "same"; +/** One function's signature: its arity, each parameter's kind (the last repeats), and its result. */ +interface FnSignature { + readonly min: number; + readonly max: number; // Infinity for variadic + readonly params: readonly ParamKind[]; + readonly result: "string" | "int" | "same"; + /** The "same" type must be orderable (greatest / least). */ + readonly ordered?: boolean; +} +const VARIADIC = Number.POSITIVE_INFINITY; +/** + * rc.21 part B: every expression function, by name. A closed set — never free SQL. Each lowers to + * the dialect's own function (Postgres and SQLite spellings live in the view emitter). + */ +export const EXPR_FUNCTIONS: Readonly> = { + [EXPR_FN_COALESCE]: { min: 1, max: VARIADIC, params: ["same"], result: "same" }, + [EXPR_FN_GREATEST]: { min: 1, max: VARIADIC, params: ["same"], result: "same", ordered: true }, + [EXPR_FN_LEAST]: { min: 1, max: VARIADIC, params: ["same"], result: "same", ordered: true }, + [EXPR_FN_NULLIF]: { min: 2, max: 2, params: ["same", "same"], result: "same" }, + [EXPR_FN_LOWER]: { min: 1, max: 1, params: ["string"], result: "string" }, + [EXPR_FN_UPPER]: { min: 1, max: 1, params: ["string"], result: "string" }, + [EXPR_FN_BTRIM]: { min: 1, max: 2, params: ["string", "string"], result: "string" }, + [EXPR_FN_SPLIT_PART]: { min: 3, max: 3, params: ["string", "string", "int"], result: "string" }, + [EXPR_FN_CONCAT]: { min: 1, max: VARIADIC, params: ["scalar"], result: "string" }, + [EXPR_FN_CONCAT_WS]: { min: 2, max: VARIADIC, params: ["string", "scalar"], result: "string" }, + [EXPR_FN_SUBSTRING]: { min: 2, max: 3, params: ["string", "int", "int"], result: "string" }, + [EXPR_FN_REPLACE]: { min: 3, max: 3, params: ["string", "string", "string"], result: "string" }, + [EXPR_FN_LEFT]: { min: 2, max: 2, params: ["string", "int"], result: "string" }, + [EXPR_FN_RIGHT]: { min: 2, max: 2, params: ["string", "int"], result: "string" }, + [EXPR_FN_LENGTH]: { min: 1, max: 1, params: ["string"], result: "int" }, +}; + +/** The field subtypes a cast may name in `as`. */ +export const EXPR_CAST_TARGETS: readonly string[] = [ + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, +]; +const NUMERIC_SUBTYPES: ReadonlySet = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); +const INTEGER_SUBTYPES: ReadonlySet = new Set([FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG]); +const NON_SCALAR_SUBTYPES: ReadonlySet = new Set([FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP]); + +/** + * Why a value of `from` cannot be cast to `to`, or undefined when it can. `intStoredEnum` is + * whether the operand is an enum field stored as an integer (`@intValueMap`). The same table in + * every port: a cast never makes a value of a kind the source cannot hold. + */ +export function castProblem(from: string | undefined, to: string, intStoredEnum: boolean): string | undefined { + if (from === undefined) return undefined; // a null literal casts to anything + if (NON_SCALAR_SUBTYPES.has(from)) return `a field.${from} value cannot be cast`; + if (from === to) return undefined; + if (from === FIELD_SUBTYPE_ENUM) { + if (to === FIELD_SUBTYPE_STRING) return intStoredEnum ? "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int" : undefined; + if (INTEGER_SUBTYPES.has(to)) return intStoredEnum ? undefined : "only an enum stored as an integer (@intValueMap) can be cast to a number"; + return `an enum cannot be cast to ${to}`; + } + if (to === FIELD_SUBTYPE_STRING) return undefined; + if (from === FIELD_SUBTYPE_STRING) return undefined; // the database parses it + // Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if (NUMERIC_SUBTYPES.has(to)) { + if (from === FIELD_SUBTYPE_BOOLEAN) return to === FIELD_SUBTYPE_INT ? undefined : `a boolean casts only to int, not ${to}`; + return NUMERIC_SUBTYPES.has(from) ? undefined : `a ${from} cannot be cast to ${to}`; + } + if (to === FIELD_SUBTYPE_BOOLEAN) return from === FIELD_SUBTYPE_INT ? undefined : `a ${from} cannot be cast to boolean; only an int can`; + if (to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP) { + return from === FIELD_SUBTYPE_DATE || from === FIELD_SUBTYPE_TIMESTAMP ? undefined : `a ${from} cannot be cast to ${to}`; + } + return `a ${from} cannot be cast to ${to}`; +} + +/** The function names an expression tree calls, and whether it casts, for the CHECK-condition subset. */ +export function exprViewOnlyNode(node: unknown): string | undefined { + if (!isObj(node)) return undefined; + if (EXPR_CAST in node) return EXPR_CAST; + if (EXPR_CASE in node) return EXPR_CASE; + if (EXPR_NOW in node) return EXPR_NOW; + if ("fn" in node && node.fn !== EXPR_FN_COALESCE) return String(node.fn); + if (typeof node.field === "string" && node.field.includes(".")) return `the path "${node.field}"`; + for (const key of ["left", "right", "arg"]) { + const hit = exprViewOnlyNode(node[key]); + if (hit !== undefined) return hit; + } + if (Array.isArray(node.args)) { + for (const a of node.args) { + const hit = exprViewOnlyNode(a); + if (hit !== undefined) return hit; + } + } + return undefined; +} const COMPARISON_OPS: ReadonlySet = new Set([ FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, @@ -66,9 +181,12 @@ const NODE_KEYS: ReadonlyMap = new Map([ ["op", ["op", "left", "right", "arg", "args"]], ]); const ARM_KEYS: readonly string[] = [EXPR_CASE_WHEN, EXPR_CASE_THEN]; -const NUMERIC_SUBTYPES: ReadonlySet = new Set([ - FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, -]); + +/** `now` takes only `startOf` beside it: any other key is refused. */ +function extraNowKeys(node: Record): string[] { + const extra = Object.keys(node).filter((k) => k !== EXPR_NOW && k !== EXPR_NOW_START_OF); + return extra.length === 0 ? [] : [`expression '${EXPR_NOW}' takes only '${EXPR_NOW_START_OF}' beside it, not ${extra.join(", ")}`]; +} export type ExprLiteral = string | number | boolean | null; export type ExprNode = @@ -77,9 +195,10 @@ export type ExprNode = | { op: string; left: ExprNode; right: ExprNode } // comparison | { op: string; arg: ExprNode } // isNull / isNotNull / not | { op: string; args: ExprNode[] } // and / or - | { fn: string; args: ExprNode[] } // coalesce - | { case: { when: ExprNode; then: ExprNode }[]; else?: ExprNode; operand?: ExprNode } // case - | { now: string; startOf?: string }; // now + | { fn: string; args: ExprNode[] } // coalesce and the rc.21 function set + | { case: { when: ExprNode; then: ExprNode }[]; else?: ExprNode; operand?: ExprNode } // rc.19 case + | { now: string; startOf?: string } // rc.19 now + | { cast: ExprNode; as: string; dbColumnType?: string }; // rc.21 cast function isObj(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); @@ -108,7 +227,7 @@ export function validateExprNode(node: unknown): string[] { const startOf = node[EXPR_NOW_START_OF]; return EXPR_NOW_START_OF in node && !(RELATIVE_START_OF_UNITS as readonly unknown[]).includes(startOf) ? [`expression '${EXPR_NOW_START_OF}' must be one of ${RELATIVE_START_OF_UNITS.join(", ")}, got ${JSON.stringify(startOf)}`] - : []; + : extraNowKeys(node); } if (EXPR_CASE in node) { const arms = node[EXPR_CASE]; @@ -125,10 +244,33 @@ export function validateExprNode(node: unknown): string[] { if (EXPR_CASE_OPERAND in node) errs.push(...validateExprNode(node[EXPR_CASE_OPERAND])); return errs; } + if (EXPR_CAST in node) { + const extra = Object.keys(node).filter((k) => k !== EXPR_CAST && k !== EXPR_CAST_AS && k !== EXPR_CAST_DB_COLUMN_TYPE); + if (extra.length > 0) return [`expression '${EXPR_CAST}' takes only '${EXPR_CAST_AS}' and '${EXPR_CAST_DB_COLUMN_TYPE}' beside it, not ${extra.join(", ")}`]; + const to = node[EXPR_CAST_AS]; + if (typeof to !== "string" || !EXPR_CAST_TARGETS.includes(to)) { + return [`'${EXPR_CAST}' requires '${EXPR_CAST_AS}': one of ${EXPR_CAST_TARGETS.join(", ")}`]; + } + if (EXPR_CAST_DB_COLUMN_TYPE in node) { + const spelling = node[EXPR_CAST_DB_COLUMN_TYPE]; + const parsed = typeof spelling === "string" ? parseDbColumnType(spelling) : undefined; + if (parsed === undefined || parsed.kind === "uuid" || parsed.kind === "jsonb" || to !== FIELD_SUBTYPE_STRING) { + return [`'${EXPR_CAST}' '${EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '${EXPR_CAST_AS}: ${FIELD_SUBTYPE_STRING}'`]; + } + } + return validateExprNode(node[EXPR_CAST]); + } if ("fn" in node) { - if (node.fn !== EXPR_FN_COALESCE) return [`unknown expression fn '${String(node.fn)}'`]; - return Array.isArray(node.args) && node.args.length >= 1 - ? node.args.flatMap(validateExprNode) : [`'${EXPR_FN_COALESCE}' requires a non-empty args array`]; + const sig = typeof node.fn === "string" ? EXPR_FUNCTIONS[node.fn] : undefined; + if (sig === undefined || !Object.prototype.hasOwnProperty.call(EXPR_FUNCTIONS, node.fn as string)) { + return [`unknown expression fn '${String(node.fn)}'`]; + } + const name = node.fn as string; + if (!Array.isArray(node.args) || node.args.length < Math.max(sig.min, 1)) { + return [sig.min <= 1 ? `'${name}' requires a non-empty args array` : `'${name}' requires at least ${sig.min} args`]; + } + if (node.args.length > sig.max) return [`'${name}' takes at most ${sig.max} args, got ${node.args.length}`]; + return node.args.flatMap(validateExprNode); } if ("op" in node) { const op = node.op; @@ -147,7 +289,7 @@ export function validateExprNode(node: unknown): string[] { } return [`unknown expression op '${op}'`]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"]; } /** The subtype of a scalar literal (coarse: an integer number → int, else double). */ @@ -195,7 +337,12 @@ export interface InferResult { * arg subType. Also enforces per-operand op legality against `OPS_BY_SUBTYPE` * (the same bands filters use), so e.g. `gt` on a boolean operand is rejected. */ -export function inferExprType(node: ExprNode, resolveField: (name: string) => string | undefined): InferResult { +export function inferExprType( + node: ExprNode, + resolveField: (name: string) => string | undefined, + /** rc.21 cast: whether a `{ field }` names an enum stored as an integer (`@intValueMap`). */ + isIntStoredEnum: (name: string) => boolean = () => false, +): InferResult { const structural = validateExprNode(node); if (structural.length) return { type: undefined, errors: structural }; const n = node as Record; @@ -212,12 +359,12 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if (EXPR_CASE in n) { const errors: string[] = []; const arms = n[EXPR_CASE] as { when: ExprNode; then: ExprNode }[]; - const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField) : undefined; + const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField, isIntStoredEnum) : undefined; if (operand !== undefined) errors.push(...operand.errors); const results: (string | undefined)[] = []; const resultNodes: unknown[] = []; for (const arm of arms) { - const w = inferExprType(arm.when, resolveField); + const w = inferExprType(arm.when, resolveField, isIntStoredEnum); errors.push(...w.errors); if (operand === undefined && w.type !== undefined && w.type !== FIELD_SUBTYPE_BOOLEAN) { errors.push(`a searched '${EXPR_CASE}' needs a boolean '${EXPR_CASE_WHEN}', got ${w.type}`); @@ -225,13 +372,13 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if (operand?.type !== undefined && w.type !== undefined && !("value" in arm.when) && w.type !== operand.type) { errors.push(`a simple '${EXPR_CASE}' compares its ${operand.type} '${EXPR_CASE_OPERAND}' with a ${w.type} '${EXPR_CASE_WHEN}'`); } - const t = inferExprType(arm.then, resolveField); + const t = inferExprType(arm.then, resolveField, isIntStoredEnum); errors.push(...t.errors); results.push(t.type); resultNodes.push(arm.then); } if (EXPR_CASE_ELSE in n) { - const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField); + const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField, isIntStoredEnum); errors.push(...e.errors); results.push(e.type); resultNodes.push(n[EXPR_CASE_ELSE]); @@ -243,20 +390,52 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st return { type: unified.type, errors }; } - if ("fn" in n) { // coalesce - const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField)); + if (EXPR_CAST in n) { + const inner = n[EXPR_CAST] as ExprNode; + const operand = inferExprType(inner, resolveField, isIntStoredEnum); + const to = n[EXPR_CAST_AS] as string; + const innerObj = inner as Record; + const fieldRef = typeof innerObj.field === "string" ? innerObj.field : undefined; + const problem = castProblem(operand.type, to, fieldRef !== undefined && isIntStoredEnum(fieldRef)); + return { type: to, errors: problem === undefined ? operand.errors : [...operand.errors, `'${EXPR_CAST}': ${problem}`] }; + } + if ("fn" in n) { + const name = n.fn as string; + const sig = EXPR_FUNCTIONS[name]!; + const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField, isIntStoredEnum)); const errors = argResults.flatMap((a) => a.errors); - const unified = unifyTypes(n.args as ExprNode[], argResults.map((a) => a.type)); - if (unified.differing !== undefined) { - errors.push(`'${EXPR_FN_COALESCE}' arguments have differing types (${unified.differing.join(", ")})`); + const same: string[] = []; + const sameNodes: unknown[] = []; + argResults.forEach((a, i) => { + const kind = sig.params[Math.min(i, sig.params.length - 1)]!; + if (a.type === undefined) return; // a null literal fits any parameter + if (kind === "same") { same.push(a.type); sameNodes.push((n.args as ExprNode[])[i]); } + else if (kind === "string" && a.type !== FIELD_SUBTYPE_STRING) { + errors.push(`'${name}' argument ${i + 1} must be a string, got ${a.type}`); + } else if (kind === "int" && a.type !== FIELD_SUBTYPE_INT) { + // Postgres resolves these functions over int4 only (no implicit bigint → int for a call). + errors.push(`'${name}' argument ${i + 1} must be an int, got ${a.type}${a.type === FIELD_SUBTYPE_LONG ? "; cast it ({ cast: , as: int })" : ""}`); + } else if (kind === "scalar" && NON_SCALAR_SUBTYPES.has(a.type)) { + errors.push(`'${name}' argument ${i + 1} must be a scalar, got ${a.type}`); + } + }); + // Adaptable literals (an int literal beside a decimal) fit the typed anchor, as main's coalesce did. + const unifiedAll = unifyTypes(sameNodes, same); + const unified = unifiedAll.type; + if (unifiedAll.differing !== undefined) { + errors.push(`'${name}' arguments have differing types (${unifiedAll.differing.join(", ")})`); } - return { type: unified.type, errors }; + if (sig.ordered && unified !== undefined && (unified === FIELD_SUBTYPE_BOOLEAN || NON_SCALAR_SUBTYPES.has(unified))) { + errors.push(`'${name}' needs ordered arguments, got ${unified}`); + } + const type = sig.result === "same" ? unified : sig.result === "int" ? FIELD_SUBTYPE_INT : FIELD_SUBTYPE_STRING; + return { type, errors }; } const op = n.op as string; if (COMPARISON_OPS.has(op)) { - const l = inferExprType(n.left as ExprNode, resolveField); - const r = inferExprType(n.right as ExprNode, resolveField); + const l = inferExprType(n.left as ExprNode, resolveField, isIntStoredEnum); + const r = inferExprType(n.right as ExprNode, resolveField, isIntStoredEnum); const errors = [...l.errors, ...r.errors]; if (l.type !== undefined && !opsForSubType(l.type).includes(op as FilterOp)) { errors.push(`op '${op}' is not legal for a ${l.type} operand`); @@ -264,13 +443,13 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st return { type: FIELD_SUBTYPE_BOOLEAN, errors }; } if (NULL_OPS.has(op)) { - return { type: FIELD_SUBTYPE_BOOLEAN, errors: inferExprType(n.arg as ExprNode, resolveField).errors }; + return { type: FIELD_SUBTYPE_BOOLEAN, errors: inferExprType(n.arg as ExprNode, resolveField, isIntStoredEnum).errors }; } if (op === EXPR_OP_NOT || VARIADIC_LOGIC_OPS.has(op)) { const kids = op === EXPR_OP_NOT ? [n.arg as ExprNode] : (n.args as ExprNode[]); const errors: string[] = []; for (const k of kids) { - const kt = inferExprType(k, resolveField); + const kt = inferExprType(k, resolveField, isIntStoredEnum); errors.push(...kt.errors); if (kt.type !== undefined && kt.type !== FIELD_SUBTYPE_BOOLEAN) { errors.push(`op '${op}' requires boolean operands, got ${kt.type}`); diff --git a/server/typescript/packages/metadata/src/core/field/enum-storage.ts b/server/typescript/packages/metadata/src/core/field/enum-storage.ts new file mode 100644 index 0000000000..7a2fce032a --- /dev/null +++ b/server/typescript/packages/metadata/src/core/field/enum-storage.ts @@ -0,0 +1,29 @@ +// rc.21 — the string a string-stored field.enum member is stored as: its @stringValueMap entry, +// else the member itself. ONE definition every consumer that writes a member into the database +// (a CHECK, a column length, a DEFAULT, a @condition literal, a converter) reads, so none can +// spell a member the database does not hold. + +import type { MetaData } from "../../shared/meta-data.js"; +import { FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_VALUES } from "./field-constants.js"; + +/** The effective (ADR-0039: resolving, it may be inherited) `@stringValueMap`, or undefined. */ +export function stringValueMapOf(field: MetaData): Readonly> | undefined { + const raw = field.attr(FIELD_ATTR_STRING_VALUE_MAP); + if (raw === undefined || raw === null || typeof raw !== "object" || Array.isArray(raw)) return undefined; + return raw as Record; +} + +/** The string `member` is stored as: its @stringValueMap entry, else the member. */ +export function storedEnumValue(field: MetaData, member: string): string { + const map = stringValueMapOf(field); + const stored = map?.[member]; + return typeof stored === "string" ? stored : member; +} + +/** Every member of @values (ADR-0039: resolving), as stored, in declaration order. */ +export function storedEnumValues(field: MetaData): string[] { + const values = field.attr(FIELD_ATTR_VALUES); + return (Array.isArray(values) ? values : []) + .filter((v): v is string => typeof v === "string") + .map((v) => storedEnumValue(field, v)); +} diff --git a/server/typescript/packages/metadata/src/core/field/field-constants.ts b/server/typescript/packages/metadata/src/core/field/field-constants.ts index 0c340412a1..e313497dfb 100644 --- a/server/typescript/packages/metadata/src/core/field/field-constants.ts +++ b/server/typescript/packages/metadata/src/core/field/field-constants.ts @@ -202,6 +202,15 @@ export const FIELD_ATTR_VALUES = "values"; */ export const FIELD_ATTR_INT_VALUE_MAP = "intValueMap"; +/** + * field.enum (rc.21) — optional per-member stored strings: `{ member: string }`, the string twin of + * {@link FIELD_ATTR_INT_VALUE_MAP}, for a string-stored enum whose database spelling differs from its + * member symbols. Keys must exactly match @values; values must be unique non-empty strings. Refused + * with @intValueMap and on an array enum. The column, its CHECK, its length, a @default and a + * @condition literal hold the stored strings; the native type and the wire keep the members. + */ +export const FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap"; + /** * Pattern every enum member must satisfy: a legal identifier in all target * languages (TS union member, Java/C#/Python enum member). Ensures symbol == diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index d3eb2bf19b..cc1f081144 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -264,9 +264,9 @@ export const FIELD_DEFINITION: ProviderDefinition = { "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ { "type": "attr", @@ -275,7 +275,7 @@ export const FIELD_DEFINITION: ProviderDefinition = { "isArray": true, "min": 1, "max": 1, - "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." + "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", @@ -300,6 +300,14 @@ export const FIELD_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." + }, + { + "type": "attr", + "subType": "properties", + "name": "stringValueMap", + "min": 0, + "max": 1, + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, diff --git a/server/typescript/packages/metadata/src/core/object/object-constants.ts b/server/typescript/packages/metadata/src/core/object/object-constants.ts index baccb04673..3dc397c180 100644 --- a/server/typescript/packages/metadata/src/core/object/object-constants.ts +++ b/server/typescript/packages/metadata/src/core/object/object-constants.ts @@ -42,7 +42,7 @@ export const OBJECT_ATTR_DISCRIMINATOR = "discriminator"; /** FR-014: on a subtype of an entity with @discriminator: the value that * identifies rows of this subtype in the shared discriminator field. */ export const OBJECT_ATTR_DISCRIMINATOR_VALUE = "discriminatorValue"; -/** An object's collection name, in its own casing (the C# DbSet property). */ +/** rc.19 (R57) — an object's collection name (DbSet, REST segment, TS exports, reverse hop). */ export const OBJECT_ATTR_COLLECTION_NAME = "collectionName"; // --------------------------------------------------------------------------- @@ -54,6 +54,11 @@ export const OBJECT_ATTR_COLLECTION_NAME = "collectionName"; * but resolves against the projection's OWN declared fields rather than one * aggregated entity. An aggregate-derived field is not addressable (fail-closed). */ export const OBJECT_PROJECTION_ATTR_FILTER = "filter"; +// rc.21 part B: a projection UNIONed with others (U15), and one with a row per array element (U14). +export const OBJECT_PROJECTION_ATTR_UNION = "union"; +export const OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll"; +export const OBJECT_PROJECTION_ATTR_GRAIN = "grain"; +export const OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal"; // --------------------------------------------------------------------------- // FR-044 — object.report attrs diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index 76f8689026..a69583af2a 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -181,7 +181,40 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." + "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." + }, + { + "type": "attr", + "subType": "string", + "name": "union", + "isArray": true, + "min": 0, + "max": 1, + "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." + }, + { + "type": "attr", + "subType": "boolean", + "name": "unionAll", + "min": 0, + "max": 1, + "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." + }, + { + "type": "attr", + "subType": "string", + "name": "grain", + "min": 0, + "max": 1, + "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." + }, + { + "type": "attr", + "subType": "string", + "name": "grainOrdinal", + "min": 0, + "max": 1, + "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", diff --git a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts index 6c4ad9af13..fcf50b502e 100644 --- a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts +++ b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts @@ -110,3 +110,35 @@ export function findReverseReferenceHops( } return found; } + +/** + * rc.21 — every reverse hop a `@via` may take from `target`: one per identity.reference onto it + * from a concrete object, under that object's {@link reverseHopName}. For the "no such + * relationship" message, so an author who guessed a hop name (the reference's own name, a plural + * the holder's `@collectionName` overrides) sees the one the rule gives. + */ +export function reverseReferenceHopsOnto( + target: MetaObject, + objects: readonly MetaObject[], +): { hopName: string; hop: ReverseReferenceHop }[] { + const found: { hopName: string; hop: ReverseReferenceHop }[] = []; + for (const holder of objects) { + if (holder.isAbstract) continue; + for (const ref of holder.referenceIdentities()) { + // ADR-0059 R7: compare the bound target, never a short name. + if (refTarget(ref, IDENTITY_REFERENCE_ATTR_REFERENCES) === target) { + found.push({ hopName: reverseHopName(holder), hop: { holder, referenceIdentity: ref } }); + } + } + } + return found; +} + +/** The message suffix naming {@link reverseReferenceHopsOnto}'s hops, or "" when there are none. */ +export function reverseHopHint(target: MetaObject, objects: readonly MetaObject[]): string { + const hops = reverseReferenceHopsOnto(target, objects); + if (hops.length === 0) return ""; + return ` The reverse hops from ${target.name} are: ` + + hops.map((h) => `"${h.hopName}" (walks ${h.hop.holder.name}.${h.hop.referenceIdentity.name} backwards)`).join(", ") + + " — a reverse hop is named by the holder's collection name (its @collectionName, else the plural), first letter lowercased."; +} diff --git a/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts b/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts index 03381467c8..ce1ffb5272 100644 --- a/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts +++ b/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts @@ -37,6 +37,7 @@ import { FIELD_ATTR_CURRENCY, FIELD_ATTR_FILTERABLE, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_REQUIRED, @@ -59,6 +60,8 @@ const CARRIED_ATTRS = [ FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + // rc.21: a @stringValueMap enum is read through its stored strings, here as everywhere. + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts index acbbbd0f74..1e52df5e22 100644 --- a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts +++ b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts @@ -57,6 +57,8 @@ export type ComparisonOp = (typeof VALIDATOR_COMPARISON_OPS)[number]; export const VALIDATOR_ATTR_CONDITION = "condition"; /** Every validator (db provider): the database name of the CHECK it generates. */ export const VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; +/** A CHECK-generating validator or field.enum (db provider): `false` generates no database CHECK. Absent: true. */ +export const VALIDATOR_ATTR_DB_CHECK = "dbCheck"; /** The cross-field validators: the database enforces them, nothing else evaluates them. */ export const CROSS_FIELD_VALIDATOR_SUBTYPES: readonly string[] = [ VALIDATOR_SUBTYPE_COMPARISON, diff --git a/server/typescript/packages/metadata/src/enum-length.ts b/server/typescript/packages/metadata/src/enum-length.ts index af3d3e5a90..86dc5c6fb7 100644 --- a/server/typescript/packages/metadata/src/enum-length.ts +++ b/server/typescript/packages/metadata/src/enum-length.ts @@ -11,6 +11,7 @@ import { FIELD_SUBTYPE_ENUM, } from "./core/field/field-constants.js"; import { TYPE_OBJECT } from "./shared/base-types.js"; +import { storedEnumValues, stringValueMapOf } from "./core/field/enum-storage.js"; /** The `enums` block in `.metaobjects/config.json`. */ export const ENUMS_KEY_MAX_LENGTH = "maxLength"; @@ -48,15 +49,14 @@ export function resolveEnumMaxLength(field: MetaData): number | undefined { if (typeof own === "number") return own; const fallback = enumDefaultsOf(field).maxLength; if (fallback === undefined) return undefined; - const values = field.attr(FIELD_ATTR_VALUES); - const longest = (Array.isArray(values) ? values : []) - .filter((v): v is string => typeof v === "string") + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + const longest = storedEnumValues(field) .reduce((a, v) => (a === undefined || v.length > a.length ? v : a), undefined); if (longest !== undefined && longest.length > fallback) { const owner = field.parent; const label = owner !== undefined && owner.type === TYPE_OBJECT ? `${owner.name}.${field.name}` : field.name; throw new MetaModelError( - `field.enum "${label}" has the member "${longest}" (${longest.length} characters), longer than ` + + `field.enum "${label}" has the ${stringValueMapOf(field) === undefined ? "member" : "stored value"} "${longest}" (${longest.length} characters), longer than ` + `the project's enums.maxLength ${fallback}. Give the field its own @maxLength of at least ` + `${longest.length}, raise enums.maxLength, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" }, diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index aa62e206bb..0be9f19be7 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -161,6 +161,10 @@ export const ERROR_CODES = [ "ERR_SEQUENCE_WITHOUT_INCREMENT", // identity.primary @sequenceStart below 1, or past what its key field can hold. "ERR_SEQUENCE_START_OUT_OF_RANGE", + // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + // A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. + "ERR_CROSS_FIELD_WITHOUT_CHECK", "ERR_STORAGE_WITHOUT_OBJECT_REF", // ADR-0013 — a field.object REQUIRES @objectRef (open/untyped JSON uses // the physical @dbColumnType: jsonb escape hatch on field.string instead). diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index b1253eab77..1fa511f1cf 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -27,6 +27,7 @@ export * from "./shared/base-types.js"; export * from "./shared/structural.js"; export * from "./core/object/object-constants.js"; export * from "./core/field/field-constants.js"; +export * from "./core/field/enum-storage.js"; export * from "./core/field/duration-wire.js"; // FR-037 R1 — THE mutability accessors. Every consumer deciding "may this be // written, and when?" must go through these rather than reading the attr, so the @@ -99,7 +100,10 @@ export { } from "./core/requirement/resolve-claim.js"; export * from "./core/relationship/relationship-constants.js"; export * from "./core/query/query-constants.js"; -export { EXPR_OP_IS_NOT_NULL, EXPR_OP_NOT, EXPR_FN_COALESCE, type ExprNode } from "./core/attr/meta-attr-expression.js"; +export { + EXPR_OP_IS_NOT_NULL, EXPR_OP_NOT, EXPR_FN_COALESCE, EXPR_CAST, EXPR_CAST_AS, EXPR_CAST_DB_COLUMN_TYPE, EXPR_FUNCTIONS, EXPR_CAST_TARGETS, + castProblem, exprViewOnlyNode, type ExprNode, +} from "./core/attr/meta-attr-expression.js"; export * from "./persistence/source/source-constants.js"; export * from "./persistence/origin/origin-constants.js"; export * from "./template/template-constants.js"; @@ -168,7 +172,7 @@ export { MetaRelationship } from "./core/relationship/meta-relationship.js"; // Cross-entity reference lookup export { resolveFlattenedMember, resolveFieldPathColumn, type FlattenedMember } from "./core/field/flattened-member.js"; export { - findReferenceBetween, findReferencesBetween, findReverseReferenceHops, reverseHopName, + findReferenceBetween, findReferencesBetween, findReverseReferenceHops, reverseHopName, reverseReferenceHopsOnto, reverseHopHint, type ReverseReferenceHop, } from "./core/relationship/find-reference.js"; export type { ReferenceLookup } from "./core/relationship/find-reference.js"; @@ -372,6 +376,10 @@ export type { Scope, CompiledScope } from "./scope.js"; export { validateAttrSchema } from "./attr-schema-validate.js"; export type { AttrSchemaValidationResult } from "./attr-schema-validate.js"; +// rc.21 part B (I2): the widened-extender warning, which `meta gen` prints (the load's own +// warning channel is not printed by the CLI). +export { validateExtenderSubtypeScope } from "./loader/validation-passes.js"; + // Guide URLs pinned to the running release's tag (prerelease → main). export { DOCS_REPO_URL, DOCS_DEFAULT_REF, docsRefForVersion, docsBlobUrl, pinDocsRefs, diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 0fa15aaab9..654bacda73 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateDerivedCycles, validateExtenderSubtypeScope, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -608,7 +608,7 @@ export class MetaDataLoader { } errors.push( new ParseError( - `the SuperClass '${failure.ref}' does not exist (referenced by ${failure.nodeFqn})${didYouMeanSuperHint(root, failure.ref)}`, + `the SuperClass '${failure.ref}' does not exist (referenced by ${failure.nodeFqn})${failure.memberHint ?? didYouMeanSuperHint(root, failure.ref)}`, { code: "ERR_UNRESOLVED_SUPER", source: resolvedSource(failure.source, failure.nodeFqn, failure.ref), @@ -636,6 +636,8 @@ export class MetaDataLoader { // Fifth pass: @filterable without index drift warning. warnings.push(...validateFilterableHasIndex(root)); + // rc.21 part B (I2): an extender whose view widened with the identity-anchor rule. + warnings.push(...validateExtenderSubtypeScope(root)); // SP-H Unit9 — @filterable on a subtype with no operator band → error // (would silently generate a filter that rejects every request). @@ -663,6 +665,10 @@ export class MetaDataLoader { // an aggregate-derived or dangling ref is fail-closed (ERR_BAD_ATTR_FILTER). errors.push(...validateProjectionFilter(root)); errors.push(...validateOriginSegmentsAndCorrelation(root)); + // rc.21 part B — @union shapes and @grain projections. + errors.push(...validateProjectionUnionAndGrain(root)); + // rc.21 part B fix round 2 (N3): a derived field that depends on itself has no SQL. + errors.push(...validateDerivedCycles(root)); // FR-044 — reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). @@ -732,9 +738,12 @@ export class MetaDataLoader { // identity.primary @sequenceStart / @sequenceName need @generation "increment". errors.push(...validateIdentitySequence(root)); - // Cross-field validators: exactlyOne names two or more fields; @condition names real fields. + // Cross-field validators: atLeastOne @max in range, exactlyOne names two or more fields; @condition names real fields. errors.push(...validateCrossFieldValidators(root, this._strict)); + // @dbCheck: false with @constraintName names a CHECK that is never created. + errors.push(...validateDbCheck(root)); + // Tenth pass: one-primary multi-source rule — if an object has ≥1 source, // exactly one must carry role "primary" (ERR_SOURCE_NO_PRIMARY / // ERR_SOURCE_MULTIPLE_PRIMARY). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 165d42858a..05a74b8019 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -17,15 +17,22 @@ import { VALIDATOR_ATTR_EQUALS, VALIDATOR_ATTR_FIELDS, VALIDATOR_ATTR_WHEN, + VALIDATOR_ATTR_MAX, VALIDATOR_SUBTYPE_EXACTLY_ONE, VALIDATOR_SUBTYPE_AT_LEAST_ONE, - VALIDATOR_ATTR_MAX, VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_ATTR_CONSTRAINT_NAME, + VALIDATOR_ATTR_DB_CHECK, + VALIDATOR_SUBTYPE_LENGTH, + VALIDATOR_SUBTYPE_NUMERIC, + VALIDATOR_SUBTYPE_REGEX, } from "../core/validator/validator-constants.js"; import { parseDurationLiteral } from "../core/field/duration-wire.js"; import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; +import { findReverseReferenceHops, reverseHopHint } from "../core/relationship/find-reference.js"; +import { storedEnumValues, stringValueMapOf } from "../core/field/enum-storage.js"; import { resolveFlattenedMember } from "../core/field/flattened-member.js"; import { resolveFilterPath } from "../core/relationship/filter-path.js"; import { effectiveProjectionFilter } from "../core/object/effective-projection-filter.js"; @@ -69,6 +76,11 @@ import { OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_VALUE, OBJECT_SUBTYPE_PROJECTION, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + OBJECT_ATTR_DISCRIMINATOR, } from "../core/object/object-constants.js"; import { MetaSource } from "../persistence/source/meta-source.js"; import { resolveColumnName, resolveFlattenedColumnName } from "../naming.js"; @@ -84,6 +96,7 @@ import { FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STORAGE, STORAGE_FLATTENED, + STORAGE_JSONB, FIELD_ATTR_DEFAULT, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -94,6 +107,7 @@ import { FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_SUBTYPE_OBJECT, @@ -107,7 +121,7 @@ import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_DURATION, } from "../core/field/field-constants.js"; -import { FIELD_ATTR_COLUMN, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; +import { FIELD_ATTR_COLUMN, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_WHERE, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; import { SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; import { IDENTITY_ATTR_FIELDS, @@ -119,6 +133,13 @@ import { ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, + ORIGIN_FUNCTION_IDENTIFIER, ORIGIN_PASSTHROUGH_ATTR_FROM, ORIGIN_PASSTHROUGH_ATTR_VIA, ORIGIN_PASSTHROUGH_ATTR_CONVERT, @@ -152,6 +173,8 @@ import { EXPR_NOW, inferExprType, validateExprNode, + exprViewOnlyNode, + EXPR_CAST_TARGETS, type ExprNode, } from "../core/attr/meta-attr-expression.js"; import { SORT_ORDER_VALUES } from "../core/query/query-constants.js"; @@ -186,7 +209,6 @@ import { REQUIREMENT_ATTR_SUPERSEDED_BY, REQUIREMENT_STATUS_RETIRED, } from "../core/requirement/requirement-constants.js"; -import { findReverseReferenceHops } from "../core/relationship/find-reference.js"; // --------------------------------------------------------------------------- // Layout dataGrid @defaultSortField validation @@ -824,7 +846,8 @@ function _validateViaPath( errors.push( new ParseError( `origin.@via "${viaAttr}" on ${projectionName}.${fieldName}: no such relationship or reference "${relName}" on ${currentObj.name}. ` + - `Deepest valid prefix was "${prefix}".`, + `Deepest valid prefix was "${prefix}".` + + (isMetaRoot(root) ? reverseHopHint(currentObj as MetaObject, root.objects()) : ""), { code: "ERR_INVALID_ORIGIN", source: resolvedSource(originSource, referrer, viaAttr), @@ -888,14 +911,43 @@ function _validateViaPath( /** A hop's effective @cardinality, or undefined when not declared. A reference * hop (a forward FK) is inherently to-one — a child names the parent it points at. */ -function _hopCardinality(rel: MetaData, reverse?: ReadonlyMap): string | undefined { - // A reference walked backwards reaches every row that references the walked-from one. - if (reverse?.has(rel) === true) return CARDINALITY_MANY; +function _hopCardinality(rel: MetaData, reverse?: ReadonlyMap, uniqueReverseIsOne = false): string | undefined { + // R-walk: a reference walked backwards reaches every row that references the walked-from one — + // unless (rc.21 part B) its holder declares a unique identity over exactly the reference's fields, + // so at most one row references it: then a passthrough may walk it (the aggregate rule keeps calling + // it to-many: an aggregate over it stays legal, as it was). + if (reverse?.has(rel) === true) return uniqueReverseIsOne && _reverseHopIsUnique(rel) ? CARDINALITY_ONE : CARDINALITY_MANY; if (_isReferenceHop(rel)) return CARDINALITY_ONE; const v = rel.attr(RELATIONSHIP_ATTR_CARDINALITY); return typeof v === "string" ? v : undefined; } +/** The field names an identity or reference declares (`@fields`, a string or a list). */ +function _identityFieldSet(node: MetaData): string[] { + const raw = node.attr(IDENTITY_ATTR_FIELDS); + const list = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : []; + return list.map((f) => String(f).trim()).filter((f) => f.length > 0).sort(); +} + +/** + * rc.21 part B: whether a reference walked backwards reaches at most one row — its holder (or an + * ancestor it inherits identities from) declares an identity.primary or identity.secondary whose + * fields are exactly the reference's fields. Derived from the model; no new vocabulary. + */ +function _reverseHopIsUnique(rel: MetaData): boolean { + const holder = rel.parent; + if (holder === undefined) return false; + const fields = _identityFieldSet(rel).join(","); + if (fields === "") return false; + // ADR-0039: resolving — a unique identity may be inherited. + // A partial (@where) or expression (@expr) unique index is unique over a subset or a value, not + // over the reference's rows, so it never makes the hop to-one. + return holder.children().some((c) => c.type === TYPE_IDENTITY + && (c.subType === IDENTITY_SUBTYPE_PRIMARY || c.subType === IDENTITY_SUBTYPE_SECONDARY) + && c.attr(IDENTITY_ATTR_WHERE) === undefined && c.attr(IDENTITY_ATTR_EXPR) === undefined + && _identityFieldSet(c).join(",") === fields); +} + /** * Derive the BASE entity a no-`@via` origin path anchors at (spec §5): * - an entity (or any non-projection host) is its own base — derived fields @@ -956,6 +1008,16 @@ function _deriveBaseEntity( } } + // 1b) rc.21 part B (G13): a projection that extends another projection and declares no identity of + // its own keeps the identity its super anchors with: the inherited identity still names the base, + // so an extender's own fields (a TPH subtype's columns, say) do not move it. + const ownIdentity = obj.ownChildren().some((c) => c.type === TYPE_IDENTITY); + const superProjection = obj.superResolved; + if (!ownIdentity && superProjection !== undefined && superProjection.type === TYPE_OBJECT + && superProjection.subType === OBJECT_SUBTYPE_PROJECTION && _anchorsByIdentity(superProjection)) { + return _deriveBaseEntity(superProjection, root, fieldName, originSource, errors); + } + // 2) Fallback: the single distinct entity targeted by plain field-extends — // again preferring the ref-named owner over the physical declaring ancestor. const targets = new Set(); @@ -1004,6 +1066,74 @@ function _deriveBaseEntity( return undefined; } +/** + * rc.21 part B (I2): warn when an extender's view WIDENED with the identity-anchor rule — a projection + * with no identity of its own whose base its super anchors on a TPH base, that binds a field to a + * column only a subtype carries, and that scopes no row by the discriminator. Before rc.21 its base + * was that subtype and its view held only the subtype's rows; now it is the TPH base's, every row. + */ +export function validateExtenderSubtypeScope(root: MetaData): string[] { + const warnings: string[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_PROJECTION)) { + // An abstract extender emits no view, so nothing it declares widened one (fix round 2, N4). + if (obj.isAbstract) continue; + // ADR-0039: own — the identity anchor rule applies to an extender that declares none of its own. + if (obj.ownChildren().some((c) => c.type === TYPE_IDENTITY)) continue; + const sup = obj.superResolved; + if (sup === undefined || sup.type !== TYPE_OBJECT || sup.subType !== OBJECT_SUBTYPE_PROJECTION || !_anchorsByIdentity(sup)) continue; + const base = _deriveBaseEntity(obj, root, "@extends", obj.source, []); + if (base === undefined) continue; + // ADR-0039: resolving — the discriminator may be declared on an ancestor of the base. + const discriminator = _tphDiscriminatorOf(base); + if (discriminator === undefined) continue; + if (filterKeys(effectiveProjectionFilter(obj)).includes(discriminator)) continue; + const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; + // ADR-0039: own — only the extender's OWN fields chose its base before rc.21 (an inherited field + // was anchored by the super's identity then too), so only they can have widened it. + const subtypeFields: string[] = []; + let subtype: MetaData | undefined; + for (const f of obj.ownChildren().filter((c) => c.type === TYPE_FIELD)) { + const owner = _refNamedOwner(f, root, referrerPkg); + if (owner === undefined || owner === base || !_isDescendantOf(owner, base)) continue; + subtypeFields.push(`"${f.name}" (${owner.name}.${f.superRef?.split(".").pop() ?? f.name})`); + subtype ??= owner; + } + if (subtype !== undefined) { + warnings.push( + `object.projection ${obj.name}: ${subtypeFields.join(", ")} read columns only a subtype carries, over the TPH base ` + + `${base.name} with no @filter on its discriminator "${discriminator}", so the view returns every ${base.name} row ` + + `(rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped ` + + `view, add @filter { ${discriminator}: } or declare identity.primary { extends: ${subtype.name}.primary }.`, + ); + } + } + return warnings; +} + +/** The discriminator field of the TPH level `obj` belongs to (its own, or an ancestor's), if any. */ +function _tphDiscriminatorOf(obj: MetaData): string | undefined { + for (let cur: MetaData | undefined = obj; cur !== undefined && cur.type === TYPE_OBJECT; cur = cur.superResolved) { + // ADR-0039: own — the level that declares the discriminator. + const d = cur.ownAttr(OBJECT_ATTR_DISCRIMINATOR); + if (typeof d === "string") return d; + } + return undefined; +} + +/** Whether `obj` extends `ancestor`, directly or through levels. */ +function _isDescendantOf(obj: MetaData, ancestor: MetaData): boolean { + for (let cur = obj.superResolved; cur !== undefined; cur = cur.superResolved) if (cur === ancestor) return true; + return false; +} + +/** rc.21 part B: whether a projection (or a projection it extends) anchors its base with an extended identity. */ +function _anchorsByIdentity(obj: MetaData): boolean { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (obj.ownChildren().some((c) => c.type === TYPE_IDENTITY && c.superResolved?.type === TYPE_IDENTITY)) return true; + const sup = obj.superResolved; + return sup !== undefined && sup.type === TYPE_OBJECT && sup.subType === OBJECT_SUBTYPE_PROJECTION && _anchorsByIdentity(sup); +} + /** * True when the `@from`/`@of` target entity IS the host's base relation: the * derived base entity itself, or an ancestor on the base's (or the host's) @@ -1098,7 +1228,7 @@ function _checkPassthroughCardinality( reverse?: ReadonlyMap, ): void { for (const rel of hops) { - if (_hopCardinality(rel, reverse) === CARDINALITY_MANY) { + if (_hopCardinality(rel, reverse, true) === CARDINALITY_MANY) { errors.push( new ParseError( `origin.passthrough on ${obj.name}.${fieldName}: @via hop "${reverse?.get(rel) ?? rel.name}" is to-many ` + @@ -1394,6 +1524,33 @@ export function validateOriginPaths(root: MetaData): ParseError[] { continue; } const fromTarget = _validateFromPath(from, root, obj, field.name, origin.source, errors); + // rc.21 part B (U14): on a @grain projection, a @from on the grain field's value object + // reads a member of the array element; there is no path to walk. + if (fromTarget !== undefined && fromTarget.entity === _grainValueObject(obj, root)) { + const convert = origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_CONVERT) === true; + _checkPassthroughType(field, fromTarget.field, from, convert, obj, origin.source, errors); + const member = fromTarget.field as { resolvedIsArray?: () => boolean }; + if (member.resolvedIsArray?.() === true || fromTarget.field.subType === FIELD_SUBTYPE_OBJECT || fromTarget.field.subType === FIELD_SUBTYPE_MAP) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" is not a scalar member of the @grain element.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } + if (origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) !== undefined) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" reads the @grain element, which takes no @via.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } + // fix round M2: a value object's enum member is held in the document as its symbol; a value + // map (@intValueMap / @stringValueMap) describes a column the element does not have. + if (fromTarget.field.subType === FIELD_SUBTYPE_ENUM + && (fromTarget.field.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined || fromTarget.field.attr(FIELD_ATTR_STRING_VALUE_MAP) !== undefined)) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" is an enum with a value map, but a @grain element holds the member's symbol; ` + + `read it as a field.string, or drop the map on the value object's member.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } + continue; + } // FR-024 B6 — extends/origin agreement (host-agnostic; runs whether // @via is explicit, inferred, or a base-relation column). if (fromTarget !== undefined) { @@ -1661,50 +1818,34 @@ export function validateOriginPaths(root: MetaData): ParseError[] { // Type inference against the base entity's EFFECTIVE fields (ADR-0039). const base = _deriveBaseEntity(obj, root, field.name, src, errors); if (base === undefined) continue; - // A ref names one of the projection's own fields first (a - // passthrough — joined or not —, an origin.first or another origin.computed), else a base - // field. Never itself, never an aggregate (it would need the grouped row). - const ownOriginOf = (name: string): MetaData | undefined => - // ADR-0039: own — origin.* never inherits (ADR-0029), so a field's origin is declared on it. - obj.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.ownChildren().find((c) => c.type === TYPE_ORIGIN); - const resolveField = (name: string): string | undefined => { + // rc.19 computed-over-joined: a ref names one of the projection's own fields first (a + // passthrough — joined or not —, an origin.first, another origin.computed or, rc.21 U13, a + // scalar origin.aggregate, read on the grouped row), else a base field, else (rc.21 U3, a + // projection only) a PATH of to-one hops from the base and a field of the entity reached, + // joined but not output. Never itself; never a collect (an array). + const fieldNode = (name: string): MetaData | undefined => { if (obj !== base && name !== field.name) { const own = obj.children().find((f) => f.type === TYPE_FIELD && f.name === name); - const ownOrigin = ownOriginOf(name); - if (own !== undefined && ownOrigin?.subType !== ORIGIN_SUBTYPE_AGGREGATE) return own.subType; - if (own !== undefined) return undefined; + if (own !== undefined) return own; } - return base.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.subType; + const baseField = base.children().find((f) => f.type === TYPE_FIELD && f.name === name); + if (baseField !== undefined || obj === base || !name.includes(".")) return baseField; + const path = resolveFilterPath(base as MetaObject, name); + return path !== undefined && typeof path !== "string" ? path.field : undefined; }; - // A sibling computed ref is inlined by the view, so the refs must not lead back here. - const computedRefs = (name: string): string[] => { - const o = ownOriginOf(name); - // ADR-0039: own — origin.* never inherits (ADR-0029), so @expr is declared on the origin. - return o?.subType === ORIGIN_SUBTYPE_COMPUTED - ? expressionFieldRefs(o.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR)).filter((r) => r !== name) - : []; + const resolveField = (name: string): string | undefined => { + const node = fieldNode(name); + if (node === undefined) return undefined; + const nodeOrigin = node.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (node !== field && nodeOrigin?.subType === ORIGIN_SUBTYPE_AGGREGATE + && nodeOrigin.ownAttr(ORIGIN_AGGREGATE_ATTR_AGG) === AGG_COLLECT) return undefined; + return node.subType; }; - const reach = (start: string): Set => { - const seen = new Set(); - const pending = computedRefs(start); - for (let r = pending.pop(); r !== undefined; r = pending.pop()) { - if (!seen.has(r)) pending.push(...computedRefs(r)); - seen.add(r); - } - return seen; + const isIntStoredEnum = (name: string): boolean => { + const node = fieldNode(name); + return node?.subType === FIELD_SUBTYPE_ENUM && node.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined; }; - const reached = obj !== base ? reach(field.name) : new Set(); - if (reached.has(field.name)) { - // One error per cycle, on its first-declared member. - const first = obj.children().find((f) => f.type === TYPE_FIELD && reached.has(f.name) && reach(f.name).has(field.name)); - if (first?.name === field.name) { - errors.push(new ParseError( - `origin.computed on ${obj.name}.${field.name}: @expr refers back to this field through other computed fields; a view cannot inline a cycle.`, - { code: "ERR_INVALID_ORIGIN", source: src })); - } - continue; - } - const inferred = inferExprType(expr as ExprNode, resolveField); + const inferred = inferExprType(expr as ExprNode, resolveField, isIntStoredEnum); if (inferred.errors.length > 0) { for (const m of inferred.errors) { errors.push(new ParseError( @@ -1716,13 +1857,7 @@ export function validateOriginPaths(root: MetaData): ParseError[] { // A literal compared with a field must be able to equal it: of its kind, and for an enum // one of its @values (the same rule a validator's @condition follows). Resolved as the // inference resolved the ref: a projection field first, else a base field. - const literalProblem = literalComparisonProblem(expr, (name) => { - if (obj !== base && name !== field.name) { - const own = obj.children().find((f) => f.type === TYPE_FIELD && f.name === name); - if (own !== undefined) return ownOriginOf(name)?.subType === ORIGIN_SUBTYPE_AGGREGATE ? undefined : own; - } - return base.children().find((f) => f.type === TYPE_FIELD && f.name === name); - }); + const literalProblem = literalComparisonProblem(expr, (name) => fieldNode(name)); if (literalProblem !== undefined) { errors.push(new ParseError( `origin.computed on ${obj.name}.${field.name}: @expr ${literalProblem}`, @@ -1780,6 +1915,8 @@ export function validateOriginPaths(root: MetaData): ParseError[] { _validateOrderByKeys( origin.ownAttr(ORIGIN_ATTR_ORDER_BY), ofTarget?.entity, obj, field.name, "origin.first", src, errors); + } else if (origin.subType === ORIGIN_SUBTYPE_FUNCTION) { + _validateFunctionOrigin(origin, obj, field, root, errors); } } } @@ -1787,6 +1924,76 @@ export function validateOriginPaths(root: MetaData): ParseError[] { return errors; } +/** + * rc.21 part B (U10) — origin.function: a call of a database function the project owns. Its name + * and schema are plain identifiers (never free SQL); each argument names a scalar field of the + * host (an entity), or of the projection (not an aggregate, not the field itself) or its base. + */ +function _validateFunctionOrigin(origin: MetaData, obj: MetaData, field: MetaData, root: MetaData, errors: ParseError[]): void { + const src = origin.source; + const where = `origin.function on ${obj.name}.${field.name}`; + // ADR-0039: own — origin.* never inherits (ADR-0029). + for (const attr of [ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA]) { + const v = origin.ownAttr(attr); + if (v !== undefined && (typeof v !== "string" || !ORIGIN_FUNCTION_IDENTIFIER.test(v))) { + errors.push(new ParseError( + `${where}: @${attr} ${JSON.stringify(v)} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + const args = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + // rc.21 part B fix round (I4): the declared signature. Each parameter and the result is a field + // subtype (the cast targets); the result is the carrying field's, each argument its parameter's. + const rawParams = origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + const params = rawParams === undefined ? [] : Array.isArray(rawParams) ? rawParams : [rawParams]; + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + for (const t of [...params, ...(returns === undefined ? [] : [returns])]) { + if (typeof t !== "string" || !EXPR_CAST_TARGETS.includes(t)) { + errors.push(new ParseError( + `${where}: ${JSON.stringify(t)} is not a parameter or return type; use one of ${EXPR_CAST_TARGETS.join(", ")}.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } + if (typeof returns === "string" && returns !== field.subType) { + errors.push(new ParseError( + `${where}: @returns ${returns}, but the field is field.${field.subType}; the declared return type must be the field's type.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + if (params.length !== args.length) { + errors.push(new ParseError( + `${where}: @params declares ${params.length} parameter type(s) for ${args.length} argument(s); declare one per @args entry.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + const isProjection = obj.subType === OBJECT_SUBTYPE_PROJECTION; + const base = isProjection ? _deriveBaseEntity(obj, root, field.name, src, []) : obj; + for (const [index, name] of args.entries()) { + const own = typeof name === "string" && name !== field.name + ? obj.children().find((c) => c.type === TYPE_FIELD && c.name === name) : undefined; + const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); + const arg = own ?? (typeof name === "string" && base !== undefined + ? base.children().find((c) => c.type === TYPE_FIELD && c.name === name) : undefined); + if (arg === undefined || name === field.name) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", which is not a field of ${isProjection ? `the projection or its base entity` : `"${obj.name}"`}.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (ownOrigin?.subType === ORIGIN_SUBTYPE_AGGREGATE) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", an origin.aggregate; a function takes values of the row, not of the group.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (arg.subType === FIELD_SUBTYPE_OBJECT || arg.subType === FIELD_SUBTYPE_MAP || (arg as { resolvedIsArray?: () => boolean }).resolvedIsArray?.()) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", a field.${arg.subType}${(arg as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() ? " array" : ""}; a function argument is a scalar.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (typeof params[index] === "string" && arg.subType !== params[index]) { + errors.push(new ParseError( + `${where}: argument ${index + 1} "${String(name)}" is a field.${arg.subType}, but parameter ${index + 1} is declared ${String(params[index])}; ` + + `pass an origin.computed field that casts it ({ cast: { field: ${String(name)} }, as: ${String(params[index])} }).`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } +} + // --------------------------------------------------------------------------- // FR-024 B6 — derived-field providability (spec §7 population doctrine). // @@ -1831,10 +2038,10 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] for (const field of obj.ownChildren().filter((c) => c.type === TYPE_FIELD)) { const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); if (origin === undefined) continue; - // A derived field a projection reaches (its @filter or a passthrough + // rc.19 entity-derived: a derived field a projection reaches (its @filter or a passthrough // @from) is lowered inline there, so it needs no read source. Only the inlinable origins. - if ((origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_COMPUTED) - && reached.has(field)) continue; + if ((origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_COMPUTED + || origin.subType === ORIGIN_SUBTYPE_FUNCTION) && reached.has(field)) continue; errors.push( new ParseError( `derived field "${obj.name}.${field.name}" carries an origin.* but entity "${obj.name}" declares no ` + @@ -1882,11 +2089,93 @@ export function projectionReachedEntityFields(root: MetaData): Set { const target = _validateFromPath(from, root, obj, field.name, origin.source, silent); if (target !== undefined) reached.add(target.field); } + // rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + for (const origin of field.ownChildren().filter((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_COMPUTED)) { + if (base === undefined || base === obj) continue; + for (const name of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) { + if (!name.includes(".")) continue; + const path = resolveFilterPath(base as MetaObject, name); + if (path !== undefined && typeof path !== "string") reached.add(path.field); + } + } } } + // rc.21 part B fix round (I4): a reached origin.function inlines its arguments on the same row, so a + // derived argument (an origin.computed cast, say) is reached too. + for (const f of [...reached]) _reachFunctionArgs(f, reached); return reached; } +function _reachFunctionArgs(f: MetaData, reached: Set): void { + // ADR-0039: own — origin.* never inherits (ADR-0029). + const origin = f.ownChildren().find((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_FUNCTION); + const host = f.parent; + if (origin === undefined || host === undefined) return; + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + for (const name of raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]) { + const arg = host.children().find((c) => c.type === TYPE_FIELD && c.name === name); + if (arg !== undefined && !reached.has(arg)) { + reached.add(arg); + _reachFunctionArgs(arg, reached); + } + } +} + +/** + * rc.21 part B fix round 2 (N3): no derived field depends on itself. A view inlines a derived + * field's dependencies on the same row — an origin.function's @args, an origin.computed + * expression's field refs — so a cycle among them (a's argument is b, b's is a) has no SQL and + * would recurse forever. Refused at load, once per cycle, naming the path (ERR_INVALID_ORIGIN). + */ +export function validateDerivedCycles(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { + // ADR-0039: effective — an inherited field's origin is inlined on the extender's row too. + const fields = obj.children().filter((c) => c.type === TYPE_FIELD); + const byName = new Map(fields.map((f) => [f.name, f])); + // ADR-0039: own — origin.* never inherits (ADR-0029); it is the field's own child. + const originOf = (f: MetaData) => f.ownChildren().find((c) => c.type === TYPE_ORIGIN); + const deps = (f: MetaData): MetaData[] => { + const origin = originOf(f); + const names: string[] = []; + // A function naming itself in @args is refused by _validateFunctionOrigin already. On an entity, + // a computed expression reading its own name reads itself: a one-node cycle, reported here (fix + // round 3, M3). On a projection that name is the base entity's field, so it is no cycle. + let selfAllowed = false; + if (origin?.subType === ORIGIN_SUBTYPE_FUNCTION) { + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + for (const n of raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]) if (typeof n === "string") names.push(n); + } else if (origin?.subType === ORIGIN_SUBTYPE_COMPUTED) { + selfAllowed = obj.subType !== OBJECT_SUBTYPE_PROJECTION; + for (const n of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) names.push(n.split(".")[0]!); + } + return names.map((n) => byName.get(n)) + .filter((d): d is MetaData => d !== undefined && (selfAllowed || d !== f) && originOf(d) !== undefined); + }; + const done = new Set(); + const reported = new Set(); + const visit = (f: MetaData, path: MetaData[]): void => { + const at = path.indexOf(f); + if (at >= 0) { + const cycle = [...path.slice(at), f].map((x) => x.name); + const key = [...cycle.slice(0, -1)].sort().join(","); + if (!reported.has(key)) { + reported.add(key); + errors.push(new ParseError( + `${obj.name}.${f.name}: a derived field depends on itself through ${cycle.join(" → ")}; a view inlines each dependency on the same row, so the cycle has no SQL. Break it.`, + { code: "ERR_INVALID_ORIGIN", source: originOf(f)?.source ?? f.source })); + } + return; + } + if (done.has(f)) return; + for (const d of deps(f)) visit(d, [...path, f]); + done.add(f); + }; + for (const f of fields) if (originOf(f) !== undefined) visit(f, []); + } + return errors; +} + /** * Origin segments and correlated filters, on every origin.first / origin.aggregate: * - `@segment` names a segment.filter declared on the related entity (the @of entity, else @@ -1918,7 +2207,7 @@ export function validateOriginSegmentsAndCorrelation(root: MetaData): ParseError const silent: ParseError[] = []; const base = _deriveBaseEntity(obj, root, field.name, origin.source, silent); if (base === undefined) continue; - checkCorrelatedOperands(filter, base, where, origin.source, errors); + checkCorrelatedOperands(filter, base, where, origin.source, errors, obj.subType === OBJECT_SUBTYPE_PROJECTION); } } } @@ -1946,11 +2235,13 @@ function originRelatedEntity(origin: MetaData, obj: MetaData, root: MetaData): M return current; } -function checkCorrelatedOperands(filter: unknown, base: MetaData, where: string, source: ErrorSource, errors: ParseError[]): void { +function checkCorrelatedOperands( + filter: unknown, base: MetaData, where: string, source: ErrorSource, errors: ParseError[], onProjection: boolean, +): void { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return; for (const [key, clause] of Object.entries(filter as Record)) { if (key === FILTER_COMPOSE_AND || key === FILTER_COMPOSE_OR) { - if (Array.isArray(clause)) for (const sub of clause) checkCorrelatedOperands(sub, base, where, source, errors); + if (Array.isArray(clause)) for (const sub of clause) checkCorrelatedOperands(sub, base, where, source, errors, onProjection); continue; } if (typeof clause !== "object" || clause === null || Array.isArray(clause)) continue; @@ -1973,8 +2264,17 @@ function checkCorrelatedOperands(filter: unknown, base: MetaData, where: string, { code: "ERR_BAD_ATTR_FILTER", source }, )); } else if (typeof name !== "string" || !base.children().some((c) => c.type === TYPE_FIELD && c.name === name)) { + // rc.21 part B (U4): on a projection, the operand may be a PATH of to-one hops from the base + // row and a field of the entity reached ("orderId.customerId"), joined on the outer row. + const path = typeof name === "string" && name.includes(".") && onProjection + ? resolveFilterPath(base as MetaObject, name) : undefined; + if (path !== undefined && typeof path !== "string") continue; errors.push(new ParseError( - `${where}: @filter on "${key}" names base-row field "${String(name)}", which "${base.name}" does not declare.`, + typeof path === "string" + ? `${where}: @filter on "${key}" compares with the base-row path "${name}": ${path}.` + : typeof name === "string" && name.includes(".") && !onProjection + ? `${where}: @filter on "${key}" compares with the path "${name}"; a path operand is legal only on a projection, whose view joins it.` + : `${where}: @filter on "${key}" names base-row field "${String(name)}", which "${base.name}" does not declare.`, { code: "ERR_BAD_ATTR_FILTER", source }, )); } @@ -1998,7 +2298,7 @@ function expressionNodes(node: unknown, out: Record[] = []): Re if (typeof node !== "object" || node === null) return out; const n = node as Record; out.push(n); - for (const key of ["left", "right", "arg", EXPR_CASE_OPERAND, EXPR_CASE_ELSE]) expressionNodes(n[key], out); + for (const key of ["left", "right", "arg", "cast", EXPR_CASE_OPERAND, EXPR_CASE_ELSE]) expressionNodes(n[key], out); if (Array.isArray(n["args"])) for (const a of n["args"] as unknown[]) expressionNodes(a, out); if (Array.isArray(n[EXPR_CASE])) { for (const arm of n[EXPR_CASE] as unknown[]) { @@ -2044,6 +2344,13 @@ function conditionProblem(condition: unknown, obj: MetaObject): string | undefin if (unrenderable !== undefined) { return `is not a valid expression: a condition takes no '${EXPR_CASE in unrenderable ? EXPR_CASE : EXPR_NOW}' node, since a CHECK can hold neither a CASE nor the current time.`; } + // rc.21 part B: a CHECK holds the condition's SQL, rendered by every port's CHECK emitter, which + // takes fields, literals, comparisons, null tests, and / or / not and coalesce. The rest of the + // expression grammar (case, now, cast, the other functions, paths) is for views only. + const viewOnly = exprViewOnlyNode(condition); + if (viewOnly !== undefined) { + return `uses ${viewOnly}, which a CHECK condition cannot hold: it takes fields, literals, comparisons, null tests, and / or / not, and coalesce.`; + } const fields = new Map(obj.fields().map((f) => [f.name, f] as const)); const inferred = inferExprType(condition as ExprNode, (name) => fields.get(name)?.subType); if (inferred.errors.length > 0) return `is not a valid expression: ${inferred.errors.join("; ")}.`; @@ -2219,6 +2526,49 @@ export function validateIdentitySequence(root: MetaData): ParseError[] { return errors; } +// --------------------------------------------------------------------------- +// @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no +// database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the +// node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK) rather than one of them silently ignored. +// A cross-field validator is enforced only by its CHECK, so @dbCheck: false on one is refused +// (ERR_CROSS_FIELD_WITHOUT_CHECK), and that is the one error such a node gets. +// Read RESOLVING (ADR-0039), reported on each node that declares either of the two itself. +// --------------------------------------------------------------------------- + +const DB_CHECK_VALIDATOR_SUBTYPES: readonly string[] = [ + VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, ...CROSS_FIELD_VALIDATOR_SUBTYPES, +]; + +export function validateDbCheck(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + const visit = (node: MetaData, owner: string | undefined): void => { + const checked = (node.type === TYPE_VALIDATOR && DB_CHECK_VALIDATOR_SUBTYPES.includes(node.subType)) + || (node.type === TYPE_FIELD && node.subType === FIELD_SUBTYPE_ENUM); + if (checked && (node.ownAttr(VALIDATOR_ATTR_DB_CHECK) !== undefined || node.ownAttr(VALIDATOR_ATTR_CONSTRAINT_NAME) !== undefined)) { + const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + const label = `${node.type}.${node.subType} "${owner !== undefined ? `${owner}.` : ""}${node.name}"`; + if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && CROSS_FIELD_VALIDATOR_SUBTYPES.includes(node.subType)) { + // A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.push(new ParseError( + `${label} sets @dbCheck: false, but this validator is enforced only by its CHECK, so the rule would be ` + + `enforced nowhere. Remove the validator, or remove @dbCheck: false.`, + { code: "ERR_CROSS_FIELD_WITHOUT_CHECK", source: node.source }, + )); + } else if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && typeof name === "string" && name.length > 0) { + errors.push(new ParseError( + `${label} sets @dbCheck: false and @constraintName "${name}"; with no CHECK there is nothing for the name to name. ` + + `Remove @constraintName, or remove @dbCheck: false.`, + { code: "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", source: node.source }, + )); + } + } + const next = node.type === TYPE_OBJECT || node.type === TYPE_FIELD ? node.name : owner; + for (const child of node.ownChildren()) visit(child, next); + }; + for (const child of root.ownChildren()) visit(child, undefined); + return errors; +} + // --------------------------------------------------------------------------- // field.enum @maxLength — the column length of a string-stored enum: // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the @@ -2242,7 +2592,7 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { } }; const checkEnum = (field: MetaData): void => { - const declares = [FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP] + const declares = [FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP] .some((a) => field.ownAttr(a) !== undefined); const maxLength = field.attr(FIELD_ATTR_MAX_LENGTH); if (!declares || typeof maxLength !== "number") return; @@ -2255,13 +2605,13 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { )); return; } - const values = field.attr(FIELD_ATTR_VALUES); - const tooLong = (Array.isArray(values) ? values : []) - .filter((v): v is string => typeof v === "string" && v.length > maxLength) + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + const tooLong = storedEnumValues(field) + .filter((v) => v.length > maxLength) .sort((a, b) => b.length - a.length); if (tooLong.length > 0) { errors.push(new ParseError( - `field.enum "${label}" @maxLength ${maxLength} is shorter than its member "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, + `field.enum "${label}" @maxLength ${maxLength} is shorter than its ${stringValueMapOf(field) === undefined ? "member" : "stored value"} "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", source: field.source }, )); } @@ -2269,7 +2619,6 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { visit(root); return errors; } - // --------------------------------------------------------------------------- // field.object + @storage cross-attribute validation // @@ -3207,6 +3556,119 @@ function entityFieldAggregates(f: MetaData): boolean { return origin !== undefined && origin.subType === ORIGIN_SUBTYPE_AGGREGATE; } +/** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ +function _grainValueObject(obj: MetaData, root: MetaData): MetaData | undefined { + if (obj.subType !== OBJECT_SUBTYPE_PROJECTION) return undefined; + const grain = obj.attr(OBJECT_PROJECTION_ATTR_GRAIN); + if (typeof grain !== "string") return undefined; + const base = _deriveBaseEntity(obj, root, "@grain", obj.source, []); + const field = base?.children().find((c) => c.type === TYPE_FIELD && c.name === grain); + return field === undefined ? undefined : refTarget(field, FIELD_ATTR_OBJECT_REF); +} + +/** + * rc.21 part B — the projection shapes beside a plain view: + * - `@union` names projections whose rows join this one's: each must be an object.projection + * other than this one, with the same effective fields in order (name, subtype, array-ness and + * @column) — ERR_BAD_ATTR_VALUE otherwise; `@unionAll` needs `@union`; + * - `@grain` names a base-entity field.object array stored as jsonb; such a projection holds no + * origin.aggregate, and `@grainOrdinal` names one of its own field.int / field.long fields with + * no origin. + */ +export function validateProjectionUnionAndGrain(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_PROJECTION)) { + const bad = (message: string): void => { + errors.push(new ParseError(`object.projection ${obj.name}: ${message}`, { code: "ERR_BAD_ATTR_VALUE", source: obj.source })); + }; + // ADR-0039: own — a projection's @union, @grain names ITS view's shape; an extender declares its own. + const union = obj.ownAttr(OBJECT_PROJECTION_ATTR_UNION); + if (obj.ownAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) !== undefined && union === undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION_ALL} needs @${OBJECT_PROJECTION_ATTR_UNION}.`); + } + if (union !== undefined) { + const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; + const mine = obj.children().filter((c) => c.type === TYPE_FIELD); + for (const name of Array.isArray(union) ? union : [union]) { + const member = typeof name === "string" ? resolveObjectRef(root, name, referrerPkg).node : undefined; + if (member === undefined || member.type !== TYPE_OBJECT || member.subType !== OBJECT_SUBTYPE_PROJECTION) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} names "${String(name)}", which is not an object.projection.`); + continue; + } + if (member === obj) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} names the projection itself.`); + continue; + } + const theirs = member.children().filter((c) => c.type === TYPE_FIELD); + // fix round M4: an enum's members and value maps are part of the column's meaning. + const describe = (f: MetaData): string => { + const arr = (f as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true ? "[]" : ""; + const col = f.attr(FIELD_ATTR_COLUMN); + const enumShape = f.subType !== FIELD_SUBTYPE_ENUM ? "" + : ` ${JSON.stringify([f.attr(FIELD_ATTR_VALUES) ?? null, f.attr(FIELD_ATTR_INT_VALUE_MAP) ?? null, f.attr(FIELD_ATTR_STRING_VALUE_MAP) ?? null])}`; + return `${f.name}: field.${f.subType}${arr}${typeof col === "string" ? ` @column ${col}` : ""}${enumShape}`; + }; + // fix round M4: a member's own @union would be flattened away, silently. + if (member.ownAttr(OBJECT_PROJECTION_ATTR_UNION) !== undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} member "${member.name}" declares its own @${OBJECT_PROJECTION_ATTR_UNION}; name its members here instead.`); + } + const a = mine.map(describe); + const b = theirs.map(describe); + if (a.length !== b.length || a.some((x, i) => x !== b[i])) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} member "${member.name}" has a different shape: ` + + `(${b.join(", ")}) where this view is (${a.join(", ")}). A union's members have the same fields, in order.`); + } + } + } + const grain = obj.ownAttr(OBJECT_PROJECTION_ATTR_GRAIN); + const ordinal = obj.ownAttr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); + if (ordinal !== undefined && grain === undefined) bad(`@${OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} needs @${OBJECT_PROJECTION_ATTR_GRAIN}.`); + if (typeof grain === "string") { + const base = _deriveBaseEntity(obj, root, "@grain", obj.source, []); + const field = base?.children().find((c) => c.type === TYPE_FIELD && c.name === grain); + const isArray = (field as { resolvedIsArray?: () => boolean } | undefined)?.resolvedIsArray?.() === true; + const storage = field?.attr(FIELD_ATTR_STORAGE); + if (field === undefined || field.subType !== FIELD_SUBTYPE_OBJECT || !isArray || (storage !== undefined && storage !== STORAGE_JSONB) + || refTarget(field, FIELD_ATTR_OBJECT_REF) === undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_GRAIN} "${grain}" must name a field.object array (isArray, jsonb storage, with @objectRef) of the base entity${base === undefined ? "" : ` "${base.name}"`}.`); + } + for (const f of obj.children().filter((c) => c.type === TYPE_FIELD)) { + if (f.ownChildren().some((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_AGGREGATE)) { + bad(`"${f.name}" is an origin.aggregate; a @grain view has one row per element and groups nothing.`); + } + } + if (ordinal !== undefined) { + const f = obj.children().find((c) => c.type === TYPE_FIELD && c.name === ordinal); + if (f === undefined || (f.subType !== FIELD_SUBTYPE_INT && f.subType !== FIELD_SUBTYPE_LONG) + || f.ownChildren().some((c) => c.type === TYPE_ORIGIN) || f.superRef !== undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} "${String(ordinal)}" must name a field.int or field.long of the projection, with no origin and no extends.`); + } + } + } + } + return errors; +} + +/** + * rc.21 part B (U13): whether an origin.computed reads an origin.aggregate of its projection, + * directly or through another computed. Such a value exists only on the grouped row, so a WHERE + * (the view @filter) cannot hold it. + */ +function computedReadsAggregate(f: MetaData, obj: MetaData, seen: Set = new Set()): boolean { + if (seen.has(f.name)) return false; + seen.add(f.name); + // ADR-0039: own — origin.* never inherits (ADR-0029). + const origin = f.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (origin?.subType !== ORIGIN_SUBTYPE_COMPUTED) return false; + for (const name of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) { + if (name === f.name) continue; + const other = obj.children().find((c) => c.type === TYPE_FIELD && c.name === name); + if (other === undefined) continue; + if (entityFieldAggregates(other) || computedReadsAggregate(other, obj, seen)) return true; + } + return false; +} + /** Every field key of a (desugared) filter, through and/or. */ function filterKeys(filter: unknown, out: string[] = []): string[] { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return out; @@ -3241,7 +3703,7 @@ export function validateProjectionFilter(root: MetaData): ParseError[] { const derived = origin !== undefined && origin.subType !== ORIGIN_SUBTYPE_PASSTHROUGH && - origin.subType !== ORIGIN_SUBTYPE_COMPUTED; + (origin.subType !== ORIGIN_SUBTYPE_COMPUTED || computedReadsAggregate(f, obj)); // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) // stores as an integer, so `like` is not in its band. fields.set(f.name, { derived, ops: opsForField(f) }); diff --git a/server/typescript/packages/metadata/src/naming.ts b/server/typescript/packages/metadata/src/naming.ts index d21b0bee7b..c7362e4c96 100644 --- a/server/typescript/packages/metadata/src/naming.ts +++ b/server/typescript/packages/metadata/src/naming.ts @@ -439,30 +439,33 @@ export function pluralize(s: string): string { } /** - * An object's collection name, in the object's own casing: its own `@collectionName`, else the - * project's pluralizer (`naming.collections`, {@link physicalNamingOf}) over its name. Each - * artifact that reads it applies its own casing. Own, not resolving: a name inherited from an abstract base would give every - * subtype one collection. + * An object's collection name, in the object's own casing: its own + * `@collectionName`, else the project's pluralizer + * (`naming.collections`, {@link physicalNamingOf}) over its name. Each artifact then applies its + * own casing (REST: snake_case; a TS export: as is; a Drizzle variable: lowerFirst). Own, not + * resolving: a name inherited from an abstract base would give every subtype one collection. */ export function collectionNameOf(obj: MetaData): string { - return declaredCollectionName(obj) ?? pluralizer(physicalNamingOf(obj).collections ?? DEFAULT_PLURALIZER)(obj.name); + const declared = declaredCollectionName(obj); + if (declared !== undefined) return declared.name; + return pluralizer(physicalNamingOf(obj).collections ?? DEFAULT_PLURALIZER)(obj.name); } /** - * The REST collection segment an object is served under: {@link collectionSegmentOf} over its - * name, its own `@collectionName` and the project's `naming.collections`. Every route, `$path` - * and REST path in the documentation reads it. + * rc.19 fix round (I3) — the REST collection segment an object is served under: {@link + * collectionSegmentOf} over its name, its declared collection name and the project's + * `naming.collections`. Every port's routes, `$path`, OpenAPI and docs REST paths read it. */ export function collectionSegment(obj: MetaData): string { - return collectionSegmentOf(obj.name, declaredCollectionName(obj), physicalNamingOf(obj).collections); + return collectionSegmentOf(obj.name, declaredCollectionName(obj)?.name, physicalNamingOf(obj).collections); } /** - * The REST collection segment for an object named `name` (shared with C#: - * `fixtures/naming-conformance/collection-segments.json`): + * The REST collection segment for an object named `name` (`fixtures/naming-conformance/ + * collection-segments.json`, shared with C#): * - a declared `@collectionName` wins, snake_cased ({@link snakeCollectionName}); * - else a configured pluralizer's output over the name, snake_cased the same way; - * - else the rule every port has always served: snake_case, then {@link pluralize}. + * - else the historical rule, byte-identical to rc.18: snake_case, then {@link pluralize}. * A pluralizer is applied only when the project configures one, so an unconfigured project's * segments never move (`FAQ` stays `faqs`, never `fa_qs`). */ @@ -482,11 +485,13 @@ export function snakeCollectionName(s: string): string { return m !== null ? toSnakeCase(m[1]!) + m[2]! : toSnakeCase(s); } -/** The collection name an object declares itself (`@collectionName`); undefined when it declares none. */ -export function declaredCollectionName(obj: MetaData): string | undefined { - // ADR-0039: own — a collection name is the declaring object's alone (see collectionNameOf). +/** + * The collection name an object declares itself (`@collectionName`); undefined when it + * declares none. + */ +export function declaredCollectionName(obj: MetaData): { name: string } | undefined { const own = obj.ownAttr(OBJECT_ATTR_COLLECTION_NAME); - return typeof own === "string" && own !== "" ? own : undefined; + return typeof own === "string" && own !== "" ? { name: own } : undefined; } /** diff --git a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts index 3ec3dfcdf5..72838fd33b 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts @@ -58,28 +58,75 @@ export const DB_COLUMN_TYPE_JSONB = "jsonb"; */ export const FIELD_ATTR_LOCAL_TIME = "localTime"; +/** rc.21 part B (U2): the text column spellings `@dbColumnType` takes on a field.string. */ +export const DB_COLUMN_TYPE_TEXT = "text"; +export const DB_COLUMN_TYPE_VARCHAR = "varchar"; +export const DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying"; + /** - * The closed set of legal `@dbColumnType` values (raw-dialect passthrough deferred). + * The closed set of legal bare `@dbColumnType` values (raw-dialect passthrough deferred). * dbColumnType slim-and-derive (ADR-0036 Wave 1, decision 4): the native-array * overrides `uuid_array`/`text_array` are fully removed — native `uuid[]`/`text[]` * are DERIVED from a field subtype + `isArray`, never declared via an escape hatch. * Wave 2 (decision 1) retires `timestamp_with_tz` entirely — tz-awareness moves to - * `field.timestamp` (instant by default) + `@localTime` (the naive opt-out). The - * legal set is now just `{ uuid, jsonb }`, both on field.string. + * `field.timestamp` (instant by default) + `@localTime` (the naive opt-out). + * rc.21 part B (U2) adds the text spellings: `text`, an unbounded `varchar` / `character + * varying`, and the sized `varchar(n)`, `character varying(n)` and `character(n)` + * ({@link parseDbColumnType}), all on field.string. */ export const DB_COLUMN_TYPE_VALUES = [ DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, ] as const; export type DbColumnTypeValue = (typeof DB_COLUMN_TYPE_VALUES)[number]; +/** The sized spellings, as written in a message: `n` is a positive integer. */ +export const DB_COLUMN_TYPE_SIZED_SPELLINGS = ["varchar(n)", "character varying(n)", "character(n)"] as const; + /** * Legal `@dbColumnType` value → the field subtypes it may be applied to (ADR-0013, * R6 Plan 2b). Any other (subtype × value) pairing — or an unrecognized value — is * an ERR_BAD_ATTR_VALUE. Keyed by value; the value-set is enforced by membership in - * this map. Subtype names are the bare FIELD_SUBTYPE_* constants (string). + * this map. Subtype names are the bare FIELD_SUBTYPE_* constants (string). The sized + * spellings are field.string's too. */ export const DB_COLUMN_TYPE_LEGAL_SUBTYPES: Readonly> = { [DB_COLUMN_TYPE_UUID]: [FIELD_SUBTYPE_STRING], [DB_COLUMN_TYPE_JSONB]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_TEXT]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_VARCHAR]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_CHARACTER_VARYING]: [FIELD_SUBTYPE_STRING], } as const; + +/** A parsed `@dbColumnType`: what the column is, and its declared length for a sized spelling. */ +export type ParsedDbColumnType = + | { readonly kind: "uuid" } + | { readonly kind: "jsonb" } + | { readonly kind: "text" } + | { readonly kind: "varchar"; readonly length?: number } + | { readonly kind: "char"; readonly length: number }; + +/** + * rc.21 part B (U2): parse a `@dbColumnType` value, or undefined for one that is not legal. The + * spellings are Postgres's own, matched exactly (lowercase, one space): `varchar` and `character + * varying` are the one unbounded varying type, `varchar(n)` and `character varying(n)` the sized + * one, `character(n)` the fixed-length one. Every port parses them alike. + */ +export function parseDbColumnType(value: string): ParsedDbColumnType | undefined { + if (value === DB_COLUMN_TYPE_UUID) return { kind: "uuid" }; + if (value === DB_COLUMN_TYPE_JSONB) return { kind: "jsonb" }; + if (value === DB_COLUMN_TYPE_TEXT) return { kind: "text" }; + if (value === DB_COLUMN_TYPE_VARCHAR || value === DB_COLUMN_TYPE_CHARACTER_VARYING) return { kind: "varchar" }; + const sized = /^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$/.exec(value); + if (sized === null) return undefined; + const length = Number(sized[2]); + return sized[1] === "character" ? { kind: "char", length } : { kind: "varchar", length }; +} + +/** The field subtypes a `@dbColumnType` value is legal on, or undefined for a value that is not legal. */ +export function dbColumnTypeLegalSubtypes(value: string): readonly string[] | undefined { + return parseDbColumnType(value) === undefined ? undefined : [FIELD_SUBTYPE_STRING]; +} diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 91d4fe284f..24a6714c31 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -35,11 +35,7 @@ export const DB_DEFINITION: ProviderDefinition = { "name": "dbColumnType", "min": 0, "max": 1, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, @@ -265,6 +261,14 @@ export const DB_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
__chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." + }, + { + "type": "attr", + "subType": "boolean", + "name": "dbCheck", + "min": 0, + "max": 1, + "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, @@ -288,6 +292,14 @@ export const DB_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." + }, + { + "type": "attr", + "subType": "boolean", + "name": "dbCheck", + "min": 0, + "max": 1, + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, @@ -323,7 +335,7 @@ export const DB_DEFINITION: ProviderDefinition = { "name": "constraintName", "min": 0, "max": 1, - "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider." + "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, { "type": "attr", diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts index 4891508cbf..7420344e3c 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts @@ -27,6 +27,8 @@ export const ORIGIN_SUBTYPE_AGGREGATE = "aggregate"; // by @orderBy along @via, projecting @of (argmax-then-project). export const ORIGIN_SUBTYPE_COMPUTED = "computed"; export const ORIGIN_SUBTYPE_FIRST = "first"; +// rc.21 part B (U10): a value computed by a database function the project owns. +export const ORIGIN_SUBTYPE_FUNCTION = "function"; export const ORIGIN_SUBTYPES = [ SUBTYPE_BASE, @@ -34,6 +36,7 @@ export const ORIGIN_SUBTYPES = [ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ] as const; export type OriginSubType = (typeof ORIGIN_SUBTYPES)[number]; @@ -46,6 +49,7 @@ export const ASSEMBLY_ORIGIN_SUBTYPES = [ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ] as const; // passthrough attrs @@ -81,6 +85,15 @@ export const ORIGIN_FIRST_ATTR_OF = "of"; export const ORIGIN_FIRST_ATTR_VIA = "via"; export const ORIGIN_FIRST_ATTR_FILTER = "filter"; +// rc.21 part B (U10) origin.function attrs: the function's name, its schema, and its arguments. +export const ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; +export const ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; +export const ORIGIN_FUNCTION_ATTR_ARGS = "args"; +export const ORIGIN_FUNCTION_ATTR_PARAMS = "params"; +export const ORIGIN_FUNCTION_ATTR_RETURNS = "returns"; +/** A plain SQL identifier: what @function and @schema may hold (never free SQL). */ +export const ORIGIN_FUNCTION_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/; + // aggregate function vocabulary. // // AGGREGATE_FUNCTIONS is the NUMERIC/ORDINAL reduce set — each maps directly to a @@ -108,11 +121,11 @@ export const ORIGIN_AGG_VALUES = [ ] as const; export type OriginAggValue = (typeof ORIGIN_AGG_VALUES)[number]; -/** A segment.filter of the related entity scoping the related rows +/** rc.19 origin-segment: a segment.filter of the related entity scoping the related rows * (origin.first, origin.aggregate), ANDed with @filter — mirrors measure.aggregate @segment. */ export const ORIGIN_ATTR_SEGMENT = "segment"; -/** The null-safe comparisons an origin @filter may make with a base-row +/** rc.19 correlated-filter: the null-safe comparisons an origin @filter may make with a base-row * field operand (`{ field: "" }`): IS DISTINCT FROM / IS NOT DISTINCT FROM. */ export const FILTER_OP_IS_DISTINCT_FROM = "isDistinctFrom"; export const FILTER_OP_IS_NOT_DISTINCT_FROM = "isNotDistinctFrom"; diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index be18d1dc7e..6541892303 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -93,7 +93,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." + "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, { "type": "attr", @@ -101,7 +101,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "segment", "min": 0, "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", @@ -138,6 +138,56 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "function", + "min": 1, + "max": 1, + "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." + }, + { + "type": "attr", + "subType": "string", + "name": "schema", + "min": 0, + "max": 1, + "description": "The schema the function lives in, a plain identifier. Absent: public." + }, + { + "type": "attr", + "subType": "string", + "name": "args", + "isArray": true, + "min": 0, + "max": 1, + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." + }, + { + "type": "attr", + "subType": "string", + "name": "params", + "isArray": true, + "min": 0, + "max": 1, + "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." + }, + { + "type": "attr", + "subType": "string", + "name": "returns", + "min": 1, + "max": 1, + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." + } + ] + }, { "type": "origin", "subType": "first", @@ -176,7 +226,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." + "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, { "type": "attr", @@ -184,7 +234,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "segment", "min": 0, "max": 1, - "description": "Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." + "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } diff --git a/server/typescript/packages/metadata/src/super-resolve.ts b/server/typescript/packages/metadata/src/super-resolve.ts index aa81b086f0..78aa77874a 100644 --- a/server/typescript/packages/metadata/src/super-resolve.ts +++ b/server/typescript/packages/metadata/src/super-resolve.ts @@ -15,8 +15,8 @@ import type { MetaData } from "./shared/meta-data.js"; import { PACKAGE_SEPARATOR, CHILD_REF_SEPARATOR } from "./shared/structural.js"; import { ownerCandidateKeys, RefOverDropError } from "./naming-refs.js"; -import { TYPE_IDENTITY } from "./shared/base-types.js"; -import { IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/identity/identity-constants.js"; +import { TYPE_IDENTITY, TYPE_OBJECT } from "./shared/base-types.js"; +import { IDENTITY_SUBTYPE_PRIMARY, IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/identity/identity-constants.js"; // --------------------------------------------------------------------------- // Tree search helper @@ -223,6 +223,11 @@ export interface DeferredSuperFailure { target?: { type: string; subType: string }; /** target-mismatch only: the extending node's type/subtype, for the message. */ referrer?: { type: string; subType: string }; + /** + * unresolved dotted ref only (rc.21, U1): when the OWNER resolves but the member does not, a + * message suffix naming the owner's members of the referrer's type, inherited ones included. + */ + memberHint?: string; } /** @@ -344,15 +349,49 @@ export function resolveDeferredSupers(root: MetaData): DeferredSuperFailure[] { // set (e.g. Base extends AbstractRoot). Memoized — no re-work. resolveNode(target); } else { + const memberHint = dottedMemberHint(node, effectivePkg); failures.push({ nodeFqn: node.fqn(), ref: node.superRef, source: node.source, kind: "unresolved", + ...(memberHint !== undefined ? { memberHint } : {}), }); } }; + // rc.21 (U1): a dotted ref whose OWNER resolves but whose member does not names the owner's + // members of the referrer's type, inherited ones included — the usual cause is an identity + // spelled by its field (`Owner.id`) where the identity is named otherwise (an unnamed + // identity.primary is "primary"). Without it the only hint was the same-named object's FQN, + // which is wrong advice when the owner was found. + const dottedMemberHint = (node: MetaData, pkg: string): string | undefined => { + const ref = node.superRef; + if (ref === undefined || !isChildTargetingRef(ref)) return undefined; + const parsed = parseChildTargetingRef(ref); + if (parsed === undefined) return undefined; + const owner = tryResolve(parsed.ownerRef, pkg); + if (owner === undefined || owner === "over-drop") return undefined; + let current: MetaData = owner; + for (const seg of parsed.path.slice(0, -1)) { + const matches = current.children().filter((c) => c.name === seg); + if (matches.length !== 1) return undefined; + current = matches[0]!; + } + const last = parsed.path[parsed.path.length - 1]!; + // ADR-0039: resolving — an inherited member is a legal target. + const candidates = current.children().filter((c) => c.type === node.type); + const ownerName = current.type === TYPE_OBJECT ? current.resolutionKey() : current.fqn(); + const listed = candidates.length === 0 + ? `it has no ${node.type} children` + : `its ${node.type} children are: ${candidates.map((c) => `"${c.name}" (${c.type}.${c.subType})`).join(", ")}`; + // The default name of an unnamed identity.primary is its subtype (the registry's defaultName). + const unnamed = node.type === TYPE_IDENTITY && candidates.some((c) => c.name === IDENTITY_SUBTYPE_PRIMARY) + ? ` An ${TYPE_IDENTITY}.${IDENTITY_SUBTYPE_PRIMARY} declared without a name is named "${IDENTITY_SUBTYPE_PRIMARY}".` + : ""; + return ` '${ownerName}' has no ${node.type} named "${last}"; ${listed}.${unnamed}`; + }; + for (const node of pending) resolveNode(node); return failures; } diff --git a/server/typescript/packages/metadata/test/db-definition-completeness.test.ts b/server/typescript/packages/metadata/test/db-definition-completeness.test.ts index 4b26ddd99a..20c10f2feb 100644 --- a/server/typescript/packages/metadata/test/db-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/db-definition-completeness.test.ts @@ -78,9 +78,10 @@ describe("db provider (data-driven) — attr placement", () => { } }); - test("@dbColumnType description renders the legal-value list (uuid | jsonb — timestamp_with_tz retired)", () => { + test("@dbColumnType description renders the legal-value list (uuid, jsonb and the rc.21 text spellings — timestamp_with_tz retired)", () => { const attr = registry.find(TYPE_FIELD, "string")!.attributes.find((a) => a.name === "dbColumnType")!; - expect(attr.description).toContain("uuid | jsonb"); + expect(attr.description).toContain("uuid (a native Postgres uuid column"); + expect(attr.description).toContain("character(n)"); }); test("@localTime is on field.timestamp ONLY (ADR-0036 Wave 2)", () => { diff --git a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts index 7d95baeaaf..049e4e30ec 100644 --- a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts @@ -12,7 +12,7 @@ // decimal → @precision, @scale // object → @objectRef // currency → @currency -// enum → @values, @provided, @intValueMap, @maxLength +// enum → @values, @provided, @intValueMap, @stringValueMap, @maxLength // int/long/double/float/boolean/date/time/timestamp/uuid → none // - the "any attr" wildcard is gone; a misplaced attr is now ERR_UNKNOWN_ATTR. // @@ -104,6 +104,8 @@ const ENUM_CORE_EXTRA: Record = { values: { valueType: "string", required: true }, provided: { valueType: "boolean", required: false }, intValueMap: { valueType: "intMap", required: false }, + // rc.21: the per-member stored strings of a string-stored enum (refused beside @intValueMap). + stringValueMap: { valueType: "properties", required: false }, // The column length of a string-stored enum (refused beside @intValueMap at load). maxLength: { valueType: "int", required: false }, }; @@ -111,6 +113,7 @@ const ENUM_CORE_EXTRA: Record = { // db provider: the name of the CHECK an enum's member list generates. const ENUM_DB_EXTRA: Record = { constraintName: { valueType: "string", required: false }, + dbCheck: { valueType: "boolean", required: false }, }; /** Scoped concern attrs (db / prompt). */ diff --git a/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts b/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts index 487920436d..e654c86ee4 100644 --- a/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts +++ b/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts @@ -54,7 +54,7 @@ describe("FR-014 happy paths", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -72,10 +72,10 @@ describe("FR-014 happy paths", () => { }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }], + "@discriminatorValue": "Coupon", + children: [{ "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }], }, }, ], @@ -181,7 +181,7 @@ describe("FR-014 ERR_DISCRIMINATOR_VALUE_DUPLICATE", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -306,7 +306,7 @@ describe("FR-014 ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, diff --git a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts index fc396982fe..0dec82de4f 100644 --- a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts +++ b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts @@ -51,9 +51,9 @@ describe("FR-015 happy paths", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, @@ -62,13 +62,13 @@ describe("FR-015 happy paths", () => { // FR-024 (B4b): proc-result shapes are object.projection (read-only, // external assembly); identity dropped (optional; no base entity here). "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "PhaseSummaryArgs", + "@proc": "fn_get_stage_summary", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "phaseId" } }, diff --git a/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts b/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts index 0bbba79f5f..ff03728c97 100644 --- a/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts +++ b/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts @@ -188,12 +188,12 @@ describe("FR-016 MetaSource.physicalName — four-step resolution", () => { test("step 1: kind-matching @proc for storedProc kind", async () => { const s = await firstSource( - oneSourceEntity("PhaseSummary", { + oneSourceEntity("StageSummary", { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", + "@proc": "fn_get_stage_summary", }), ); - expect(s.physicalName).toBe("fn_get_phase_summary"); + expect(s.physicalName).toBe("fn_get_stage_summary"); }); test("step 1: kind-matching @materializedView for materializedView kind", async () => { @@ -218,12 +218,12 @@ describe("FR-016 MetaSource.physicalName — four-step resolution", () => { test("step 2: legacy @table for non-table kind still resolves", async () => { const s = await firstSource( - oneSourceEntity("PhaseSummary", { + oneSourceEntity("StageSummary", { "@kind": "storedProc", - "@table": "fn_legacy_phase_summary", + "@table": "fn_legacy_stage_summary", }), ); - expect(s.physicalName).toBe("fn_legacy_phase_summary"); + expect(s.physicalName).toBe("fn_legacy_stage_summary"); }); test("step 3: derives from source's structural name when no alias is set (table kind)", async () => { diff --git a/server/typescript/packages/metadata/test/object-definition-completeness.test.ts b/server/typescript/packages/metadata/test/object-definition-completeness.test.ts index cf7cac81a4..17cb0a2547 100644 --- a/server/typescript/packages/metadata/test/object-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/object-definition-completeness.test.ts @@ -73,6 +73,11 @@ const NORMALIZE: Record = { // to a view-level WHERE); mirrors origin.aggregate's filter-attr placement. const PROJECTION_FILTER: Record = { filter: { valueType: "filter", required: false }, + // rc.21 part B: @union / @unionAll (U15), @grain / @grainOrdinal (U14). + union: { valueType: "string", required: false }, + unionAll: { valueType: "boolean", required: false }, + grain: { valueType: "string", required: false }, + grainOrdinal: { valueType: "string", required: false }, }; // FR-044 — object.report carries its six declaration attrs (five, plus the optional @spine). The array-valued ones @@ -86,10 +91,10 @@ const REPORT_ATTRS: Record = { spine: { valueType: "string", required: false }, }; -// Cross-port attrs some ports act on: @collectionName (implementedIn C# and TypeScript) on entity / -// projection / report, and the JVM's @object / @objectAdapter on object.base, which every subtype -// composes. -const COLLECTION_NAME: Record = { +// R40 kind 2 — language-specific attrs every port loads: the JVM's @object / @objectAdapter on object.base, which +// every subtype composes. +const DB_SET_NAME: Record = { + // rc.19 (R57): @collectionName (kind 1, C# + TypeScript). collectionName: { valueType: "string", required: false }, }; @@ -99,10 +104,10 @@ const JVM_BINDING: Record = { }; function expectedAttrsFor(subType: string): Record { - if (subType === OBJECT_SUBTYPE_ENTITY) return { ...DISCRIMINATOR, ...COLLECTION_NAME, ...JVM_BINDING }; + if (subType === OBJECT_SUBTYPE_ENTITY) return { ...DISCRIMINATOR, ...DB_SET_NAME, ...JVM_BINDING }; if (subType === OBJECT_SUBTYPE_VALUE) return { ...NORMALIZE, ...JVM_BINDING }; - if (subType === OBJECT_SUBTYPE_PROJECTION) return { ...PROJECTION_FILTER, ...COLLECTION_NAME, ...JVM_BINDING }; - if (subType === OBJECT_SUBTYPE_REPORT) return { ...REPORT_ATTRS, ...COLLECTION_NAME, ...JVM_BINDING }; + if (subType === OBJECT_SUBTYPE_PROJECTION) return { ...PROJECTION_FILTER, ...DB_SET_NAME, ...JVM_BINDING }; + if (subType === OBJECT_SUBTYPE_REPORT) return { ...REPORT_ATTRS, ...DB_SET_NAME, ...JVM_BINDING }; // base carries only the JVM bindings (discriminator moved to entity only). return { ...JVM_BINDING }; } diff --git a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts index ace8020c3d..f812b8794e 100644 --- a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts @@ -69,6 +69,14 @@ const EXPECTED: Record> = { // Origin @segment. segment: { valueType: "string", required: false }, }, + // rc.21 part B (U10). + function: { + function: { valueType: "string", required: true }, + schema: { valueType: "string", required: false }, + args: { valueType: "string", required: false }, + params: { valueType: "string", required: false }, + returns: { valueType: "string", required: true }, + }, }; describe("origin provider externalization — completeness", () => { diff --git a/server/typescript/packages/metadata/test/port-scoped-attr.test.ts b/server/typescript/packages/metadata/test/port-scoped-attr.test.ts index db41058139..f4e4a2adfd 100644 --- a/server/typescript/packages/metadata/test/port-scoped-attr.test.ts +++ b/server/typescript/packages/metadata/test/port-scoped-attr.test.ts @@ -32,10 +32,6 @@ describe("a JVM-only attribute", () => { expect(await codes(model(`"@objectAdapter": ["com.acme.DiagnosisAdapter"],`))).not.toEqual([]); }); - test("the never-released @dbSetName is not vocabulary (it is @collectionName)", async () => { - expect(await codes(model(`"@dbSetName": "Diagnosis",`))).toContain("ERR_UNKNOWN_ATTR"); - }); - test("an attribute the registry does not carry still fails", async () => { expect(await codes(model(`"@objectAdapterX": "com.acme.DiagnosisAdapter",`))).toContain("ERR_UNKNOWN_ATTR"); }); diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts new file mode 100644 index 0000000000..53f53731e3 --- /dev/null +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -0,0 +1,319 @@ +// rc.21 part B — the view vocabulary at load: each construct is accepted where it means +// something and refused, with its code, where it does not. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "../src/index.js"; + +const ENTITIES = [ + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, { "field.int": { name: "rank" } }, + { "field.object": { name: "nested", "@objectRef": "Note" } } ] } }, + { "object.value": { name: "Note", children: [ { "field.string": { name: "text" } } ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "zip" } }, + { "field.string": { name: "tags", isArray: true } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "field.object": { name: "primary", "@objectRef": "Contact" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.enum": { name: "kind", "@values": ["A", "B"] } }, + { "field.int": { name: "n" } }, + { "field.string": { name: "ref" } }, + { "field.timestamp": { name: "at" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId" } }, + { "field.long": { name: "customerId" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, +]; + +const orderView = (fields: unknown[], extra: Record = {}) => ({ "object.projection": { name: "V", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "v" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + ...fields, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }); +const computed = (name: string, subType: string, expr: unknown) => + ({ [`field.${subType}`]: { name, children: [ { "origin.computed": { "@expr": expr } } ] } }); + +async function load(...extra: unknown[]): Promise<{ code: string; message: string }[]> { + const doc = { "metadata.root": { package: "acme", children: [...ENTITIES, ...extra] } }; + const { errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + return errors.map((e) => ({ code: String((e as { code?: string }).code), message: e.message })); +} +const ok = async (...extra: unknown[]) => expect(await load(...extra)).toEqual([]); +const refused = async (code: string, pattern: RegExp, ...extra: unknown[]) => { + const errors = await load(...extra); + expect(errors.some((e) => e.code === code && pattern.test(e.message))).toBe(true); +}; + +describe("U2 — @dbColumnType text spellings", () => { + const entity = (attr: Record) => ({ "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + { "field.string": { name: "c", ...attr } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }); + test("text, varchar, character varying and the sized spellings load on a field.string", async () => { + for (const t of ["text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)"]) { + await ok(entity({ "@dbColumnType": t })); + } + }); + test("a misspelling, a zero length, another subtype and a @maxLength over n are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /'VARCHAR' is not legal/, entity({ "@dbColumnType": "VARCHAR" })); + await refused("ERR_BAD_ATTR_VALUE", /'character\(0\)' is not legal/, entity({ "@dbColumnType": "character(0)" })); + await refused("ERR_BAD_ATTR_VALUE", /@maxLength: 10 over '@dbColumnType: character\(3\)'/, entity({ "@dbColumnType": "character(3)", "@maxLength": 10 })); + await refused("ERR_BAD_ATTR_VALUE", /'varchar' is not legal on field.int/, { "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + { "field.int": { name: "c", "@dbColumnType": "varchar" } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }); + }); +}); + +describe("U11, U12, U13 — the function set and the cast", () => { + test("typed functions and casts load", async () => { + await ok(orderView([ + computed("a", "string", { fn: "splitPart", args: [{ field: "ref" }, { value: "-" }, { value: 1 }] }), + computed("b", "string", { fn: "concatWs", args: [{ value: " " }, { field: "ref" }, { field: "n" }] }), + computed("c", "int", { fn: "length", args: [{ fn: "btrim", args: [{ field: "ref" }] }] }), + computed("d", "string", { cast: { field: "id" }, as: "string" }), + computed("e", "int", { cast: { field: "status" }, as: "int" }), + computed("f", "string", { cast: { value: null }, as: "string", dbColumnType: "varchar(4)" }), + computed("g", "timestamp", { fn: "greatest", args: [{ field: "at" }, { value: null }] }), + computed("h", "string", { fn: "nullif", args: [{ field: "ref" }, { value: "" }] }), + ])); + }); + test("an unknown function, a bad arity and a wrong argument type are refused", async () => { + await refused("ERR_UNKNOWN_EXPR_NODE", /unknown expression fn 'initcap'/, orderView([computed("a", "string", { fn: "initcap", args: [{ field: "ref" }] })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /'splitPart' requires at least 3 args/, orderView([computed("a", "string", { fn: "splitPart", args: [{ field: "ref" }] })])); + await refused("ERR_INVALID_ORIGIN", /'lower' argument 1 must be a string, got int/, orderView([computed("a", "string", { fn: "lower", args: [{ field: "n" }] })])); + await refused("ERR_INVALID_ORIGIN", /'greatest' arguments have differing types/, orderView([computed("a", "int", { fn: "greatest", args: [{ field: "n" }, { field: "id" }] })])); + await refused("ERR_INVALID_ORIGIN", /'greatest' needs ordered arguments/, orderView([computed("a", "boolean", { fn: "greatest", args: [{ value: true }, { value: false }] })])); + }); + test("a cast the source cannot hold is refused (U8: an enum casts to int only when int-stored)", async () => { + await refused("ERR_INVALID_ORIGIN", /only an enum stored as an integer/, orderView([computed("a", "int", { cast: { field: "kind" }, as: "int" })])); + await refused("ERR_INVALID_ORIGIN", /cast it to int/, orderView([computed("a", "string", { cast: { field: "status" }, as: "string" })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /requires 'as': one of/, orderView([computed("a", "string", { cast: { field: "id" }, as: "enum" })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /'dbColumnType' is a text spelling/, orderView([computed("a", "string", { cast: { field: "id" }, as: "string", dbColumnType: "uuid" })])); + await refused("ERR_INVALID_ORIGIN", /a timestamp cannot be cast to int/, orderView([computed("a", "int", { cast: { field: "at" }, as: "int" })])); + }); + test("an int-stored enum and an int still differ in a case without the cast", async () => { + await refused("ERR_INVALID_ORIGIN", /'case' results have differing types/, orderView([computed("a", "int", { + case: [{ when: { op: "eq", left: { field: "n" }, right: { value: 0 } }, then: { field: "status" } }], else: { field: "n" } })])); + await ok(orderView([computed("a", "int", { + case: [{ when: { op: "eq", left: { field: "n" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], else: { field: "n" } })])); + }); + test("an expression over an aggregate loads, and is not filterable", async () => { + const last = { "field.timestamp": { name: "last", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }; + await ok(orderView([last, computed("touched", "timestamp", { fn: "greatest", args: [{ field: "at" }, { field: "last" }] })])); + await refused("ERR_BAD_ATTR_FILTER", /touched/, orderView([last, computed("touched", "timestamp", { fn: "greatest", args: [{ field: "at" }, { field: "last" }] })], + { "@filter": { touched: { isNull: false } } })); + }); + test("a CHECK @condition refuses the view-only nodes", async () => { + await refused("ERR_BAD_ATTR_VALUE", /uses lower, which a CHECK condition cannot hold/, { "object.entity": { name: "W", children: [ + { "source.rdb": { "@table": "w" } }, { "field.long": { name: "id" } }, { "field.string": { name: "a" } }, { "field.string": { name: "b" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "validator.requiredWhen": { name: "r", "@field": "b", "@condition": { op: "eq", left: { fn: "lower", args: [{ field: "a" }] }, right: { value: "x" } } } } ] } }); + }); +}); + +describe("U3, U4 — paths in an expression and in a correlated operand", () => { + test("a path ref and a path operand load on a projection", async () => { + await ok(orderView([ + computed("zip5", "string", { fn: "left", args: [{ field: "customerId.zip" }, { value: 5 }] }), + { "field.long": { name: "ev", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + ])); + }); + test("a path that does not resolve is refused", async () => { + await refused("ERR_INVALID_ORIGIN", /does not resolve/, orderView([computed("z", "string", { field: "customerId.nope" })])); + await refused("ERR_BAD_ATTR_FILTER", /base-row path "customerId.nope"/, orderView([ + { "field.long": { name: "ev", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.nope" } } } } } ] } }])); + }); +}); + +describe("U10 — origin.function", () => { + const withFn = (fn: Record) => ({ "object.entity": { name: "Customer2", children: [ + { "source.rdb": { "@table": "customers2" } }, { "field.long": { name: "id" } }, { "field.string": { name: "zip" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "field.string": { name: "tier", children: [ { "origin.function": fn } ] } } ] } }); + const reach = { "object.projection": { name: "P2", children: [ + { "source.rdb": { "@kind": "view", "@table": "p2" } }, + { "field.long": { name: "id", extends: "Customer2.id" } }, + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer2.tier" } } ] } }, + { "identity.primary": { name: "id", extends: "Customer2.id" } } ] } }; + test("a declared call on an entity, reached by a projection, loads", async () => { + await ok(withFn({ "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" }), reach); + }); + test("free SQL, an unknown argument and a non-scalar argument are refused", async () => { + await refused("ERR_INVALID_ORIGIN", /is not a plain identifier/, withFn({ "@function": "tier_of(1); drop table x", "@args": [], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /@args names "nope"/, withFn({ "@function": "tier_of", "@args": ["nope"], "@params": ["long"], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /a field.object array; a function argument is a scalar/, withFn({ "@function": "tier_of", "@args": ["contacts"], "@params": ["string"], "@returns": "string" }), reach); + }); + // rc.21 part B fix round (I4): the declared signature is checked. + test("an argument of another type than its parameter, a return type other than the field's, and a short @params are refused", async () => { + await refused("ERR_INVALID_ORIGIN", /argument 1 "id" is a field.long, but parameter 1 is declared int; pass an origin.computed field that casts it/, + withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["int"], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /@returns int, but the field is field.string/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "int" }), reach); + await refused("ERR_INVALID_ORIGIN", /@params declares 1 parameter type\(s\) for 2 argument\(s\)/, + withFn({ "@function": "tier_of", "@args": ["id", "zip"], "@params": ["long"], "@returns": "string" }), reach); + await refused("ERR_MISSING_REQUIRED_ATTR", /returns/, withFn({ "@function": "tier_of", "@args": [] }), reach); + }); + test("an argument cast through an origin.computed field loads", async () => { + await ok({ "object.entity": { name: "Customer2", children: [ + { "source.rdb": { "@table": "customers2" } }, { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "field.int": { name: "idAsInt", children: [ { "origin.computed": { "@expr": { cast: { field: "id" }, as: "int" } } } ] } }, + { "field.string": { name: "tier", children: [ { "origin.function": { "@function": "tier_of", "@args": ["idAsInt"], "@params": ["int"], "@returns": "string" } } ] } } ] } }, reach); + }); + // Fix round 2 (N3): a view inlines a derived field's dependencies on the same row; a cycle has no SQL. + test("a cycle through derived function arguments is refused, naming the path", async () => { + const meter = (...fields: unknown[]) => ({ "object.entity": { name: "Meter", children: [ + { "source.rdb": { "@table": "meters" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ...fields ] } }); + const fnField = (name: string, arg: string) => ({ "field.long": { name, children: [ + { "origin.function": { "@function": `f_${name}`, "@args": [arg], "@params": ["long"], "@returns": "long" } } ] } }); + const meterRow = { "object.projection": { name: "MeterRow", children: [ { "source.rdb": { "@kind": "view", "@table": "v_meter" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { "field.long": { name: "a", children: [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } } ] } }; + // function → function + await refused("ERR_INVALID_ORIGIN", /Meter\.a: a derived field depends on itself through a → b → a/, meter(fnField("a", "b"), fnField("b", "a")), meterRow); + // function → computed → function + await refused("ERR_INVALID_ORIGIN", /depends on itself through a → c → a/, + meter(fnField("a", "c"), { "field.long": { name: "c", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "a" }, { field: "id" } ] } } } ] } }), meterRow); + // A chain without a cycle loads. + await ok(meter(fnField("a", "b"), fnField("b", "id")), meterRow); + }); + // Fix round 3 (M3): on an entity, a computed field that reads its own name reads itself. + test("an entity's computed field that reads itself is a one-node cycle; on a projection the name is the base field", async () => { + const selfRef = { "field.long": { name: "a", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "a" }, { field: "id" } ] } } } ] } }; + await refused("ERR_INVALID_ORIGIN", /Meter\.a: a derived field depends on itself through a → a/, + { "object.entity": { name: "Meter", children: [ { "source.rdb": { "@table": "meters" } }, { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, selfRef ] } }, + { "object.projection": { name: "MeterRow", children: [ { "source.rdb": { "@kind": "view", "@table": "v_meter" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { "field.long": { name: "a", children: [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } } ] } }); + // A projection field over the base field of the same name is no cycle. + await ok(orderView([computed("customerId", "long", { fn: "coalesce", args: [ { field: "customerId" }, { field: "id" } ] })])); + }); + test("an unreached function field on an entity with no read source is refused", async () => { + await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "string" })); + }); +}); + +describe("U14 — @grain", () => { + const grain = (extra: Record, fields: unknown[]) => ({ "object.projection": { name: "G", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "g" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + ...fields ] } }); + const kind = { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }; + test("one row per element loads, with a position", async () => { + await ok(grain({ "@grain": "contacts", "@grainOrdinal": "pos" }, [{ "field.int": { name: "pos" } }, kind])); + }); + test("a scalar array, a single object, a nested member, an aggregate and a bad ordinal are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /@grain "tags" must name a field.object array/, grain({ "@grain": "tags" }, [kind])); + await refused("ERR_BAD_ATTR_VALUE", /@grain "primary" must name a field.object array/, grain({ "@grain": "primary" }, [kind])); + await refused("ERR_INVALID_ORIGIN", /is not a scalar member of the @grain element/, grain({ "@grain": "contacts" }, + [{ "field.object": { name: "nested", "@objectRef": "Note", children: [ { "origin.passthrough": { "@from": "Contact.nested" } } ] } }])); + await refused("ERR_BAD_ATTR_VALUE", /a @grain view has one row per element/, grain({ "@grain": "contacts" }, [kind, + { "field.long": { name: "n", children: [ { "origin.aggregate": { "@agg": "count", "@of": "Order.id", "@via": "Customer.orders" } } ] } }])); + await refused("ERR_BAD_ATTR_VALUE", /@grainOrdinal "pos" must name a field.int or field.long/, grain({ "@grain": "contacts", "@grainOrdinal": "pos" }, + [{ "field.string": { name: "pos" } }, kind])); + }); +}); + +describe("U15 — @union", () => { + const branch = (name: string, entity: string, idField: string, label: Record) => ({ "object.projection": { name, abstract: true, children: [ + { "field.long": { name: "personId", extends: `${entity}.${idField}` } }, label ] } }); + const label = (from: string) => ({ "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [{ field: from }] } } } ] } }); + const union = (extra: Record) => ({ "object.projection": { name: "U", extends: "A", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "u" } } ] } }); + test("projections of one shape union", async () => { + await ok(branch("A", "Customer", "id", label("zip")), branch("B", "Order", "customerId", label("ref")), union({ "@union": ["B"], "@unionAll": true })); + }); + test("a different shape, a non-projection, itself and @unionAll alone are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /member "B" has a different shape/, branch("A", "Customer", "id", label("zip")), + branch("B", "Order", "customerId", { "field.int": { name: "label", children: [ { "origin.computed": { "@expr": { field: "n" } } } ] } }), union({ "@union": ["B"] })); + await refused("ERR_BAD_ATTR_VALUE", /names "Order", which is not an object.projection/, branch("A", "Customer", "id", label("zip")), union({ "@union": ["Order"] })); + await refused("ERR_BAD_ATTR_VALUE", /names the projection itself/, branch("A", "Customer", "id", label("zip")), union({ "@union": ["U"] })); + await refused("ERR_BAD_ATTR_VALUE", /@unionAll needs @union/, branch("A", "Customer", "id", label("zip")), union({ "@unionAll": true })); + }); +}); + +// rc.21 part B fix round (I2): an extender keeps its super's identity anchor, so a projection over a +// TPH base that reads a subtype-only column now returns every base row. The load warns, unless a +// discriminator filter (or its own identity) scopes it. +describe("an extender whose view widened over a TPH base", () => { + const tph = [ + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { name: "id" } }, { "field.string": { name: "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + ]; + const row = (extra: Record = {}, children: unknown[] = []) => ({ "object.projection": { name: "TruckRow", extends: "VehicleBase", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { name: "payload", extends: "Truck.payloadClass" } }, ...children ] } }); + async function warningsOf(...extra: unknown[]): Promise { + const { errors, warnings } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...tph, ...extra] } }))]); + expect(errors).toEqual([]); + return warnings.map((w) => (typeof w === "string" ? w : (w as { message: string }).message)); + } + test("warns, naming the remedy", async () => { + const w = (await warningsOf(row())).filter((m) => m.includes("TruckRow")); + expect(w.length).toBe(1); + expect(w[0]).toMatch(/"payload" \(Truck.payloadClass\) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator "kind"/); + expect(w[0]).toMatch(/@filter \{ kind: \} or declare identity.primary \{ extends: Truck.primary \}/); + }); + test("an abstract extender emits no view: no warning (fix round 2)", async () => { + expect((await warningsOf(row({ abstract: true }))).filter((m) => m.includes("TruckRow"))).toEqual([]); + }); + test("a discriminator filter, or its own identity, scopes it: no warning", async () => { + expect((await warningsOf(row({ "@filter": { kind: "TRUCK" } }))).filter((m) => m.includes("TruckRow"))).toEqual([]); + expect((await warningsOf(row({}, [{ "field.long": { name: "vehicleId", extends: "Truck.id" } }, + { "identity.primary": { name: "id", extends: "Truck.primary" } }]))).filter((m) => m.includes("TruckRow"))).toEqual([]); + }); +}); + +// rc.21 part B fix round minors. +describe("fix round: casts Postgres has, value-mapped grain members, union value maps", () => { + test("M1: a boolean casts only to and from int; a count parameter takes only an int", async () => { + await refused("ERR_INVALID_ORIGIN", /a long cannot be cast to boolean; only an int can/, orderView([computed("a", "boolean", { cast: { field: "id" }, as: "boolean" })])); + await refused("ERR_INVALID_ORIGIN", /a boolean casts only to int, not long/, orderView([computed("a", "long", { cast: { value: true }, as: "long" })])); + await ok(orderView([computed("a", "boolean", { cast: { field: "n" }, as: "boolean" })])); + await refused("ERR_INVALID_ORIGIN", /'left' argument 2 must be an int, got long; cast it/, orderView([computed("a", "string", { fn: "left", args: [{ field: "ref" }, { field: "id" }] })])); + await ok(orderView([computed("a", "string", { fn: "left", args: [{ field: "ref" }, { cast: { field: "id" }, as: "int" }] })])); + }); + test("M2: a @grain member that is a value-mapped enum is refused", async () => { + const doc = [ + { "object.value": { name: "Tag", children: [ { "field.enum": { name: "kind", "@values": ["A", "B"], "@intValueMap": { A: 0, B: 1 } } } ] } }, + { "object.entity": { name: "Item", children: [ { "source.rdb": { "@table": "items" } }, { "field.long": { name: "id" } }, + { "field.object": { name: "tags", "@objectRef": "Tag", isArray: true, "@storage": "jsonb" } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "ItemTag", "@grain": "tags", children: [ { "source.rdb": { "@kind": "view", "@view": "v_item_tag" } }, + { "field.long": { name: "itemId", extends: "Item.id" } }, + { "field.enum": { name: "kind", "@values": ["A", "B"], "@intValueMap": { A: 0, B: 1 }, children: [ { "origin.passthrough": { "@from": "Tag.kind" } } ] } } ] } }, + ]; + await refused("ERR_INVALID_ORIGIN", /is an enum with a value map, but a @grain element holds the member's symbol/, ...doc); + }); + test("M4: union members whose enum value maps differ, and a member's own @union, are refused", async () => { + const branch = (name: string, map: Record, extra: Record = {}) => ({ "object.projection": { name, abstract: true, ...extra, children: [ + { "field.long": { name: "rowId", extends: "Order.id" } }, + { "field.enum": { name: "state", "@values": ["X", "Y"], "@intValueMap": map, children: [ { "origin.passthrough": { "@from": "Order.status", "@convert": true } } ] } } ] } }); + const union = { "object.projection": { name: "U", extends: "A", "@union": ["B"], children: [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } }; + await refused("ERR_BAD_ATTR_VALUE", /member "B" has a different shape/, branch("A", { X: 0, Y: 1 }), branch("B", { X: 1, Y: 0 }), union); + await refused("ERR_BAD_ATTR_VALUE", /member "B" declares its own @union/, branch("A", { X: 0, Y: 1 }), branch("B", { X: 0, Y: 1 }, { "@union": ["C"] }), + branch("C", { X: 0, Y: 1 }), union); + }); +}); diff --git a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts index d0a8737a2d..86714d5216 100644 --- a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts +++ b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts @@ -80,6 +80,8 @@ describe("#210 — assembly origins are illegal on an object.value host", () => aggregate: { "origin.aggregate": { "@agg": "count", "@of": "t::ai::Author.id", "@via": "t::ai::Author.books" } }, computed: { "origin.computed": { "@expr": { op: "isNotNull", arg: { field: "name" } } } }, first: { "origin.first": { "@of": "t::ai::Author.name", "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"] } }, + // rc.21 part B (U10). + function: { "origin.function": { "@function": "f", "@returns": "int" } }, }; test("the originNode table covers exactly the ASSEMBLY_ORIGIN_SUBTYPES set (drift guard)", () => { diff --git a/server/typescript/packages/metadata/test/types/origin.test.ts b/server/typescript/packages/metadata/test/types/origin.test.ts index 5d5c0ed1bb..e97ba19986 100644 --- a/server/typescript/packages/metadata/test/types/origin.test.ts +++ b/server/typescript/packages/metadata/test/types/origin.test.ts @@ -24,9 +24,9 @@ describe("origin type constants", () => { expect(ORIGIN_SUBTYPE_PASSTHROUGH).toBe("passthrough"); expect(ORIGIN_SUBTYPE_AGGREGATE).toBe("aggregate"); }); - test("ORIGIN_SUBTYPES contains base + passthrough + aggregate + computed + first", () => { + test("ORIGIN_SUBTYPES contains base + passthrough + aggregate + computed + first + function", () => { // FR-037 R2 (#336) retired `collection` to reserved-not-registered. - expect(ORIGIN_SUBTYPES).toEqual([SUBTYPE_BASE, "passthrough", "aggregate", "computed", "first"]); + expect(ORIGIN_SUBTYPES).toEqual([SUBTYPE_BASE, "passthrough", "aggregate", "computed", "first", "function"]); }); test("passthrough attrs are camelCase", () => { expect(ORIGIN_PASSTHROUGH_ATTR_FROM).toBe("from"); diff --git a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts index 1fca9b71d5..5cb01cfcfa 100644 --- a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts +++ b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts @@ -29,3 +29,40 @@ describe("ERR_UNRESOLVED_SUPER names the fix", () => { expect(err!.message).not.toContain("exists in"); }); }); + +// rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the +// root inherits from an abstract base in another package. The identity is unnamed, so it is named +// "primary": `Shipment.primary` resolves through the inherited member, and `Shipment.id` +// (the identity spelled by its field) names the members it could have meant. +describe("a dotted extends onto an inherited identity", () => { + const common = JSON.stringify({ "metadata.root": { package: "acme::common", children: [ + { "object.entity": { name: "BaseEntity", abstract: true, children: [ + { "field.int": { name: "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } }); + const auth = (target: string) => JSON.stringify({ "metadata.root": { package: "acme::shipping", children: [ + { "object.entity": { name: "Shipment", extends: "acme::common::BaseEntity", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "shipments" } }, + { "field.string": { name: "kind" } } ] } }, + { "object.entity": { name: "AirShipment", extends: "Shipment", "@discriminatorValue": "Air", children: [ + { "field.string": { name: "key" } } ] } }, + { "object.projection": { name: "ShipmentView", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_shipments" } }, + { "field.int": { name: "id", extends: "Shipment.id" } }, + { "field.string": { name: "key", extends: "AirShipment.key" } }, + { "identity.primary": { extends: target } } ] } } ] } }); + const load = (target: string) => new MetaDataLoader({ strict: true }).load([ + new InMemoryStringSource(common, { id: "common.json", format: "json" }), + new InMemoryStringSource(auth(target), { id: "auth.json", format: "json" }), + ]); + + test("resolves through the member the owner inherits", async () => { + expect((await load("Shipment.primary")).errors).toEqual([]); + }); + + test("a missing member lists the owner's members, not a package qualification", async () => { + const err = (await load("Shipment.id")).errors.find((e) => (e as { code?: string }).code === "ERR_UNRESOLVED_SUPER"); + expect(err!.message).toContain(`'acme::shipping::Shipment' has no identity named "id"; its identity children are: "primary" (identity.primary).`); + expect(err!.message).toContain(`An identity.primary declared without a name is named "primary".`); + expect(err!.message).not.toContain("Qualify it with its package"); + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index 6691c962e2..b55117c724 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -1252,12 +1252,21 @@ function diffTableChecks( // on a name-matched check is still caught as drop+add. Postgres constraints are always // named, so it keeps the exact name-keyed behavior (exprFallback off). const exprFallback = dialect === "sqlite" || dialect === "d1"; - const actualByName = new Map(actual.checks.filter((c) => c.name !== "").map((c) => [c.name, c])); + // rc.21 (N1): SQLite and D1 accept two CHECKs under one name, and the expected schema may hold + // two there, so a name keys a LIST: the same-name actual with the same rule is taken first. + const actualByName = new Map(); + for (const c of actual.checks) { + if (c.name === "") continue; + const list = actualByName.get(c.name) ?? []; + if (!actualByName.has(c.name)) actualByName.set(c.name, list); + list.push(c); + } const consumed = new Set(); const textColumns = textColumnsOf(actual); for (const ec of expected.checks) { - const ac = actualByName.get(ec.name); + const named = (actualByName.get(ec.name) ?? []).filter((a) => !consumed.has(a)); + const ac = named.find((a) => checkMatchesLive(canon, ec, a, textColumns)) ?? named[0]; if (ac) { consumed.add(ac); if (!checkMatchesLive(canon, ec, ac, textColumns)) { diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index c2b32c80b8..4b0ac59603 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -626,7 +626,10 @@ function identityOptions(c: Pick): string { export function pgType(t: SqlType): string { switch (t.kind) { - case "text": return t.maxLength !== undefined ? `VARCHAR(${t.maxLength})` : "TEXT"; + case "text": + if (t.variant === "char") return `CHARACTER(${t.maxLength ?? 1})`; + if (t.maxLength !== undefined) return `VARCHAR(${t.maxLength})`; + return t.variant === "varchar" ? "VARCHAR" : "TEXT"; case "integer": return t.bits === 64 ? "BIGINT" : "INTEGER"; case "real": return "DOUBLE PRECISION"; case "real4": return "REAL"; diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index 19ce6422dd..8b6169e3fa 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -574,7 +574,10 @@ export function sqliteType(t: SqlType, identity: ColumnDescriptor["identity"]): if (identity === "increment") return "INTEGER"; if (identity === "uuid") return "TEXT"; switch (t.kind) { - case "text": return t.maxLength !== undefined ? `VARCHAR(${t.maxLength})` : "TEXT"; + case "text": + if (t.variant === "char") return `CHARACTER(${t.maxLength ?? 1})`; + if (t.maxLength !== undefined) return `VARCHAR(${t.maxLength})`; + return t.variant === "varchar" ? "VARCHAR" : "TEXT"; // Use INTEGER for 64-bit and INT for 32-bit — SQLite preserves the declared type // in pragma_table_info, enabling round-trip fidelity (see introspect/sqlite.ts). case "integer": return t.bits === 64 ? "INTEGER" : "INT"; diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index f9cba66068..026243e787 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -383,9 +383,12 @@ export class UnknownSchemaConventionsError extends Error { /** A project-supplied schema-conventions object lacks members this version calls. */ export class InvalidSchemaConventionsError extends Error { override readonly name = "InvalidSchemaConventionsError"; - constructor(readonly id: string, readonly missing: readonly string[]) { - super(`the schema conventions "${id}" are missing ${missing.join(", ")} — start from a preset ` + - `({ ...efcoreConventions, id: "${id}", … }) so every member this version calls is present`); + constructor(readonly id: string, readonly missing: readonly string[], readonly removed: readonly string[] = []) { + super(missing.length > 0 + ? `the schema conventions "${id}" are missing ${missing.join(", ")} — start from a preset ` + + `({ ...efcoreConventions, id: "${id}", … }) so every member this version calls is present` + : `the schema conventions "${id}" set skipRedundantChecks, which is no longer a convention — ` + + `remove it and set "migrate": { "checks": { "skipRedundant": true } } in .metaobjects/config.json`); } } diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index cf291013d9..25c6c34f9e 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -2,6 +2,7 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, InvalidCheckNameError, type CheckNameProblem, type FkTargetViolation, } from "./errors.js"; import { negateExpression, renderExpressionSql } from "./check-expression.js"; +import { storedEnumValue, stringValueMapOf } from "@metaobjectsdev/metadata"; import { canBeUniqueConstraint, resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, @@ -62,17 +63,21 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + parseDbColumnType, FIELD_ATTR_LOCAL_TIME, FIELD_ATTR_LENIENT, STORAGE_FLATTENED, DOC_ATTR_DESCRIPTION, applyColumnNamingStrategy, physicalNamingOf, - resolveTableName, resolveColumnName, resolveFlattenedColumnName, resolveFieldPathColumn, resolveTableSchema, resolveIndexName, + resolveTableName, resolveColumnName, resolveFlattenedColumnName, resolveTableSchema, resolveIndexName, + resolveFieldPathColumn, resolveEnumMaxLength, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START, VALIDATOR_ATTR_CONDITION, + VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_CONSTRAINT_NAME, + VALIDATOR_ATTR_DB_CHECK, type ExprNode, } from "@metaobjectsdev/metadata"; import type { SqlType } from "./sql-type.js"; @@ -83,6 +88,7 @@ import type { import { qualifiedDbName } from "./qualified-name.js"; import { SQLITE_ISO_NOW } from "./column-default.js"; import { viewFingerprint } from "./view-fingerprint.js"; +import { createHash } from "node:crypto"; import { DIALECT_SQLITE, PG_IDENTIFIER_MAX_BYTES, isSqliteFamily, storedIdentifier } from "./types.js"; import { resolveReferentialActions, @@ -711,7 +717,7 @@ function buildTable( columns, indexes: buildSecondaryIndexes(entity, tableName, strategy, dialect), foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkCtx, onConflict), - checks: buildChecks(entity, tableName, strategy, dialect, skipRedundantChecks), + checks: buildChecks(entity, tableName, strategy, dialect, skipRedundantChecks, root), primaryKey, }; const entityDesc = readDescription(entity); @@ -919,9 +925,11 @@ function buildChecks( strategy: ColumnNamingStrategy, dialect: Dialect | undefined, skipRedundant: boolean, + root?: MetaData, ): CheckDescriptor[] { const checks: CheckDescriptor[] = []; - for (const field of entity.fields()) { + const fieldChecks = (field: MetaField): CheckDescriptor[] => { + const out: CheckDescriptor[] = []; // No field-level CHECKs on array columns: the derived expressions assume a // SCALAR column. `"labels" IN ('A','B')` against a text[] is a type error at // CREATE TABLE; `length(col)`/range checks are equally scalar-shaped. Array @@ -929,10 +937,10 @@ function buildChecks( // per-port validators), matching codegen-ts's column-mapper which also skips // the enum literal-union for isArray columns. // ADR-0039: resolving — array-ness may be inherited via extends. - if (field.resolvedIsArray()) continue; + if (field.resolvedIsArray()) return out; // A derived (origin-bearing) field is no column of the table (the column builder skips it // too): a CHECK on it fails CREATE TABLE. Its validators apply where it is read. - if (field.isDerived()) continue; + if (field.isDerived()) return out; const col = resolveColumnName(field, strategy); const qcol = quoteCheckCol(col); // Enum membership check. An INT-BACKED enum (@intValueMap, design D5) stores @@ -940,7 +948,9 @@ function buildChecks( // the member strings — `IN (0, 5, 9)`, not `IN ('DRAFT', …)`. The members are // still the SSOT: the integers are read THROUGH the map, keyed by member, so a // member with no mapping cannot silently vanish from the constraint. - if (field.subType === FIELD_SUBTYPE_ENUM) { + // @dbCheck: false (ADR-0039 resolving) asks for no CHECK; the enum's membership and each + // validator's rule are enforced app-side only. + if (field.subType === FIELD_SUBTYPE_ENUM && !checkOptedOut(field)) { const raw = field.attr(FIELD_ATTR_VALUES); if (Array.isArray(raw) && raw.length > 0) { const values = raw.map((v) => String(v)); @@ -962,10 +972,11 @@ function buildChecks( }); expression = `${qcol} IN (${ints.join(", ")})`; } else { - expression = `${qcol} IN (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")})`; + // rc.21: a member is stored as its @stringValueMap string, else as itself. + expression = `${qcol} IN (${values.map((v) => `'${storedEnumValue(field, v).replace(/'/g, "''")}'`).join(", ")})`; } const enumCheck = { name: `${tableName}_${col}_chk`, expression }; - checks.push(withDeclaredName(enumCheck, field)); + out.push(withDeclaredName(enumCheck, field)); } } // Validator-derived checks. @@ -975,21 +986,169 @@ function buildChecks( const enforcesLength = !isSqliteFamily(dialect); const enforcedMax = skipRedundant && enforcesLength && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { + if (checkOptedOut(v)) continue; // A declared @constraintName asks for the CHECK by name, so it is kept even where the // project's `migrate.checks.skipRedundant` would leave it out: a declaration beats a default. const keep = declaredCheckName(v) !== undefined; const check = keep ? validatorCheck(v, qcol, tableName, col, dialect) : validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); - if (check) checks.push(withDeclaredName(check, v)); + if (check) out.push(withDeclaredName(check, v)); + } + return out; + }; + for (const field of entity.fields()) checks.push(...fieldChecks(field)); + // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded columns, + // so it carries their CHECKs too — subtypes in name order, so every port lists them alike. A + // concrete subtype is one that declares its own @discriminatorValue (the loader requires one on + // every concrete subtype, ERR_DISCRIMINATOR_VALUE_MISSING), the set the C# port takes. + const discriminator = entity.attr(OBJECT_ATTR_DISCRIMINATOR); + const subtypes = root === undefined ? [] : [...tphConcreteSubtypes(entity, root)] + // ADR-0039: own — a concrete subtype declares its OWN value. + .filter((c) => c.ownAttr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined) + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const valueOf = (sub: MetaObject): string => String(sub.ownAttr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); + const discriminatorIn = (values: readonly string[]): ExprNode => { + const eq = (value: string): ExprNode => + ({ op: "eq", left: { field: discriminator }, right: { value } }) as unknown as ExprNode; + return values.length === 1 ? eq(values[0]!) : ({ op: "or", args: values.map(eq) } as unknown as ExprNode); + }; + if (typeof discriminator === "string" && subtypes.length > 0) { + // A column ONE field node owns (declared once, on a subtype or on an abstract level its + // subtypes share) gets the text a base column gets, with no guard: a CHECK refuses only FALSE, + // and a sibling's row holds NULL there, for which every field-level expression is NULL. So does + // a column several sibling nodes declare with identical CHECKs. Sibling nodes that disagree + // (different @values, a different pattern) each get their own CHECKs, guarded by the + // discriminator values of the subtypes carrying that node and named after the declaring object + // (`
___…`), so neither refuses the other's rows. + const baseFieldNames = new Set(entity.fields().map((f) => f.name)); + const groups = new Map(); + for (const sub of subtypes) { + // ADR-0039: effective fields — a field on an abstract level or a parent subtype is a column too. + for (const field of sub.fields()) { + if (baseFieldNames.has(field.name)) continue; + const owners = groups.get(field.name) ?? []; + if (!groups.has(field.name)) groups.set(field.name, owners); + const owner = owners.find((o) => o.node === field); + if (owner === undefined) owners.push({ node: field, values: [valueOf(sub)] }); + else owner.values.push(valueOf(sub)); + } + } + const same = (a: CheckDescriptor[], b: CheckDescriptor[]): boolean => + a.length === b.length && a.every((c, i) => c.name === b[i]!.name && c.expression === b[i]!.expression); + for (const owners of groups.values()) { + const per = owners.map((o) => ({ ...o, checks: fieldChecks(o.node) })); + if (per.every((p) => same(p.checks, per[0]!.checks))) { + checks.push(...per[0]!.checks); + continue; + } + for (const { node, values, checks: nodeChecks } of per) { + for (const check of nodeChecks) { + const guarded = wrapCondition(check, discriminatorIn(values), entity, strategy, dialect); + if (DECLARED_CHECKS.has(check)) { + DECLARED_CHECKS.add(guarded); + checks.push(guarded); + } else { + checks.push({ ...guarded, name: qualifiedCheckName(check.name, tableName, node.parent, dialect) }); + } + } + } } } // Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). + // A cross-field validator always keeps its CHECK: it is enforced nowhere else, and the loader + // refuses @dbCheck: false on one (ERR_CROSS_FIELD_WITHOUT_CHECK). for (const v of entity.validators()) { const check = crossFieldCheck(v, entity, tableName, strategy, dialect); if (check) checks.push(withDeclaredName(withCondition(check, v, entity, strategy, dialect), v)); } - return checks; + // FR-017 TPH: a cross-field validator a subtype adds holds for that subtype's rows only — + // the discriminator guards it, because unlike a field-level CHECK most cross-field rules are + // FALSE (not NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists + // every concrete subtype the validator reaches (an abstract level's, or a parent subtype's, + // reaches each of its concrete descendants), as an @condition ANDed with the validator's own. + // Its default name carries the declaring object, so the same rule on two siblings, or on a + // sibling and the base, does not collide. + if (typeof discriminator === "string" && subtypes.length > 0) { + const baseValidators = new Set(entity.validators()); + const reached = new Map(); + for (const sub of subtypes) { + // ADR-0039: effective validators — one declared on an abstract level or a parent subtype applies here too. + for (const v of sub.validators()) { + if (baseValidators.has(v)) continue; + const entry = reached.get(v); + if (entry === undefined) reached.set(v, { holder: sub, values: [valueOf(sub)] }); + else entry.values.push(valueOf(sub)); + } + } + for (const [v, { holder, values }] of reached) { + const check = crossFieldCheck(v, holder, tableName, strategy, dialect); + if (!check) continue; + const guarded = withCondition(check, v, holder, strategy, dialect, discriminatorIn(values)); + checks.push(declaredCheckName(v) !== undefined + ? withDeclaredName(guarded, v) + : { ...guarded, name: qualifiedCheckName(check.name, tableName, v.parent, dialect) }); + } + } + return distinctChecks(entity, checks, dialect); +} + +/** A default CHECK name made unique to the object that declares the rule: `
__…`. + * On Postgres it is fitted to the 63-byte identifier limit ({@link fitPgIdentifier}). */ +function qualifiedCheckName(name: string, tableName: string, declarer: MetaData | undefined, dialect: Dialect | undefined): string { + const tag = (declarer?.name ?? "subtype").toLowerCase(); + const qualified = name.startsWith(`${tableName}_`) ? `${tableName}_${tag}_${name.slice(tableName.length + 1)}` : `${tag}_${name}`; + return dialect === "sqlite" || dialect === "d1" ? qualified : fitPgIdentifier(qualified); +} + +/** + * rc.21 (N2): a generated name fitted to Postgres's 63-byte identifier limit. A longer name keeps + * its first 54 bytes (whole characters) and gains `_` and the first 8 hex digits of the SHA-256 + * of the whole name, so two long names that share a prefix stay apart, and every port spells it + * the same. A name that fits is unchanged. Postgres would otherwise truncate it at CREATE, so the + * name the schema expects would never match the database. + */ +export function fitPgIdentifier(name: string): string { + if (Buffer.byteLength(name, "utf8") <= PG_IDENTIFIER_MAX_BYTES) return name; + const hash = createHash("sha256").update(name, "utf8").digest("hex").slice(0, 8); + let head = ""; + for (const ch of name) { + if (Buffer.byteLength(head + ch, "utf8") > PG_IDENTIFIER_MAX_BYTES - 9) break; + head += ch; + } + return `${head}_${hash}`; +} + +/** + * One table's CHECKs, an exact repeat (same name, same expression) kept once, and two different + * CHECKs under one name refused where the database requires unique names: Postgres would refuse + * the second at CREATE TABLE. SQLite and D1 accept both under one name and enforce both (rc.21, + * N1: probed on SQLite 3.51 and on Miniflare's D1), so both are kept there; the CHECK diff matches + * a name to a list. A name shortened to fit the 63-byte limit that still collides is refused too. + */ +function distinctChecks(entity: MetaObject, checks: CheckDescriptor[], dialect: Dialect | undefined): CheckDescriptor[] { + const unique = dialect !== "sqlite" && dialect !== "d1"; + const byName = new Map(); + const out: CheckDescriptor[] = []; + for (const c of checks) { + const seen = byName.get(c.name); + if (seen !== undefined) { + if (seen.expression === c.expression) continue; + // A DECLARED name's collision is checkDeclaredCheckNames' to report, with its own error. + if (!unique || DECLARED_CHECKS.has(c) || DECLARED_CHECKS.has(seen)) { + out.push(c); + continue; + } + throw new Error( + `object.entity '${entity.name}': two CHECK constraints are both named '${c.name}' ` + + `(${seen.expression} | ${c.expression}); Postgres requires each constraint on a table to have its own name. ` + + `Give one of the validators (or enums) a @constraintName.`, + ); + } + byName.set(c.name, c); + out.push(c); + } + return out; } /** @@ -1061,7 +1220,15 @@ function renderEquals( || whenField.subType === FIELD_SUBTYPE_DOUBLE || whenField.subType === FIELD_SUBTYPE_FLOAT || whenField.subType === FIELD_SUBTYPE_DECIMAL || whenField.subType === FIELD_SUBTYPE_CURRENCY; if (numeric && /^-?\d+(\.\d+)?$/.test(s)) return s; - return `'${s.replace(/'/g, "''")}'`; + // rc.21: a member of a @stringValueMap enum is compared as its stored string. + const stored = whenField.subType === FIELD_SUBTYPE_ENUM ? storedEnumValue(whenField, s) : s; + return `'${stored.replace(/'/g, "''")}'`; +} + +/** Whether a validator or field.enum opts out of its CHECK (`@dbCheck: false`; ADR-0039 resolving). + * `migrate.checks.skipRedundant` is independent of it: it only ever leaves more out. */ +function checkOptedOut(node: MetaData): boolean { + return node.attr(VALIDATOR_ATTR_DB_CHECK) === false; } /** A validator's or field.enum's declared CHECK name (`@constraintName`; ADR-0039 resolving), if any. */ @@ -1124,9 +1291,21 @@ function checkDeclaredCheckNames(tables: readonly TableDescriptor[], dialect: Di */ function withCondition( check: CheckDescriptor, v: MetaValidator, entity: MetaObject, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, + guard?: ExprNode, +): CheckDescriptor { + const declared = v.attr(VALIDATOR_ATTR_CONDITION); + const own = declared === undefined || declared === null || typeof declared !== "object" ? undefined : (declared as ExprNode); + // A TPH subtype's validator holds only where its discriminator guard does (buildChecks). + const condition: ExprNode | undefined = guard === undefined + ? own + : own === undefined ? guard : ({ op: "and", args: [guard, own] } as unknown as ExprNode); + return condition === undefined ? check : wrapCondition(check, condition, entity, strategy, dialect); +} + +/** The CHECK holds only where `condition` does: the negated condition OR the rule. */ +function wrapCondition( + check: CheckDescriptor, condition: ExprNode, entity: MetaObject, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, ): CheckDescriptor { - const condition = v.attr(VALIDATOR_ATTR_CONDITION); - if (condition === undefined || condition === null || typeof condition !== "object") return check; const column = (name: string): string | undefined => { const field = entity.fields().find((f) => f.name === name); return field === undefined ? undefined : quoteCheckCol(resolveColumnName(field, strategy)); @@ -1138,9 +1317,14 @@ function withCondition( if (field?.subType === FIELD_SUBTYPE_DURATION) return durationLiteralSql(field, value, dialect, "@condition"); const intMap = field === undefined ? undefined : intValueMapOf(field); const n = intMap === undefined || typeof value !== "string" ? undefined : intMap[value]; - return typeof n === "number" ? String(n) : undefined; + if (typeof n === "number") return String(n); + // rc.21: a member compared with a @stringValueMap enum is its stored string. + if (field !== undefined && typeof value === "string" && stringValueMapOf(field) !== undefined) { + return `'${storedEnumValue(field, value).replace(/'/g, "''")}'`; + } + return undefined; }; - const unless = renderExpressionSql(negateExpression(condition as ExprNode), column, dialect, stored); + const unless = renderExpressionSql(negateExpression(condition), column, dialect, stored); return { ...check, expression: `(${unless}) OR (${check.expression})` }; } @@ -1194,6 +1378,20 @@ function crossFieldCheck( const refs = names.map((n) => resolveRef(entity, n, strategy)); if (refs.length === 0 || refs.some((r) => r === null)) return null; const firstCol = resolveColumnName(refs[0]!.field, strategy); + // @max bounds how many may be present (@max 1: exactly one). Postgres counts them with + // num_nonnulls; SQLite adds the presence tests, which it evaluates as 0 / 1. + const max = v.attr(VALIDATOR_ATTR_MAX); + if (typeof max === "number") { + const count = dialect === "sqlite" || dialect === "d1" + ? `(${refs.map((r) => `(${r!.qcol} IS NOT NULL)`).join(" + ")})` + : `num_nonnulls(${refs.map((r) => r!.qcol).join(", ")})`; + return { + name: `${tableName}_${firstCol}_atleastone_chk`, + // Two comparisons, not BETWEEN: Postgres stores a BETWEEN as these two comparisons, and + // writing it the way Postgres reads it back keeps the CHECK free of drift. + expression: max === 1 ? `${count} = 1` : `${count} >= 1 AND ${count} <= ${max}`, + }; + } return { name: `${tableName}_${firstCol}_atleastone_chk`, expression: refs.map((r) => `${r!.qcol} IS NOT NULL`).join(" OR "), @@ -1574,6 +1772,9 @@ function buildColumn( ); } col.default = { kind: "literal", value: String(mapped) }; + } else if (field.subType === FIELD_SUBTYPE_ENUM && stringValueMapOf(field) !== undefined) { + // rc.21: a string-stored enum's @default names a member; the column holds its stored string. + col.default = { kind: "literal", value: storedEnumValue(field, defaultRaw) }; } else { // #235: an EMPTY-string default (`@default: ""`) is a real literal default — // codegen emits `.default("")` and the DB gets `DEFAULT ''`, so dropping it here @@ -1681,6 +1882,11 @@ function subtypeToSqlType(field: MetaData): SqlType { case DB_COLUMN_TYPE_UUID: return { kind: "uuid" }; case DB_COLUMN_TYPE_JSONB: return { kind: "json" }; } + // rc.21 part B (U2): the text spellings. A sized one is the declared length. + const parsed = parseDbColumnType(dbColumnType); + if (parsed?.kind === "text") return { kind: "text" }; + if (parsed?.kind === "varchar") return parsed.length !== undefined ? { kind: "text", maxLength: parsed.length } : { kind: "text", variant: "varchar" }; + if (parsed?.kind === "char") return { kind: "text", maxLength: parsed.length, variant: "char" }; } // Native array columns are DERIVED from `isArray` (dbColumnType slim-and-derive diff --git a/server/typescript/packages/migrate-ts/src/expected.ts b/server/typescript/packages/migrate-ts/src/expected.ts index 6afe6d055a..e33aeeb21c 100644 --- a/server/typescript/packages/migrate-ts/src/expected.ts +++ b/server/typescript/packages/migrate-ts/src/expected.ts @@ -6,7 +6,7 @@ // not need kysely installed. Its import graph is the model walk and nothing that opens a // connection; keep it that way. -export { buildExpectedSchema, buildExpectedSchemaWithProvenance, fieldSqlType, foreignKeyIndexName, uncoveredForeignKeyColumns } from "./expected-schema.js"; +export { buildExpectedSchema, buildExpectedSchemaWithProvenance, fieldSqlType, fitPgIdentifier, foreignKeyIndexName, uncoveredForeignKeyColumns } from "./expected-schema.js"; export { pgType } from "./emit/postgres.js"; export type { BuildExpectedSchemaOptions, SchemaBuildSettings, ExpectedSchemaWithProvenance, SchemaProvenance } from "./expected-schema.js"; export { qualifiedDbName } from "./qualified-name.js"; diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 7971148795..d3e2f6ef22 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -16,6 +16,8 @@ export { } from "./referential-actions.js"; export type { ExpectedSchemaWithProvenance, SchemaProvenance, SchemaBuildSettings } from "./expected-schema.js"; export { introspect, introspectPostgres, introspectSqlite } from "./introspect/index.js"; +// rc.21 part B (N2): each declared origin.function, checked against pg_proc by `meta verify --db`. +export { checkDeclaredFunctions, DECLARED_FUNCTION_CHECK_LIMITS } from "./introspect/declared-functions.js"; export { diff } from "./diff/index.js"; export { defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, diff --git a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts new file mode 100644 index 0000000000..41b3657ae0 --- /dev/null +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -0,0 +1,169 @@ +// rc.21 part B fix round 2 (N2): `origin.function` declares its signature (`@params`, `@returns`) +// and the view casts the call to the carrying field's column type. The declaration is trusted at +// load and codegen, so a wrong one would be hidden by that cast (a `numeric` result declared `int` +// rounds). `meta verify --db` reads each declared function from `pg_proc` and refuses any whose +// parameter or return types are not the declared ones. +// +// What it does not check (fix round 3, M2): a parameter or result whose column kind has no plain +// Postgres type name here — json/jsonb, arrays, an enum, a user-defined type — matches any type at +// that position (only the arity is checked there). A domain is not seen through: `format_type` +// names the domain, so a domain-typed parameter or result is reported as a mismatch. + +import type { Kysely } from "kysely"; +import { sql } from "kysely"; +import { + isMetaObject, + TYPE_OBJECT, + TYPE_ORIGIN, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, + type MetaData, +} from "@metaobjectsdev/metadata"; +import { fieldSqlType } from "../expected-schema.js"; +import type { SqlType } from "../sql-type.js"; + +/** One declared function call, with the database type names each position accepts. */ +interface DeclaredFunction { + readonly where: string; + readonly schema: string; + readonly name: string; + readonly declared: string; + readonly params: readonly (readonly string[])[]; + readonly returns: readonly string[]; +} + +/** One overload as `pg_proc` has it, its types spelled by `format_type(oid, NULL)`. */ +interface PgFunction { + readonly args: readonly string[]; + /** How many trailing parameters have a default (`pronargdefaults`): a call may omit them. */ + readonly defaults: number; + readonly returns: string; + readonly retset: boolean; +} + +const TEXT_TYPES = ["text", "character varying", "character"] as const; + +/** The `format_type` names (no modifier) a column of this type has. Empty: not checkable. */ +function pgTypeNames(t: SqlType): readonly string[] { + switch (t.kind) { + case "text": return TEXT_TYPES; + case "integer": return [t.bits === 64 ? "bigint" : "integer"]; + case "real": return ["double precision"]; + case "real4": return ["real"]; + case "numeric": return ["numeric"]; + case "boolean": return ["boolean"]; + case "date": return ["date"]; + case "uuid": return ["uuid"]; + case "timestamp": return [t.withTimezone ? "timestamp with time zone" : "timestamp without time zone"]; + default: return []; + } +} + +/** A declared parameter subtype's names, when the argument's field cannot be read. */ +function subtypeTypeNames(subType: string): readonly string[] { + switch (subType) { + case "string": return TEXT_TYPES; + case "int": return ["integer"]; + case "long": return ["bigint"]; + case "double": return ["double precision"]; + case "float": return ["real"]; + case "decimal": return ["numeric"]; + case "boolean": return ["boolean"]; + case "date": return ["date"]; + case "uuid": return ["uuid"]; + case "timestamp": return ["timestamp with time zone", "timestamp without time zone"]; + default: return []; + } +} + +function asList(raw: unknown): string[] { + if (raw === undefined) return []; + return (Array.isArray(raw) ? raw : [raw]).filter((v): v is string => typeof v === "string"); +} + +/** Every `origin.function` the model declares, once each. */ +export function declaredFunctions(root: MetaData): DeclaredFunction[] { + const out: DeclaredFunction[] = []; + const seen = new Set(); + // ADR-0039: effective children — resolve rather than rely on root being unextended. + for (const obj of root.children()) { + if (obj.type !== TYPE_OBJECT || !isMetaObject(obj)) continue; + for (const field of obj.fields()) { + // ADR-0039: own — origin.* never inherits (ADR-0029); an inherited field is visited + // through the object that declares it, and `seen` keeps each origin once. + for (const origin of field.ownChildren()) { + if (origin.type !== TYPE_ORIGIN || origin.subType !== ORIGIN_SUBTYPE_FUNCTION || seen.has(origin)) continue; + seen.add(origin); + const name = origin.ownAttr(ORIGIN_FUNCTION_ATTR_FUNCTION); + if (typeof name !== "string") continue; + const schemaAttr = origin.ownAttr(ORIGIN_FUNCTION_ATTR_SCHEMA); + const schema = typeof schemaAttr === "string" ? schemaAttr : "public"; + const args = asList(origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS)); + const params = asList(origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS)); + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + const fields = obj.fields(); + out.push({ + where: `${obj.name}.${field.name}`, + schema, + name, + declared: `(${params.join(", ")}) → ${String(returns)}`, + params: params.map((p, i) => { + // The argument's own column type when it is a field of this object (a local or a + // zoned timestamp, say); the declared subtype's otherwise. + const argField = fields.find((f) => f.name === args[i]); + const names = argField !== undefined && argField.subType === p ? pgTypeNames(fieldSqlType(argField)) : []; + return names.length > 0 ? names : subtypeTypeNames(p); + }), + returns: pgTypeNames(fieldSqlType(field)), + }); + } + } + } + return out; +} + +async function overloads(db: Kysely, schema: string, name: string): Promise { + const result = await sql<{ args: string[]; defaults: number; returns: string; retset: boolean }>` + SELECT ARRAY(SELECT format_type(a.t, NULL) FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS a(t, i) ORDER BY a.i) AS args, + p.pronargdefaults::int AS defaults, format_type(p.prorettype, NULL) AS returns, p.proretset AS retset + FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = ${schema} AND p.proname = ${name} AND p.prokind = 'f'`.execute(db); + return result.rows.map((r) => ({ args: r.args, defaults: Number(r.defaults), returns: r.returns, retset: r.retset })); +} + +function matches(declared: DeclaredFunction, fn: PgFunction): boolean { + // 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]!)); +} + +/** + * The findings for every declared `origin.function` the Postgres database does not have with + * the declared parameter and return types: one line each, empty when all match. + */ +/** Printed under any finding: what the comparison does not see (fix round 3, M2). */ +export const DECLARED_FUNCTION_CHECK_LIMITS = + "origin.function signatures are compared by plain type name: a json, array, enum or user-defined " + + "kind is not type-checked (only the arity is), and a domain is compared by its own name, not its base type."; + +export async function checkDeclaredFunctions(db: Kysely, root: MetaData): Promise { + const findings: string[] = []; + for (const declared of declaredFunctions(root)) { + const found = await overloads(db, declared.schema, declared.name); + if (found.some((fn) => matches(declared, fn))) continue; + const qualified = `${declared.schema}.${declared.name}`; + const expected = `(${declared.params.map((p) => p.join(" | ") || "any").join(", ")}) → ${declared.returns.join(" | ") || "any"}`; + findings.push(found.length === 0 + ? `origin.function ${qualified} on ${declared.where}: no such function in the database (declared ${declared.declared}).` + : `origin.function ${qualified} on ${declared.where}: declared ${declared.declared}, which needs ${qualified}${expected}; ` + + `the database has ${found.map((fn) => `${qualified}(${fn.args.join(", ")}) → ${fn.retset ? "SETOF " : ""}${fn.returns}`).join("; ")}.`); + } + return findings; +} diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index dcc050c280..b8fe9f2292 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -124,7 +124,13 @@ export function pgTypeToSqlType( return { kind: "text", maxLength: parseInt(varcharMatch[1] ?? "0", 10) }; } if (dt === "character varying" || dt === "varchar") { - return maxLength != null ? { kind: "text", maxLength } : { kind: "text" }; + return maxLength != null ? { kind: "text", maxLength } : { kind: "text", variant: "varchar" }; + } + // rc.21 part B (U2): the fixed-length character(n) (information_schema "character", udt bpchar). + const charMatch = /^(?:character|char|bpchar)\((\d+)\)$/.exec(dt); + if (charMatch) return { kind: "text", maxLength: parseInt(charMatch[1] ?? "1", 10), variant: "char" }; + if (dt === "character" || dt === "char" || dt === "bpchar") { + return { kind: "text", maxLength: maxLength ?? 1, variant: "char" }; } if (dt === "text") { return { kind: "text" }; diff --git a/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts b/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts index fc94ddffd4..d25ee8f8d5 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts @@ -63,8 +63,12 @@ export function sqliteTypeToSqlType(declaredType: string): SqlType { // Affinity rules per sqlite.org/datatype3.html — adapted to canonical SqlType. // text affinity - const varcharMatch = /^(?:VARCHAR|CHAR|CHARACTER|TEXT)\((\d+)\)$/.exec(t); + // rc.21 part B (U2): CHARACTER(n) is what the emitter writes for a fixed-length @dbColumnType. + const charMatch = /^CHARACTER\((\d+)\)$/.exec(t); + if (charMatch) return { kind: "text", maxLength: parseInt(charMatch[1] ?? "1", 10), variant: "char" }; + const varcharMatch = /^(?:VARCHAR|CHAR|TEXT)\((\d+)\)$/.exec(t); if (varcharMatch) return { kind: "text", maxLength: parseInt(varcharMatch[1] ?? "0", 10) }; + if (t === "VARCHAR") return { kind: "text", variant: "varchar" }; if (/TEXT|CLOB|VARCHAR|CHAR/.test(t)) return { kind: "text" }; // numeric affinity diff --git a/server/typescript/packages/migrate-ts/src/schema-conventions.ts b/server/typescript/packages/migrate-ts/src/schema-conventions.ts index 3972191234..75678ff879 100644 --- a/server/typescript/packages/migrate-ts/src/schema-conventions.ts +++ b/server/typescript/packages/migrate-ts/src/schema-conventions.ts @@ -130,6 +130,9 @@ export function resolveSchemaConventions(selected: string | SchemaConventions | const missing = members.filter((m) => typeof (selected as unknown as Record)[m] !== "function"); const id = String((selected as { id?: unknown }).id ?? "(no id)"); if (missing.length > 0) throw new InvalidSchemaConventionsError(id, missing); + // Moved to `migrate.checks.skipRedundant`: a conventions object still setting it would + // otherwise be silently ignored and bring every redundant CHECK back as drift. + if ("skipRedundantChecks" in (selected as object)) throw new InvalidSchemaConventionsError(id, [], ["skipRedundantChecks"]); return selected; } const preset = PRESETS[selected]; diff --git a/server/typescript/packages/migrate-ts/src/sql-type.ts b/server/typescript/packages/migrate-ts/src/sql-type.ts index 82ec80c76f..d2f36308dd 100644 --- a/server/typescript/packages/migrate-ts/src/sql-type.ts +++ b/server/typescript/packages/migrate-ts/src/sql-type.ts @@ -6,7 +6,10 @@ * Per spec §5.2. */ export type SqlType = - | { kind: "text"; maxLength?: number } + // rc.21 part B (U2): `variant` is the @dbColumnType spelling — "varchar" an unbounded + // `character varying` (Postgres treats it as text; the diff does not tell them apart), "char" a + // fixed-length `character(n)` (blank-padded, a different type). + | { kind: "text"; maxLength?: number; variant?: "varchar" | "char" } | { kind: "integer"; bits: 32 | 64 } | { kind: "real" } // DOUBLE PRECISION (float8) — field.double | { kind: "real4" } // REAL (float4, single precision) — field.float @@ -29,7 +32,10 @@ export type SqlType = */ export function describeSqlType(t: SqlType): string { switch (t.kind) { - case "text": return t.maxLength === undefined ? "text" : `text(${t.maxLength})`; + case "text": + if (t.variant === "char") return `character(${t.maxLength ?? 1})`; + if (t.variant === "varchar" && t.maxLength === undefined) return "varchar"; + return t.maxLength === undefined ? "text" : `text(${t.maxLength})`; case "integer": return t.bits === 64 ? "bigint" : "integer"; case "numeric": return t.precision === undefined ? "numeric" @@ -44,8 +50,12 @@ export function describeSqlType(t: SqlType): string { export function sqlTypeEquals(a: SqlType, b: SqlType): boolean { if (a.kind !== b.kind) return false; switch (a.kind) { - case "text": - return a.maxLength === (b as Extract).maxLength; + case "text": { + // An unbounded varchar and text are one type to Postgres (and to SQLite), so they compare + // equal; a fixed-length character(n) is a different one. + const bt = b as Extract; + return a.maxLength === bt.maxLength && (a.variant === "char") === (bt.variant === "char"); + } case "integer": return a.bits === (b as Extract).bits; case "numeric": { @@ -85,6 +95,8 @@ export function isWidening(from: SqlType, to: SqlType): boolean { switch (from.kind) { case "text": { const t = to as Extract; + // To or from a blank-padded character(n) is never a plain widening. + if ((from.variant === "char") !== (t.variant === "char")) return false; // unbounded → bounded: lossy if (from.maxLength === undefined) return false; // bounded → unbounded: widening diff --git a/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts new file mode 100644 index 0000000000..e78f10dcf5 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts @@ -0,0 +1,109 @@ +// rc.21 fix round (I2): two different CHECKs under one default name are refused at build, naming +// both, instead of a CREATE TABLE the database refuses ("constraint already exists"). +// rc.21 part B (N1): only where the database requires unique names. SQLite and D1 accept and +// enforce two CHECKs under one name, so they keep both, and the CHECK diff converges on them. +// rc.21 part B (N2): a qualified default name is fitted to Postgres's 63-byte identifier limit. + +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Kysely, sql } from "kysely"; +import { LibsqlDialect } from "@libsql/kysely-libsql"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema, fitPgIdentifier } from "../src/expected-schema.js"; +import { diff } from "../src/diff/index.js"; +import { emit } from "../src/emit/index.js"; +import { introspect } from "../src/introspect/index.js"; + +const WINDOW = JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Window", children: [ + { "source.rdb": { "@table": "windows" } }, + { "field.long": { name: "id" } }, + { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } }); + +async function load(json: string) { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(errors).toEqual([]); + return root; +} + +test("two CHECKs under one default name are refused on Postgres", async () => { + const root = await load(WINDOW); + expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/both named 'windows_a_cmp_chk'.*Postgres requires/); +}); + +test("SQLite and D1 keep both CHECKs under the one name", async () => { + const root = await load(WINDOW); + for (const dialect of ["sqlite", "d1"] as const) { + const windows = buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === "windows")!; + expect(windows.checks.filter((c) => c.name === "windows_a_cmp_chk").map((c) => c.expression)) + .toEqual(['"a" < "b"', '"a" < "c"']); + } +}); + +test("SQLite: a table holding both same-named CHECKs migrates once and then shows no change", async () => { + const root = await load(WINDOW); + const dir = mkdtempSync(join(tmpdir(), "migrate-ts-dup-check-")); + const k = new Kysely>({ dialect: new LibsqlDialect({ url: `file:${join(dir, "t.db")}` }) }); + try { + const expected = buildExpectedSchema(root, { dialect: "sqlite" }); + const { up } = emit((await diff(expected, await introspect(k, "sqlite"), { dialect: "sqlite" })).changes, { dialect: "sqlite", expectedSchema: expected }); + for (const stmt of up.split(";").map((s) => s.trim()).filter((s) => s.length > 0)) await sql.raw(stmt).execute(k); + // Both rules hold. + await sql.raw("INSERT INTO windows (id, a, b, c) VALUES (1, 1, 2, 3)").execute(k); + await expect(sql.raw("INSERT INTO windows (id, a, b, c) VALUES (2, 1, 9, 0)").execute(k)).rejects.toThrow(/CHECK/); + await expect(sql.raw("INSERT INTO windows (id, a, b, c) VALUES (3, 1, 0, 9)").execute(k)).rejects.toThrow(/CHECK/); + const again = await diff(expected, await introspect(k, "sqlite"), { dialect: "sqlite" }); + expect(again.changes.filter((c) => c.kind === "add-check" || c.kind === "drop-check")).toEqual([]); + } finally { + await k.destroy(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("fitPgIdentifier keeps a name that fits and shortens a longer one to 63 bytes, deterministically", () => { + expect(fitPgIdentifier("devices_meter_serial_chk")).toBe("devices_meter_serial_chk"); + const long = `${"x".repeat(40)}_${"y".repeat(30)}_chk`; + const fitted = fitPgIdentifier(long); + expect(Buffer.byteLength(fitted)).toBe(63); + expect(fitted.startsWith("x".repeat(40) + "_" + "y".repeat(13))).toBe(true); + expect(fitted).toMatch(/_[0-9a-f]{8}$/); + expect(fitPgIdentifier(long)).toBe(fitted); + // Two long names sharing their first 54 bytes stay apart. + expect(fitPgIdentifier(long.replace("_chk", "_cmp"))).not.toBe(fitted); + // Whole characters only: a multi-byte character is never split. + const wide = "é".repeat(40); + expect(Buffer.byteLength(fitPgIdentifier(wide))).toBeLessThanOrEqual(63); + // The spelling every port pins (C#: CheckConstraintConformanceTests). + expect(fitPgIdentifier("measurement_devices_with_a_rather_long_table_name_meterdevicekind_serial_chk")) + .toBe("measurement_devices_with_a_rather_long_table_name_mete_559a7830"); + expect(fitPgIdentifier(wide)).toBe(`${"é".repeat(27)}_84fe2e03`); +}); + +test("a qualified TPH CHECK name over 63 bytes is fitted on Postgres and kept on SQLite", async () => { + const table = "measurement_devices_with_a_rather_long_table_name"; + const root = await load(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Device", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": table } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 20 } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "MeterDeviceKind", extends: "Device", "@discriminatorValue": "METER", children: [ + { "field.enum": { name: "serial", "@values": ["M1", "M2"] } } ] } }, + { "object.entity": { name: "SensorDeviceKind", extends: "Device", "@discriminatorValue": "SENSOR", children: [ + { "field.enum": { name: "serial", "@values": ["S1", "S2"] } } ] } }, + ] } })); + const names = (dialect: "postgres" | "sqlite") => + buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === table)!.checks + .filter((c) => c.expression.includes('"serial"')).map((c) => c.name); + const pg = names("postgres"); + expect(pg.length).toBe(2); + for (const n of pg) expect(Buffer.byteLength(n)).toBe(63); + expect(pg).toEqual([`${table}_meterdevicekind_serial_chk`, `${table}_sensordevicekind_serial_chk`].map(fitPgIdentifier)); + expect(new Set(pg).size).toBe(2); + expect(names("sqlite")).toEqual([`${table}_meterdevicekind_serial_chk`, `${table}_sensordevicekind_serial_chk`]); +}); diff --git a/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts b/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts new file mode 100644 index 0000000000..98a5f1ffc9 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts @@ -0,0 +1,37 @@ +// rc.21 part B (U2): the text @dbColumnType spellings are the column types `meta migrate` creates; +// an unbounded varchar and text compare as one type, a character(n) as its own. + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; +import { pgType } from "../src/emit/postgres.js"; +import { sqliteType } from "../src/emit/sqlite.js"; +import { sqlTypeEquals, isWidening } from "../src/sql-type.js"; +import { pgTypeToSqlType } from "../src/introspect/postgres.js"; +import { sqliteTypeToSqlType } from "../src/introspect/sqlite-shared.js"; + +test("each spelling is its column type on Postgres and SQLite", async () => { + const spellings = ["text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)"]; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + ...spellings.map((t, i) => ({ "field.string": { name: `c${i}`, "@dbColumnType": t } })), + { "identity.primary": { name: "id", "@fields": "id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + const cols = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!.columns.filter((c) => c.name !== "id"); + expect(cols.map((c) => pgType(c.sqlType))).toEqual(["TEXT", "VARCHAR", "VARCHAR", "VARCHAR(12)", "VARCHAR(12)", "CHARACTER(3)"]); + expect(cols.map((c) => sqliteType(c.sqlType, undefined))).toEqual(["TEXT", "VARCHAR", "VARCHAR", "VARCHAR(12)", "VARCHAR(12)", "CHARACTER(3)"]); +}); + +test("introspection reads them back to the same types", () => { + expect(sqlTypeEquals(pgTypeToSqlType("character varying", null), { kind: "text", variant: "varchar" })).toBe(true); + expect(pgTypeToSqlType("character", 3)).toEqual({ kind: "text", maxLength: 3, variant: "char" }); + expect(sqliteTypeToSqlType("CHARACTER(3)")).toEqual({ kind: "text", maxLength: 3, variant: "char" }); + expect(sqliteTypeToSqlType("VARCHAR")).toEqual({ kind: "text", variant: "varchar" }); +}); + +test("an unbounded varchar equals text; character(n) equals neither, and is no widening", () => { + expect(sqlTypeEquals({ kind: "text" }, { kind: "text", variant: "varchar" })).toBe(true); + expect(sqlTypeEquals({ kind: "text", maxLength: 3 }, { kind: "text", maxLength: 3, variant: "char" })).toBe(false); + expect(isWidening({ kind: "text", maxLength: 3, variant: "char" }, { kind: "text" })).toBe(false); +}); diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts index 9324b15aca..2522d471fe 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts @@ -99,8 +99,8 @@ describe("buildExpectedSchema — field.object @storage", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.rdb": { "@table": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.rdb": { "@table": "players" } }, { "field.long": { name: "id" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -109,8 +109,8 @@ describe("buildExpectedSchema — field.object @storage", () => { }, }); const snap = buildExpectedSchema(root, { dialect: "postgres" }); - const patients = snap.tables.find((t) => t.name === "patients")!; - const contactInfos = patients.columns.find((c) => c.name === "contact_infos"); + const players = snap.tables.find((t) => t.name === "players")!; + const contactInfos = players.columns.find((c) => c.name === "contact_infos"); expect(contactInfos?.sqlType.kind).toBe("json"); }); diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts index 617307d718..db2f98ac14 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts @@ -30,11 +30,11 @@ function model(clientIdField: Record): string { }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "field.uuid": { "name": "id" } }, { "field.uuid": { "name": "clientId", "@column": "ClientId" } }, - { "source.rdb": { "name": "src", "@table": "Patients" } }, + { "source.rdb": { "name": "src", "@table": "Players" } }, { "identity.primary": { "name": "pk", "@fields": ["id"] } }, { "identity.reference": { @@ -51,9 +51,9 @@ function model(clientIdField: Record): string { }); } -function patientFk(root: MetaData) { +function playerFk(root: MetaData) { const snapshot = buildExpectedSchema(root, { dialect: "postgres" }); - const table = snapshot.tables.find((t) => t.name === "Patients"); + const table = snapshot.tables.find((t) => t.name === "Players"); expect(table).toBeDefined(); expect(table!.foreignKeys).toHaveLength(1); return table!.foreignKeys[0]!; @@ -62,7 +62,7 @@ function patientFk(root: MetaData) { describe("buildExpectedSchema — FK refColumns resolve the target PK's @column override", () => { test("target PK field with @column override → refColumns uses the physical name", async () => { const root = await loadJson(model({ "name": "id", "@column": "Id" })); - const fk = patientFk(root); + const fk = playerFk(root); expect(fk.columns).toEqual(["ClientId"]); expect(fk.refTable).toBe("Clients"); expect(fk.refColumns).toEqual(["Id"]); @@ -70,7 +70,7 @@ describe("buildExpectedSchema — FK refColumns resolve the target PK's @column test("target PK field without @column override → refColumns keeps the field name", async () => { const root = await loadJson(model({ "name": "id" })); - const fk = patientFk(root); + const fk = playerFk(root); expect(fk.refColumns).toEqual(["id"]); }); }); diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts index 7d30ae8565..27486f3613 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts @@ -20,17 +20,17 @@ async function loadTph() { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ]}}, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.int": { name: "quantity", "@required": true } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ]}}, - { "object.entity": { name: "PriorAuthAuth", extends: "Auth", "@discriminatorValue": "PriorAuth", children: [ + { "object.entity": { name: "PermitAuth", extends: "Auth", "@discriminatorValue": "Permit", children: [ { "field.string": { name: "approver", "@maxLength": 80 } }, ]}}, ], @@ -48,8 +48,8 @@ describe("buildExpectedSchema — TPH single table", () => { const names = snap.tables.map((t) => t.name).sort(); expect(names).toContain("auths"); expect(names).not.toContain("bridge_auths"); - expect(names).not.toContain("copay_auths"); - expect(names).not.toContain("prior_auth_auths"); + expect(names).not.toContain("coupon_auths"); + expect(names).not.toContain("permit_auths"); // exactly one table expect(snap.tables.length).toBe(1); }); @@ -58,7 +58,7 @@ describe("buildExpectedSchema — TPH single table", () => { const snap = buildExpectedSchema(await loadTph(), { dialect: "postgres" }); const auths = snap.tables.find((t) => t.name === "auths")!; const cols = auths.columns.map((c) => c.name).sort(); - expect(cols).toEqual(["approver", "copay_amount", "id", "quantity", "reference", "type"]); + expect(cols).toEqual(["approver", "coupon_amount", "id", "quantity", "reference", "type"]); }); test("subtype-only columns are NULLABLE even when the field is @required", async () => { @@ -67,8 +67,8 @@ describe("buildExpectedSchema — TPH single table", () => { const quantity = auths.columns.find((c) => c.name === "quantity")!; // quantity is @required on BridgeAuth, but must be nullable in the single table. expect(quantity.nullable).toBe(true); - const copay = auths.columns.find((c) => c.name === "copay_amount")!; - expect(copay.nullable).toBe(true); + const coupon = auths.columns.find((c) => c.name === "coupon_amount")!; + expect(coupon.nullable).toBe(true); }); // A TPH subtype-only column must carry NO DB default, for the same reason it is diff --git a/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts b/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts index 7f31fe22f5..52611d9994 100644 --- a/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts @@ -333,8 +333,9 @@ describe("pgTypeToSqlType normalization", () => { expect(pgTypeToSqlType("varchar(120)")).toEqual({ kind: "text", maxLength: 120 }); }); - test("character varying (unbounded) → text", () => { - expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text" }); + // rc.21 part B (U2): unbounded varchar keeps its spelling, and compares equal to text. + test("character varying (unbounded) → text, spelled varchar", () => { + expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text", variant: "varchar" }); }); test("text → text", () => { diff --git a/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts b/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts index 838e301024..5dd9f6aa3b 100644 --- a/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts @@ -40,7 +40,7 @@ const AFTER: Shape = { kindColumn: "kind", microchip: true, nameRequired: false function model(s: Shape): string { return JSON.stringify({ "metadata.root": { - package: "clinic", + package: "depot", children: [ { "object.entity": { diff --git a/server/typescript/packages/migrate-ts/test/string-value-map.test.ts b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts new file mode 100644 index 0000000000..6ac1d9ef8c --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts @@ -0,0 +1,34 @@ +// rc.21 — a string-stored field.enum whose database spelling differs from its members +// (@stringValueMap): the column default, length and CHECK hold the stored strings. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Article", children: [ + { "source.rdb": { "@table": "articles" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Draft", "Published"], "@default": "Draft", + "@stringValueMap": { Draft: "draft", Published: "published" } } }, + { "field.enum": { name: "channel", "@values": ["Email", "TextMessage"], "@maxLength": 16, + "@stringValueMap": { Email: "EMAIL_V1", TextMessage: "SMS_LEGACY" } } }, + { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } } ] } } ] } }; + +describe("@stringValueMap in the expected schema", () => { + test("the default, the length and the CHECK hold the stored strings", async () => { + const { root, errors } = await new MetaDataLoader({ strict: true }).load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const table = buildExpectedSchema(root, { dialect: "postgres" }).tables.find((t) => t.name === "articles")!; + const status = table.columns.find((c) => c.name === "status")!; + expect(status.default).toEqual({ kind: "literal", value: "draft" }); + expect(table.checks.map((c) => c.expression)).toContain(`"channel" IN ('EMAIL_V1', 'SMS_LEGACY')`); + }); + + test("a stored string longer than @maxLength is refused at load", async () => { + const m = JSON.parse(JSON.stringify(MODEL)); + m["metadata.root"].children[0]["object.entity"].children[3]["field.enum"]["@maxLength"] = 9; + const { errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(m))]); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`shorter than its stored value "SMS_LEGACY"`); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts b/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts index 324be0a7f7..e72ddf8446 100644 --- a/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts @@ -24,8 +24,8 @@ describe("pgTypeToSqlType", () => { expect(pgTypeToSqlType("varchar(64)")).toEqual({ kind: "text", maxLength: 64 }); // bare varchar + separate maxLength column expect(pgTypeToSqlType("character varying", 100)).toEqual({ kind: "text", maxLength: 100 }); - // bare varchar with no length info → plain text - expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text" }); + // bare varchar with no length info → text, spelled varchar (rc.21 U2; it equals text in the diff) + expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text", variant: "varchar" }); expect(pgTypeToSqlType("text")).toEqual({ kind: "text" }); }); diff --git a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts index 5980574104..8883113101 100644 --- a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts @@ -106,4 +106,9 @@ describe("resolveSchemaConventions", () => { expect(() => resolveSchemaConventions(partial)) .toThrow(/schema conventions "acme" are missing foreignKeyName, foreignKeyIndexes, uniqueKeyKind/); }); + + test("a conventions object that still sets skipRedundantChecks is refused, pointing at migrate.checks", () => { + expect(() => resolveSchemaConventions({ ...efcoreConventions, id: "acme", skipRedundantChecks: true } as never)) + .toThrow(/skipRedundantChecks, which is no longer a convention .*"skipRedundant": true/); + }); }); diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts index 14cc548338..9eb84fd2a9 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts @@ -349,7 +349,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index fb3c60a107..d05d6239de 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -5,7 +5,8 @@ import { IDENTITY_ATTR_FIELDS, OBJECT_SUBTYPE_REPORT, DEFAULT_COLUMN_NAMING_STRATEGY, - FIELD_SUBTYPE_DURATION, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_ENUM, + storedEnumValue, stringValueMapOf, resolveTableName, resolveTableSchema, resolveColumnName, durationToStoredMicros, formatPostgresInterval, parseDurationLiteral, } from "@metaobjectsdev/metadata"; @@ -192,6 +193,20 @@ function encodeFilterValue(field: MetaData, value: T, dialect?: Dialect): T { // nothing on a microsecond column and fail on an interval one. throw new MetadataError(`filter on field.duration '${field.name}' needs the driver's dialect to encode ${JSON.stringify(value)}`); } + // rc.21: a @stringValueMap enum is compared as the member's stored string. Unlike an + // @intValueMap symbol (which cannot equal an integer), an unmapped member passed through could + // equal ANOTHER member's stored string and match its rows, so it is refused, as a write is + // (rc.21 part B ruling N4, every port). + const storedMap = field.subType === FIELD_SUBTYPE_ENUM && typeof value === "string" ? stringValueMapOf(field) : undefined; + if (storedMap !== undefined) { + if (typeof storedMap[value as string] !== "string") { + throw new MetadataError( + `filter on field.enum '${field.name}': ${JSON.stringify(value)} has no stored string in @stringValueMap ` + + `(declared: ${JSON.stringify(storedMap)}) — the value is not one of the members the model declares.`, + ); + } + return storedEnumValue(field, value as string) as T; + } const intMap = intValueMapOf(field); if (intMap === undefined || typeof value !== "string") return value; const stored = intMap[value]; diff --git a/server/typescript/packages/runtime-ts/src/type-coercer.ts b/server/typescript/packages/runtime-ts/src/type-coercer.ts index b85552cc6d..634b72d576 100644 --- a/server/typescript/packages/runtime-ts/src/type-coercer.ts +++ b/server/typescript/packages/runtime-ts/src/type-coercer.ts @@ -38,6 +38,8 @@ import { STORAGE_JSONB, STORAGE_FLATTENED, DB_COLUMN_TYPE_JSONB, + storedEnumValue, + stringValueMapOf, } from "@metaobjectsdev/metadata"; import type { Dialect, Row } from "./persistence-driver.js"; import { decimalFits, decimalToWire, parseDecimalInput } from "./decimal-wire.js"; @@ -47,7 +49,7 @@ import { export function coerceRowOnRead(entity: MetaData, row: Row, dialect: Dialect): Row { const hydrated = parseJsonTextArrays(entity, deserializeJsonbObjectFields(entity, row)); - const decoded = canonicalizeDurations(entity, canonicalizeDecimals(entity, decodeIntBackedEnums(entity, hydrated))); + const decoded = canonicalizeDurations(entity, canonicalizeDecimals(entity, decodeStoredStringEnums(entity, decodeIntBackedEnums(entity, hydrated)))); if (dialect !== "sqlite" && dialect !== "mysql") return decoded; return mapBooleansFromInt(entity, decoded); } @@ -100,6 +102,57 @@ function encodeIntBackedEnum(intMap: Record, value: unknown): un * null would hide the corruption behind a nullable column. Every port throws * here — the generated Drizzle `customType`'s `fromDriver` included. */ +/** + * rc.21 — a string-stored enum with `@stringValueMap` holds each member's stored string; the row + * read back carries the MEMBER. A stored string with no member throws, for the reason an unmapped + * integer does (the database holds a value the model does not describe). Scalar only: the loader + * refuses the attribute on an array enum. + */ +function decodeStoredStringEnums(entity: MetaData, row: Row): Row { + let out: Row | null = null; + // ADR-0039: resolving — the enum may be inherited from a base via extends. + for (const child of entity.children()) { + if (child.type !== TYPE_FIELD || child.subType !== FIELD_SUBTYPE_ENUM) continue; + const map = stringValueMapOf(child); + if (map === undefined || !(child.name in row)) continue; + const raw = row[child.name]; + if (typeof raw !== "string") continue; + const member = Object.keys(map).find((k) => map[k] === raw); + if (member === undefined) { + throw new Error( + `field.enum '${child.name}' read stored value '${raw}' with no member in ` + + `@stringValueMap (declared: ${JSON.stringify(map)}) — the database holds a value the model does not describe.`, + ); + } + out ??= { ...row }; + out[child.name] = member; + } + return out ?? row; +} + +/** rc.21 — the write side of {@link decodeStoredStringEnums}: member → stored string. */ +function encodeStoredStringEnums(entity: MetaData, row: Row): Row { + let out: Row | null = null; + for (const child of entity.children()) { + if (child.type !== TYPE_FIELD || child.subType !== FIELD_SUBTYPE_ENUM) continue; + const map = stringValueMapOf(child); + if (map === undefined || !(child.name in row)) continue; + const raw = row[child.name]; + if (typeof raw !== "string") continue; + // An unmapped member THROWS (rc.21 ruling, every port): no CHECK need stand behind it + // (@dbCheck: false), and writing the symbol would store a spelling the column does not hold. + if (typeof map[raw] !== "string") { + throw new Error( + `field.enum '${child.name}' cannot write '${raw}': it has no stored string in ` + + `@stringValueMap (declared: ${JSON.stringify(map)}) — the value is not one of the members the model declares.`, + ); + } + out ??= { ...row }; + out[child.name] = storedEnumValue(child, raw); + } + return out ?? row; +} + function decodeIntBackedEnums(entity: MetaData, row: Row): Row { let out: Row | null = null; // ADR-0039: resolving — an int-backed enum may be inherited from a base via extends. @@ -204,7 +257,7 @@ export function coerceRowOnWrite(entity: MetaData, row: Row, dialect: Dialect): // Dialect-independent: an int-backed enum's column is INTEGER on every dialect // (SQLite has one integer storage class), so the symbol→int encode is not gated // on the dialect the way the boolean mapping below is. - const encoded = encodeIntBackedEnums(entity, jsonbColumned); + const encoded = encodeStoredStringEnums(entity, encodeIntBackedEnums(entity, jsonbColumned)); if (dialect === "mysql") return mapBooleansToInt(entity, isoTimestampsToDates(entity, encoded)); if (dialect !== "sqlite") return encoded; return mapBooleansToInt(entity, encoded); diff --git a/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts b/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts index 9fb851f980..96e0441b7b 100644 --- a/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts +++ b/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts @@ -25,11 +25,11 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, quantity INTEGER, - copay_amount TEXT + coupon_amount TEXT ); `); await client.execute( - `INSERT INTO auths (id, type, quantity, copay_amount) VALUES (1,'Bridge',5,NULL),(2,'Copay',NULL,'10.00');`, + `INSERT INTO auths (id, type, quantity, coupon_amount) VALUES (1,'Bridge',5,NULL),(2,'Coupon',NULL,'10.00');`, ); const db = drizzle(client); @@ -37,7 +37,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { id: integer("id").primaryKey({ autoIncrement: true }), type: text("type").notNull(), quantity: integer("quantity"), - copay_amount: text("copay_amount"), + coupon_amount: text("coupon_amount"), }); // Per-subtype schemas omit the discriminator (the route injects it). @@ -96,7 +96,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { // Own update, with a sneaky discriminator in the body — must be stripped. const own = await fastify.inject({ - method: "PATCH", url: "/auths/bridge/1", payload: { quantity: 9, type: "Copay" }, + method: "PATCH", url: "/auths/bridge/1", payload: { quantity: 9, type: "Coupon" }, }); expect(own.statusCode).toBe(200); const row = JSON.parse(own.body) as { type: string; quantity: number }; @@ -114,7 +114,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { // patch must never reach the driver. test("PATCH carrying ONLY the discriminator is a no-op 200, not a 500", async () => { const res = await fastify.inject({ - method: "PATCH", url: "/auths/bridge/1", payload: { type: "Copay" }, + method: "PATCH", url: "/auths/bridge/1", payload: { type: "Coupon" }, }); expect(res.statusCode).toBe(200); const row = JSON.parse(res.body) as { type: string; quantity: number }; diff --git a/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts b/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts index 24c0257d6a..7c2f520772 100644 --- a/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts +++ b/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts @@ -347,3 +347,24 @@ describe("ObjectManager reads a view-backed report (FR-044)", () => { expect(await om.count("Sale")).toBe(2); }); }); + +// rc.21 fix round (I3): a report dimension over a @stringValueMap enum reads and filters as its +// member — the row model carries the map from its type source, as it carries @intValueMap. +describe("a report dimension over a @stringValueMap enum", () => { + test("reads the member and filters by its stored string; an unknown stored value throws", async () => { + const model = JSON.parse(JSON.stringify(SALES).replace( + `"@intValueMap":{"OPEN":1,"CLOSED":2}`, `"@stringValueMap":{"OPEN":"open_v1","CLOSED":"closed_v1"}`)); + const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(result.errors.map((e) => e.message)).toEqual([]); + if (!isMetaRoot(result.root)) throw new Error("not a root"); + const driver = inMemoryDriver({ + seed: { v_sales_by_status: [{ status: "open_v1", sales: 4, revenue: 4000 }, { status: "closed_v1", sales: 6, revenue: 9000 }] }, + pkFields: { v_sales_by_status: ["status"] }, + }); + const om = new ObjectManager({ metadata: result.root, driver }); + expect(await om.findMany("SalesByStatus", { status: "OPEN" })).toEqual([{ status: "OPEN", sales: 4, revenue: 4000 }]); + const bad = new ObjectManager({ metadata: result.root, driver: inMemoryDriver({ + seed: { v_sales_by_status: [{ status: "lost", sales: 1, revenue: 1 }] }, pkFields: { v_sales_by_status: ["status"] } }) }); + await expect(bad.findMany("SalesByStatus")).rejects.toThrow(/no member in @stringValueMap/); + }); +}); diff --git a/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts b/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts index 012370aec7..a55ade50ee 100644 --- a/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts +++ b/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts @@ -30,7 +30,7 @@ const TPH_META = JSON.stringify({ children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -46,10 +46,10 @@ const TPH_META = JSON.stringify({ }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }], + "@discriminatorValue": "Coupon", + children: [{ "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }], }, }, ], @@ -70,8 +70,8 @@ beforeEach(async () => { const driver = inMemoryDriver({ seed: { auths: [ - { id: 1, type: "Bridge", reference: "REF-1", quantity: 5, copay_amount: null }, - { id: 2, type: "Copay", reference: "REF-2", quantity: null, copay_amount: "12.50" }, + { id: 1, type: "Bridge", reference: "REF-1", quantity: 5, coupon_amount: null }, + { id: 2, type: "Coupon", reference: "REF-2", quantity: null, coupon_amount: "12.50" }, ], }, pkFields: { auths: ["id"] }, @@ -91,13 +91,13 @@ describe("ObjectManager TPH — subtype field/identity/source resolution (effect test("base entity reads polymorphically (all rows, tagged by discriminator)", async () => { const rows = await om.findMany("Auth", undefined, { orderBy: [["id", "asc"]] }); - expect(rows.map((r) => r.type)).toEqual(["Bridge", "Copay"]); + expect(rows.map((r) => r.type)).toEqual(["Bridge", "Coupon"]); }); }); describe("ObjectManager TPH — discriminator scoping", () => { test("findById is scoped to the subtype — a different-subtype row is invisible (null)", async () => { - // id 2 is a Copay; addressing it through BridgeAuth must NOT return it. + // id 2 is a Coupon; addressing it through BridgeAuth must NOT return it. expect(await om.findById("BridgeAuth", 2)).toBeNull(); }); @@ -108,7 +108,7 @@ describe("ObjectManager TPH — discriminator scoping", () => { test("count on a subtype counts only that subtype's rows", async () => { expect(await om.count("BridgeAuth")).toBe(1); - expect(await om.count("CopayAuth")).toBe(1); + expect(await om.count("CouponAuth")).toBe(1); }); }); @@ -124,9 +124,9 @@ describe("ObjectManager TPH — create injects the discriminator", () => { test("a cross-subtype-only column is rejected (not a field of this subtype)", async () => { // Identity matters: create() has many other reachable throws (validation, // unsafe-name, identity resolution) — the rejection must be about THIS column. - const attempt = om.create("BridgeAuth", { reference: "X", quantity: 1, copayAmount: "1.00" }); + const attempt = om.create("BridgeAuth", { reference: "X", quantity: 1, couponAmount: "1.00" }); await expect(attempt).rejects.toThrow(MetadataError); - await expect(attempt).rejects.toThrow(/Unknown field 'copayAmount' on entity 'BridgeAuth'/); + await expect(attempt).rejects.toThrow(/Unknown field 'couponAmount' on entity 'BridgeAuth'/); }); }); @@ -139,7 +139,7 @@ describe("ObjectManager TPH — update/delete are subtype-scoped + discriminator }); test("update is scoped — patching a different subtype's row is not found", async () => { - // id 2 is a Copay; through BridgeAuth it's invisible → not found (default + // id 2 is a Coupon; through BridgeAuth it's invisible → not found (default // ifMissing="throw"), exactly like updating a non-existent id. await expect(om.update("BridgeAuth", 2, { quantity: 99 })).rejects.toThrow(NotFoundError); // With ifMissing="ignore" the scoped-out row resolves to null, not the row. @@ -147,18 +147,18 @@ describe("ObjectManager TPH — update/delete are subtype-scoped + discriminator }); test("update cannot change the discriminator (stripped from the patch)", async () => { - const updated = await om.update("BridgeAuth", 1, { type: "Copay", quantity: 7 } as Record); + const updated = await om.update("BridgeAuth", 1, { type: "Coupon", quantity: 7 } as Record); expect(updated).not.toBeNull(); expect(updated!.type).toBe("Bridge"); expect(updated!.quantity).toBe(7); }); test("delete is scoped — deleting a different subtype's row is not found", async () => { - // id 2 is a Copay; through BridgeAuth it's invisible → not found. + // id 2 is a Coupon; through BridgeAuth it's invisible → not found. await expect(om.delete("BridgeAuth", 2)).rejects.toThrow(NotFoundError); expect(await om.delete("BridgeAuth", 2, { ifMissing: "ignore" })).toBe(false); - // the Copay row is still there - expect(await om.findById("CopayAuth", 2)).not.toBeNull(); + // the Coupon row is still there + expect(await om.findById("CouponAuth", 2)).not.toBeNull(); }); test("delete removes the subtype's own row", async () => { diff --git a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts new file mode 100644 index 0000000000..9e9201549e --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts @@ -0,0 +1,51 @@ +// rc.21 — a string-stored field.enum with @stringValueMap: the ObjectManager writes the member's +// stored string, reads the member back, and binds the stored string in a filter. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, type MetaData } from "@metaobjectsdev/metadata"; +import { coerceRowOnRead, coerceRowOnWrite } from "../src/type-coercer.js"; +import { compileFilter } from "../src/query-builder.js"; + +async function upload(): Promise { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Article", children: [ + { "source.rdb": { "@table": "articles" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Draft", "Published"], "@stringValueMap": { Draft: "draft", Published: "published" } } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + return root.findObject("Article")!; +} + +describe("@stringValueMap — ObjectManager codec", () => { + test("writes the stored string and reads the member", async () => { + const entity = await upload(); + expect(coerceRowOnWrite(entity, { id: 1, status: "Published" }, "postgres")["status"]).toBe("published"); + expect(coerceRowOnRead(entity, { id: 1, status: "published" }, "postgres")["status"]).toBe("Published"); + }); + + test("an unmapped stored string read back throws", async () => { + const entity = await upload(); + expect(() => coerceRowOnRead(entity, { id: 1, status: "lost" }, "postgres")).toThrow(/no member in @stringValueMap/); + }); + + test("a filter binds the stored string", async () => { + const entity = await upload(); + expect(JSON.stringify(compileFilter(entity, { status: "Draft" }))).toContain('"draft"'); + }); +}); + +describe("@stringValueMap — an unmapped member", () => { + test("is refused on write, naming the field", async () => { + const entity = await upload(); + expect(() => coerceRowOnWrite(entity, { id: 1, status: "Archived" }, "postgres")).toThrow(/cannot write 'Archived'/); + }); + + // rc.21 part B (N4): a filter refuses it too, in every port. Passed through, a symbol can equal + // another member's stored string ({ A: "B", B: "C" } filtering "B" would match member A's rows). + test("is refused in a filter, naming the field", async () => { + const entity = await upload(); + expect(() => compileFilter(entity, { status: "Archived" })).toThrow(/filter on field.enum 'status': "Archived" has no stored string/); + expect(() => compileFilter(entity, { status: { $in: ["Draft", "Archived"] } })).toThrow(/"Archived" has no stored string/); + }); +}); diff --git a/server/typescript/packages/sdk/test/collection-naming-memory.test.ts b/server/typescript/packages/sdk/test/collection-naming-memory.test.ts new file mode 100644 index 0000000000..21de648f6e --- /dev/null +++ b/server/typescript/packages/sdk/test/collection-naming-memory.test.ts @@ -0,0 +1,72 @@ +// rc.19 (R57; fix round M4) — `naming.collections` in `.metaobjects/config.json` selects the +// pluralizer, through the same reader every project load goes through: an unknown name is +// refused when the file is read, a built-in or an application's own is carried onto the +// loaded root, and the collection names and REST segments follow it. Nothing configured, the +// segment is rc.18's. + +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + collectionNameOf, collectionSegment, registerPluralizer, resetNamingStrategiesForTesting, type MetaRoot, +} from "@metaobjectsdev/metadata"; +import { loadMemory } from "../src/memory.js"; +import { DEFAULT_METADATA_DIR } from "../src/metadata-files.js"; + +let project: string; +beforeEach(() => { + project = mkdtempSync(join(tmpdir(), "mo-collections-")); +}); +afterEach(() => { + rmSync(project, { recursive: true, force: true }); + resetNamingStrategiesForTesting(); +}); + +function write(naming: Record | undefined): void { + mkdirSync(join(project, ".metaobjects"), { recursive: true }); + writeFileSync(join(project, ".metaobjects", "config.json"), + JSON.stringify({ schema_version: 1, ...(naming !== undefined ? { naming } : {}) })); + mkdirSync(join(project, DEFAULT_METADATA_DIR), { recursive: true }); + writeFileSync(join(project, DEFAULT_METADATA_DIR, "meta.acme.json"), JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "FAQ", children: [ + { "source.rdb": { "@table": "faqs" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id" } }, + ] } }, + ] } })); +} + +const faq = (root: MetaRoot) => root.objects().find((o) => o.name === "FAQ")!; + +describe("naming.collections, read from .metaobjects/config.json", () => { + test("nothing configured: the standard collection name, and rc.18's segment", async () => { + write(undefined); + const root = await loadMemory(project); + expect(collectionNameOf(faq(root))).toBe("FAQs"); + expect(collectionSegment(faq(root))).toBe("faqs"); + }); + + test("a built-in is carried onto the loaded root", async () => { + write({ collections: "none" }); + const root = await loadMemory(project); + expect(root.physicalNaming.collections).toBe("none"); + expect(collectionNameOf(faq(root))).toBe("FAQ"); + expect(collectionSegment(faq(root))).toBe("faq"); + }); + + test("an application's own pluralizer, registered before the load", async () => { + registerPluralizer("listing", (n) => n + "List"); + write({ collections: "listing" }); + const root = await loadMemory(project); + expect(collectionNameOf(faq(root))).toBe("FAQList"); + expect(collectionSegment(faq(root))).toBe("faq_list"); + }); + + test("an unknown name is refused when the file is read, naming the built-ins", async () => { + write({ collections: "klingon" }); + const err = await loadMemory(project).then(() => undefined, (e: unknown) => e as Error); + expect(err).toBeInstanceOf(Error); + expect(err!.message).toMatch(/"naming.collections" names "klingon".*built in: standard, none/); + }); +}); diff --git a/server/typescript/packages/test-generators/src/generators/entity.ts b/server/typescript/packages/test-generators/src/generators/entity.ts index ced0ea9be7..6d3c2234c6 100644 --- a/server/typescript/packages/test-generators/src/generators/entity.ts +++ b/server/typescript/packages/test-generators/src/generators/entity.ts @@ -56,6 +56,7 @@ import { hasWritableRdbSource, formatTs, ownedRuntimeImport, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, namesRef, namesConstArg, @@ -186,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), content: await formatTs(renderEntity(entity, renderContext, { allowlists })), }; }); diff --git a/server/typescript/packages/test-generators/src/generators/queries.ts b/server/typescript/packages/test-generators/src/generators/queries.ts index 6933c4c227..8d03e08142 100644 --- a/server/typescript/packages/test-generators/src/generators/queries.ts +++ b/server/typescript/packages/test-generators/src/generators/queries.ts @@ -44,6 +44,7 @@ import { isWriteThrough, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, GENERATED_EDIT_NOTE, @@ -171,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat } claimModuleNames(ctx, entity); return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.queries.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), content: await formatTs(renderQueries(entity, ctx.renderContext)), }; }), diff --git a/server/typescript/packages/test-generators/src/generators/report-export.ts b/server/typescript/packages/test-generators/src/generators/report-export.ts index a192742d34..77ec25579c 100644 --- a/server/typescript/packages/test-generators/src/generators/report-export.ts +++ b/server/typescript/packages/test-generators/src/generators/report-export.ts @@ -27,6 +27,7 @@ import { GENERATED_EDIT_NOTE, GENERATED_HEADER, effectivePackage, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, formatTs, isCredentialField, @@ -239,7 +240,7 @@ export function reportExport(opts?: ReportExportOpts): Generator { name: "report-export", emitsReportExport: true, generate: async (ctx: GenContext): Promise => { - const layout = ctx.config.outputLayout ?? "flat"; + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; const extStyle = ctx.config.extStyle ?? "js"; const selfTarget = ctx.renderContext?.selfTarget; if (selfTarget === undefined) throw new Error("report-export: no render context (run it through runGen)."); diff --git a/server/typescript/packages/test-generators/src/generators/routes.ts b/server/typescript/packages/test-generators/src/generators/routes.ts index 1cd10a6824..16837743da 100644 --- a/server/typescript/packages/test-generators/src/generators/routes.ts +++ b/server/typescript/packages/test-generators/src/generators/routes.ts @@ -74,6 +74,7 @@ import { knownFieldsLine, servesReadApi, formatTs, + DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, crossEntitySpecifier, @@ -666,7 +667,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, @@ -768,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator ?? ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir), }; return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", effectivePackage(entity), `${entity.name}.routes.ts`), + path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), }; }); diff --git a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts index 2a9c7ea955..e687d1acdb 100644 --- a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts @@ -26,17 +26,22 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, resolveIndexName } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, resolveIndexName, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { flattenedMembersOf } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; import { foreignKeyIndexesOf, storedIndexName } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -186,7 +191,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -200,16 +205,31 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -218,6 +238,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -303,8 +325,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -443,6 +469,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -812,6 +854,60 @@ function renderColumn( : columnLine; } +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): CheckEntry[] | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: CheckEntry[] = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + const name = typeof declared === "string" && declared.length > 0 + ? declared + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); + }); + return out; +} + /** * Drizzle's identity options for what the model declares, the same two meta migrate writes * (`SEQUENCE NAME … START WITH n`): `{ name: "Old_Id_seq", startWith: 1000 }`, or nothing. diff --git a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts index c02b3dc950..c9392157cb 100644 --- a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,37 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts b/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts index fd7406700b..eb5392b047 100644 --- a/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts +++ b/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts @@ -23,6 +23,7 @@ import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; import { sortableFields, declaredSortDefaultOrder } from "./filter-shared.js"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { httpRuntimeSpecifier } from "@metaobjectsdev/codegen-ts/engine"; +import { DEFAULT_OUTPUT_LAYOUT } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; /** @@ -31,7 +32,7 @@ import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; * (`owned-runtime.ts`). Absent `ctx`, or with no `httpRuntimeImport`, the package: the * byte-identical default. */ -const PACKAGE_DEFAULT = { outputLayout: "flat", extStyle: "none" } as const; +const PACKAGE_DEFAULT = { outputLayout: DEFAULT_OUTPUT_LAYOUT, extStyle: "none" } as const; function allowlistTypesFrom(entity: MetaObject, ctx: RenderContext | undefined): string { return httpRuntimeSpecifier("allowlists", ctx ?? PACKAGE_DEFAULT, effectivePackage(entity)); diff --git a/server/typescript/packages/test-generators/src/templates/zod-validators.ts b/server/typescript/packages/test-generators/src/templates/zod-validators.ts index 049c8f2d60..99723899aa 100644 --- a/server/typescript/packages/test-generators/src/templates/zod-validators.ts +++ b/server/typescript/packages/test-generators/src/templates/zod-validators.ts @@ -712,6 +712,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); diff --git a/site-reference/index.html b/site-reference/index.html index 79a602afa7..e84f2d14c5 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -82,7 +82,7 @@ - + @@ -162,7 +162,7 @@ - + @@ -316,6 +316,11 @@ + + + + + diff --git a/site-reference/providers.html b/site-reference/providers.html index 1314c59016..97fd3cff37 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -51,13 +51,13 @@ INDEX.md lists by type.

metaobjects-core-types

Core metaobjects metamodel types and subtypes.

-

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

+

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

Contributes attributes:

  • field.base: @default, @mutability, @required, @unique
  • field.currency: @currency
  • field.decimal: @precision, @scale
  • -
  • field.enum: @intValueMap, @maxLength, @provided, @values
  • +
  • field.enum: @intValueMap, @maxLength, @provided, @stringValueMap, @values
  • field.inet: @lenient
  • field.map: @objectRef, @valueType
  • field.object: @objectRef
  • @@ -68,11 +68,12 @@

    metaobjects-core-types

  • identity.secondary: @fields
  • object.base: @object, @objectAdapter
  • object.entity: @collectionName, @discriminator, @discriminatorValue
  • -
  • object.projection: @collectionName, @filter
  • +
  • object.projection: @collectionName, @filter, @grain, @grainOrdinal, @union, @unionAll
  • object.report: @collectionName, @dimensions, @filter, @from, @measures, @segment, @spine
  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @segment, @via
  • origin.computed: @expr
  • origin.first: @filter, @of, @orderBy, @segment, @via
  • +
  • origin.function: @args, @function, @params, @returns, @schema
  • origin.passthrough: @convert, @from, @via
  • relationship.aggregation: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • relationship.association: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • @@ -103,7 +104,7 @@

    metaobjects-db

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

    metaobjects-db

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

metaobjects-documentation

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

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

attr.double

Allowed children

No structural children.

attr.expression

-

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

+

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

Owning provider: metaobjects-core-types

Attributes

No subtype-specific attributes.

diff --git a/site-reference/types/field.html b/site-reference/types/field.html index e8ff866b9f..676cac1f74 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -89,9 +89,9 @@

field.base

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

field.boolean

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

field.currency

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

field.date

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

field.decimal

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

field.double

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

field.duration

- + - + @@ -1138,9 +1138,9 @@

field.duration

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

    -

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

    +

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

    Owning provider: metaobjects-core-types

    -

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

    +

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

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

    Attributes

    attr.expressionA structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. types/attr.md#attrexpression
    field.enumString-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). types/field.md#fieldenum
    types/origin.md#originfirst
    origin.functionA value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.types/origin.md#originfunction
    origin.passthrough A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). types/origin.md#originpassthrough string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default
    @@ -1192,13 +1192,22 @@

    field.enum

    + + + + + + + + + - + - + @@ -1336,6 +1345,15 @@

    field.enum

    + + + + + + + + + @@ -1351,7 +1369,7 @@

    field.enum

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

    field.float

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

    field.inet

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

    field.int

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

    field.long

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

    field.map

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

    field.object

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

    field.string

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

    field.time

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

    field.timestamp

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

    field.uri

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

    field.uuid

    - + - + diff --git a/site-reference/types/identity.html b/site-reference/types/identity.html index 1b2266494c..5b0868bf63 100644 --- a/site-reference/types/identity.html +++ b/site-reference/types/identity.html @@ -130,7 +130,7 @@

    identity.reference

    - + diff --git a/site-reference/types/object.html b/site-reference/types/object.html index baa81c01cc..7578d5a9d0 100644 --- a/site-reference/types/object.html +++ b/site-reference/types/object.html @@ -206,7 +206,25 @@

    object.projection

    - + + + + + + + + + + + + + + + + + + + @@ -226,6 +244,24 @@

    object.projection

    + + + + + + + + + + + + + + + + + +
    When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means).
    @dbCheckbooleannometaobjects-dbfalse: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @dbColumnType string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'.
    @stringValueMappropertiesnometaobjects-core-typesOptional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE).
    @unique boolean no metaobjects-core-typesMember symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string.Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it.
    @xmlText string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default string no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @default metaobjects-dbPhysical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. <table>_<firstFkColumn>_fk). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider.Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. <table>_<firstFkColumn>_fk). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1.
    @enforce metaobjects-core-typesOptional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field.Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19).
    @grainstringnometaobjects-core-typesrc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection.
    @grainOrdinalstringnometaobjects-core-typesrc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array.
    @object metaobjects-core-types JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it.
    @unionstring[]nometaobjects-core-typesrc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless.
    @unionAllbooleannometaobjects-core-typesrc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default.

    Allowed children

      diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index 545feab624..d05225a155 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -93,7 +93,7 @@

      origin.aggregate

      metaobjects-core-types -Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or { field: "" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom. +Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). @of @@ -120,7 +120,7 @@

      origin.aggregate

      metaobjects-core-types -Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. +Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. @via @@ -195,7 +195,7 @@

      origin.first

      metaobjects-core-types -Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or { field: "" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom. +Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field, or — correlated-filter — { field: "" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19). @of @@ -222,7 +222,7 @@

      origin.first

      metaobjects-core-types -Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. +Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates. @via @@ -236,6 +236,71 @@

      origin.first

      Allowed children

      No structural children.

      +

      origin.function

      +

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

      +

      Owning provider: metaobjects-core-types

      +

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

      +

      Attributes

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      AttributeTypeRequiredDefaultAllowed valuesProviderDescription
      @argsstring[]nometaobjects-core-typesThe fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments.
      @functionstringyesmetaobjects-core-typesThe function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase.
      @paramsstring[]nometaobjects-core-typesThe function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN).
      @returnsstringyesmetaobjects-core-typesThe function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc).
      @schemastringnometaobjects-core-typesThe schema the function lives in, a plain identifier. Absent: public.
      +

      Allowed children

      +

      No structural children.

      origin.passthrough

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

      Owning provider: metaobjects-core-types

      diff --git a/site-reference/types/validator.html b/site-reference/types/validator.html index 8f9383a3a8..544f233217 100644 --- a/site-reference/types/validator.html +++ b/site-reference/types/validator.html @@ -125,6 +125,15 @@

      validator.atLeastOne

      The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. + + + + + + + + + @@ -210,6 +219,15 @@

      validator.comparison

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

      validator.exactlyOne

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

      validator.length

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

      validator.numeric

      @dbCheckbooleannometaobjects-dbOn a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
      @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. + + + + + + + + + @@ -418,6 +463,15 @@

      validator.presentIff

      @dbCheckbooleannometaobjects-dbOn a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
      @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. + + + + + + + + + @@ -474,6 +528,15 @@

      validator.regex

      @dbCheckbooleannometaobjects-dbOn a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
      @equals string yes The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. + + + + + + + + + @@ -548,6 +611,15 @@

      validator.requiredWhen

      @dbCheckbooleannometaobjects-dbOn a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
      @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1. + + + + + + + + + diff --git a/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md b/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md index 4c5a8ec159..d3f1f99c43 100644 --- a/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md +++ b/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md @@ -24,7 +24,7 @@ Where ADR-0007 made a separate, weaker choice was inside the `rdb` paradigm: it | TypeORM | `@Entity({ name })` | `@ViewEntity({ name })` | (raw SQL only) | | SQL standard | `CREATE TABLE` | `CREATE VIEW` | `CREATE PROCEDURE` / `CREATE FUNCTION` | -Zero of them call a non-table relation "table." The single-attr choice in ADR-0007 was a deviation from universal practice, made for internal-design simplicity at the cost of reader ergonomics. Metadata files in adopter projects would read `@table: "fn_get_phase_summary_per_case"` with `@kind: "storedProc"` — internally consistent but immediately disorienting to anyone scanning the source. +Zero of them call a non-table relation "table." The single-attr choice in ADR-0007 was a deviation from universal practice, made for internal-design simplicity at the cost of reader ergonomics. Metadata files in adopter projects would read `@table: "fn_get_stage_summary_per_consignment"` with `@kind: "storedProc"` — internally consistent but immediately disorienting to anyone scanning the source. The decision to revisit happens now because: 1. **No external adopters depend on `@table`-for-everything yet.** The cost of revising is bounded; the cost of shipping the smell to 1.0 is permanent. diff --git a/spec/decisions/ADR-0044-payload-record-naming-cross-package-collision.md b/spec/decisions/ADR-0044-payload-record-naming-cross-package-collision.md index 6f16cb2598..a465c558c3 100644 --- a/spec/decisions/ADR-0044-payload-record-naming-cross-package-collision.md +++ b/spec/decisions/ADR-0044-payload-record-naming-cross-package-collision.md @@ -89,3 +89,20 @@ The cross-package case this ADR exists for still works, without a rename: `ERR_PAYLOAD_NAME_COLLISION` is no longer raised by any port. `ERR_NAME_COLLISION` is a codegen-time code, like it. + +## Amendment (2026-11-09) — release-line text of the same decision, superseded by Amendment 1 above + +The package-qualified derived name is **removed** in C# and TypeScript. A value object's type is +its own name and is never rewritten. The rename had ADR-0044's admitted instability (adding an +unrelated object renamed an existing type), and ADR-0056's model-wide widening made it worse: an +**abstract** object that emits nothing could force a concrete value object elsewhere to be +renamed. A real collision is refused instead, by the run's one claim registry: a generator claims +each name when it emits it (`ctx.Claim(scope, name, claimant, remedy)` — a type per C# namespace or +TypeScript module, a DbSet per context, a route segment per routes entry, a finder per class, an +index per schema), and a second claimant of one name in one scope fails with +`ERR_NAME_COLLISION`, naming both metadata nodes and the remedy. An object that emits nothing +claims nothing. The cross-package case this ADR exists for works without a rename: in C# by +mapping the packages to distinct namespaces (`GenConfig.PackageNamespaces`), in TypeScript by the +package output layout. `ERR_PAYLOAD_NAME_COLLISION` is no longer raised by those two ports. Python +still renames (its flat generated package); Java and Kotlin never did. Tracked with the other +port gaps in `docs/CONFORMANCE.md`. diff --git a/spec/decisions/ADR-0056-value-object-types-are-generated-once.md b/spec/decisions/ADR-0056-value-object-types-are-generated-once.md index b70ad2a9b3..735eadc40b 100644 --- a/spec/decisions/ADR-0056-value-object-types-are-generated-once.md +++ b/spec/decisions/ADR-0056-value-object-types-are-generated-once.md @@ -166,6 +166,20 @@ meets two same-named value objects binds them under local import aliases, and th mirrors and mappers, declarations of that one module, take the alias (`AcmeAlphaNoteExtracted`). No module declares a renamed type. +## Amendment 2, release-line text (2026-11-09) — superseded by Amendment 2 above + +Rule 2's collision-aware name (the package-qualified `AcmeAlphaNote`) is removed in C# and +TypeScript; see [ADR-0044's amendment](ADR-0044-payload-record-naming-cross-package-collision.md). +The type is generated once, under its own name, in its own namespace or module, and every tier +references that name. Two objects that would emit one type into one namespace are refused by the +run's claim registry (`ERR_NAME_COLLISION`), with the remedy of mapping the packages apart. A +private member of a generated class that is keyed by a value object (C#'s extract-tier mappers) +may still carry the package to stay unique inside that class; that is a member name, never a type. +Likewise a TypeScript file that meets two same-named value objects binds them under local import +aliases (`import type { Note as AcmeAlphaNote }`), and the extract tier's mirrors and mappers — +declarations of that one module — take the alias (`AcmeAlphaNoteExtracted`). No module declares +a renamed type. + ## Alternatives considered - **One copy per consuming package (the #387 proposal).** Rejected: it fixes the compile error by diff --git a/spec/metamodel/attr.json b/spec/metamodel/attr.json index 19031ccb34..ec55a95947 100644 --- a/spec/metamodel/attr.json +++ b/spec/metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 4e087e72f0..1c61a0bdac 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
      @dbCheckbooleannometaobjects-dbOn a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
      @equals string yes
      __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
      __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
      ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
      ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { @@ -85,7 +87,7 @@ "type": "identity", "subType": "reference", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
      __fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
      __fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider." }, { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider." } ] diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index 3b4a4ce9fc..46a2f064ce 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index 244fd1655a..d169a02544 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -53,7 +53,11 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.isActive'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index d5b5b85415..e8cfe7e735 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -27,8 +27,8 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -42,6 +42,19 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } + ] + }, { "type": "origin", "subType": "first", @@ -52,8 +65,8 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or { field: \"\" }, a field of the base row, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom." }, - { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity). Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } ] } ] diff --git a/tools/prerelease/prerelease-link.sh b/tools/prerelease/prerelease-link.sh index a6e74a61a1..70e1198178 100755 --- a/tools/prerelease/prerelease-link.sh +++ b/tools/prerelease/prerelease-link.sh @@ -192,6 +192,14 @@ sed_inplace() { # sed_inplace # or not anything matched), so only the awk call sites route through this. is # `had_newline` captured on immediately before the awk call that produced ; a # caller that already knows nothing needs preserving can pass "1", which is a no-op here. +# In-place extended-regex sed that works on GNU and BSD (macOS) sed alike. Both accept the +# backup suffix only ATTACHED to -i (-i.suffix); a bare `-i -E` makes BSD sed take "-E" as the +# suffix, leaving -E behind and running the expression as a basic regex, whose ( ) groups +# do not capture. Neither sed adds a missing trailing newline here (verified on both). +sed_inplace() { # sed_inplace + sed -E -i.mo-sed-bak "$1" "$2" && rm -f "$2.mo-sed-bak" +} + finish_rewrite() { # finish_rewrite local f="$1" tmp="$2" had="$3" mv "$tmp" "$f"