From 521b1c140d4203e9dbf9fe27b4944267aac647c6 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Mon, 2 Nov 2026 06:47:57 -0500
Subject: [PATCH 01/51] fix(metadata): resolve bare root-level @objectRef in
Java loader (#525)
* fix(metadata): root-level node resolves a bare @objectRef in its own package (#522); one bump rule for a new attribute (#523)
* chore(site): refresh payload fixture count
---
AGENTS.md | 2 +-
CHANGELOG.md | 8 +++
docs/1.0-readiness.md | 2 +-
docs/CONFORMANCE.md | 6 +--
docs/RELEASING.md | 2 +-
examples/showcase/site-payload.json | 2 +-
.../expected-errors.json | 15 ++++++
.../input/meta.json | 14 +++++
.../providers.json | 1 +
.../expected.json | 51 +++++++++++++++++++
.../input/meta.json | 32 ++++++++++++
.../providers.json | 1 +
.../validation/RegisteredValidation.java | 10 +++-
13 files changed, 137 insertions(+), 9 deletions(-)
create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json
create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json
create mode 100644 fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json
create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/expected.json
create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/input/meta.json
create mode 100644 fixtures/conformance/root-level-field-object-bare-ref/providers.json
diff --git a/AGENTS.md b/AGENTS.md
index 1ce9781050..31c4c7fa80 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (421 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (423 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical.
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3631b5903c..b7b19f608f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -56,6 +56,14 @@ here.**
It now generates `tags: list[str] = []`, from the same four spellings TypeScript accepts, or
from a native YAML list such as `default: [a, b]`. A default Python cannot spell as a list is
left to the database.
+- **Java: a bare `@objectRef` on a field declared directly under `metadata.root` now resolves.**
+ A root-level `field.object` (the reusable template other fields `extends`) with
+ `@objectRef: "Address"` failed to load in Java even when `Address` sat in the same package,
+ while TypeScript loaded it. A root-level node now resolves a bare reference in its own
+ package, as ADR-0042 specifies, and a real miss still fails with `ERR_UNRESOLVED_OBJECT_REF`.
+ The error no longer names the loader as the owner of a root-level node. Two new conformance
+ fixtures (`root-level-field-object-bare-ref`, `error-root-level-field-objectref-unresolved`)
+ hold every port to it; C#, Python and TypeScript already passed.
## [1.2.0] — 2026-10-30
diff --git a/docs/1.0-readiness.md b/docs/1.0-readiness.md
index ced552c54c..b54be142ed 100644
--- a/docs/1.0-readiness.md
+++ b/docs/1.0-readiness.md
@@ -117,7 +117,7 @@ Status legend: ✅ done · 🔶 in progress · ⬜ not started · ❓ **[RATIFY]
(attribute ⇒ PATCH, top-level type ⇒ MINOR, subtype ⇒ PATCH when inert), and Amendment 2
separates the package and metamodel axes. Trigger
is *new public surface, not code size*: package **MINOR** only for newly-dependable
- surface (codegen output, CLI flag, a newly-supported vocab member); package **PATCH**
+ surface (codegen-engine surface, CLI flag, a new top-level type); package **PATCH**
for bugfix/refactor; the **Metamodel spec version** bumps only on a shared
vocabulary/wire change. The fast `7.3→7.7` minor run was breaking *velocity*; decouple
+ this rule ends the churn.
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index 73b8182683..d7e9157567 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| Corpus | Fixtures | TS | Java | Kotlin | C# | Python |
|---|---|---|---|---|---|---|
-| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 421 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ |
@@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker.
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (421)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (423)
| Fixture prefix | Feature doc |
|---|---|
@@ -611,7 +611,7 @@ files into a real Cube.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 421 + yaml 16 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45
+ render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 +
dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the
`cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 4a8f6df227..5006db9ed3 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -266,7 +266,7 @@ what they render is generator output and does not.)
| Codegen **ENGINE** public surface **additive** (new `render*` primitive, new `GenContext` field, optional param) | new `render*` primitive | PATCH (MINOR if it headlines a feature release) | MINOR |
| Codegen **ENGINE** public surface **breaking**, or changed **CLI semantics** | `relativeModuleSpecifier` +required param | **MINOR** | MAJOR |
| A **runtime library**'s public surface (`runtime-ts`, `render`, OMDB, ObjectManager, web client) — additive / breaking | a new mount option / a removed export | PATCH / **MINOR** | MINOR / MAJOR |
-| New **attribute** on an existing type/subtype | `@intValueMap`, `@lenient`, `@maxTokens` | **PATCH** | MINOR |
+| New **attribute** on an existing type/subtype | `@intValueMap`, `@lenient`, `@maxTokens` | **PATCH** | **PATCH** |
| New **subtype** of an existing type | `field.uri`, `index.lookup`, `attr.intMap` | **PATCH** when inert (see the vocabulary rule below); **MINOR** when it changes existing metadata's meaning/output, narrows something previously permitted, or headlines a feature | MINOR |
| New top-level metadata **type** | `requirement.*`, `index.*`, `api.*` | **MINOR** | MINOR |
| **Breaking** metamodel-vocabulary change (retire an attr/subtype/type; narrow what is permitted) | FR-037 `@readOnly`, FR-038 `@verifiedBy`, ADR-0052 `@promptStyle` re-homing | **MINOR** (pre-1.0 MINOR *is* the breaking slot) | **`metamodelVersion` MAJOR**, package MINOR (ADR-0035 Am. 2) |
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index 82e51fcbdd..6e9ec3f63d 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,7 +7,7 @@
"metamodel": "1.2"
},
"counts": {
- "fixtures": 421,
+ "fixtures": 423,
"corpora": 35,
"baseTypes": 17
},
diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json
new file mode 100644
index 0000000000..3c510ca24d
--- /dev/null
+++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_UNRESOLVED_OBJECT_REF",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['field.object']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json
new file mode 100644
index 0000000000..e0afebb868
--- /dev/null
+++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/input/meta.json
@@ -0,0 +1,14 @@
+{
+ "metadata.root": {
+ "package": "acme::shop",
+ "children": [
+ {
+ "field.object": {
+ "name": "AddrTemplate",
+ "abstract": true,
+ "@objectRef": "Missing"
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json b/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-root-level-field-objectref-unresolved/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/root-level-field-object-bare-ref/expected.json b/fixtures/conformance/root-level-field-object-bare-ref/expected.json
new file mode 100644
index 0000000000..b8f056a7c3
--- /dev/null
+++ b/fixtures/conformance/root-level-field-object-bare-ref/expected.json
@@ -0,0 +1,51 @@
+{
+ "metadata.root": {
+ "package": "acme::shop",
+ "children": [
+ {
+ "object.value": {
+ "name": "Address",
+ "children": [
+ {
+ "field.string": {
+ "name": "street"
+ }
+ },
+ {
+ "field.string": {
+ "name": "city"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "field.object": {
+ "name": "AddrTemplate",
+ "package": "acme::shop",
+ "abstract": true,
+ "@objectRef": "acme::shop::Address"
+ }
+ },
+ {
+ "object.value": {
+ "name": "Contact",
+ "children": [
+ {
+ "field.string": {
+ "name": "name"
+ }
+ },
+ {
+ "field.object": {
+ "name": "billing",
+ "extends": "acme::shop::AddrTemplate"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
+
diff --git a/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json b/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json
new file mode 100644
index 0000000000..39fbb18e57
--- /dev/null
+++ b/fixtures/conformance/root-level-field-object-bare-ref/input/meta.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::shop",
+ "children": [
+ {
+ "object.value": {
+ "name": "Address",
+ "children": [
+ { "field.string": { "name": "street" } },
+ { "field.string": { "name": "city" } }
+ ]
+ }
+ },
+ {
+ "field.object": {
+ "name": "AddrTemplate",
+ "abstract": true,
+ "@objectRef": "Address"
+ }
+ },
+ {
+ "object.value": {
+ "name": "Contact",
+ "children": [
+ { "field.string": { "name": "name" } },
+ { "field.object": { "name": "billing", "extends": "AddrTemplate" } }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/root-level-field-object-bare-ref/providers.json b/fixtures/conformance/root-level-field-object-bare-ref/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/root-level-field-object-bare-ref/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
index 99cf268c8c..c9656f581c 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
@@ -40,7 +40,10 @@ private static void walk(MetaData node, MetaDataRegistry registry, ValidationCon
// BARE refs against it. Nested nodes carry no package of their own, so they inherit the
// enclosing object's. Mirrors TS validation-registry.ts.
String pkg = referrerPkg;
- if (node instanceof MetaObject) {
+ // A root-level node of any type (e.g. an abstract field.object template that other
+ // fields extend) is a top-level declaration too: it carries its own package and its
+ // bare refs resolve in it, not against the empty context.
+ if (node instanceof MetaObject || node.getParent() instanceof MetaRoot) {
String p = node.getPackage();
pkg = (p != null && !p.isEmpty()) ? p : referrerPkg;
}
@@ -64,7 +67,10 @@ private static void walk(MetaData node, MetaDataRegistry registry, ValidationCon
MetaObject target = ctx.symbols().resolveObject(entityRef, pkg);
// Qualify the node name with its owning entity (e.g. "Order.items") so the
// error is locatable from the message alone, not just the source envelope.
- String qname = (node.getParent() != null && node.getParent().getShortName() != null
+ // A root-level node has no owning entity: the parent is the loader/root, whose
+ // name must not be printed as an owner.
+ String qname = (node.getParent() != null && !(node.getParent() instanceof MetaRoot)
+ && node.getParent().getShortName() != null
&& !node.getParent().getShortName().isEmpty())
? node.getParent().getShortName() + "." + node.getShortName()
: node.getShortName();
From 27cfc4bf55ad0be5bc0b6d707070802be37256b8 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Mon, 2 Nov 2026 10:42:49 -0500
Subject: [PATCH 02/51] fix(migrate-ts): block unowned view column drops and
restore SQLite drop-column rollback (#526)
* fix(migrate): refuse a column drop under an unowned view; SQLite down re-adds the column
A live view the tool does not own (@unmanaged, or outside the scoped schemas) that still
reads a dropped column now blocks the drop at plan time, naming the view
(--allow drop-column-read-by-view to proceed). The SQLite/D1 down for drop-column re-adds
the column instead of writing a TODO. Docs note: edit an @sql body when removing a column
it reads.
* no-mistakes(review): Omit non-constant defaults in SQLite drop-column rollback
* no-mistakes(test): Block drop-column read by unowned or hand-made views
* no-mistakes(test): Fix allow-hint test typecheck; unowned-view block verified live
* no-mistakes(document): Docs current; SQLite rollback default omission documented in migrations-and-drift.md.
---
CHANGELOG.md | 16 ++
.../references/read-views-and-projections.md | 7 +
docs/features/migrations-and-drift.md | 22 +++
.../references/read-views-and-projections.md | 7 +
.../references/read-views-and-projections.md | 7 +
.../references/read-views-and-projections.md | 7 +
.../references/read-views-and-projections.md | 7 +
.../references/read-views-and-projections.md | 7 +
server/typescript/packages/cli/README.md | 2 +-
.../packages/cli/src/commands/migrate.ts | 2 +-
server/typescript/packages/cli/src/index.ts | 2 +-
.../typescript/packages/cli/src/lib/allow.ts | 7 +-
.../typescript/packages/cli/src/lib/args.ts | 4 +
.../cli/test/__snapshots__/cli.test.ts.snap | 2 +-
.../cli/test/allow-hint-tokens.test.ts | 15 ++
.../test/drop-column-view-pg.test.ts | 116 +++++++++++++++
.../test/drop-column-view-sqlite.test.ts | 138 ++++++++++++++++++
.../packages/migrate-ts/src/diff/index.ts | 38 +++++
.../packages/migrate-ts/src/diff/status.ts | 14 +-
.../packages/migrate-ts/src/emit/sqlite.ts | 29 +++-
.../packages/migrate-ts/src/types.ts | 18 ++-
.../test/drop-column-unowned-view.test.ts | 138 ++++++++++++++++++
server/typescript/packages/sdk/src/config.ts | 1 +
23 files changed, 597 insertions(+), 9 deletions(-)
create mode 100644 server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts
create mode 100644 server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts
create mode 100644 server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7b19f608f..8b13247ac0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,22 @@ here.**
## [Unreleased]
+### Fixed
+
+- **`meta migrate` refuses, at plan time, to drop a column a view it does not own still reads.**
+ With `--from-db`, a declared-`@unmanaged` view or one outside the scoped schemas whose live body
+ names the dropped column now blocks the `drop-column`, and the message names the view and the
+ column. Before, the migration was written and failed at apply on both Postgres (`cannot drop
+ column … other objects depend on it`) and SQLite (`error in view … after drop column`). A view with
+ no recorded body is not matched, and an offline run cannot see live views. Pass
+ `--allow drop-column-read-by-view` (config token `drop-column-read-by-view`) to proceed.
+- **The SQLite and D1 down migration for `drop-column` re-adds the column.** It wrote a TODO comment
+ and still recreated the view with the old SQL, so the view failed with `no such column` after a
+ rollback. It now runs `ADD COLUMN` from the recorded column, as Postgres does; the data is not
+ restored, and a `NOT NULL` column with no default comes back nullable, which is all SQLite allows.
+- **Docs: edit an `@sql` body when you remove a column it reads.** The tool never parses the body;
+ Postgres fails at apply and SQLite applies and leaves a broken view.
+
### Added
- **Contract emitters: JSON Schema and OpenAPI generators (FR-022).** `jsonSchemaFile()`
diff --git a/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md b/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/agent-context/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md
index 790692ea09..7e38e0aea7 100644
--- a/docs/features/migrations-and-drift.md
+++ b/docs/features/migrations-and-drift.md
@@ -632,6 +632,28 @@ migrate` never creates, drops, or drift-checks it, and `meta verify --db` report
*external (declared)*. The two are mutually exclusive. See
[ADR-0043](../../spec/decisions/ADR-0043-ddl-ownership-escape-valves.md).
+**Removing a column a view reads.** For a view the tool derives, `meta migrate` finds the
+views that read the column and drops and recreates them around the change. Two kinds of view
+are not rewritten, so you edit them yourself:
+
+- **An `@sql` body.** The tool never parses it, so it cannot know the body still names a
+ column you removed. **Edit the body in the same change that removes the column.** Left
+ alone, the migration is still written. On Postgres it then fails at apply with `column
+ "…" does not exist`. On SQLite it applies and leaves a view that errors when queried.
+- **An `@unmanaged` view, or a hand-made one.** With `--from-db`, `meta migrate` reads the
+ live view bodies. If one it does not own names the column the plan drops, the drop is
+ blocked at plan time and the message names the view and the column; otherwise Postgres
+ fails at apply (`cannot drop column … because other objects depend on it`) and SQLite
+ fails with `error in view … after drop column`. Change the view first, or pass `--allow
+ drop-column-read-by-view` to proceed anyway. A view with no recorded body cannot be
+ matched, and an offline run (no database) cannot see live views, so neither is checked.
+
+A rollback of a dropped column re-adds it on every engine, with its type, but the data is
+not restored. On SQLite a column that was `NOT NULL` with no default comes back nullable,
+because SQLite cannot add it any other way. SQLite also cannot add a column with an
+expression default (or a `uuid` identity default) to a populated table, so the rollback
+omits that default and says so in a `NOTE`.
+
## Verified by
The following conformance fixtures gate this feature's behavior across ports:
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
index c58b0e5adc..06d2ccf2e8 100644
--- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
+++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md
@@ -153,6 +153,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo
- Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc /
tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`).
+**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never
+parses an `@sql` body, so it cannot see that the body still names the column. The migration
+is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it
+applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten
+either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads
+and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first.
+
**A `passthrough` field must match its `@from` source's type.** A passthrough
forwards the source value unchanged, so the projection field's `field.`
and array-ness must be identical to the source field's — a `field.uuid` source
diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md
index cae4c2ba87..25e779ad6d 100644
--- a/server/typescript/packages/cli/README.md
+++ b/server/typescript/packages/cli/README.md
@@ -176,7 +176,7 @@ Flags:
- `--shadow-db ` — Postgres scratch database the expected schema is applied to for `--from-db` / `--apply` drift (also `SHADOW_DATABASE_URL` or `migrate.shadowDatabaseUrl`). Read [How CHECK constraints and expression indexes are compared](../../../../docs/features/migrations-and-drift.md#how-check-constraints-and-expression-indexes-are-compared) for the three paths.
- `--out-dir ` (default `./.metaobjects/migrations`)
- `--slug ` — required when changes are pending (e.g., `add-user-shipping`)
-- `--allow ` — destructive-change permissions: `drop-column,drop-table,type-change,drop-index,drop-fk,drop-check,drop-view,drop-view-cascade,adopt-view,nullable-to-not-null,drop-identity-default,drop-unmanaged,drop-comment`
+- `--allow ` — destructive-change permissions: `drop-column,drop-table,type-change,drop-index,drop-fk,drop-check,drop-view,drop-view-cascade,drop-column-read-by-view,adopt-view,nullable-to-not-null,drop-identity-default,drop-unmanaged,drop-comment`
- `--on-ambiguous abort|rename|drop-add` (default `abort`) — non-interactive
- `--rename-table [schema.]old=new` / `--rename-column [schema.]table.old=new` — declare a rename (repeatable), so the migration is `RENAME` instead of drop+add whatever the rename heuristic makes of the names. Refused if nothing matches. See [Renames and populated tables](../../../../docs/features/migrations-and-drift.md#renames-and-populated-tables).
- `--dry-run` — print the SQL pair, write nothing (under `--format json|toon` the pair is the document's `sql` field, so stdout stays one parseable document)
diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts
index ae661808de..a5d8bc30da 100644
--- a/server/typescript/packages/cli/src/commands/migrate.ts
+++ b/server/typescript/packages/cli/src/commands/migrate.ts
@@ -120,7 +120,7 @@ MIGRATE FLAGS:
--slug Required to WRITE a migration (not for --dry-run) (e.g., --slug add-user-shipping)
--allow Comma-separated destructive-change permissions:
drop-column,drop-table,type-change,drop-index,drop-fk,
- drop-check,drop-view,drop-view-cascade,
+ drop-check,drop-view,drop-view-cascade,drop-column-read-by-view,
adopt-view,nullable-to-not-null,drop-identity-default,
drop-unmanaged,drop-comment
drop-column DELETES the column and every value in it. If
diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts
index a294da47d0..d63cc68585 100644
--- a/server/typescript/packages/cli/src/index.ts
+++ b/server/typescript/packages/cli/src/index.ts
@@ -176,7 +176,7 @@ MIGRATE FLAGS:
--slug Required when changes are present (e.g., add-user-shipping)
--allow Comma-separated destructive-change permissions:
drop-column,drop-table,type-change,drop-index,drop-fk,
- drop-check,drop-view,drop-view-cascade,
+ drop-check,drop-view,drop-view-cascade,drop-column-read-by-view,
adopt-view,nullable-to-not-null,drop-identity-default,
drop-comment,drop-unmanaged
drop-column DELETES the column's data; for a renamed
diff --git a/server/typescript/packages/cli/src/lib/allow.ts b/server/typescript/packages/cli/src/lib/allow.ts
index f1a7bc7c88..a6db944138 100644
--- a/server/typescript/packages/cli/src/lib/allow.ts
+++ b/server/typescript/packages/cli/src/lib/allow.ts
@@ -27,6 +27,8 @@ export const ALLOW_TOKEN_MAP: Record = {
"drop-view": "dropView",
// Gates DROP VIEW ... CASCADE. Additional to drop-view, never implied by it.
"drop-view-cascade": "dropViewCascade",
+ // Gates dropping a column a view this tool does not own still reads.
+ "drop-column-read-by-view": "dropColumnReadByView",
// Gates overwriting an unfingerprinted (hand-written or pre-fingerprint) view.
"adopt-view": "adoptView",
"nullable-to-not-null": "nullableToNotNull",
@@ -66,7 +68,10 @@ export function describeChange(c: Change): string {
case "drop-table": return c.table;
case "rename-table": return `${c.from} → ${c.to}`;
case "add-column": return `${c.table}.${c.column.name}`;
- case "drop-column": return `${c.table}.${c.column}`;
+ case "drop-column":
+ return c.readBy === undefined || c.readBy.length === 0
+ ? `${c.table}.${c.column}`
+ : `${c.table}.${c.column} (read by view ${c.readBy.join(", ")})`;
case "rename-column": return `${c.table}.${c.from} → ${c.table}.${c.to}`;
case "change-column-type": {
// A type change carries its column's default change, so the default is reported here.
diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts
index 0280813a89..7155271048 100644
--- a/server/typescript/packages/cli/src/lib/args.ts
+++ b/server/typescript/packages/cli/src/lib/args.ts
@@ -314,6 +314,10 @@ export const ALLOW_TOKENS = [
// views and materialized views owned by OTHER applications, which this tool
// neither manages nor can restore. `--allow drop-view` alone never cascades.
"drop-view-cascade",
+ // drop-column-read-by-view permits dropping a column that a live view this tool
+ // does not own (`@unmanaged`, or outside the scoped schemas) still reads. The tool
+ // never rewrites such a view, so without this `migrate` refuses at plan time.
+ "drop-column-read-by-view",
// adopt-view permits overwriting an existing view that carries no MetaObjects
// fingerprint — i.e. taking ownership of a hand-written view, or of one created
// before fingerprinting existed. Every environment upgrading from an older
diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap
index 06921804fb..6e8edb3474 100644
--- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap
+++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap
@@ -156,7 +156,7 @@ MIGRATE FLAGS:
--slug Required when changes are present (e.g., add-user-shipping)
--allow Comma-separated destructive-change permissions:
drop-column,drop-table,type-change,drop-index,drop-fk,
- drop-check,drop-view,drop-view-cascade,
+ drop-check,drop-view,drop-view-cascade,drop-column-read-by-view,
adopt-view,nullable-to-not-null,drop-identity-default,
drop-comment,drop-unmanaged
drop-column DELETES the column's data; for a renamed
diff --git a/server/typescript/packages/cli/test/allow-hint-tokens.test.ts b/server/typescript/packages/cli/test/allow-hint-tokens.test.ts
index f0c9cf94af..2213ab9f06 100644
--- a/server/typescript/packages/cli/test/allow-hint-tokens.test.ts
+++ b/server/typescript/packages/cli/test/allow-hint-tokens.test.ts
@@ -142,3 +142,18 @@ describe("following the hints unblocks the change", () => {
expect(await blocked(scenario, ["drop-view-cascade", "adopt-view"])).toEqual([]);
});
});
+
+describe("a drop-column held by a view the tool does not own", () => {
+ test("the blocked entry names the view that reads the column", async () => {
+ const r = await diff({
+ expected: snap([T({ columns: [T().columns[0]!] })]),
+ actual: snap([T()], [{ name: "v_hand", sql: "SELECT id, label FROM t" }]),
+ dialect: "sqlite",
+ allow: { dropColumn: true },
+ });
+ const entries = blockedEntriesFor(r.blocked, r.changes);
+ const entry = entries.find((e) => e.kind === "drop-column");
+ expect(entry?.description).toBe("t.label (read by view v_hand)");
+ expect(entry?.allowFlag).toBe("drop-column-read-by-view");
+ });
+});
diff --git a/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts b/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts
new file mode 100644
index 0000000000..a56de0d046
--- /dev/null
+++ b/server/typescript/packages/integration-tests/test/drop-column-view-pg.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Dropping a column under a view the tool does not own, against a real Postgres.
+ *
+ * An `@unmanaged` view that still reads the dropped column is refused at plan time and
+ * named (Postgres otherwise fails at apply: "cannot drop column … other objects depend on
+ * it"); one that does not read it is not blocked, and applies.
+ */
+import { splitSqlStatements } from "@metaobjectsdev/migrate-ts";
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from "bun:test";
+import {
+ buildExpectedSchema, collectUnmanagedNames, diff, emit, introspectPostgres, postgresViewReplaceProbe,
+ type AllowOptions,
+} 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";
+
+function literalColumns(root: T): T {
+ (root as unknown as { physicalNaming: unknown }).physicalNaming = { columns: "literal", tables: "snake_case" };
+ return root;
+}
+
+const NICKNAME = `{ "field.string": { "name": "nickname" } }`;
+const NICKNAME_VIEW = `{ "field.string": { "name": "nickname", "extends": "Account.nickname" } }`;
+
+function meta(withNickname: boolean, extra: string[] = []): string {
+ return `{ "metadata.root": { "package": "acme", "children": [
+ { "object.entity": { "name": "Account", "children": [
+ { "source.rdb": { "@table": "accounts" } },
+ { "field.long": { "name": "id" } },
+ { "field.string": { "name": "name" } },
+ ${withNickname ? NICKNAME + "," : ""}
+ { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }
+ ] } },
+ { "object.projection": { "name": "AccountView", "children": [
+ { "source.rdb": { "@kind": "view", "@table": "v_account" } },
+ { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } },
+ { "field.long": { "name": "id", "extends": "Account.id" } },
+ { "field.string": { "name": "name", "extends": "Account.name" } }
+ ${withNickname ? "," + NICKNAME_VIEW : ""}
+ ] } }
+ ${extra.map((e) => "," + e).join("\n")}
+ ] } }`;
+}
+
+// A view declared @unmanaged: someone else owns its DDL, so migrate never rewrites it.
+const UNMANAGED_VIEW = `{ "object.projection": { "name": "HandView", "children": [
+ { "source.rdb": { "@kind": "view", "@table": "v_hand", "@unmanaged": true } },
+ { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } },
+ { "field.long": { "name": "id", "extends": "Account.id" } }
+] } }`;
+
+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);
+beforeEach(async () => {
+ await sql.raw("DROP SCHEMA public CASCADE").execute(k);
+ await sql.raw("CREATE SCHEMA public").execute(k);
+});
+
+async function applyRaw(text: string): Promise {
+ for (const stmt of splitSqlStatements(text)) await sql.raw(stmt.endsWith(";") ? stmt : `${stmt};`).execute(k);
+}
+
+async function migrate(metaJson: string, allow: AllowOptions = {}) {
+ const root = (await new MetaDataLoader().load([new InMemoryStringSource(metaJson)])).root;
+ const expected = buildExpectedSchema(literalColumns(root), {
+ views: buildProjectionViews(literalColumns(root), { dialect: "postgres" }),
+ });
+ const result = await diff({
+ expected, actual: await introspectPostgres(k), dialect: "postgres",
+ viewReplaceProbe: postgresViewReplaceProbe(k), allow, unmanagedNames: collectUnmanagedNames(root),
+ });
+ const emittable = result.changes.filter((c) => c.status.state !== "blocked");
+ const out = emittable.length === 0 ? { up: "", down: "" } : emit(emittable, { dialect: "postgres" });
+ if (result.blocked.length === 0 && out.up.trim().length > 0) await applyRaw(out.up);
+ return { result, ...out };
+}
+
+describe("drop-column under a view the tool does not own — real Postgres", () => {
+ test("an unmanaged view that reads the dropped column is blocked and named; the DB is untouched", async () => {
+ await migrate(meta(true, [UNMANAGED_VIEW]));
+ await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "nickname" FROM "accounts"`).execute(k);
+
+ const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true });
+ const blocked = result.blocked.find((c) => c.kind === "drop-column");
+ expect(blocked?.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" });
+ expect(blocked?.status.blockedReason).toContain("v_hand");
+ expect(blocked?.status.blockedReason).toContain("accounts.nickname");
+
+ // The plan it refused is the one Postgres fails at apply.
+ await expect(migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true, dropColumnReadByView: true }))
+ .rejects.toThrow(/depend on it/);
+ }, 60_000);
+
+ test("an unmanaged view that does not read the dropped column is not blocked", async () => {
+ await migrate(meta(true, [UNMANAGED_VIEW]));
+ await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "name" FROM "accounts"`).execute(k);
+
+ const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true });
+ expect(result.blocked).toEqual([]);
+ await sql.raw(`SELECT * FROM "v_hand"`).execute(k);
+ }, 60_000);
+});
diff --git a/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts b/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts
new file mode 100644
index 0000000000..3d41581b3b
--- /dev/null
+++ b/server/typescript/packages/integration-tests/test/drop-column-view-sqlite.test.ts
@@ -0,0 +1,138 @@
+/**
+ * Dropping a column under a view, against a real SQLite.
+ *
+ * - A view the tool does not own (`@unmanaged`) that still reads the dropped column is
+ * refused at plan time and named; one that does not read it is not.
+ * - The down of a `drop-column` re-adds the column, so rolling back leaves the managed view
+ * the migration dropped and recreated queryable again. (D1 renders through the same path.)
+ */
+import { describe, test, expect, beforeEach, afterEach } 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 {
+ buildExpectedSchema, collectUnmanagedNames, diff, emit, introspectSqlite, type AllowOptions,
+} from "@metaobjectsdev/migrate-ts";
+import { buildProjectionViews } from "@metaobjectsdev/codegen-ts";
+import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";
+
+function literalColumns(root: T): T {
+ (root as unknown as { physicalNaming: unknown }).physicalNaming = { columns: "literal", tables: "snake_case" };
+ return root;
+}
+
+const TIMEOUT_MS = 60_000;
+const NICKNAME = `{ "field.string": { "name": "nickname" } }`;
+const NICKNAME_VIEW = `{ "field.string": { "name": "nickname", "extends": "Account.nickname" } }`;
+
+function meta(withNickname: boolean, extra: string[] = []): string {
+ return `{ "metadata.root": { "package": "acme", "children": [
+ { "object.entity": { "name": "Account", "children": [
+ { "source.rdb": { "@table": "accounts" } },
+ { "field.long": { "name": "id" } },
+ { "field.string": { "name": "name" } },
+ ${withNickname ? NICKNAME + "," : ""}
+ { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }
+ ] } },
+ { "object.projection": { "name": "AccountView", "children": [
+ { "source.rdb": { "@kind": "view", "@table": "v_account" } },
+ { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } },
+ { "field.long": { "name": "id", "extends": "Account.id" } },
+ { "field.string": { "name": "name", "extends": "Account.name" } }
+ ${withNickname ? "," + NICKNAME_VIEW : ""}
+ ] } }
+ ${extra.map((e) => "," + e).join("\n")}
+ ] } }`;
+}
+
+// A view declared @unmanaged: someone else owns its DDL, so migrate never rewrites it.
+const UNMANAGED_VIEW = `{ "object.projection": { "name": "HandView", "children": [
+ { "source.rdb": { "@kind": "view", "@table": "v_hand", "@unmanaged": true } },
+ { "identity.primary": { "name": "id", "extends": "Account.id", "@fields": "id" } },
+ { "field.long": { "name": "id", "extends": "Account.id" } }
+] } }`;
+
+let tmpDir: string;
+let k: Kysely>;
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), "drop-column-view-sqlite-"));
+ k = new Kysely({ dialect: new LibsqlDialect({ url: `file:${join(tmpDir, "test.db")}` }) });
+});
+afterEach(async () => {
+ await k.destroy();
+ rmSync(tmpDir, { recursive: true, force: true });
+});
+
+// libsql execute() is single-statement; no emitted body here carries an inner ";".
+async function applyRaw(text: string): Promise {
+ for (const stmt of text.split("\n").filter((l) => !l.startsWith("--")).join("\n").split(";").map((s) => s.trim()).filter(Boolean)) {
+ await sql.raw(stmt).execute(k);
+ }
+}
+
+async function migrate(metaJson: string, allow: AllowOptions = {}) {
+ const root = (await new MetaDataLoader().load([new InMemoryStringSource(metaJson)])).root;
+ const expected = buildExpectedSchema(literalColumns(root), {
+ dialect: "sqlite",
+ views: buildProjectionViews(literalColumns(root), { dialect: "sqlite" }),
+ });
+ const actual = await introspectSqlite(k);
+ const result = await diff({ expected, actual, dialect: "sqlite", allow, unmanagedNames: collectUnmanagedNames(root) });
+ const emittable = result.changes.filter((c) => c.status.state !== "blocked");
+ const out = emittable.length === 0
+ ? { up: "", down: "" }
+ : emit(emittable, {
+ dialect: "sqlite", expectedSchema: expected, actualSchema: actual,
+ ...(actual.meta !== undefined && { actualMeta: actual.meta }),
+ });
+ if (result.blocked.length === 0 && out.up.trim().length > 0) await applyRaw(out.up);
+ return { result, ...out };
+}
+
+describe("drop-column under a view — real SQLite", () => {
+ test("an unmanaged view that reads the dropped column is blocked and named; the DB is untouched", async () => {
+ await migrate(meta(true, [UNMANAGED_VIEW]));
+ await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "nickname" FROM "accounts"`).execute(k);
+
+ const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true });
+ const blocked = result.blocked.find((c) => c.kind === "drop-column");
+ expect(blocked?.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" });
+ expect(blocked?.status.blockedReason).toContain("v_hand");
+ expect(blocked?.status.blockedReason).toContain("accounts.nickname");
+
+ // With the flag the plan is allowed through.
+ await expect(migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true, dropColumnReadByView: true }))
+ .rejects.toThrow(/v_hand/); // SQLite then refuses the drop at apply: the view still reads it
+ }, TIMEOUT_MS);
+
+ test("an unmanaged view that does not read the dropped column is not blocked", async () => {
+ await migrate(meta(true, [UNMANAGED_VIEW]));
+ await sql.raw(`CREATE VIEW "v_hand" AS SELECT "id", "name" FROM "accounts"`).execute(k);
+
+ const { result } = await migrate(meta(false, [UNMANAGED_VIEW]), { dropColumn: true });
+ expect(result.blocked).toEqual([]);
+ await sql.raw(`SELECT * FROM "v_hand"`).execute(k);
+ }, TIMEOUT_MS);
+
+ test("rolling back a drop-column re-adds it, and the managed view is queryable again", async () => {
+ await migrate(meta(true));
+ await sql.raw(`INSERT INTO "accounts" ("id","name","nickname") VALUES (1,'a','n1'),(2,'b','n2')`).execute(k);
+
+ const { result, down } = await migrate(meta(false), { dropColumn: true, dropView: true });
+ expect(result.blocked).toEqual([]);
+ expect(down).toContain(`ADD COLUMN "nickname"`);
+ // Applied: the column and the view's column are gone.
+ await expect(sql.raw(`SELECT "nickname" FROM "v_account"`).execute(k)).rejects.toThrow();
+
+ await applyRaw(down);
+ const rows = await sql.raw(`SELECT * FROM "v_account" ORDER BY "id"`).execute(k);
+ expect(rows.rows).toHaveLength(2);
+ expect(Object.keys(rows.rows[0] as object)).toContain("nickname");
+ // The data is not restored, and the migration says so.
+ expect((rows.rows[0] as { nickname: unknown }).nickname).toBeNull();
+ expect(down).toMatch(/column data is not restored/i);
+ }, TIMEOUT_MS);
+});
diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts
index d73e4b0c30..ef9640c4b8 100644
--- a/server/typescript/packages/migrate-ts/src/diff/index.ts
+++ b/server/typescript/packages/migrate-ts/src/diff/index.ts
@@ -317,6 +317,12 @@ export async function diff(
// that is exactly the object a cascade must not destroy silently.
annotateViewDropDependents(args.actual.views, changes);
+ // A live view this tool neither rewrites nor drops stays in place and blocks a column drop
+ // at apply. Whether a planned drop-view/replace-view is itself blocked is decided by the
+ // statuses, so assign them first; applyStatus below assigns them again over the final list.
+ applyStatus(changes, args.allow ?? {});
+ annotateUnownedColumnReaders(args.actual.views, changes);
+
// Pass 3: column renames (table renames were resolved in Pass 1c).
await detectColumnRenames(changes, args.onAmbiguous, args.renames);
// Pass 3b: a renamed column carries the constraints and indexes named after it.
@@ -1249,6 +1255,38 @@ function annotateViewDropDependents(actual: readonly ViewDescriptor[], changes:
}
}
+/**
+ * Mark each `drop-column` that a live view this migration leaves in place still reads.
+ *
+ * A view with a drop-view or replace-view in `changes` that is not blocked is dropped or
+ * rewritten around the change, so it does not strand the drop. Every other live view
+ * does: a declared-`@unmanaged` one, one in a schema the model does not scope, a hand-made
+ * one whose drop-view is blocked. A view with no recorded body cannot be matched, so it is
+ * not blocked on.
+ */
+function annotateUnownedColumnReaders(
+ actual: readonly ViewDescriptor[],
+ changes: Change[],
+): void {
+ const handled = new Set();
+ for (const c of changes) {
+ if (c.status.state === "blocked") continue;
+ if (c.kind === "drop-view") handled.add(viewIdentity({ name: c.view, ...schemaSpread(c.schema) }));
+ else if (c.kind === "replace-view") handled.add(viewIdentity({ name: c.view.name, ...schemaSpread(c.schema) }));
+ }
+ const unowned = actual.filter((v) => v.sql !== undefined && !handled.has(viewIdentity(v)));
+ if (unowned.length === 0) return;
+ const liveName = liveTableNames(changes);
+ for (const c of changes) {
+ if (c.kind !== "drop-column") continue;
+ const table = liveName(c.table);
+ const readBy = unowned
+ .filter((v) => sqlNamesIdentifier(v.sql!, table) && sqlNamesIdentifier(v.sql!, c.column))
+ .map((v) => (v.schema !== undefined ? `${v.schema}.${v.name}` : v.name));
+ if (readBy.length > 0) c.readBy = readBy;
+ }
+}
+
/**
* Postgres: a view reading a column blocks `ALTER … ALTER COLUMN TYPE`, a drop and a rename
* of it, so those force the view to be dropped-before / recreated-after. A new default or a
diff --git a/server/typescript/packages/migrate-ts/src/diff/status.ts b/server/typescript/packages/migrate-ts/src/diff/status.ts
index 672bb42b17..a777fc390f 100644
--- a/server/typescript/packages/migrate-ts/src/diff/status.ts
+++ b/server/typescript/packages/migrate-ts/src/diff/status.ts
@@ -55,8 +55,18 @@ function blockFor(
recreatedViews: ReadonlySet,
): Block | null {
switch (c.kind) {
- case "drop-column":
- return gate(allow, "dropColumn", "destructive: drop-column not allowed (pass allow.dropColumn)");
+ case "drop-column": {
+ const blocked = gate(allow, "dropColumn", "destructive: drop-column not allowed (pass allow.dropColumn)");
+ if (blocked !== null) return blocked;
+ const readBy = c.readBy ?? [];
+ if (readBy.length > 0) {
+ return gate(allow, "dropColumnReadByView",
+ `drop-column ${c.table}.${c.column} is still read by ${readBy.length} view(s) MetaObjects does not own `
+ + `(${readBy.join(", ")}). It never rewrites them, so the drop fails at apply. `
+ + `Change the view(s) first, or pass allow.dropColumnReadByView`);
+ }
+ return null;
+ }
case "drop-table":
return gate(allow, "dropTable", "destructive: drop-table not allowed (pass allow.dropTable)");
case "drop-index":
diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts
index afeeb6811e..9689dafbf0 100644
--- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts
+++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts
@@ -430,6 +430,33 @@ export function renderCreateView(v: ViewDescriptor): string {
return `CREATE VIEW ${quote(v.name)} AS\n${v.sql};`;
}
+/**
+ * Re-add a dropped column from the descriptor the diff kept (`restore`). The data is not
+ * restored. SQLite refuses `ADD COLUMN … NOT NULL` with no default, so such a column comes
+ * back nullable rather than leaving the rollback unable to run.
+ */
+function renderDropColumnDown(c: Extract): string {
+ if (c.restore === undefined) {
+ return `-- WARNING: down migration cannot restore data\n-- TODO: re-add dropped column "${c.column}" manually with original type/nullable/default`;
+ }
+ const { default: dflt, identity, ...rest } = c.restore;
+ const nonConstant = dflt?.kind === "expr" || (dflt === undefined && identity === "uuid");
+ const literal = dflt?.kind === "literal" ? dflt : undefined;
+ const loosen = !c.restore.nullable && literal === undefined;
+ const column: ColumnDescriptor = {
+ ...rest,
+ nullable: c.restore.nullable || loosen,
+ ...(literal !== undefined ? { default: literal } : {}),
+ ...(identity === "increment" ? { identity } : {}),
+ };
+ return [
+ `ALTER TABLE ${quote(c.table)} ADD COLUMN ${renderColumnInline(column)};`,
+ "-- NOTE: column data is not restored by this down migration.",
+ ...(nonConstant ? [`-- NOTE: ${quote(c.column)} had a non-constant default; SQLite cannot add a column with one to a populated table, so the default is omitted.`] : []),
+ ...(loosen ? [`-- NOTE: ${quote(c.column)} was NOT NULL with no default; SQLite cannot add it that way, so it returns nullable.`] : []),
+ ].join("\n");
+}
+
function renderDownNative(c: Change): string {
switch (c.kind) {
case "create-table": return `DROP TABLE ${quote(c.table.name)};`;
@@ -439,7 +466,7 @@ function renderDownNative(c: Change): string {
return `ALTER TABLE ${quote(c.to)} RENAME TO ${quote(c.from)};`;
}
case "add-column": return `ALTER TABLE ${quote(c.table)} DROP COLUMN ${quote(c.column.name)};`;
- case "drop-column": return `-- WARNING: down migration cannot restore data\n-- TODO: re-add dropped column "${c.column}" manually`;
+ case "drop-column": return renderDropColumnDown(c);
case "rename-column": {
assertNoCarriedRenames(c);
return `ALTER TABLE ${quote(c.table)} RENAME COLUMN ${quote(c.to)} TO ${quote(c.from)};`;
diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts
index b08fb361db..a7527d5ce8 100644
--- a/server/typescript/packages/migrate-ts/src/types.ts
+++ b/server/typescript/packages/migrate-ts/src/types.ts
@@ -252,7 +252,15 @@ export type Change =
status: ChangeStatus;
}
| { kind: "add-column"; table: string; schema?: string; column: ColumnDescriptor; status: ChangeStatus }
- | { kind: "drop-column"; table: string; schema?: string; column: string; restore?: ColumnDescriptor; status: ChangeStatus }
+ | {
+ kind: "drop-column"; table: string; schema?: string; column: string; restore?: ColumnDescriptor; status: ChangeStatus;
+ /**
+ * Live views this tool does not own (declared `@unmanaged`, or outside the scoped
+ * schemas) whose recorded body names the dropped column. The drop fails at apply
+ * while they stand, so it is blocked pending `allow.dropColumnReadByView`.
+ */
+ readBy?: readonly string[];
+ }
| {
kind: "rename-column"; table: string; schema?: string; from: string; to: string;
/**
@@ -471,6 +479,14 @@ export interface AllowOptions {
* dependents snapshot rather than silently cascading.
*/
dropViewCascade?: boolean;
+ /**
+ * Gates dropping a column that a live view this tool does NOT own still reads (a view
+ * declared `@unmanaged`, or one outside the scoped schemas). The tool never rewrites
+ * such a view, so the drop fails at apply on Postgres (`cannot drop column … other
+ * objects depend on it`) and on SQLite (`error in view … after drop column`). Granting
+ * this lets the plan through, for when the view is dealt with first or in the same release.
+ */
+ dropColumnReadByView?: boolean;
/**
* Gates overwriting an existing view that carries NO MetaObjects fingerprint —
* i.e. taking ownership of it. It is either hand-written or predates
diff --git a/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts b/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts
new file mode 100644
index 0000000000..8c76c483ee
--- /dev/null
+++ b/server/typescript/packages/migrate-ts/test/drop-column-unowned-view.test.ts
@@ -0,0 +1,138 @@
+/**
+ * A view this tool does not own is never rewritten, so it strands a column drop at apply.
+ * The plan must refuse and name the view; a view that does not read the column, or has no
+ * recorded body, must not block. The SQLite down must re-add the dropped column.
+ */
+import { describe, test, expect } from "bun:test";
+import { Database } from "bun:sqlite";
+import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";
+import type { MetaData } from "@metaobjectsdev/metadata";
+import { buildExpectedSchema } from "../src/expected-schema.js";
+import { diff } from "../src/diff/index.js";
+import { emit } from "../src/emit/index.js";
+import type { SchemaSnapshot, ViewDescriptor } from "../src/types.js";
+
+async function load(fields: string): Promise {
+ return (await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({
+ "metadata.root": { children: [{
+ "object.entity": { name: "Account", children: [
+ { "field.long": { name: "id" } },
+ { "field.string": { name: "name" } },
+ ...JSON.parse(fields),
+ { "source.rdb": { name: "src", "@table": "accounts" } },
+ { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } },
+ ] },
+ }] },
+ }))])).root;
+}
+
+const NICKNAME = '[{"field.string":{"name":"nickname"}}]';
+
+function withViews(s: SchemaSnapshot, views: ViewDescriptor[]): SchemaSnapshot {
+ return { ...s, views };
+}
+
+for (const dialect of ["postgres", "sqlite"] as const) {
+ describe(`drop-column under a view the tool does not own (${dialect})`, () => {
+ async function plan(views: ViewDescriptor[], unmanagedNames: string[], allow = {}) {
+ const prior = withViews(buildExpectedSchema(await load(NICKNAME), { dialect }), views);
+ const next = buildExpectedSchema(await load("[]"), { dialect });
+ return diff({ expected: next, actual: prior, dialect, allow: { dropColumn: true, ...allow }, unmanagedNames });
+ }
+ const schema = dialect === "postgres" ? "public" : undefined;
+ const view = (sql: string | undefined): ViewDescriptor => ({
+ name: "v_hand", ...(schema !== undefined ? { schema } : {}), ...(sql !== undefined ? { sql } : {}),
+ });
+ const id = "public.v_hand"; // viewIdentity defaults an absent schema to "public"
+
+ test("an @unmanaged view that reads the column blocks the drop and is named", async () => {
+ const r = await plan([view("SELECT id, nickname FROM accounts")], [id]);
+ expect(r.blocked.length).toBe(1);
+ const status = r.blocked[0]!.status;
+ expect(status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" });
+ expect((status as { blockedReason: string }).blockedReason).toContain("v_hand");
+ expect((status as { blockedReason: string }).blockedReason).toContain("accounts.nickname");
+ });
+
+ test("allow.dropColumnReadByView lifts the block", async () => {
+ const r = await plan([view("SELECT id, nickname FROM accounts")], [id], { dropColumnReadByView: true });
+ expect(r.blocked).toEqual([]);
+ });
+
+ test("an @unmanaged view that does not read the column does not block", async () => {
+ const r = await plan([view("SELECT id, name FROM accounts")], [id]);
+ expect(r.blocked).toEqual([]);
+ });
+
+ test("a hand-made view (declared by no metadata) that reads the column blocks the drop while its drop-view is blocked", async () => {
+ const r = await plan([view("SELECT id, nickname FROM accounts")], []);
+ const dropColumn = r.changes.find((c) => c.kind === "drop-column")!;
+ expect(dropColumn.status).toMatchObject({ state: "blocked", blockedBy: "dropColumnReadByView" });
+ expect((dropColumn.status as { blockedReason: string }).blockedReason).toContain("v_hand");
+ });
+
+ test("a hand-made view whose drop-view is allowed is dropped around the change, so it does not block the drop", async () => {
+ const r = await plan([view("SELECT id, nickname FROM accounts")], [], { dropView: true });
+ expect(r.blocked).toEqual([]);
+ });
+
+ test("a view with no recorded body does not block", async () => {
+ const r = await plan([view(undefined)], [id]);
+ expect(r.blocked).toEqual([]);
+ });
+ });
+}
+
+describe("sqlite down of drop-column", () => {
+ test("re-adds the column with its type and says the data is not restored", async () => {
+ const prior = buildExpectedSchema(await load(NICKNAME), { dialect: "sqlite" });
+ const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" });
+ const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } });
+ const { up, down } = emit(r.changes, { dialect: "sqlite" });
+ expect(up).toContain('DROP COLUMN "nickname"');
+ expect(down).toContain('ALTER TABLE "accounts" ADD COLUMN "nickname"');
+ expect(down).toMatch(/column data is not restored/i);
+ expect(down).not.toMatch(/TODO/);
+ });
+
+ test("D1 renders the same down", async () => {
+ const prior = buildExpectedSchema(await load(NICKNAME), { dialect: "d1" });
+ const next = buildExpectedSchema(await load("[]"), { dialect: "d1" });
+ const r = await diff({ expected: next, actual: prior, dialect: "d1", allow: { dropColumn: true } });
+ const { down } = emit(r.changes, { dialect: "d1", expectedSchema: next, actualSchema: prior });
+ expect(down).toContain('ALTER TABLE "accounts" ADD COLUMN "nickname"');
+ });
+
+ test("a NOT NULL column with no default returns nullable, since SQLite cannot add it otherwise", async () => {
+ const prior = buildExpectedSchema(await load('[{"field.string":{"name":"nickname","@required":true}}]'), { dialect: "sqlite" });
+ const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" });
+ const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } });
+ const { down } = emit(r.changes, { dialect: "sqlite" });
+ expect(down).toMatch(/ADD COLUMN "nickname" \w+(\(\d+\))?;/);
+ expect(down).not.toContain("NOT NULL;");
+ expect(down).toMatch(/NOT NULL with no default/);
+ });
+ test("rollback applies to a populated table when the dropped column had an expression or uuid default", async () => {
+ // Oracle: SQLite itself refuses ADD COLUMN with a non-constant default on a table holding rows.
+ const prior = buildExpectedSchema(await load(
+ '[{"field.timestamp":{"name":"createdAt","@required":true}},{"field.uuid":{"name":"token","@required":true}}]',
+ ), { dialect: "sqlite" });
+ const createdAt = prior.tables[0]!.columns.find((c) => c.name === "created_at")!;
+ createdAt.default = { kind: "expr", value: "now()" };
+ const token = prior.tables[0]!.columns.find((c) => c.name === "token")!;
+ token.identity = "uuid";
+ delete token.default;
+ const next = buildExpectedSchema(await load("[]"), { dialect: "sqlite" });
+ const r = await diff({ expected: next, actual: prior, dialect: "sqlite", allow: { dropColumn: true } });
+ const { down } = emit(r.changes, { dialect: "sqlite" });
+
+ const db = new Database(":memory:");
+ db.run('CREATE TABLE "accounts" ("id" INTEGER PRIMARY KEY, "name" TEXT)');
+ db.run(`INSERT INTO "accounts" ("name") VALUES ('a')`);
+ expect(() => db.exec(down)).not.toThrow();
+ const cols = (db.query('PRAGMA table_info("accounts")').all() as { name: string }[]).map((c) => c.name);
+ expect(cols).toContain("created_at");
+ expect(cols).toContain("token");
+ expect(down).toMatch(/non-constant default/);
+ });
+});
diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts
index c33e5397be..40d127843d 100644
--- a/server/typescript/packages/sdk/src/config.ts
+++ b/server/typescript/packages/sdk/src/config.ts
@@ -45,6 +45,7 @@ export const AllowTokenEnum = z.enum([
"drop-check",
"drop-view",
"drop-view-cascade",
+ "drop-column-read-by-view",
"adopt-view",
"nullable-to-not-null",
"drop-identity-default",
From 2049f5efd420204a027b474f08c4807ebaf8944d Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Tue, 3 Nov 2026 23:51:00 -0500
Subject: [PATCH 03/51] fix(metadata): exempt read-only @sql views from
column-name collision check (#528)
* fix(metadata): exempt @sql views from the duplicate-column check in every port
* no-mistakes(review): Narrow SQL-view column exemption to read-only objects; gate wording
* no-mistakes(review): Refresh conformance fixture count to 426
* no-mistakes(document): Refreshed collision error-code description; other docs already current
---
AGENTS.md | 2 +-
CHANGELOG.md | 11 +++
docs/CONFORMANCE.md | 6 +-
examples/showcase/site-payload.json | 2 +-
fixtures/conformance/ERROR-CODES.json | 2 +-
.../expected.json | 39 ++++++++
.../input/meta.demo.json | 16 +++
.../providers.json | 1 +
.../expected-errors.json | 15 +++
.../input/meta.demo.json | 16 +++
.../providers.json | 1 +
.../expected-errors.json | 15 +++
.../input/meta.demo.json | 18 ++++
.../providers.json | 1 +
.../ColumnNameCollisionMessageTests.cs | 68 +++++++++++++
.../MetaObjects/Loader/ValidationPasses.cs | 20 +++-
.../metaobjects/loader/ValidationPhase.java | 29 +++++-
.../ColumnNameCollisionMessageTest.java | 98 +++++++++++++++++++
.../metaobjects/loader/validation_passes.py | 28 +++++-
.../test_column_name_collision_message.py | 77 +++++++++++++++
.../metadata/src/loader/validation-passes.ts | 28 +++++-
.../column-name-collision-message.test.ts | 26 +++++
22 files changed, 505 insertions(+), 14 deletions(-)
create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json
create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json
create mode 100644 fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json
create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json
create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json
create mode 100644 fixtures/conformance/error-column-name-collision-derived-view/providers.json
create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json
create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json
create mode 100644 fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json
create mode 100644 server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs
create mode 100644 server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java
create mode 100644 server/python/tests/unit/test_column_name_collision_message.py
create mode 100644 server/typescript/packages/metadata/test/column-name-collision-message.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 31c4c7fa80..ee01045468 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (423 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (426 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical.
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b13247ac0..d218fd9a9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,17 @@ here.**
### Fixed
+- **`ERR_COLUMN_NAME_COLLISION` no longer rejects a read-only view whose columns come from `@sql`.**
+ The 1.2.0 check treated every field of a sourced object as a column MetaObjects creates. For a
+ `source.rdb @kind: view` with an `@sql` body, the author's SQL defines the columns and the fields
+ only read them, so two fields on one column are legal and nothing can be written. That object is
+ now exempt in all four ports (TypeScript, Java, C#, Python), provided every source of the object
+ is read-only. A derived view (no `@sql`), which emits a select list from its fields, and an object
+ with a writable table source plus an `@sql` view replica are still checked. When both colliding fields already carry an
+ explicit `@column`, the message now says to rename one field or point one `@column` at a different
+ column, instead of suggesting a `@column` they already have. The error code is unchanged. New
+ conformance fixtures: `column-name-shared-in-sql-view-ok`, `error-column-name-collision-derived-view` and
+ `error-column-name-collision-table-with-sql-view`.
- **`meta migrate` refuses, at plan time, to drop a column a view it does not own still reads.**
With `--from-db`, a declared-`@unmanaged` view or one outside the scoped schemas whose live body
names the dropped column now blocks the `drop-column`, and the message names the view and the
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index d7e9157567..16d963fd0e 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) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 426 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ |
@@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker.
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (423)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (426)
| Fixture prefix | Feature doc |
|---|---|
@@ -611,7 +611,7 @@ files into a real Cube.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 426 + yaml 16 + verify 45
+ render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 +
dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the
`cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index 6e9ec3f63d..7330d646f0 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,7 +7,7 @@
"metamodel": "1.2"
},
"counts": {
- "fixtures": 423,
+ "fixtures": 426,
"corpora": 35,
"baseTypes": 17
},
diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json
index d2c931bbad..278b1b50f0 100644
--- a/fixtures/conformance/ERROR-CODES.json
+++ b/fixtures/conformance/ERROR-CODES.json
@@ -38,7 +38,7 @@
"ERR_EXTENDS_ORIGIN_MISMATCH": "FR-024 (ADR-0029 decision 7): a field declares both an entity-nested extends (shape lineage) and an origin.passthrough @from (data lineage) and they disagree — the resolved @from target is not the field's resolved extends target (nor anywhere on its extends chain). Host-agnostic (projections, entities, values). origin.aggregate is never judged (it computes something new); a top-level abstract extends target is never judged (shape-only reuse makes no lineage claim).",
"ERR_PASSTHROUGH_TYPE_MISMATCH": "#185: a field carrying origin.passthrough @from: \"Entity.field\" declares a field. or array-ness that differs from its resolved source field — a passthrough forwards the value unchanged, so its type must be identical. Host-agnostic (projections, entities, values, stored-proc parameter refs). Nullability is NOT judged (a view over an outer join legitimately widens NOT NULL → nullable). Opt out of a deliberate type change with @convert: true on the origin.passthrough (an acknowledgement — it does not generate a cast); real type-converting projections are origin.expression's job (#159).",
"ERR_DERIVED_FIELD_NO_READ_SOURCE": "FR-024 (spec §7): an object.entity field carrying an origin.* child is derived (read-only) and must be providable — the entity must declare at least one source with a read-only @kind (view/materializedView/storedProc/tableFunction, e.g. a @role replica view beside the table primary). Table-only or source-less entities with origin-bearing fields error on the field. Projections and object.value hosts are exempt. Until the Phase-E B4b cutover removes view-primary entities, a read-only-kind PRIMARY source also counts as providable (legacy spelling).",
- "ERR_COLUMN_NAME_COLLISION": "Two fields of one stored object (a concrete object declaring a source) resolve to the same physical column name: snake_case folds `userId` and `userID` into `user_id`, or two fields share an explicit @column. Only RESOLVED physical names are compared (explicit @column honoured, inherited fields included, derived and source-less objects exempt). The message names both fields and the column.",
+ "ERR_COLUMN_NAME_COLLISION": "Two fields of one stored object (a concrete object declaring a source) resolve to the same physical column name: snake_case folds `userId` and `userID` into `user_id`, or two fields share an explicit @column. Only RESOLVED physical names are compared (explicit @column honoured, inherited fields included, derived and source-less objects exempt, and so is an object whose every source is read-only and at least one is a `@sql` view, since the author's SQL defines those columns). The message names both fields and the column.",
"ERR_INVALID_TEMPLATE": "A template (prompt/output) declares a @payloadRef that does not resolve, or @requiredSlots that are not fields on its payload.",
"ERR_INVALID_RELATIONSHIP": "FR-017: a M:N relationship's slim vocabulary is invalid — @through does not resolve to a junction declaring two identity.reference children (ADR-0042: @through resolves package-locally when bare, exactly when FQN — a bare cross-package @through no longer binds elsewhere), @sourceRefField does not match one of them, or a M:N-only attr (@through/@sourceRefField/@symmetric) is set on a non-M:N (1:N / @cardinality:one) relationship; OR a relationship's @objectRef does not resolve to any object in the loaded tree (a dangling target).",
"ERR_INVALID_REFERENCE": "An identity.reference @references names an FK target object that does not resolve to any object in the loaded tree (a dangling cross-reference between metadata).",
diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json
new file mode 100644
index 0000000000..388777ebf5
--- /dev/null
+++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/expected.json
@@ -0,0 +1,39 @@
+{
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ {
+ "object.projection": {
+ "name": "UserView",
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@sql": "SELECT u.id, u.username FROM app_user u",
+ "@view": "user_view"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id",
+ "@column": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "userName",
+ "@column": "username"
+ }
+ },
+ {
+ "field.string": {
+ "name": "displayName",
+ "@column": "username"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json
new file mode 100644
index 0000000000..5314b05bf1
--- /dev/null
+++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/input/meta.demo.json
@@ -0,0 +1,16 @@
+{
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ { "object.projection": {
+ "name": "UserView",
+ "children": [
+ { "source.rdb": { "@kind": "view", "@view": "user_view", "@sql": "SELECT u.id, u.username FROM app_user u" } },
+ { "field.long": { "name": "id", "@column": "id" } },
+ { "field.string": { "name": "userName", "@column": "username" } },
+ { "field.string": { "name": "displayName", "@column": "username" } }
+ ]
+ }}
+ ]
+ }
+}
diff --git a/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json b/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json
new file mode 100644
index 0000000000..aefa027b6a
--- /dev/null
+++ b/fixtures/conformance/column-name-shared-in-sql-view-ok/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types", "metaobjects-db"]
diff --git a/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json b/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json
new file mode 100644
index 0000000000..a19f7ad425
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-derived-view/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_COLUMN_NAME_COLLISION",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.demo.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['object.projection'].children[3]['field.string']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json b/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json
new file mode 100644
index 0000000000..50ac7e9092
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-derived-view/input/meta.demo.json
@@ -0,0 +1,16 @@
+{
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ { "object.projection": {
+ "name": "UserView",
+ "children": [
+ { "source.rdb": { "@kind": "view", "@view": "user_view" } },
+ { "field.long": { "name": "id", "@column": "id" } },
+ { "field.string": { "name": "userName", "@column": "username" } },
+ { "field.string": { "name": "displayName", "@column": "username" } }
+ ]
+ }}
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-column-name-collision-derived-view/providers.json b/fixtures/conformance/error-column-name-collision-derived-view/providers.json
new file mode 100644
index 0000000000..aefa027b6a
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-derived-view/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types", "metaobjects-db"]
diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json
new file mode 100644
index 0000000000..ce96277156
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_COLUMN_NAME_COLLISION",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.demo.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[4]['field.string']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json
new file mode 100644
index 0000000000..1c87fd5e2a
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/input/meta.demo.json
@@ -0,0 +1,18 @@
+{
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ { "object.entity": {
+ "name": "Account",
+ "children": [
+ { "source.rdb": { "@kind": "table", "@table": "account" } },
+ { "source.rdb": { "@kind": "view", "@view": "account_view", "@role": "replica", "@sql": "SELECT a.id, a.username FROM account a" } },
+ { "field.long": { "name": "id", "@column": "id" } },
+ { "field.string": { "name": "userName", "@column": "username" } },
+ { "field.string": { "name": "displayName", "@column": "username" } },
+ { "identity.primary": { "name": "id", "@fields": ["id"] } }
+ ]
+ }}
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json b/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json
new file mode 100644
index 0000000000..aefa027b6a
--- /dev/null
+++ b/fixtures/conformance/error-column-name-collision-table-with-sql-view/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types", "metaobjects-db"]
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs
new file mode 100644
index 0000000000..cb2d329912
--- /dev/null
+++ b/server/csharp/MetaObjects.Conformance.Tests/ColumnNameCollisionMessageTests.cs
@@ -0,0 +1,68 @@
+// ERR_COLUMN_NAME_COLLISION advice wording and the @sql view exemption.
+//
+// Mirrors typescript/packages/metadata/test/column-name-collision-message.test.ts.
+
+using MetaObjects;
+using MetaObjects.Loader;
+using Xunit;
+
+namespace MetaObjects.Conformance.Tests;
+
+public class ColumnNameCollisionMessageTests
+{
+ private static string[] CollisionMessages(string sourceChild, string fieldA, string fieldB)
+ {
+ var doc = $$"""
+ { "metadata.root": { "package": "demo", "children": [
+ { "object.entity": { "name": "Account", "children": [
+ {{sourceChild}},
+ { "field.long": { "name": "id" } },
+ {{fieldA}},
+ {{fieldB}},
+ { "identity.primary": { "name": "id", "@fields": ["id"] } }
+ ] } }
+ ] } }
+ """;
+ return MetaDataLoader.FromString(doc, MetaDataFormat.Json).Errors
+ .Where(e => e.Code == ErrorCode.ERR_COLUMN_NAME_COLLISION)
+ .Select(e => e.Message)
+ .ToArray();
+ }
+
+ private const string Table = """{ "source.rdb": { "@kind": "table", "@table": "account" } }""";
+
+ [Fact]
+ public void Two_explicit_columns_on_one_column_do_not_suggest_adding_a_column()
+ {
+ var msg = Assert.Single(CollisionMessages(Table,
+ """{ "field.string": { "name": "userName", "@column": "username" } }""",
+ """{ "field.string": { "name": "displayName", "@column": "username" } }"""));
+ Assert.Contains("point one @column at a different column", msg);
+ Assert.DoesNotContain("give one an explicit @column", msg);
+ }
+
+ [Fact]
+ public void Implicit_collision_still_suggests_an_explicit_column()
+ {
+ var msg = Assert.Single(CollisionMessages(Table,
+ """{ "field.string": { "name": "userId" } }""",
+ """{ "field.string": { "name": "userID" } }"""));
+ Assert.Contains("give one an explicit @column", msg);
+ }
+
+ [Fact]
+ public void Sql_view_may_share_a_column_between_fields()
+ {
+ var doc = """
+ { "metadata.root": { "package": "demo", "children": [
+ { "object.projection": { "name": "UserView", "children": [
+ { "source.rdb": { "@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t" } },
+ { "field.long": { "name": "id", "@column": "id" } },
+ { "field.string": { "name": "userName", "@column": "username" } },
+ { "field.string": { "name": "displayName", "@column": "username" } }
+ ] } }
+ ] } }
+ """;
+ Assert.Empty(MetaDataLoader.FromString(doc, MetaDataFormat.Json).Errors);
+ }
+}
diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
index 13f06857b2..7d11a0ca44 100644
--- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs
+++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
@@ -4445,6 +4445,19 @@ void Walk(MetaData node)
// declaring at least one source (a source-less object generates nothing); derived
// fields and field.object (may flatten to several columns) are skipped.
// ADR-0039: effective children, so an inherited field collides like an own one.
+ // Exempt: an object whose every source is read-only and at least one is a
+ // source.rdb @kind: view with an @sql body. The author's SQL defines that view's columns
+ // and the fields only READ them, so two fields on one column create no duplicate column
+ // and nothing can be written. A derived view (no @sql) emits a select list from its
+ // fields, and an object with a writable source has a real table whose columns
+ // MetaObjects creates; both stay checked.
+ private static bool ReadsThroughSqlView(MetaData obj)
+ {
+ var sources = obj.Children().OfType().ToList();
+ return sources.All(s => s.IsReadOnly()) &&
+ sources.Any(s => s.EffectiveKind == SourceConstants.SOURCE_KIND_VIEW && s.SqlBody is not null);
+ }
+
public static IReadOnlyList ValidateColumnNameCollisions(MetaData root)
{
var errors = new List();
@@ -4452,6 +4465,7 @@ public static IReadOnlyList ValidateColumnNameCollisions(MetaData roo
{
if (obj.IsAbstract) continue;
if (!obj.Children().Any(c => c.Type == TYPE_SOURCE)) continue;
+ if (ReadsThroughSqlView(obj)) continue;
var seen = new Dictionary(StringComparer.Ordinal);
foreach (var field in obj.Children().OfType())
{
@@ -4464,8 +4478,10 @@ public static IReadOnlyList ValidateColumnNameCollisions(MetaData roo
}
errors.Add(new MetaError(
$"fields \"{first.Name}\" and \"{field.Name}\" on \"{obj.Name}\" both resolve to " +
- $"physical column \"{column}\". Rename one field, or give one an explicit @column " +
- "so the two columns differ.",
+ $"physical column \"{column}\". " +
+ (first.DbColumn is { Length: > 0 } && field.DbColumn is { Length: > 0 }
+ ? "Rename one field, or point one @column at a different column."
+ : "Rename one field, or give one an explicit @column so the two columns differ."),
ErrorCode.ERR_COLUMN_NAME_COLLISION,
Envelope: field.Source));
}
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 1ddc61efbc..f4c4b8c615 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
@@ -5409,11 +5409,34 @@ private static void walkRetiredRequirementLinks(MetaData node) {
* generates nothing); derived fields and {@code field.object} (may flatten to several
* columns) are skipped. ADR-0039: resolving accessors, so an inherited field collides like
* an own one.
+ *
+ *
Exempt: an object whose every source is read-only and at least one is a
+ * {@code source.rdb @kind: view} with an {@code @sql} body. The author's SQL defines that
+ * view's columns and the fields only READ them, so two fields on one column create no
+ * duplicate column and nothing can be written. A derived view (no {@code @sql}) emits a
+ * select list from its fields, and an object with a writable source has a real table whose
+ * columns MetaObjects creates; both stay checked.
*/
+ private static boolean readsThroughSqlView(MetaObject obj) {
+ boolean sqlView = false;
+ for (MetaSource s : obj.getChildren(MetaSource.class, true)) {
+ if (!s.isReadOnly()) return false;
+ if (MetaSource.KIND_VIEW.equals(s.getEffectiveKind()) && s.getSqlBody() != null) sqlView = true;
+ }
+ return sqlView;
+ }
+
+ private static boolean hasExplicitColumn(MetaField> field) {
+ if (!field.hasMetaAttr(CoreDBMetaDataProvider.COLUMN, true)) return false;
+ String v = field.getMetaAttr(CoreDBMetaDataProvider.COLUMN, true).getValueAsString();
+ return v != null && !v.isEmpty();
+ }
+
static void validateColumnNameCollisions(MetaRoot root) {
for (MetaObject obj : root.getChildren(MetaObject.class, false)) {
if (isAbstract(obj)) continue;
if (obj.getChildren(MetaSource.class, true).isEmpty()) continue;
+ if (readsThroughSqlView(obj)) continue;
java.util.Map> seen = new java.util.HashMap<>();
for (MetaField> field : obj.getChildren(MetaField.class, true)) {
if (ObjectField.SUBTYPE_OBJECT.equals(field.getSubType()) || field.isDerived()) continue;
@@ -5424,8 +5447,10 @@ static void validateColumnNameCollisions(MetaRoot root) {
ErrorMessageConstants.ERR_COLUMN_NAME_COLLISION
+ ": fields \"" + first.getName() + "\" and \"" + field.getName()
+ "\" on \"" + obj.getName() + "\" both resolve to physical column \""
- + column + "\". Rename one field, or give one an explicit @column so the"
- + " two columns differ.",
+ + column + "\". "
+ + (hasExplicitColumn(first) && hasExplicitColumn(field)
+ ? "Rename one field, or point one @column at a different column."
+ : "Rename one field, or give one an explicit @column so the two columns differ."),
ErrorCode.ERR_COLUMN_NAME_COLLISION, field.getSource());
}
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java b/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java
new file mode 100644
index 0000000000..c60512241a
--- /dev/null
+++ b/server/java/metadata/src/test/java/com/metaobjects/source/ColumnNameCollisionMessageTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2003 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.source;
+
+import com.metaobjects.ErrorCode;
+import com.metaobjects.MetaDataException;
+import com.metaobjects.loader.InMemoryStringSource;
+import com.metaobjects.loader.MetaDataLoader;
+import com.metaobjects.registry.SharedRegistryTestBase;
+import org.junit.Test;
+
+import java.net.URI;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * ERR_COLUMN_NAME_COLLISION advice wording and the {@code @sql} view exemption. Mirrors
+ * {@code packages/metadata/test/column-name-collision-message.test.ts} in the TS reference port.
+ */
+public class ColumnNameCollisionMessageTest extends SharedRegistryTestBase {
+
+ private static final String TABLE = "{ \"source.rdb\": { \"@kind\": \"table\", \"@table\": \"account\" } }";
+
+ private static String doc(String source, String fieldA, String fieldB) {
+ return "{ \"metadata.root\": { \"package\": \"demo\", \"children\": ["
+ + " { \"object.entity\": { \"name\": \"Account\", \"children\": ["
+ + source + ","
+ + " { \"field.long\": { \"name\": \"id\" } },"
+ + fieldA + "," + fieldB + ","
+ + " { \"identity.primary\": { \"name\": \"id\", \"@fields\": [\"id\"] } }"
+ + " ] } } ] } }";
+ }
+
+ private void load(String canonical, String id) {
+ MetaDataLoader loader = createTestLoader("ColumnNameCollisionMessageTest",
+ java.util.Collections.emptyList());
+ loader.load(List.of(new InMemoryStringSource(canonical, id)));
+ }
+
+ private String collisionMessage(String canonical, String id) {
+ try {
+ load(canonical, id);
+ } catch (MetaDataException e) {
+ assertTrue("expected ERR_COLUMN_NAME_COLLISION; got " + e.getMessage(),
+ e.getCode().filter(c -> c == ErrorCode.ERR_COLUMN_NAME_COLLISION).isPresent());
+ return e.getMessage();
+ }
+ fail("expected ERR_COLUMN_NAME_COLLISION");
+ return null;
+ }
+
+ @Test
+ public void twoExplicitColumnsOnOneColumnDoNotSuggestAddingAColumn() {
+ String msg = collisionMessage(doc(TABLE,
+ "{ \"field.string\": { \"name\": \"userName\", \"@column\": \"username\" } }",
+ "{ \"field.string\": { \"name\": \"displayName\", \"@column\": \"username\" } }"), "explicit.json");
+ assertTrue(msg, msg.contains("point one @column at a different column"));
+ assertFalse(msg, msg.contains("give one an explicit @column"));
+ }
+
+ @Test
+ public void implicitCollisionStillSuggestsAnExplicitColumn() {
+ String msg = collisionMessage(doc(TABLE,
+ "{ \"field.string\": { \"name\": \"userId\" } }",
+ "{ \"field.string\": { \"name\": \"userID\" } }"), "implicit.json");
+ assertTrue(msg, msg.contains("give one an explicit @column"));
+ }
+
+ @Test
+ public void sqlViewMayShareAColumnBetweenFields() {
+ load("""
+ { "metadata.root": { "package": "demo", "children": [
+ { "object.projection": { "name": "UserView", "children": [
+ { "source.rdb": { "@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t" } },
+ { "field.long": { "name": "id", "@column": "id" } },
+ { "field.string": { "name": "userName", "@column": "username" } },
+ { "field.string": { "name": "displayName", "@column": "username" } }
+ ] } }
+ ] } }
+ """, "sqlview.json");
+ }
+}
diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py
index 34e1886d77..bb2c548cee 100644
--- a/server/python/src/metaobjects/loader/validation_passes.py
+++ b/server/python/src/metaobjects/loader/validation_passes.py
@@ -64,6 +64,7 @@
from ..meta.meta_data import MetaData
from ..meta.persistence.source.meta_source import MetaSource
from ..meta.persistence.source.source_constants import (
+ SOURCE_KIND_VIEW,
SOURCE_READ_ONLY_KINDS,
SOURCE_ROLE_PRIMARY,
)
@@ -4198,6 +4199,12 @@ def _validate_index_lookup_fields(root: MetaData, errors: list[MetaError]) -> No
# ---------------------------------------------------------------------------
+def _has_explicit_column(field: MetaData) -> bool:
+ from ..meta.core.field import field_constants as fc
+ col = field.get_meta_attr(fc.FIELD_ATTR_COLUMN)
+ return isinstance(col, str) and col != ""
+
+
def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) -> None:
"""ERR_COLUMN_NAME_COLLISION: two fields of one stored object resolving to the SAME
physical column (``userId`` + ``userID`` both snake_case to ``user_id``, or two
@@ -4208,6 +4215,13 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) ->
honoured. Scope: a concrete object declaring at least one source (a source-less
object generates nothing); derived fields and ``field.object`` (may flatten to
several columns) are skipped. ADR-0039: effective children (inherited fields count).
+
+ Exempt: an object whose every source is read-only and at least one is a
+ ``source.rdb @kind: view`` with an ``@sql`` body. The author's SQL defines that view's
+ columns and the fields only READ them, so two fields on one column create no duplicate
+ column and nothing can be written. A derived view (no ``@sql``) emits a select list
+ from its fields, and an object with a writable source has a real table whose columns
+ MetaObjects creates; both stay checked.
"""
from ..naming import resolve_column_name
from ..meta.core.field.meta_field import MetaField
@@ -4216,6 +4230,12 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) ->
continue
if not any(c.type == TYPE_SOURCE for c in obj.children()):
continue
+ sources = [c for c in obj.children() if isinstance(c, MetaSource)]
+ if all(s.is_read_only() for s in sources) and any(
+ s.effective_kind() == SOURCE_KIND_VIEW and s.sql_body() is not None
+ for s in sources
+ ):
+ continue
seen: dict[str, MetaData] = {}
for field in obj.children():
if not isinstance(field, MetaField) or field.sub_type == FIELD_SUBTYPE_OBJECT \
@@ -4230,8 +4250,12 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) ->
code=ErrorCode.ERR_COLUMN_NAME_COLLISION,
message=(
f'fields "{first.name}" and "{field.name}" on "{obj.name}" both resolve '
- f'to physical column "{column}". Rename one field, or give one an '
- f"explicit @column so the two columns differ."
+ f'to physical column "{column}". '
+ + (
+ "Rename one field, or point one @column at a different column."
+ if _has_explicit_column(first) and _has_explicit_column(field)
+ else "Rename one field, or give one an explicit @column so the two columns differ."
+ )
),
envelope=field.source,
))
diff --git a/server/python/tests/unit/test_column_name_collision_message.py b/server/python/tests/unit/test_column_name_collision_message.py
new file mode 100644
index 0000000000..24245a0ce6
--- /dev/null
+++ b/server/python/tests/unit/test_column_name_collision_message.py
@@ -0,0 +1,77 @@
+"""ERR_COLUMN_NAME_COLLISION advice wording and the @sql view exemption.
+
+Mirrors ``server/typescript/packages/metadata/test/column-name-collision-message.test.ts``.
+"""
+from __future__ import annotations
+
+import json
+
+from metaobjects import load_string
+from metaobjects.errors import ErrorCode
+
+TABLE = {"source.rdb": {"@kind": "table", "@table": "account"}}
+
+
+def _collision_messages(source: dict, field_a: dict, field_b: dict) -> list[str]:
+ doc = {
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Account",
+ "children": [
+ source,
+ {"field.long": {"name": "id"}},
+ field_a,
+ field_b,
+ {"identity.primary": {"name": "id", "@fields": ["id"]}},
+ ],
+ }
+ }
+ ],
+ }
+ }
+ result = load_string(json.dumps(doc))
+ return [e.message for e in result.errors if e.code == ErrorCode.ERR_COLUMN_NAME_COLLISION]
+
+
+def test_two_explicit_columns_on_one_column_do_not_suggest_adding_a_column() -> None:
+ (msg,) = _collision_messages(
+ TABLE,
+ {"field.string": {"name": "userName", "@column": "username"}},
+ {"field.string": {"name": "displayName", "@column": "username"}},
+ )
+ assert "point one @column at a different column" in msg
+ assert "give one an explicit @column" not in msg
+
+
+def test_implicit_collision_still_suggests_an_explicit_column() -> None:
+ (msg,) = _collision_messages(
+ TABLE,
+ {"field.string": {"name": "userId"}},
+ {"field.string": {"name": "userID"}},
+ )
+ assert "give one an explicit @column" in msg
+
+
+def test_sql_view_may_share_a_column_between_fields() -> None:
+ doc = {
+ "metadata.root": {
+ "package": "demo",
+ "children": [
+ {
+ "object.projection": {
+ "name": "UserView",
+ "children": [
+ {"source.rdb": {"@kind": "view", "@view": "v", "@sql": "SELECT id, username FROM t"}},
+ {"field.long": {"name": "id", "@column": "id"}},
+ {"field.string": {"name": "userName", "@column": "username"}},
+ {"field.string": {"name": "displayName", "@column": "username"}},
+ ],
+ }
+ }
+ ],
+ }
+ }
+ assert load_string(json.dumps(doc)).errors == []
diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts
index 116eed45a8..3d72cc712b 100644
--- a/server/typescript/packages/metadata/src/loader/validation-passes.ts
+++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts
@@ -87,7 +87,8 @@ import {
FIELD_SUBTYPE_TIMESTAMP,
FIELD_SUBTYPE_UUID,
} from "../core/field/field-constants.js";
-import { FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR } from "../persistence/db/db-constants.js";
+import { FIELD_ATTR_COLUMN, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR } from "../persistence/db/db-constants.js";
+import { SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js";
import {
IDENTITY_ATTR_FIELDS,
IDENTITY_SUBTYPE_REFERENCE,
@@ -2777,13 +2778,33 @@ export function validateRetiredRequirementLinks(root: MetaData): ParseError[] {
// object generates nothing); derived fields (origin.*) and field.object (which may
// flatten to several columns) are not columns of this table and are skipped.
// ADR-0039: effective fields, so an inherited field collides like an own one.
+// Exempt: an object whose every source is read-only and at least one is a
+// `source.rdb @kind: view` with an `@sql` body. The author's SQL defines that view's
+// columns and the fields only READ them, so two fields on one column create no
+// duplicate column and nothing can be written. A derived view (no `@sql`) emits a
+// select list from its fields, and an object with a writable source has a real table
+// whose columns MetaObjects creates; both stay checked.
// ---------------------------------------------------------------------------
+function readsThroughSqlView(obj: MetaData): boolean {
+ const sources = obj.children().filter((c): c is MetaSource => c instanceof MetaSource);
+ return (
+ sources.every((s) => s.isReadOnly()) &&
+ sources.some((s) => s.effectiveKind === SOURCE_KIND_VIEW && s.sqlBody !== undefined)
+ );
+}
+
+function hasExplicitColumn(field: MetaData): boolean {
+ const col = field.attr(FIELD_ATTR_COLUMN);
+ return typeof col === "string" && col !== "";
+}
+
export function validateColumnNameCollisions(root: MetaData): ParseError[] {
const errors: ParseError[] = [];
for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) {
if (obj.isAbstract) continue;
if (!obj.children().some((c) => c.type === TYPE_SOURCE)) continue;
+ if (readsThroughSqlView(obj)) continue;
const seen = new Map();
for (const field of obj.children()) {
if (!isMetaField(field) || field.subType === FIELD_SUBTYPE_OBJECT || field.isDerived()) continue;
@@ -2796,7 +2817,10 @@ export function validateColumnNameCollisions(root: MetaData): ParseError[] {
errors.push(
new ParseError(
`fields "${first.name}" and "${field.name}" on "${obj.name}" both resolve to physical column ` +
- `"${column}". Rename one field, or give one an explicit @column so the two columns differ.`,
+ `"${column}". ` +
+ (hasExplicitColumn(first) && hasExplicitColumn(field)
+ ? "Rename one field, or point one @column at a different column."
+ : "Rename one field, or give one an explicit @column so the two columns differ."),
{ code: "ERR_COLUMN_NAME_COLLISION", source: field.source },
),
);
diff --git a/server/typescript/packages/metadata/test/column-name-collision-message.test.ts b/server/typescript/packages/metadata/test/column-name-collision-message.test.ts
new file mode 100644
index 0000000000..45ece7f8cb
--- /dev/null
+++ b/server/typescript/packages/metadata/test/column-name-collision-message.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { join } from "node:path";
+import { tsAdapter } from "./conformance/adapter.js";
+
+const CORPUS = join(import.meta.dir, "../../../../../fixtures/conformance");
+const PROVIDERS = ["metaobjects-core-types", "metaobjects-db"];
+
+async function messages(fixture: string): Promise {
+ const out = await tsAdapter.loadFixture(join(CORPUS, fixture, "input"), PROVIDERS);
+ return (out.errors ?? []).map((e) => e.message ?? "");
+}
+
+test("two explicit @column on one column: advice does not suggest adding @column", async () => {
+ const [msg] = await messages("error-column-name-collision-derived-view");
+ expect(msg).toContain("point one @column at a different column");
+ expect(msg).not.toContain("give one an explicit @column");
+});
+
+test("implicit collision still suggests an explicit @column", async () => {
+ const [msg] = await messages("error-column-name-collision");
+ expect(msg).toContain("give one an explicit @column");
+});
+
+test("an @sql view may share a column between fields", async () => {
+ expect(await messages("column-name-shared-in-sql-view-ok")).toEqual([]);
+});
From 37ca9384a4cbeac9c0cfb67c4912b789e6390ca0 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Wed, 4 Nov 2026 01:04:50 -0500
Subject: [PATCH 04/51] feat: enforce cross-field validators in every port's
generated create models (#530)
* feat: generated record models enforce cross-field validators in every port
validator.comparison/requiredWhen/presentIff/atLeastOne are now enforced by the
full create model (Zod refinement, Bean Validation, IValidatableObject, Pydantic
model_validator), mirroring the DB CHECK semantics. PATCH models and CHECK
emission are unchanged. Gated by validation-conformance cross-field cases.
* no-mistakes(review): Enforce cross-field rules on TPH subtype create in TS, Java, Kotlin
* no-mistakes(review): Fix C# inherited Validate, TS array skip, behavioral tests
* no-mistakes(review): Fix C# decimal/double comparison and Python array skip
* no-mistakes(review): Parenthesize Kotlin cross-field getter; behavioral wrap test
* no-mistakes(review): Python comparison rejects unorderable timestamps as validation error
* no-mistakes(review): Replace TS zod cross-field source-text tests with execution
* no-mistakes(review): Skip cross-field rules on server-owned fields in JVM/C#
* no-mistakes(review): Import KotlinCrossFieldRules in ejectable Kotlin generators
* no-mistakes(document): Updated stale cross-field gap note in docs/1.0-readiness.md to point at the new enforcement docs. Author already updated CHANGELOG, features/entities.md, the FR-036 spec, the authoring skill, the validation-conformance README and CONFORMANCE.md.
---
CHANGELOG.md | 16 ++
.../skills/metaobjects-authoring/SKILL.md | 6 +-
docs/1.0-readiness.md | 28 +-
docs/CONFORMANCE.md | 2 +-
docs/features/entities.md | 22 ++
...ion-enforcement-and-fr-035-release-gaps.md | 17 +-
.../codegen/generators/routes.ts | 9 +-
.../codegen/templates/queries-file.ts | 9 +-
.../codegen/templates/zod-validators.ts | 160 ++++++++++-
.../showcase/codegen/generators/routes.ts | 9 +-
.../codegen/templates/queries-file.ts | 9 +-
.../codegen/templates/zod-validators.ts | 160 ++++++++++-
.../skills/metaobjects-authoring/SKILL.md | 6 +-
.../skills/metaobjects-authoring/SKILL.md | 6 +-
.../skills/metaobjects-authoring/SKILL.md | 6 +-
.../skills/metaobjects-authoring/SKILL.md | 6 +-
.../skills/metaobjects-authoring/SKILL.md | 6 +-
fixtures/validation-conformance/README.md | 24 ++
.../cross-field-cases.json | 263 ++++++++++++++++++
.../meta.cross-field.json | 33 +++
.../CrossFieldValidationConformanceTests.cs | 125 +++++++++
.../CrossFieldValidatorGenerationTests.cs | 232 +++++++++++++++
.../Generators/EntityGenerator.cs | 256 +++++++++++++++++
server/java/codegen-kotlin/pom.xml | 1 +
.../generator/kotlin/GeneratorRegistry.kt | 8 +-
.../generator/kotlin/KotlinCrossFieldRules.kt | 105 +++++++
.../generator/kotlin/KotlinEntityGenerator.kt | 48 ++++
.../kotlin/KotlinSpringControllerGenerator.kt | 12 +
.../kotlin/KotlinCrossFieldValidationTest.kt | 94 +++++++
.../kotlin/ValidationConformanceTest.kt | 19 +-
.../spring/SpringControllerGenerator.java | 20 +-
.../generator/spring/SpringDtoGenerator.java | 11 +-
.../spring/SpringGeneratorSupport.java | 147 ++++++++++
.../GeneratedTphCrossFieldCompileRunTest.java | 163 +++++++++++
.../SpringCrossFieldValidationTest.java | 132 +++++++++
.../spring/ValidationConformanceTest.java | 36 ++-
.../TphCrossFieldControllerRunTest.kt | 112 ++++++++
.../metaobjects/mojo/EjectSupportTest.java | 3 +-
.../codegen/generators/entity_model.py | 118 ++++++++
.../codegen/test_validation_conformance.py | 111 ++++++++
.../src/templates/form-file.ts | 9 +-
.../codegen-ts/src/reference/routes.ts | 9 +-
.../codegen-ts/src/templates/queries-file.ts | 9 +-
.../codegen-ts/src/templates/routes-file.ts | 9 +-
.../src/templates/zod-validators.ts | 160 ++++++++++-
.../codegen-ts/test/tph-cross-field.test.ts | 180 ++++++++++++
.../codegen-ts/test/zod-cross-field.test.ts | 129 +++++++++
.../integration-tests/src/validation-cases.ts | 8 +
...validation-conformance-cross-field.test.ts | 69 +++++
.../test-generators/src/generators/routes.ts | 9 +-
.../src/templates/queries-file.ts | 9 +-
.../src/templates/zod-validators.ts | 160 ++++++++++-
52 files changed, 3207 insertions(+), 103 deletions(-)
create mode 100644 fixtures/validation-conformance/cross-field-cases.json
create mode 100644 fixtures/validation-conformance/meta.cross-field.json
create mode 100644 server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
create mode 100644 server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidatorGenerationTests.cs
create mode 100644 server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt
create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldValidationTest.kt
create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphCrossFieldCompileRunTest.java
create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCrossFieldValidationTest.java
create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/TphCrossFieldControllerRunTest.kt
create mode 100644 server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts
create mode 100644 server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts
create mode 100644 server/typescript/packages/integration-tests/test/validation-conformance-cross-field.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d218fd9a9a..2726877493 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,22 @@ here.**
## [Unreleased]
+### Added
+
+- **Generated record models enforce the four cross-field validators in every port.**
+ `validator.comparison`, `validator.requiredWhen`, `validator.presentIff` and
+ `validator.atLeastOne` used to render only as DB `CHECK` constraints, so a store with no `CHECK`
+ support (a graph or document database) enforced none of them and the application had to repeat the
+ rules in its writer. The full create/insert model now enforces them with the language's native
+ mechanism: a Zod refinement on the insert schema (TypeScript), a class-level Bean Validation
+ constraint on the create DTO (Java, Kotlin), `IValidatableObject` (C#) and a Pydantic
+ `model_validator` (Python). Semantics mirror the `CHECK` derivation: null-safe, `comparison` passes
+ when either side is null, `@equals` is read per the gating field's subtype. PATCH and
+ partial-update models are unchanged (a partial body cannot see the merged row, so the database
+ `CHECK` remains the enforcement there), and `CHECK` emission is unchanged. A record that violates a
+ declared rule is now rejected at the model where it used to reach the database. Gated by
+ `fixtures/validation-conformance/cross-field-cases.json` in all five ports.
+
### Fixed
- **`ERR_COLUMN_NAME_COLLISION` no longer rejects a read-only view whose columns come from `@sql`.**
diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/agent-context/skills/metaobjects-authoring/SKILL.md
+++ b/agent-context/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/docs/1.0-readiness.md b/docs/1.0-readiness.md
index b54be142ed..08ba4ef1d8 100644
--- a/docs/1.0-readiness.md
+++ b/docs/1.0-readiness.md
@@ -155,29 +155,11 @@ Status legend: ✅ done · 🔶 in progress · ⬜ not started · ❓ **[RATIFY]
in all three non-TS ports; a Python runtime path dropped an inherited M:N) — assume
more lurk, and lead every cross-port fix with a shared fixture.
- **Known instance, measured 2026-09-06 — the four entity-scoped cross-field validators.**
- `validator.comparison`, `requiredWhen`, `presentIff` and `atLeastOne` are registered
- vocabulary in all five ports and are taught by the shipped `metaobjects-authoring` skill,
- but their only enforcement is the database `CHECK` that TS-owned `migrate` emits (gated by
- `migrate-ts/test/validator-check/cross-field.test.ts`, 7 tests). **No port's generated API
- tier validates them:** Python's `entity_model.py` and C#'s `EntityGenerator.cs` dispatch
- only on the four FIELD-scoped validators (`length`, `array`, `numeric`, `regex`), and the
- shared `validation-conformance` corpus covers only those same four — **zero fixtures across
- every behavioral corpus touch the cross-field family.** They are also four of the 13 entries
- in `registry-conformance/coverage-report.json`'s `untestedSubTypes`, which is the same list
- the `.base` defect hid in until `0.25.0`.
-
- Consequence for an adopter today: a request body violating a declared cross-field rule is
- refused by the DATABASE, not by the API, in every port — a constraint violation rather than
- a 400.
-
- **This does not block the cut**, and the reason is worth stating so it is not re-litigated:
- the vocabulary is enforced (the CHECK reaches every port, because schema is TS-owned per
- ADR-0015), and adding API-tier enforcement later changes no load verdict and no metadata —
- it is additive, and reaches an adopter as a wrong request failing earlier and more clearly.
- What must NOT happen is adding a cross-port `validation-conformance` fixture for these
- before the ports implement the tier; that turns three lanes red to record a gap this bullet
- already records.
+ **Known instance (measured 2026-09-06, resolved Unreleased).** The four entity-scoped cross-field
+ validators (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) were enforced only by the DB
+ `CHECK`. The generated record model now enforces them in every port; see
+ [features/entities.md](features/entities.md#cross-field-validators) and the CHANGELOG `[Unreleased]` entry.
+ They remain among the `untestedSubTypes` in `registry-conformance/coverage-report.json`, which tracks the registry, not the generated behavior.
## F. Adoption proof (the audit as readiness signal)
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index 16d963fd0e..6487032d76 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -38,7 +38,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 59 (53 query + 6 migration) | all 59; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 53 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) |
| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 119 (31 core + 10 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL |
| [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) |
-| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) |
+| [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 20 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 | ✓ | ✓ | ✓ | ✓ | ✓ |
diff --git a/docs/features/entities.md b/docs/features/entities.md
index 74f96a2a36..5247997235 100644
--- a/docs/features/entities.md
+++ b/docs/features/entities.md
@@ -319,6 +319,28 @@ row = om.create("Author", {"name": "Ada", "bio": None})
found = om.find_by_id("Author", row["id"])
```
+## Cross-field validators
+
+`validator.comparison`, `validator.requiredWhen`, `validator.presentIff` and `validator.atLeastOne`
+are declared as children of the entity and reference sibling fields by name. They are enforced in
+two places:
+
+- **The generated full record (create) model**, in every port, with the language's native
+ mechanism: a Zod refinement on the insert schema (TypeScript), a class-level Bean Validation
+ constraint on the create DTO (Java, Kotlin), `IValidatableObject` (C#) and a Pydantic
+ `model_validator` (Python). A store with no `CHECK` support, such as a graph or document
+ database, is therefore still covered.
+- **A database `CHECK` constraint**, derived by `meta migrate`.
+
+The two share one set of semantics: absent or null is SQL `NULL`; `comparison` passes when either
+side is null; `requiredWhen` is violated only when the gate equals `@equals` and the target is null;
+`presentIff` requires the target to be present exactly when the gate equals `@equals`; `atLeastOne`
+needs one non-null field. `@equals` is read per the gating field's subtype. The shared cases in
+`fixtures/validation-conformance/cross-field-cases.json` gate all five ports.
+
+PATCH and partial-update models do **not** enforce these rules, because a partial body cannot see
+the merged row. The database `CHECK` is the enforcement there.
+
## Verified by
The following conformance fixtures gate this feature's behavior across ports:
diff --git a/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md b/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md
index 728d593ac4..c03e51005a 100644
--- a/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md
+++ b/docs/superpowers/specs/2026-07-14-fr-036-constraint-validation-enforcement-and-fr-035-release-gaps.md
@@ -50,10 +50,21 @@ has no empty-string case):**
(no anchors) accepts `"xxABCyy"` on TS/Python, rejects on Java/Kotlin/C#. Ruling 2 pins **full-match**.
**Field-scoped vs entity-scoped split is correct and load-bearing:** cross-field validators
-(`comparison`, `presentIff`, `requiredWhen`, `atLeastOne`) render ONLY as TS-owned DB CHECK
+(`comparison`, `presentIff`, `requiredWhen`, `atLeastOne`) were rendered ONLY as TS-owned DB CHECK
constraints (`migrate-ts/src/expected-schema.ts`), never as jakarta/Zod — so they evaluate the MERGED
-row after UPDATE and hold under PATCH with zero handler work. Do NOT add cross-field validation to any
-port's handler. Per-field only.
+row after UPDATE and hold under PATCH with zero handler work. PATCH and partial-update handlers still
+add nothing: a partial body cannot see the merged row, so the DB CHECK stays the enforcement there.
+
+> **Amended (Unreleased) — record models now enforce cross-field rules.** The original reading above
+> ("DB CHECK only") left a store with no CHECK constraints (a graph or document database, say) with
+> no enforcement of these four validators at all. Every port's generated **full record model** — the
+> create/insert shape — now also enforces them, in the language's native idiom: a Zod refinement on
+> the insert schema (TS), a class-level Bean Validation constraint on the create DTO (Java, Kotlin),
+> `IValidatableObject` on the create model (C#) and a Pydantic `model_validator(mode="after")`
+> (Python). The semantics mirror the DB CHECK derivation exactly (null-safe; `comparison` passes when
+> either side is null; `@equals` rendered per the gating field's subtype) and are gated by the shared
+> `fixtures/validation-conformance/cross-field-cases.json` cases in all five port runners. PATCH and
+> partial-update models are deliberately unchanged, and DB CHECK emission is unchanged.
---
diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts
index 56a79d85b6..08d409771c 100644
--- a/examples/advanced-modeling/codegen/generators/routes.ts
+++ b/examples/advanced-modeling/codegen/generators/routes.ts
@@ -94,6 +94,7 @@ import {
} from "@metaobjectsdev/codegen-ts/engine";
import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js";
import { isTphDiscriminatorBase, tphPlan } from "../templates/tph-discriminator.js";
+import { hasInsertRefinements } from "../templates/zod-validators.js";
// --- composition (OWNED) — assembles one .routes.ts. Change this to change the output. ---
// Dispatch: a TPH discriminator base → polymorphic list/get + a per-subtype CRUD set; a
@@ -621,7 +622,11 @@ function renderTphRoutes(
const subFileSpec = entityModuleSpecifier(
ctx.selfTarget, ctx.entityModuleTarget, effectivePackage(sub), sub.name, ctx.extStyle,
);
- const subInsertSym = imp(`${sub.name}InsertSchema@${subFileSpec}`);
+ // A subtype with cross-field rules has a refined InsertSchema, which Zod will not
+ // `.omit()`; its codegen exports the discriminator-less refined body instead.
+ const subInsertBody = hasInsertRefinements(sub)
+ ? code`${imp(`${sub.name}InsertBodySchema@${subFileSpec}`)}`
+ : code`${imp(`${sub.name}InsertSchema@${subFileSpec}`)}.omit({ ${discField}: true })`;
// FR-036 Program B: the per-subtype UPDATE must carry the FR-035 present-key
// tristate (a non-@required subtype column accepts an explicit null → clears;
// a @required column's explicit null is rejected). The subtype's own
@@ -640,7 +645,7 @@ function renderTphRoutes(
path: ${baseConstSym}.$path + ${JSON.stringify(`/${segment}`)},
db: ${dbSym},
table: ${tableSym},
- insertSchema: ${subInsertSym}.omit({ ${discField}: true }),
+ insertSchema: ${subInsertBody},
updateSchema: ${subUpdateSym},
filterAllowlist: ${subFilterSym},
sortAllowlist: ${subSortSym},
diff --git a/examples/advanced-modeling/codegen/templates/queries-file.ts b/examples/advanced-modeling/codegen/templates/queries-file.ts
index e9e3c386d9..d7362d6181 100644
--- a/examples/advanced-modeling/codegen/templates/queries-file.ts
+++ b/examples/advanced-modeling/codegen/templates/queries-file.ts
@@ -28,7 +28,7 @@ import { isTphDiscriminatorBase, tphConcreteSubtypes } from "./tph-discriminator
import { isProjection, isWriteThrough } from "@metaobjectsdev/codegen-ts/engine";
import { isReport } from "@metaobjectsdev/codegen-ts/engine";
import { hasItemRoute } from "@metaobjectsdev/codegen-ts/engine";
-import { hasAutoSetFields } from "./zod-validators.js";
+import { hasAutoSetFields, hasInsertRefinements } from "./zod-validators.js";
import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine";
/**
@@ -372,6 +372,9 @@ export async function list${pluralize(baseName)}(db: Db, opts?: { limit?: number
// the schema (schemaInputType), so a subtype module from an owned entity generator
// that predates the `Create` alias still satisfies it.
const subCreateSym = schemaInputType(subInsertSym);
+ // A refined (cross-field) InsertSchema has no `.partial()`; the partial update reads
+ // the unrefined shape, as an unrefined subtype's does.
+ const subPartialSym = hasInsertRefinements(sub) ? imp(`${sub.name}InsertBaseSchema@${subFileSpec}`) : subInsertSym;
subtypeSections.push(code`
export async function list${pluralize(sub.name)}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${subTypeSym}[]> {
@@ -395,7 +398,7 @@ ${supportsReturning(ctx.dialect) ? code`export async function create${sub.name}(
}
export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> {
- const validated = ${subInsertSym}.partial().parse(data) as Record;
+ const validated = ${subPartialSym}.partial().parse(data) as Record;
// The discriminator is immutable — a ${sub.name} can never become another subtype.
const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated;
const [row] = await db.update(${tableSym}).set(safe)
@@ -417,7 +420,7 @@ export async function create${sub.name}(db: Db, data: ${subCreateSym}): Promise<
}
export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> {
- const validated = ${subInsertSym}.partial().parse(data) as Record;
+ const validated = ${subPartialSym}.partial().parse(data) as Record;
// The discriminator is immutable — a ${sub.name} can never become another subtype.
const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated;
if (Object.keys(safe).length > 0) {
diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts
index ea4945feae..661966d8ea 100644
--- a/examples/advanced-modeling/codegen/templates/zod-validators.ts
+++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts
@@ -28,6 +28,10 @@ import {
FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_JSONB,
AUTO_SET_ON_CREATE, AUTO_SET_ON_UPDATE,
VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_MIN, VALIDATOR_ATTR_PATTERN,
+ VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN,
+ VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE,
+ VALIDATOR_ATTR_LEFT, VALIDATOR_ATTR_OP, VALIDATOR_ATTR_RIGHT,
+ VALIDATOR_ATTR_FIELD, VALIDATOR_ATTR_WHEN, VALIDATOR_ATTR_EQUALS, VALIDATOR_ATTR_FIELDS,
GENERATION_INCREMENT, GENERATION_UUID,
OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE,
OBJECT_SUBTYPE_VALUE,
@@ -256,6 +260,135 @@ function isInsertRequiredPk(field: MetaField, assignedPk: Set): boolean
return field.attr(FIELD_ATTR_DEFAULT) === undefined;
}
+// ── Entity-scoped cross-field validators on the full (insert) record ──────────
+// validator.comparison / requiredWhen / presentIff / atLeastOne are enforced on the
+// INSERT-shaped schemas only, as one `.superRefine`. A PATCH body cannot see the merged
+// row, so the Update schema is deliberately left alone (the DB CHECK stays the guard
+// there). Semantics mirror the migrate-ts CHECK derivation: absent / null / undefined is
+// SQL NULL, "" is NOT null; a comparison with a NULL side passes; requiredWhen is violated
+// only when the gate EQUALS the literal and the target is null; presentIff requires
+// (target != null) === (gate equals literal), a null gate being "not equal".
+
+const CROSS_FIELD_OPS: Record = {
+ gt: ">", gte: ">=", lt: "<", lte: "<=", ne: "!==", eq: "===",
+};
+
+const NUMERIC_SUBTYPES: ReadonlySet = new Set([
+ FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
+ FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
+]);
+
+/** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
+function insertSchemaFieldNameSet(obj: MetaObject): Set {
+ const autoGen = autoGenPkFieldNames(obj);
+ const out = new Set();
+ for (const f of obj.fields()) {
+ if (autoGen.has(f.name)) continue;
+ if (isReadOnlyMutability(f) || f.isDerived()) continue;
+ out.add(f.name);
+ }
+ return out;
+}
+
+/** The @equals literal as a TS expression, typed by the gating field's subtype. */
+function crossFieldLiteral(raw: unknown, when: MetaField): { lit: string; numeric: boolean } {
+ const s = String(raw);
+ if (when.subType === FIELD_SUBTYPE_BOOLEAN) {
+ return { lit: s === "true" || s === "1" || s === "TRUE" ? "true" : "false", numeric: false };
+ }
+ if (NUMERIC_SUBTYPES.has(when.subType) && /^-?\d+(\.\d+)?$/.test(s)) return { lit: s, numeric: true };
+ return { lit: JSON.stringify(s), numeric: false };
+}
+
+/** Does this object declare at least one cross-field validator that will be enforced
+ * on its insert schema? Exported so the route, query and form emitters can tell a refined
+ * schema (which Zod will not `.omit()` or `.partial()`) from a plain object; a refined TPH
+ * subtype also exports `InsertBaseSchema` (unrefined) and `InsertBodySchema`
+ * (refined, pinned discriminator omitted). */
+export function hasInsertRefinements(obj: MetaObject): boolean {
+ return crossFieldRefinementBody(obj).length > 0;
+}
+
+function crossFieldRefinementBody(obj: MetaObject): string[] {
+ const inSchema = insertSchemaFieldNameSet(obj);
+ const byName = new Map(obj.fields().map((f) => [f.name, f] as const));
+ // A reference must name a field that exists AND is in the insert schema; otherwise skip
+ // the validator (migrate skips on a missing field; a readOnly/derived/auto-PK field is
+ // never in the body, so enforcing on it would reject every create).
+ const ref = (name: unknown): MetaField | undefined => {
+ if (typeof name !== "string" || !inSchema.has(name)) return undefined;
+ return byName.get(name);
+ };
+ // A TPH subtype's discriminator is pinned to one literal, so the rule reads that literal:
+ // the same refinement then holds whether or not the body carries the discriminator.
+ const pin = tphDiscriminatorPin(obj);
+ const acc = (f: MetaField) => pin !== undefined && f.name === pin.fieldName
+ ? JSON.stringify(pin.value)
+ : `row[${JSON.stringify(f.name)}]`;
+ const issue = (path: string, msg: string) =>
+ `ctx.addIssue({ code: "custom", path: [${path}], message: ${JSON.stringify(msg)} });`;
+ const blocks: string[] = [];
+ // ADR-0039: entity.validators() is the resolving accessor (never ownValidators).
+ for (const v of obj.validators()) {
+ switch (v.subType) {
+ case VALIDATOR_SUBTYPE_COMPARISON: {
+ const left = ref(v.attr(VALIDATOR_ATTR_LEFT));
+ const right = ref(v.attr(VALIDATOR_ATTR_RIGHT));
+ const opName = String(v.attr(VALIDATOR_ATTR_OP));
+ const op = CROSS_FIELD_OPS[opName];
+ if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+ const numeric = NUMERIC_SUBTYPES.has(left.subType);
+ const c = numeric
+ ? "Number(l) - Number(r)"
+ : "l instanceof Date && r instanceof Date ? l.getTime() - r.getTime() : String(l) < String(r) ? -1 : String(l) > String(r) ? 1 : 0";
+ blocks.push(
+ ` {\n const l: unknown = ${acc(left)};\n const r: unknown = ${acc(right)};\n` +
+ ` if (l != null && r != null) {\n const c = ${c};\n` +
+ ` if (!(c ${op} 0)) ${issue(JSON.stringify(left.name), `${left.name} must be ${opName} ${right.name}`)}\n }\n }`,
+ );
+ break;
+ }
+ case VALIDATOR_SUBTYPE_REQUIRED_WHEN:
+ case VALIDATOR_SUBTYPE_PRESENT_IFF: {
+ const target = ref(v.attr(VALIDATOR_ATTR_FIELD));
+ const when = ref(v.attr(VALIDATOR_ATTR_WHEN));
+ if (!target || !when || when.resolvedIsArray()) break;
+ const { lit, numeric } = crossFieldLiteral(v.attr(VALIDATOR_ATTR_EQUALS), when);
+ const gate = numeric ? `g != null && Number(g) === ${lit}` : `g === ${lit}`;
+ const path = JSON.stringify(target.name);
+ const decl = ` const g: unknown = ${acc(when)};\n const t: unknown = ${acc(target)};\n const open = ${gate};\n`;
+ if (v.subType === VALIDATOR_SUBTYPE_REQUIRED_WHEN) {
+ blocks.push(` {\n${decl} if (open && t == null) ${issue(path, `${target.name} is required when ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`);
+ } else {
+ blocks.push(` {\n${decl} if ((t != null) !== open) ${issue(path, `${target.name} must be present if and only if ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`);
+ }
+ break;
+ }
+ case VALIDATOR_SUBTYPE_AT_LEAST_ONE: {
+ const raw = v.attr(VALIDATOR_ATTR_FIELDS);
+ const names = Array.isArray(raw) ? raw : (typeof raw === "string" ? [raw] : []);
+ const refs = names.map(ref);
+ if (refs.length === 0 || refs.some((r) => r === undefined)) break;
+ const fields = refs as MetaField[];
+ const anyPresent = fields.map((f) => `${acc(f)} != null`).join(" || ");
+ blocks.push(` if (!(${anyPresent})) ${issue(JSON.stringify(fields[0]!.name), `at least one of ${fields.map((f) => f.name).join(", ")} is required`)}`);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ return blocks;
+}
+
+/** `.superRefine(...)` suffix for an insert-shaped schema, or "" when the object has no
+ * enforceable cross-field validator (output is then byte-identical to before). */
+function insertRefinementSuffix(obj: MetaObject): string {
+ const blocks = crossFieldRefinementBody(obj);
+ if (blocks.length === 0) return "";
+ return `.superRefine((row, ctx) => {\n${blocks.join("\n")}\n})`;
+}
+
/**
* Emit ONLY the `InsertSchema`. Used by the value-object file emitter
* for metaobjects with no writable source.rdb — those have no PATCH/update
@@ -322,7 +455,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co
return code`
${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({
${joinCode(insertFieldLines, { on: ",\n" })}
-});
+})${insertRefinementSuffix(obj)};
`;
}
@@ -535,6 +668,25 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
const docs = renderDocsFor(obj);
const docsPrefix = docs ? `${docs}\n` : "";
+ // A Zod object carrying refinements cannot be `.omit()`ed or `.partial()`ed, and a TPH
+ // subtype's route and form omit the pinned discriminator while its update query takes a
+ // partial. So when both apply, the unrefined shape is exported as `InsertBaseSchema`
+ // and refined twice: as `InsertSchema` and, discriminator omitted, as
+ // `InsertBodySchema`.
+ const refineSuffix = insertRefinementSuffix(obj);
+ const insertDecl = refineSuffix !== "" && tphPin !== undefined
+ ? code`export const ${objName}InsertBaseSchema = ${z}.object({
+${joinCode(insertFieldLines, { on: ",\n" })}
+});
+
+${docsPrefix}export const ${insertSchemaName} = ${objName}InsertBaseSchema${refineSuffix};
+
+/** ${insertSchemaName} without the pinned \`${tphPin.fieldName}\` — the body a per-subtype route accepts. */
+export const ${objName}InsertBodySchema = ${objName}InsertBaseSchema.omit({ ${tphPin.fieldName}: true })${refineSuffix};`
+ : code`${docsPrefix}export const ${insertSchemaName} = ${z}.object({
+${joinCode(insertFieldLines, { on: ",\n" })}
+})${refineSuffix};`;
+
// #203 — emit the preserving insert-shape only for @autoSet entities (nothing to
// preserve otherwise). Backs `insertPreserving` (import/restore/replication).
const preservingBlock = emitPreserving
@@ -545,16 +697,14 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
* (no create-time now() stamp) so the caller's original values are preserved. */
export const ${preservingSchemaName} = ${z}.object({
${joinCode(preservingFieldLines, { on: ",\n" })}
-});
+})${insertRefinementSuffix(obj)};
/** Typed input of \`insertPreserving${objName}\` — ${preservingSchemaName}'s pre-transform shape. */
export type ${objName}CreatePreserving = ${z}.input;`
: code``;
return code`
-${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({
-${joinCode(insertFieldLines, { on: ",\n" })}
-});
+${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${insertDecl}
${docsPrefix}export const ${updateSchemaName} = ${z}.object({
${joinCode(updateFieldLines, { on: ",\n" })}
diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts
index 56a79d85b6..08d409771c 100644
--- a/examples/showcase/codegen/generators/routes.ts
+++ b/examples/showcase/codegen/generators/routes.ts
@@ -94,6 +94,7 @@ import {
} from "@metaobjectsdev/codegen-ts/engine";
import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js";
import { isTphDiscriminatorBase, tphPlan } from "../templates/tph-discriminator.js";
+import { hasInsertRefinements } from "../templates/zod-validators.js";
// --- composition (OWNED) — assembles one .routes.ts. Change this to change the output. ---
// Dispatch: a TPH discriminator base → polymorphic list/get + a per-subtype CRUD set; a
@@ -621,7 +622,11 @@ function renderTphRoutes(
const subFileSpec = entityModuleSpecifier(
ctx.selfTarget, ctx.entityModuleTarget, effectivePackage(sub), sub.name, ctx.extStyle,
);
- const subInsertSym = imp(`${sub.name}InsertSchema@${subFileSpec}`);
+ // A subtype with cross-field rules has a refined InsertSchema, which Zod will not
+ // `.omit()`; its codegen exports the discriminator-less refined body instead.
+ const subInsertBody = hasInsertRefinements(sub)
+ ? code`${imp(`${sub.name}InsertBodySchema@${subFileSpec}`)}`
+ : code`${imp(`${sub.name}InsertSchema@${subFileSpec}`)}.omit({ ${discField}: true })`;
// FR-036 Program B: the per-subtype UPDATE must carry the FR-035 present-key
// tristate (a non-@required subtype column accepts an explicit null → clears;
// a @required column's explicit null is rejected). The subtype's own
@@ -640,7 +645,7 @@ function renderTphRoutes(
path: ${baseConstSym}.$path + ${JSON.stringify(`/${segment}`)},
db: ${dbSym},
table: ${tableSym},
- insertSchema: ${subInsertSym}.omit({ ${discField}: true }),
+ insertSchema: ${subInsertBody},
updateSchema: ${subUpdateSym},
filterAllowlist: ${subFilterSym},
sortAllowlist: ${subSortSym},
diff --git a/examples/showcase/codegen/templates/queries-file.ts b/examples/showcase/codegen/templates/queries-file.ts
index e9e3c386d9..d7362d6181 100644
--- a/examples/showcase/codegen/templates/queries-file.ts
+++ b/examples/showcase/codegen/templates/queries-file.ts
@@ -28,7 +28,7 @@ import { isTphDiscriminatorBase, tphConcreteSubtypes } from "./tph-discriminator
import { isProjection, isWriteThrough } from "@metaobjectsdev/codegen-ts/engine";
import { isReport } from "@metaobjectsdev/codegen-ts/engine";
import { hasItemRoute } from "@metaobjectsdev/codegen-ts/engine";
-import { hasAutoSetFields } from "./zod-validators.js";
+import { hasAutoSetFields, hasInsertRefinements } from "./zod-validators.js";
import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine";
/**
@@ -372,6 +372,9 @@ export async function list${pluralize(baseName)}(db: Db, opts?: { limit?: number
// the schema (schemaInputType), so a subtype module from an owned entity generator
// that predates the `Create` alias still satisfies it.
const subCreateSym = schemaInputType(subInsertSym);
+ // A refined (cross-field) InsertSchema has no `.partial()`; the partial update reads
+ // the unrefined shape, as an unrefined subtype's does.
+ const subPartialSym = hasInsertRefinements(sub) ? imp(`${sub.name}InsertBaseSchema@${subFileSpec}`) : subInsertSym;
subtypeSections.push(code`
export async function list${pluralize(sub.name)}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${subTypeSym}[]> {
@@ -395,7 +398,7 @@ ${supportsReturning(ctx.dialect) ? code`export async function create${sub.name}(
}
export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> {
- const validated = ${subInsertSym}.partial().parse(data) as Record;
+ const validated = ${subPartialSym}.partial().parse(data) as Record;
// The discriminator is immutable — a ${sub.name} can never become another subtype.
const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated;
const [row] = await db.update(${tableSym}).set(safe)
@@ -417,7 +420,7 @@ export async function create${sub.name}(db: Db, data: ${subCreateSym}): Promise<
}
export async function update${sub.name}ById(db: Db, ${pkField}: ${pkType}, data: Partial<${subCreateSym}>): Promise<${subTypeSym} | null> {
- const validated = ${subInsertSym}.partial().parse(data) as Record;
+ const validated = ${subPartialSym}.partial().parse(data) as Record;
// The discriminator is immutable — a ${sub.name} can never become another subtype.
const { [${JSON.stringify(discField)}]: _disc, ...safe } = validated;
if (Object.keys(safe).length > 0) {
diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts
index ea4945feae..661966d8ea 100644
--- a/examples/showcase/codegen/templates/zod-validators.ts
+++ b/examples/showcase/codegen/templates/zod-validators.ts
@@ -28,6 +28,10 @@ import {
FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_JSONB,
AUTO_SET_ON_CREATE, AUTO_SET_ON_UPDATE,
VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_MIN, VALIDATOR_ATTR_PATTERN,
+ VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN,
+ VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE,
+ VALIDATOR_ATTR_LEFT, VALIDATOR_ATTR_OP, VALIDATOR_ATTR_RIGHT,
+ VALIDATOR_ATTR_FIELD, VALIDATOR_ATTR_WHEN, VALIDATOR_ATTR_EQUALS, VALIDATOR_ATTR_FIELDS,
GENERATION_INCREMENT, GENERATION_UUID,
OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE,
OBJECT_SUBTYPE_VALUE,
@@ -256,6 +260,135 @@ function isInsertRequiredPk(field: MetaField, assignedPk: Set): boolean
return field.attr(FIELD_ATTR_DEFAULT) === undefined;
}
+// ── Entity-scoped cross-field validators on the full (insert) record ──────────
+// validator.comparison / requiredWhen / presentIff / atLeastOne are enforced on the
+// INSERT-shaped schemas only, as one `.superRefine`. A PATCH body cannot see the merged
+// row, so the Update schema is deliberately left alone (the DB CHECK stays the guard
+// there). Semantics mirror the migrate-ts CHECK derivation: absent / null / undefined is
+// SQL NULL, "" is NOT null; a comparison with a NULL side passes; requiredWhen is violated
+// only when the gate EQUALS the literal and the target is null; presentIff requires
+// (target != null) === (gate equals literal), a null gate being "not equal".
+
+const CROSS_FIELD_OPS: Record = {
+ gt: ">", gte: ">=", lt: "<", lte: "<=", ne: "!==", eq: "===",
+};
+
+const NUMERIC_SUBTYPES: ReadonlySet = new Set([
+ FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT,
+ FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY,
+]);
+
+/** Names of the fields the INSERT-shaped schemas carry (same skip rules as the emitters). */
+function insertSchemaFieldNameSet(obj: MetaObject): Set {
+ const autoGen = autoGenPkFieldNames(obj);
+ const out = new Set();
+ for (const f of obj.fields()) {
+ if (autoGen.has(f.name)) continue;
+ if (isReadOnlyMutability(f) || f.isDerived()) continue;
+ out.add(f.name);
+ }
+ return out;
+}
+
+/** The @equals literal as a TS expression, typed by the gating field's subtype. */
+function crossFieldLiteral(raw: unknown, when: MetaField): { lit: string; numeric: boolean } {
+ const s = String(raw);
+ if (when.subType === FIELD_SUBTYPE_BOOLEAN) {
+ return { lit: s === "true" || s === "1" || s === "TRUE" ? "true" : "false", numeric: false };
+ }
+ if (NUMERIC_SUBTYPES.has(when.subType) && /^-?\d+(\.\d+)?$/.test(s)) return { lit: s, numeric: true };
+ return { lit: JSON.stringify(s), numeric: false };
+}
+
+/** Does this object declare at least one cross-field validator that will be enforced
+ * on its insert schema? Exported so the route, query and form emitters can tell a refined
+ * schema (which Zod will not `.omit()` or `.partial()`) from a plain object; a refined TPH
+ * subtype also exports `InsertBaseSchema` (unrefined) and `InsertBodySchema`
+ * (refined, pinned discriminator omitted). */
+export function hasInsertRefinements(obj: MetaObject): boolean {
+ return crossFieldRefinementBody(obj).length > 0;
+}
+
+function crossFieldRefinementBody(obj: MetaObject): string[] {
+ const inSchema = insertSchemaFieldNameSet(obj);
+ const byName = new Map(obj.fields().map((f) => [f.name, f] as const));
+ // A reference must name a field that exists AND is in the insert schema; otherwise skip
+ // the validator (migrate skips on a missing field; a readOnly/derived/auto-PK field is
+ // never in the body, so enforcing on it would reject every create).
+ const ref = (name: unknown): MetaField | undefined => {
+ if (typeof name !== "string" || !inSchema.has(name)) return undefined;
+ return byName.get(name);
+ };
+ // A TPH subtype's discriminator is pinned to one literal, so the rule reads that literal:
+ // the same refinement then holds whether or not the body carries the discriminator.
+ const pin = tphDiscriminatorPin(obj);
+ const acc = (f: MetaField) => pin !== undefined && f.name === pin.fieldName
+ ? JSON.stringify(pin.value)
+ : `row[${JSON.stringify(f.name)}]`;
+ const issue = (path: string, msg: string) =>
+ `ctx.addIssue({ code: "custom", path: [${path}], message: ${JSON.stringify(msg)} });`;
+ const blocks: string[] = [];
+ // ADR-0039: entity.validators() is the resolving accessor (never ownValidators).
+ for (const v of obj.validators()) {
+ switch (v.subType) {
+ case VALIDATOR_SUBTYPE_COMPARISON: {
+ const left = ref(v.attr(VALIDATOR_ATTR_LEFT));
+ const right = ref(v.attr(VALIDATOR_ATTR_RIGHT));
+ const opName = String(v.attr(VALIDATOR_ATTR_OP));
+ const op = CROSS_FIELD_OPS[opName];
+ if (!left || !right || !op || left.resolvedIsArray() || right.resolvedIsArray()) break;
+ const numeric = NUMERIC_SUBTYPES.has(left.subType);
+ const c = numeric
+ ? "Number(l) - Number(r)"
+ : "l instanceof Date && r instanceof Date ? l.getTime() - r.getTime() : String(l) < String(r) ? -1 : String(l) > String(r) ? 1 : 0";
+ blocks.push(
+ ` {\n const l: unknown = ${acc(left)};\n const r: unknown = ${acc(right)};\n` +
+ ` if (l != null && r != null) {\n const c = ${c};\n` +
+ ` if (!(c ${op} 0)) ${issue(JSON.stringify(left.name), `${left.name} must be ${opName} ${right.name}`)}\n }\n }`,
+ );
+ break;
+ }
+ case VALIDATOR_SUBTYPE_REQUIRED_WHEN:
+ case VALIDATOR_SUBTYPE_PRESENT_IFF: {
+ const target = ref(v.attr(VALIDATOR_ATTR_FIELD));
+ const when = ref(v.attr(VALIDATOR_ATTR_WHEN));
+ if (!target || !when || when.resolvedIsArray()) break;
+ const { lit, numeric } = crossFieldLiteral(v.attr(VALIDATOR_ATTR_EQUALS), when);
+ const gate = numeric ? `g != null && Number(g) === ${lit}` : `g === ${lit}`;
+ const path = JSON.stringify(target.name);
+ const decl = ` const g: unknown = ${acc(when)};\n const t: unknown = ${acc(target)};\n const open = ${gate};\n`;
+ if (v.subType === VALIDATOR_SUBTYPE_REQUIRED_WHEN) {
+ blocks.push(` {\n${decl} if (open && t == null) ${issue(path, `${target.name} is required when ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`);
+ } else {
+ blocks.push(` {\n${decl} if ((t != null) !== open) ${issue(path, `${target.name} must be present if and only if ${when.name} is ${String(v.attr(VALIDATOR_ATTR_EQUALS))}`)}\n }`);
+ }
+ break;
+ }
+ case VALIDATOR_SUBTYPE_AT_LEAST_ONE: {
+ const raw = v.attr(VALIDATOR_ATTR_FIELDS);
+ const names = Array.isArray(raw) ? raw : (typeof raw === "string" ? [raw] : []);
+ const refs = names.map(ref);
+ if (refs.length === 0 || refs.some((r) => r === undefined)) break;
+ const fields = refs as MetaField[];
+ const anyPresent = fields.map((f) => `${acc(f)} != null`).join(" || ");
+ blocks.push(` if (!(${anyPresent})) ${issue(JSON.stringify(fields[0]!.name), `at least one of ${fields.map((f) => f.name).join(", ")} is required`)}`);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ return blocks;
+}
+
+/** `.superRefine(...)` suffix for an insert-shaped schema, or "" when the object has no
+ * enforceable cross-field validator (output is then byte-identical to before). */
+function insertRefinementSuffix(obj: MetaObject): string {
+ const blocks = crossFieldRefinementBody(obj);
+ if (blocks.length === 0) return "";
+ return `.superRefine((row, ctx) => {\n${blocks.join("\n")}\n})`;
+}
+
/**
* Emit ONLY the `InsertSchema`. Used by the value-object file emitter
* for metaobjects with no writable source.rdb — those have no PATCH/update
@@ -322,7 +455,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co
return code`
${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({
${joinCode(insertFieldLines, { on: ",\n" })}
-});
+})${insertRefinementSuffix(obj)};
`;
}
@@ -535,6 +668,25 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
const docs = renderDocsFor(obj);
const docsPrefix = docs ? `${docs}\n` : "";
+ // A Zod object carrying refinements cannot be `.omit()`ed or `.partial()`ed, and a TPH
+ // subtype's route and form omit the pinned discriminator while its update query takes a
+ // partial. So when both apply, the unrefined shape is exported as `InsertBaseSchema`
+ // and refined twice: as `InsertSchema` and, discriminator omitted, as
+ // `InsertBodySchema`.
+ const refineSuffix = insertRefinementSuffix(obj);
+ const insertDecl = refineSuffix !== "" && tphPin !== undefined
+ ? code`export const ${objName}InsertBaseSchema = ${z}.object({
+${joinCode(insertFieldLines, { on: ",\n" })}
+});
+
+${docsPrefix}export const ${insertSchemaName} = ${objName}InsertBaseSchema${refineSuffix};
+
+/** ${insertSchemaName} without the pinned \`${tphPin.fieldName}\` — the body a per-subtype route accepts. */
+export const ${objName}InsertBodySchema = ${objName}InsertBaseSchema.omit({ ${tphPin.fieldName}: true })${refineSuffix};`
+ : code`${docsPrefix}export const ${insertSchemaName} = ${z}.object({
+${joinCode(insertFieldLines, { on: ",\n" })}
+})${refineSuffix};`;
+
// #203 — emit the preserving insert-shape only for @autoSet entities (nothing to
// preserve otherwise). Backs `insertPreserving` (import/restore/replication).
const preservingBlock = emitPreserving
@@ -545,16 +697,14 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code
* (no create-time now() stamp) so the caller's original values are preserved. */
export const ${preservingSchemaName} = ${z}.object({
${joinCode(preservingFieldLines, { on: ",\n" })}
-});
+})${insertRefinementSuffix(obj)};
/** Typed input of \`insertPreserving${objName}\` — ${preservingSchemaName}'s pre-transform shape. */
export type ${objName}CreatePreserving = ${z}.input;`
: code``;
return code`
-${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({
-${joinCode(insertFieldLines, { on: ",\n" })}
-});
+${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${insertDecl}
${docsPrefix}export const ${updateSchemaName} = ${z}.object({
${joinCode(updateFieldLines, { on: ",\n" })}
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
index a1e709017f..008e5dae1b 100644
--- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
+++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md
@@ -426,7 +426,11 @@ behavior:
Entity-scoped `validator.*` children declare invariants that reference sibling fields
**by name** (the same name-reference pattern as `identity.*`). The backend derives the
-enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored.
+enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`,
+and the generated full create/record model also enforces the rule in every port (Zod refinement,
+Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a
+store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them
+(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there.
| Subtype | Rule | Key attrs |
|---|---|---|
diff --git a/fixtures/validation-conformance/README.md b/fixtures/validation-conformance/README.md
index 0bb31d696b..b6fc8ca33e 100644
--- a/fixtures/validation-conformance/README.md
+++ b/fixtures/validation-conformance/README.md
@@ -111,6 +111,30 @@ FR-036 pin cases (the two semantic pins + the length-precedence pin):
absent `note` is still rejected. No port may apply the Pin 1 floor (min 1)
when an author has explicitly said `@min: 0`.
+## Cross-field validators — `meta.cross-field.json` + `cross-field-cases.json`
+
+A second, separate pair of files pins the four entity-scoped cross-field validators
+(`validator.comparison`, `validator.requiredWhen`, `validator.presentIff`,
+`validator.atLeastOne`) on the generated **full record (create) model**. They are separate files
+so the run-time runners, which read `cases.json`, are unaffected. The entity is `Event`; every field
+is optional, so absence is expressible in every port.
+
+The semantics mirror the DB `CHECK` derivation in `migrate-ts/src/expected-schema.ts`, with an absent
+or null value standing for SQL `NULL` (and `""` NOT null):
+
+- `comparison` (`startsAt lte endsAt`): passes when either side is null.
+- `requiredWhen`: violated only when the gating field equals `@equals` and the target is null; a null
+ gate is unconstrained. Both a string gate (`kind = BIRTH`) and a boolean gate (`flag = true`).
+- `presentIff`: the target is present exactly when the gate equals `@equals`; a null gate counts as
+ not equal, so the target must be absent.
+- `atLeastOne` (`email`, `phone`): at least one is non-null.
+- A rule naming a field the create body never carries (`reviewedBy`, `@mutability: readOnly`; likewise a
+ derived field or a store-generated key) is skipped, so `review = DONE` without a reviewer is valid.
+
+Each case violates at most one validator (single-violation design). PATCH and partial-update models
+are NOT covered here by design: they do not enforce cross-field rules, and the DB `CHECK` stays the
+enforcement for them.
+
## `field.uri` / `field.inet` strict contract (#234, ADR-0037 — Contract A)
`Account` carries two OPTIONAL fields — `website` (`field.uri`) and `sourceIp`
diff --git a/fixtures/validation-conformance/cross-field-cases.json b/fixtures/validation-conformance/cross-field-cases.json
new file mode 100644
index 0000000000..57949d652f
--- /dev/null
+++ b/fixtures/validation-conformance/cross-field-cases.json
@@ -0,0 +1,263 @@
+{
+ "cases": [
+ {
+ "name": "cross-valid-baseline",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "comparison-violated",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 5,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "comparison-equal-boundary",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 2,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "comparison-null-right-passes",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "comparison-null-left-passes",
+ "entity": "Event",
+ "payload": {
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "required-when-violated",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "required-when-other-value-unconstrained",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "DEATH",
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "required-when-gate-null-unconstrained",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "state": "OPEN",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "required-when-boolean-violated",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "flag": true
+ },
+ "expectValid": false
+ },
+ {
+ "name": "required-when-boolean-satisfied",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "flag": true,
+ "flagNote": "why"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "required-when-boolean-false-unconstrained",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "flag": false
+ },
+ "expectValid": true
+ },
+ {
+ "name": "present-iff-missing-target",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "CLOSED",
+ "email": "a@b.c"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "present-iff-forbidden-target",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "closedNote": "stray"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "present-iff-satisfied",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "CLOSED",
+ "email": "a@b.c",
+ "closedNote": "done"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "present-iff-gate-null-forbids-target",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "email": "a@b.c",
+ "closedNote": "stray"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "present-iff-both-absent",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "email": "a@b.c"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "at-least-one-violated",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN"
+ },
+ "expectValid": false
+ },
+ {
+ "name": "at-least-one-second-field",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "phone": "555"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "at-least-one-both",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "BIRTH",
+ "subject": "p1",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "phone": "555"
+ },
+ "expectValid": true
+ },
+ {
+ "name": "rule-on-read-only-field-skipped",
+ "entity": "Event",
+ "payload": {
+ "startsAt": 1,
+ "endsAt": 2,
+ "kind": "OTHER",
+ "state": "OPEN",
+ "email": "a@b.c",
+ "review": "DONE"
+ },
+ "expectValid": true
+ }
+ ]
+}
diff --git a/fixtures/validation-conformance/meta.cross-field.json b/fixtures/validation-conformance/meta.cross-field.json
new file mode 100644
index 0000000000..c2e4b65c98
--- /dev/null
+++ b/fixtures/validation-conformance/meta.cross-field.json
@@ -0,0 +1,33 @@
+{
+ "metadata.root": {
+ "package": "acme::events",
+ "children": [
+ { "object.entity": {
+ "name": "Event",
+ "children": [
+ { "source.rdb": { "@table": "events" } },
+ { "field.long": { "name": "id" } },
+ { "field.int": { "name": "startsAt" } },
+ { "field.int": { "name": "endsAt" } },
+ { "field.string": { "name": "kind" } },
+ { "field.string": { "name": "subject" } },
+ { "field.string": { "name": "state" } },
+ { "field.string": { "name": "closedNote" } },
+ { "field.boolean": { "name": "flag" } },
+ { "field.string": { "name": "flagNote" } },
+ { "field.string": { "name": "email" } },
+ { "field.string": { "name": "phone" } },
+ { "field.string": { "name": "review" } },
+ { "field.string": { "name": "reviewedBy", "@mutability": "readOnly" } },
+ { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } },
+ { "validator.comparison": { "name": "startsBeforeEnds", "@left": "startsAt", "@op": "lte", "@right": "endsAt" } },
+ { "validator.requiredWhen": { "name": "birthNeedsSubject", "@field": "subject", "@when": "kind", "@equals": "BIRTH" } },
+ { "validator.requiredWhen": { "name": "flaggedNeedsNote", "@field": "flagNote", "@when": "flag", "@equals": "true" } },
+ { "validator.presentIff": { "name": "closedIffNote", "@field": "closedNote", "@when": "state", "@equals": "CLOSED" } },
+ { "validator.atLeastOne": { "name": "reachable", "@fields": ["email", "phone"] } },
+ { "validator.requiredWhen": { "name": "reviewNeedsReviewer", "@field": "reviewedBy", "@when": "review", "@equals": "DONE" } }
+ ]
+ }}
+ ]
+ }
+}
diff --git a/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
new file mode 100644
index 0000000000..72f15b02a6
--- /dev/null
+++ b/server/csharp/MetaObjects.Codegen.Tests/CrossFieldValidationConformanceTests.cs
@@ -0,0 +1,125 @@
+using System.ComponentModel.DataAnnotations;
+using System.Reflection;
+using System.Text.Json;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using MetaObjects.Codegen;
+using MetaObjects.Codegen.Generators;
+using MetaObjects.Loader;
+using Xunit;
+
+namespace MetaObjects.Codegen.Tests;
+
+///
+/// Cross-field validator gate (C# port). Runs the shared
+/// fixtures/validation-conformance/cross-field-cases.json corpus through the GENERATED
+/// Event record (compiled in-memory with Roslyn) exactly the way
+/// does: bind the payload, then
+///
+/// with validateAllProperties: true, which invokes once the
+/// property-level attributes pass.
+///
+public sealed class CrossFieldValidationConformanceTests
+{
+ private static string CorpusDir()
+ {
+ string root = AppContext.BaseDirectory;
+ while (!Directory.Exists(Path.Combine(root, "fixtures", "validation-conformance")))
+ {
+ string? parent = Directory.GetParent(root)?.FullName;
+ if (parent is null || parent == root)
+ throw new InvalidOperationException("fixtures/validation-conformance not found");
+ root = parent;
+ }
+ return Path.Combine(root, "fixtures", "validation-conformance");
+ }
+
+ private static JsonElement[] AllCases()
+ {
+ using JsonDocument doc = JsonDocument.Parse(
+ File.ReadAllText(Path.Combine(CorpusDir(), "cross-field-cases.json")));
+ return doc.RootElement.GetProperty("cases").EnumerateArray().Select(c => c.Clone()).ToArray();
+ }
+
+ public static IEnumerable