From ebf6fc5d9f7142d85d3cfd11ead44485d4a848ca Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 04:52:22 -0500 Subject: [PATCH 1/7] feat(metadata): relative dates and case/now expressions in every loader Load and validate, in TypeScript, C#, Java (Kotlin through it) and Python: - a relative date ({ now: ... }) in a projection's and an origin.first / origin.aggregate's @filter, shape-checked where it is declared; - case and now in an origin.computed expression, and a ref in it that names another of the projection's own fields (never itself, never an aggregate) before a base field. error-relative-date-origin-host and error-relative-date-wrong-host are removed: those hosts now accept the value. New fixtures: projection-filter-relative-now, origin-filter-relative-now, origin-computed-case-over-joined, error-origin-computed-case-mixed-types. --- AGENTS.md | 2 +- CHANGELOG.md | 15 +- docs/CONFORMANCE.md | 6 +- docs/features/reporting.md | 2 +- docs/features/source-kinds.md | 8 + examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 + .../input/meta.views.json | 147 ++++++ .../providers.json | 0 .../expected-errors.json | 15 - .../expected-errors.json | 15 - .../expected.json | 260 +++++++++++ .../input/meta.views.json | 254 +++++++++++ .../providers.json | 0 .../origin-filter-relative-now/expected.json | 420 ++++++++++++++++++ .../input/meta.shop.json | 0 .../origin-filter-relative-now/providers.json | 1 + .../expected.json | 412 +++++++++++++++++ .../input/meta.shop.json | 0 .../providers.json | 1 + fixtures/metamodel-docs/expected/INDEX.md | 2 +- .../metamodel-docs/expected/types/attr.md | 2 +- .../metamodel-docs/expected/types/origin.md | 4 +- .../expected-registry.json | 6 +- .../ReportingValidationTests.cs | 12 +- .../Core/Attr/ExpressionGrammar.cs | 79 +++- .../Loader/ValidationPasses.Reporting.cs | 51 ++- .../MetaObjects/Loader/ValidationPasses.cs | 13 +- .../MetaObjects/SpecMetamodel/attr.json | 2 +- .../MetaObjects/SpecMetamodel/origin.json | 4 +- .../metaobjects/attr/ExpressionAttribute.java | 81 +++- .../loader/ReportingValidation.java | 57 ++- .../metaobjects/loader/ValidationPhase.java | 18 +- .../loader/ReportingValidationTest.java | 4 +- .../metaobjects/loader/validate_reporting.py | 68 ++- .../metaobjects/loader/validation_passes.py | 82 +++- .../src/metaobjects/spec_metamodel/attr.json | 2 +- .../metaobjects/spec_metamodel/origin.json | 4 +- .../src/core/attr/attr-definition.embedded.ts | 2 +- .../src/core/attr/meta-attr-expression.ts | 71 ++- .../src/loader/reporting-validation.ts | 50 ++- .../metadata/src/loader/validation-passes.ts | 14 +- .../origin/origin-definition.embedded.ts | 4 +- .../test/reporting-validation.test.ts | 15 +- site-reference/index.html | 2 +- site-reference/types/attr.html | 2 +- site-reference/types/origin.html | 4 +- spec/metamodel/attr.json | 2 +- spec/metamodel/origin.json | 4 +- 49 files changed, 2138 insertions(+), 98 deletions(-) create mode 100644 fixtures/conformance/error-origin-computed-case-mixed-types/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json rename fixtures/conformance/{error-relative-date-origin-host => error-origin-computed-case-mixed-types}/providers.json (100%) delete mode 100644 fixtures/conformance/error-relative-date-origin-host/expected-errors.json delete mode 100644 fixtures/conformance/error-relative-date-wrong-host/expected-errors.json create mode 100644 fixtures/conformance/origin-computed-case-over-joined/expected.json create mode 100644 fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json rename fixtures/conformance/{error-relative-date-wrong-host => origin-computed-case-over-joined}/providers.json (100%) create mode 100644 fixtures/conformance/origin-filter-relative-now/expected.json rename fixtures/conformance/{error-relative-date-origin-host => origin-filter-relative-now}/input/meta.shop.json (100%) create mode 100644 fixtures/conformance/origin-filter-relative-now/providers.json create mode 100644 fixtures/conformance/projection-filter-relative-now/expected.json rename fixtures/conformance/{error-relative-date-wrong-host => projection-filter-relative-now}/input/meta.shop.json (100%) create mode 100644 fixtures/conformance/projection-filter-relative-now/providers.json diff --git a/AGENTS.md b/AGENTS.md index 3d772c9692..60a3f86018 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/` (459 fixtures; 38 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/` (461 fixtures; 38 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 5e2d310b29..03a431c1a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,8 +37,9 @@ _npm `1.3.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates **`metamodelVersion` moves to `1.3`.** This release adds vocabulary (`field.duration`, `validator.exactlyOne`, `@constraintName`, `@condition`, `@maxLength` on `field.enum`, -`@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule and -`@collectionName`) and nothing that loaded before stops loading. The registry gains two +`@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule, +`@collectionName`, and the `case` and `now` expression nodes) and nothing that loaded before +stops loading. The registry gains two fields on a type or attr entry, carried into the registry manifest: `implementedIn` (cross-port vocabulary only the named ports implement so far, e.g. the `view.*` controls, `["typescript"]`) and `ports` (vocabulary only the named ports ever act on, e.g. `@objectAdapter`, `["java", "kotlin"]`: @@ -137,6 +138,16 @@ Each item below is described in full under Added, Changed or Fixed; this list is (`ERR_AMBIGUOUS_PATH`). A declared relationship or reference of the same name still wins. Every port's loader implements it, gated by `origin-reverse-reference-hop`, `origin-reverse-hop-collection-name` and `error-origin-reverse-hop-ambiguous`. +- **Expressions and relative dates in views.** These load and validate in every port's loader, + each gated by shared conformance fixtures: + - a projection's and an `origin.first` / `origin.aggregate`'s `@filter` take a relative date + (`{ "now": "-P7D" }`), checked for its shape (`projection-filter-relative-now`, + `origin-filter-relative-now`); the fixtures `error-relative-date-origin-host` and + `error-relative-date-wrong-host`, which asserted the refusal, are removed; + - an `origin.computed` expression may use `now` and `case` (searched, or simple with an + `operand`), and a ref in it may name another of the projection's own fields (a passthrough, + an `origin.first` or another `origin.computed`, never itself or an aggregate) before a base + field (`origin-computed-case-over-joined`, `error-origin-computed-case-mixed-types`). - **An int-backed enum can be an array.** `@intValueMap` together with `isArray: true` (the map on the field, or inherited from a shared enum) now loads in every port instead of diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 24b413c16c..9b61a4eacb 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) | 459 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 461 | ✓ | ✓ | 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 | ✓ | — | — | — | ✓ | @@ -354,7 +354,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (459) +### `fixtures/conformance/` — metamodel loader + canonical serializer (461) | Fixture prefix | Feature doc | |---|---| @@ -716,7 +716,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 459 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 461 + yaml 16 + verify 45 + render 18 + persistence 62 + api-contract 123 + source-resolution 25 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 16c3da0f0f..0e4b993f55 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -969,7 +969,7 @@ only beside `now`. | Rule | Code | Refused | |---|---|---| -| **F1** | `ERR_BAD_ATTR_FILTER` | A relative value anywhere except the `@filter` of a `segment`, a `measure.aggregate` or an `object.report`. In a `layout.dataGrid` preset, a projection `@filter` or an `origin.aggregate` `@filter` it fails the load, because no lowering exists for those hosts. | +| **F1** | `ERR_BAD_ATTR_FILTER` | A relative value anywhere except the `@filter` of a `segment`, a `measure.aggregate`, an `object.report`, an `object.projection`, an `origin.first` or an `origin.aggregate`. In a `layout.dataGrid` preset it fails the load, because no lowering exists for that host. On a projection or an origin, whose filter keys resolve elsewhere, the loader checks the value's own shape (F2's operator, duration and `startOf` rules) and the field type is checked where the filter is lowered. | | **F2** | `ERR_BAD_ATTR_FILTER` | A relative value on any field except a `field.date` or `field.timestamp`; under any operator except `gt, gte, lt, lte`; as an object that carries keys besides `now` and `startOf`; with a duration that does not match the ISO-8601 pattern `^[+-]?P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$`; or with a `startOf` other than `day`, `week` or `month`. | An operator-less `{ "occurredAt": { "now": "-P7D" } }` is read as `eq`, and `eq` is not one diff --git a/docs/features/source-kinds.md b/docs/features/source-kinds.md index 3fe738009d..2b2377b09b 100644 --- a/docs/features/source-kinds.md +++ b/docs/features/source-kinds.md @@ -196,6 +196,14 @@ round out the read-model vocabulary: **`origin.computed`** carries a closed `@ex expression grammar (a derived scalar computed from other fields), and **`origin.first`** picks one related row's column along a `@via` path (an argmax-style projection; nullable). +**Expressions and relative dates.** An `origin.computed` `@expr` may use `case` +(`{ "case": [ { "when": …, "then": … } ], "else": … }`, or with an `operand` for the simple +form) and `now` (the current instant), and a `{ "field": … }` ref in it names one of the +projection's own fields first (a passthrough, an `origin.first` or another `origin.computed`, +never itself or an aggregate), else a base field. An `origin.first` or `origin.aggregate` +`@filter`, like a projection's, may hold a relative date (`{ "now": "-P7D" }`, see +[reporting.md](reporting.md#relative-dates-in-filters)). Every port's loader validates these. + **Projection row-scope `@filter` (#207).** Distinct from the *per-aggregate* `@filter` above, an **object-level `@filter` on an `object.projection`** scopes the whole view's rows — it lowers to the view's outer `WHERE`. This is the metadata-managed way to express a diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index c12759239a..cedd67c485 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 459, + "fixtures": 461, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-origin-computed-case-mixed-types/expected-errors.json b/fixtures/conformance/error-origin-computed-case-mixed-types/expected-errors.json new file mode 100644 index 0000000000..4f85fa90d0 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-mixed-types/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.string'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json new file mode 100644 index 0000000000..54d52403ec --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json @@ -0,0 +1,147 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "BadCase", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_badcase" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.string": { + "name": "x", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "status" + }, + "right": { + "value": 0 + } + }, + "then": { + "value": "a" + } + } + ], + "else": { + "value": 1 + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-relative-date-origin-host/providers.json b/fixtures/conformance/error-origin-computed-case-mixed-types/providers.json similarity index 100% rename from fixtures/conformance/error-relative-date-origin-host/providers.json rename to fixtures/conformance/error-origin-computed-case-mixed-types/providers.json diff --git a/fixtures/conformance/error-relative-date-origin-host/expected-errors.json b/fixtures/conformance/error-relative-date-origin-host/expected-errors.json deleted file mode 100644 index 180ff9f0c0..0000000000 --- a/fixtures/conformance/error-relative-date-origin-host/expected-errors.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "errors": [ - { - "code": "ERR_BAD_ATTR_FILTER", - "source": { - "format": "json", - "files": [ - "meta.shop.json" - ], - "jsonPath": "$['metadata.root'].children[6]['object.projection'].children[2]['field.int'].children[0]['origin.aggregate']" - } - } - ], - "warnings": [] -} diff --git a/fixtures/conformance/error-relative-date-wrong-host/expected-errors.json b/fixtures/conformance/error-relative-date-wrong-host/expected-errors.json deleted file mode 100644 index 9a10663ea4..0000000000 --- a/fixtures/conformance/error-relative-date-wrong-host/expected-errors.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "errors": [ - { - "code": "ERR_BAD_ATTR_FILTER", - "source": { - "format": "json", - "files": [ - "meta.shop.json" - ], - "jsonPath": "$['metadata.root'].children[6]['object.projection']" - } - } - ], - "warnings": [] -} diff --git a/fixtures/conformance/origin-computed-case-over-joined/expected.json b/fixtures/conformance/origin-computed-case-over-joined/expected.json new file mode 100644 index 0000000000..5758a08ac8 --- /dev/null +++ b/fixtures/conformance/origin-computed-case-over-joined/expected.json @@ -0,0 +1,260 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "field.string": { + "name": "displayName" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": [ + "statusId" + ], + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "CaseLabels", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_caselabels" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.string": { + "name": "statusName", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Status.name", + "@via": "acme::views::Case.statusId" + } + } + ] + } + }, + { + "field.string": { + "name": "statusDisplay", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Status.displayName", + "@via": "acme::views::Case.statusId" + } + } + ] + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "statusDisplay" + }, + { + "field": "statusName" + } + ] + } + } + } + ] + } + }, + { + "field.int": { + "name": "outcome", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "cumulativeStatus" + }, + "right": { + "value": 0 + } + }, + "then": { + "field": "status" + } + } + ], + "else": { + "field": "cumulativeStatus" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "benefitTypeName", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "priorType" + }, + "case": [ + { + "when": { + "value": 1 + }, + "then": { + "value": "Medical" + } + }, + { + "when": { + "value": 2 + }, + "then": { + "value": "Pharmacy" + } + } + ] + } + } + } + ] + } + }, + { + "field.boolean": { + "name": "started", + "children": [ + { + "origin.computed": { + "@expr": { + "op": "gte", + "left": { + "now": "P0D" + }, + "right": { + "field": "effectiveFrom" + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json new file mode 100644 index 0000000000..bf214bb6c9 --- /dev/null +++ b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json @@ -0,0 +1,254 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "field.string": { + "name": "displayName" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "CaseLabels", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_caselabels" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.string": { + "name": "statusName", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Status.name", + "@via": "acme::views::Case.statusId" + } + } + ] + } + }, + { + "field.string": { + "name": "statusDisplay", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Status.displayName", + "@via": "acme::views::Case.statusId" + } + } + ] + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "statusDisplay" + }, + { + "field": "statusName" + } + ] + } + } + } + ] + } + }, + { + "field.int": { + "name": "outcome", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "cumulativeStatus" + }, + "right": { + "value": 0 + } + }, + "then": { + "field": "status" + } + } + ], + "else": { + "field": "cumulativeStatus" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "benefitTypeName", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "priorType" + }, + "case": [ + { + "when": { + "value": 1 + }, + "then": { + "value": "Medical" + } + }, + { + "when": { + "value": 2 + }, + "then": { + "value": "Pharmacy" + } + } + ] + } + } + } + ] + } + }, + { + "field.boolean": { + "name": "started", + "children": [ + { + "origin.computed": { + "@expr": { + "op": "gte", + "left": { + "now": "P0D" + }, + "right": { + "field": "effectiveFrom" + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-relative-date-wrong-host/providers.json b/fixtures/conformance/origin-computed-case-over-joined/providers.json similarity index 100% rename from fixtures/conformance/error-relative-date-wrong-host/providers.json rename to fixtures/conformance/origin-computed-case-over-joined/providers.json diff --git a/fixtures/conformance/origin-filter-relative-now/expected.json b/fixtures/conformance/origin-filter-relative-now/expected.json new file mode 100644 index 0000000000..2d788155ef --- /dev/null +++ b/fixtures/conformance/origin-filter-relative-now/expected.json @@ -0,0 +1,420 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Program", + "children": [ + { + "source.rdb": { + "@table": "programs" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.timestamp": { + "name": "createdAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "relationship.association": { + "name": "purchases", + "@cardinality": "many", + "@objectRef": "acme::shop::Purchase" + } + } + ] + } + }, + { + "object.entity": { + "name": "Purchase", + "children": [ + { + "source.rdb": { + "@table": "purchases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.string": { + "name": "customerEmail" + } + }, + { + "field.currency": { + "name": "amountCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "field.boolean": { + "name": "refunded" + } + }, + { + "field.timestamp": { + "name": "purchasedAt" + } + }, + { + "field.date": { + "name": "purchasedOn" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "programRef", + "@fields": [ + "programId" + ], + "@references": "acme::shop::Program" + } + }, + { + "relationship.association": { + "name": "program", + "@cardinality": "one", + "@objectRef": "acme::shop::Program" + } + }, + { + "dimension.attribute": { + "name": "program", + "@of": "acme::shop::Purchase.programId" + } + }, + { + "dimension.attribute": { + "name": "programTitle", + "@of": "acme::shop::Program.title", + "@via": "acme::shop::Purchase.program" + } + }, + { + "dimension.time": { + "name": "purchasedAt", + "@grains": [ + "day", + "week", + "month", + "quarter", + "year" + ], + "@of": "acme::shop::Purchase.purchasedAt" + } + }, + { + "dimension.time": { + "name": "programCreatedAt", + "@grains": [ + "month", + "year" + ], + "@of": "acme::shop::Program.createdAt", + "@via": "acme::shop::Purchase.program" + } + }, + { + "measure.aggregate": { + "name": "refundedPurchases", + "@agg": "count", + "@filter": { + "refunded": { + "eq": true + } + }, + "@of": [ + "acme::shop::Purchase.id" + ] + } + }, + { + "measure.aggregate": { + "name": "purchases", + "@agg": "count", + "@of": [ + "acme::shop::Purchase.id" + ], + "@segment": "active" + } + }, + { + "measure.aggregate": { + "name": "buyers", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::Purchase.customerEmail" + ], + "@segment": "active" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": [ + "acme::shop::Purchase.amountCents" + ], + "@segment": "active" + } + }, + { + "segment.filter": { + "name": "active", + "@filter": { + "status": { + "eq": "active" + } + } + } + } + ] + } + }, + { + "object.entity": { + "name": "WorkoutEvent", + "children": [ + { + "source.rdb": { + "@table": "workout_events" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.string": { + "name": "customerEmail" + } + }, + { + "field.int": { + "name": "weekNumber" + } + }, + { + "field.int": { + "name": "dayNumber" + } + }, + { + "field.string": { + "name": "eventType" + } + }, + { + "field.timestamp": { + "name": "occurredAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "dimension.attribute": { + "name": "program", + "@of": "acme::shop::WorkoutEvent.programId" + } + }, + { + "measure.aggregate": { + "name": "starters", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::WorkoutEvent.customerEmail" + ] + } + }, + { + "measure.aggregate": { + "name": "daysEngaged", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::WorkoutEvent.programId", + "acme::shop::WorkoutEvent.customerEmail", + "acme::shop::WorkoutEvent.weekNumber", + "acme::shop::WorkoutEvent.dayNumber" + ] + } + }, + { + "measure.aggregate": { + "name": "lastActivityAt", + "@agg": "max", + "@of": [ + "acme::shop::WorkoutEvent.occurredAt" + ] + } + }, + { + "measure.ratio": { + "name": "avgDaysPerStarter", + "@denominator": "starters", + "@numerator": "daysEngaged" + } + }, + { + "segment.filter": { + "name": "completions", + "@filter": { + "eventType": { + "eq": "exercise_complete" + } + } + } + } + ] + } + }, + { + "object.report": { + "name": "ProgramEngagement", + "@dimensions": [ + "program" + ], + "@from": "acme::shop::WorkoutEvent", + "@measures": [ + "starters", + "daysEngaged", + "avgDaysPerStarter", + "lastActivityAt" + ], + "@segment": "completions" + } + }, + { + "object.report": { + "name": "DailyRevenue", + "@dimensions": [ + "purchasedAt:day" + ], + "@filter": { + "purchasedAt": { + "gte": { + "now": "-P90D" + } + } + }, + "@from": "acme::shop::Purchase", + "@measures": [ + "purchases", + "revenue" + ] + } + }, + { + "object.report": { + "name": "StoreTotals", + "@from": "acme::shop::Purchase", + "@measures": [ + "purchases", + "buyers", + "revenue" + ] + } + }, + { + "object.projection": { + "name": "ProgramPurchaseCounts", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "program_purchase_counts" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::shop::Program.id" + } + }, + { + "field.int": { + "name": "recentPurchaseCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@filter": { + "purchasedAt": { + "gte": { + "now": "-P7D" + } + } + }, + "@of": "acme::shop::Purchase.id", + "@via": "acme::shop::Program.purchases" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::shop::Program.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-relative-date-origin-host/input/meta.shop.json b/fixtures/conformance/origin-filter-relative-now/input/meta.shop.json similarity index 100% rename from fixtures/conformance/error-relative-date-origin-host/input/meta.shop.json rename to fixtures/conformance/origin-filter-relative-now/input/meta.shop.json diff --git a/fixtures/conformance/origin-filter-relative-now/providers.json b/fixtures/conformance/origin-filter-relative-now/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/origin-filter-relative-now/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/projection-filter-relative-now/expected.json b/fixtures/conformance/projection-filter-relative-now/expected.json new file mode 100644 index 0000000000..80505a8e58 --- /dev/null +++ b/fixtures/conformance/projection-filter-relative-now/expected.json @@ -0,0 +1,412 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Program", + "children": [ + { + "source.rdb": { + "@table": "programs" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "title" + } + }, + { + "field.timestamp": { + "name": "createdAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "relationship.association": { + "name": "purchases", + "@cardinality": "many", + "@objectRef": "acme::shop::Purchase" + } + } + ] + } + }, + { + "object.entity": { + "name": "Purchase", + "children": [ + { + "source.rdb": { + "@table": "purchases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.string": { + "name": "customerEmail" + } + }, + { + "field.currency": { + "name": "amountCents" + } + }, + { + "field.string": { + "name": "status" + } + }, + { + "field.boolean": { + "name": "refunded" + } + }, + { + "field.timestamp": { + "name": "purchasedAt" + } + }, + { + "field.date": { + "name": "purchasedOn" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "programRef", + "@fields": [ + "programId" + ], + "@references": "acme::shop::Program" + } + }, + { + "relationship.association": { + "name": "program", + "@cardinality": "one", + "@objectRef": "acme::shop::Program" + } + }, + { + "dimension.attribute": { + "name": "program", + "@of": "acme::shop::Purchase.programId" + } + }, + { + "dimension.attribute": { + "name": "programTitle", + "@of": "acme::shop::Program.title", + "@via": "acme::shop::Purchase.program" + } + }, + { + "dimension.time": { + "name": "purchasedAt", + "@grains": [ + "day", + "week", + "month", + "quarter", + "year" + ], + "@of": "acme::shop::Purchase.purchasedAt" + } + }, + { + "dimension.time": { + "name": "programCreatedAt", + "@grains": [ + "month", + "year" + ], + "@of": "acme::shop::Program.createdAt", + "@via": "acme::shop::Purchase.program" + } + }, + { + "measure.aggregate": { + "name": "refundedPurchases", + "@agg": "count", + "@filter": { + "refunded": { + "eq": true + } + }, + "@of": [ + "acme::shop::Purchase.id" + ] + } + }, + { + "measure.aggregate": { + "name": "purchases", + "@agg": "count", + "@of": [ + "acme::shop::Purchase.id" + ], + "@segment": "active" + } + }, + { + "measure.aggregate": { + "name": "buyers", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::Purchase.customerEmail" + ], + "@segment": "active" + } + }, + { + "measure.aggregate": { + "name": "revenue", + "@agg": "sum", + "@of": [ + "acme::shop::Purchase.amountCents" + ], + "@segment": "active" + } + }, + { + "segment.filter": { + "name": "active", + "@filter": { + "status": { + "eq": "active" + } + } + } + } + ] + } + }, + { + "object.entity": { + "name": "WorkoutEvent", + "children": [ + { + "source.rdb": { + "@table": "workout_events" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.string": { + "name": "customerEmail" + } + }, + { + "field.int": { + "name": "weekNumber" + } + }, + { + "field.int": { + "name": "dayNumber" + } + }, + { + "field.string": { + "name": "eventType" + } + }, + { + "field.timestamp": { + "name": "occurredAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "dimension.attribute": { + "name": "program", + "@of": "acme::shop::WorkoutEvent.programId" + } + }, + { + "measure.aggregate": { + "name": "starters", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::WorkoutEvent.customerEmail" + ] + } + }, + { + "measure.aggregate": { + "name": "daysEngaged", + "@agg": "count", + "@distinct": true, + "@of": [ + "acme::shop::WorkoutEvent.programId", + "acme::shop::WorkoutEvent.customerEmail", + "acme::shop::WorkoutEvent.weekNumber", + "acme::shop::WorkoutEvent.dayNumber" + ] + } + }, + { + "measure.aggregate": { + "name": "lastActivityAt", + "@agg": "max", + "@of": [ + "acme::shop::WorkoutEvent.occurredAt" + ] + } + }, + { + "measure.ratio": { + "name": "avgDaysPerStarter", + "@denominator": "starters", + "@numerator": "daysEngaged" + } + }, + { + "segment.filter": { + "name": "completions", + "@filter": { + "eventType": { + "eq": "exercise_complete" + } + } + } + } + ] + } + }, + { + "object.report": { + "name": "ProgramEngagement", + "@dimensions": [ + "program" + ], + "@from": "acme::shop::WorkoutEvent", + "@measures": [ + "starters", + "daysEngaged", + "avgDaysPerStarter", + "lastActivityAt" + ], + "@segment": "completions" + } + }, + { + "object.report": { + "name": "DailyRevenue", + "@dimensions": [ + "purchasedAt:day" + ], + "@filter": { + "purchasedAt": { + "gte": { + "now": "-P90D" + } + } + }, + "@from": "acme::shop::Purchase", + "@measures": [ + "purchases", + "revenue" + ] + } + }, + { + "object.report": { + "name": "StoreTotals", + "@from": "acme::shop::Purchase", + "@measures": [ + "purchases", + "buyers", + "revenue" + ] + } + }, + { + "object.projection": { + "name": "RecentPurchase", + "@filter": { + "purchasedAt": { + "gte": { + "now": "-P7D" + } + } + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "recent_purchases" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::shop::Purchase.id" + } + }, + { + "field.timestamp": { + "name": "purchasedAt", + "extends": "acme::shop::Purchase.purchasedAt" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::shop::Purchase.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-relative-date-wrong-host/input/meta.shop.json b/fixtures/conformance/projection-filter-relative-now/input/meta.shop.json similarity index 100% rename from fixtures/conformance/error-relative-date-wrong-host/input/meta.shop.json rename to fixtures/conformance/projection-filter-relative-now/input/meta.shop.json diff --git a/fixtures/conformance/projection-filter-relative-now/providers.json b/fixtures/conformance/projection-filter-relative-now/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/projection-filter-relative-now/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 1a81c10049..d0ba64ebf9 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -19,7 +19,7 @@ children and the cardinality of that subtype. Documentation attributes | `attr.boolean` | A boolean-valued metadata attribute. Coerces to and validates as true/false. | [types/attr.md#attrboolean](types/attr.md#attrboolean) | | `attr.class` | A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets. | [types/attr.md#attrclass](types/attr.md#attrclass) | | `attr.double` | A double-precision floating-point-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrdouble](types/attr.md#attrdouble) | -| `attr.expression` | A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | +| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | | `attr.filter` | A filter-expression-valued metadata attribute. Object-shaped value that desugars a preset filter to the canonical { field: { op: value } } form (scalar→eq, array→in, null→isNull; or/and recurse). | [types/attr.md#attrfilter](types/attr.md#attrfilter) | | `attr.int` | A 32-bit-integer-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrint](types/attr.md#attrint) | | `attr.intMap` | An object-shaped attribute whose values are all integers (e.g. field.enum's @intValueMap: {memberSymbol: int}). Generic shape check only; a consumer field type layers its own semantic rules (key-set membership, uniqueness) in its own content-rule validation. | [types/attr.md#attrintmap](types/attr.md#attrintmap) | diff --git a/fixtures/metamodel-docs/expected/types/attr.md b/fixtures/metamodel-docs/expected/types/attr.md index bb647e4e3d..c59cccb5f1 100644 --- a/fixtures/metamodel-docs/expected/types/attr.md +++ b/fixtures/metamodel-docs/expected/types/attr.md @@ -68,7 +68,7 @@ _No structural children._ ### attr.expression -A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159. +A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. **Owning provider:** metaobjects-core-types diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index e3a929ed13..4a2ce7953b 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -26,7 +26,7 @@ A value reduced from the related row-set reached along a relationship path (@via | --- | --- | --- | --- | --- | --- | --- | | `@agg` | string | yes | | `count`, `sum`, `avg`, `min`, `max`, `any`, `all`, `collect` | metaobjects-core-types | The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray). | | `@distinct` | boolean | no | | | metaobjects-core-types | Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal. | -| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). | +| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field. | | `@of` | string | no | | | metaobjects-core-types | Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column). | | `@orderBy` | string[] | no | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | @@ -81,7 +81,7 @@ The single related row selected by @orderBy along @via, projecting its @of colum | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. | +| `@filter` | filter | no | | | metaobjects-core-types | Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field. | | `@of` | string | yes | | | metaobjects-core-types | Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine). | | `@orderBy` | string[] | yes | | | metaobjects-core-types | Ordering keys as 'field[:asc\|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax. | | `@via` | string | no | | | metaobjects-core-types | Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 0acf77e54d..2b39ff1a37 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -32,7 +32,7 @@ { "type": "attr", "subType": "expression", - "description": "A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159.", + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.", "attrs": [], "children": [] }, @@ -3975,7 +3975,7 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view)." + "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "name": "of", @@ -4036,7 +4036,7 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time." + "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "name": "of", diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReportingValidationTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReportingValidationTests.cs index e30c3b0873..0e414a224e 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ReportingValidationTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ReportingValidationTests.cs @@ -588,7 +588,7 @@ public void F2_a_now_key_plus_other_keys_is_refused_on_a_reporting_host() } [Fact] - public void F1_a_now_key_plus_other_keys_is_refused_on_a_non_reporting_host() + public void F1_a_now_key_plus_other_keys_is_refused_on_a_view_host() { var m = Positive(); RootChildren(m).Add(Wrap("object.projection", """ @@ -600,11 +600,9 @@ public void F1_a_now_key_plus_other_keys_is_refused_on_a_non_reporting_host() { "field.timestamp": { "name": "purchasedAt", "extends": "Purchase.purchasedAt" } }, { "identity.primary": { "name": "id", "extends": "Purchase.id" } } ] } """)); + // `now`: a projection @filter takes a relative date, so only its malformed shape is refused. string msg = Single(Load(m), ErrorCode.ERR_BAD_ATTR_FILTER); - Assert.Equal( - "object.projection 'acme::shop::RecentPurchase': @filter uses a relative date ({ now: ... }), which is " + - "legal only in the @filter of a segment, measure.aggregate or object.report.", - msg); + Assert.Contains("malformed relative date", msg); } [Fact] @@ -655,12 +653,12 @@ public void F1_a_field_literally_named_now_is_a_field_not_a_relative_date() } [Fact] - public void F1_a_field_named_now_inside_or_does_not_hide_a_real_relative_value_beside_it() + public void F1_a_field_named_now_inside_or_does_not_hide_a_malformed_relative_value_beside_it() { var m = Positive(); RootChildren(m).Add(Wrap("object.projection", """ { "name": "NowView", - "@filter": { "or": [ { "now": { "eq": 1 } }, { "purchasedAt": { "gte": { "now": "-P7D" } } } ] }, + "@filter": { "or": [ { "now": { "eq": 1 } }, { "purchasedAt": { "gte": { "now": "7 days ago" } } } ] }, "children": [ { "source.rdb": { "@kind": "view", "@view": "now_view" } }, { "field.long": { "name": "id", "extends": "Purchase.id" } }, diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index ac96a913b3..f0a1f6280c 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -31,6 +31,14 @@ public static class ExpressionGrammar public const string EXPR_OP_IS_NOT_NULL = "isNotNull"; public const string EXPR_OP_NOT = "not"; public const string EXPR_FN_COALESCE = "coalesce"; + // `case` ({ case: [ { when, then } ], else?, operand? }) and `now` ({ now, startOf? }). + public const string EXPR_CASE = "case"; + public const string EXPR_CASE_WHEN = "when"; + public const string EXPR_CASE_THEN = "then"; + public const string EXPR_CASE_ELSE = "else"; + public const string EXPR_CASE_OPERAND = "operand"; + public const string EXPR_NOW = "now"; + public const string EXPR_NOW_START_OF = "startOf"; // Node-kind keys (verbatim from the @expr tree — not metamodel attrs). private const string KEY_FIELD = "field"; @@ -69,6 +77,11 @@ void Walk(object? x) Walk(Get(n, KEY_RIGHT)); Walk(Get(n, KEY_ARG)); if (Get(n, KEY_ARGS) is IEnumerable args) foreach (var a in args) Walk(a); + Walk(Get(n, EXPR_CASE_OPERAND)); + Walk(Get(n, EXPR_CASE_ELSE)); + if (Get(n, EXPR_CASE) is IEnumerable arms) + foreach (var arm in arms) + if (arm is IReadOnlyDictionary a) { Walk(Get(a, EXPR_CASE_WHEN)); Walk(Get(a, EXPR_CASE_THEN)); } } Walk(node); return refs; @@ -107,6 +120,33 @@ public static List ValidateExprNode(object? node) : ["expression 'value' must be a scalar literal (string/number/boolean/null)"]; } + if (n.ContainsKey(EXPR_NOW)) + { + if (Get(n, EXPR_NOW) is not string) return [$"expression '{EXPR_NOW}' must be an ISO-8601 duration string"]; + var extra = n.Keys.Where(k => k != EXPR_NOW && k != EXPR_NOW_START_OF).ToList(); + return extra.Count == 0 ? [] : [$"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {string.Join(", ", extra)}"]; + } + + if (n.ContainsKey(EXPR_CASE)) + { + if (Get(n, EXPR_CASE) is not IReadOnlyList arms || arms.Count == 0) + return [$"'{EXPR_CASE}' requires a non-empty array of {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }} arms"]; + var errs = new List(); + foreach (var arm in arms) + { + if (arm is not IReadOnlyDictionary a || !a.ContainsKey(EXPR_CASE_WHEN) || !a.ContainsKey(EXPR_CASE_THEN)) + { + errs.Add($"every '{EXPR_CASE}' arm must be {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }}"); + continue; + } + errs.AddRange(ValidateExprNode(Get(a, EXPR_CASE_WHEN))); + errs.AddRange(ValidateExprNode(Get(a, EXPR_CASE_THEN))); + } + if (n.ContainsKey(EXPR_CASE_ELSE)) errs.AddRange(ValidateExprNode(Get(n, EXPR_CASE_ELSE))); + if (n.ContainsKey(EXPR_CASE_OPERAND)) errs.AddRange(ValidateExprNode(Get(n, EXPR_CASE_OPERAND))); + return errs; + } + if (n.ContainsKey(KEY_FN)) { if (Get(n, KEY_FN) is not string fn || fn != EXPR_FN_COALESCE) @@ -141,7 +181,7 @@ public static List ValidateExprNode(object? node) return [$"unknown expression op '{op}'"]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; } // ------------------------------------------------------------------------- @@ -176,6 +216,43 @@ public static InferResult InferExprType(object? node, Func reso if (n.ContainsKey(KEY_VALUE)) return new InferResult(LiteralType(Get(n, KEY_VALUE)), []); + // now: an instant; compared with a date or local timestamp it takes that kind at lowering. + if (n.ContainsKey(EXPR_NOW)) + return new InferResult(FIELD_SUBTYPE_TIMESTAMP, []); + + if (n.ContainsKey(EXPR_CASE)) + { + var errors = new List(); + var arms = (IReadOnlyList)Get(n, EXPR_CASE)!; + InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField) : null; + if (operand is { } o) errors.AddRange(o.Errors); + var results = new List(); + foreach (var armObj in arms) + { + var arm = (IReadOnlyDictionary)armObj!; + var w = InferExprType(Get(arm, EXPR_CASE_WHEN), resolveField); + errors.AddRange(w.Errors); + if (operand is null && w.Type is not null && w.Type != FIELD_SUBTYPE_BOOLEAN) + errors.Add($"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.Type}"); + if (operand is { Type: { } ot } && w.Type is not null && w.Type != ot) + errors.Add($"a simple '{EXPR_CASE}' compares its {ot} '{EXPR_CASE_OPERAND}' with a {w.Type} '{EXPR_CASE_WHEN}'"); + var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField); + errors.AddRange(t.Errors); + results.Add(t.Type); + } + if (n.ContainsKey(EXPR_CASE_ELSE)) + { + var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField); + errors.AddRange(e.Errors); + results.Add(e.Type); + } + var types = results.Where(t => t is not null).Select(t => t!).ToList(); + string? unified = types.Count > 0 ? types[0] : null; + if (unified is not null && types.Any(t => t != unified)) + errors.Add($"'{EXPR_CASE}' results have differing types ({string.Join(", ", types.Distinct())})"); + return new InferResult(unified, errors); + } + if (n.ContainsKey(KEY_FN)) // coalesce { var args = (IReadOnlyList)Get(n, KEY_ARGS)!; diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs index 326fedb044..f653e833ca 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs @@ -1061,6 +1061,44 @@ void Claim(string fieldName, string what) // F1 — relative-date values only on reporting hosts // ------------------------------------------------------------------------- + /// The view hosts whose @filter may carry a relative-date value too. + private static bool IsRelativeViewFilterHost(MetaData node) => + (node.Type == TYPE_OBJECT && node.SubType == OBJECT_SUBTYPE_PROJECTION) || + (node.Type == TYPE_ORIGIN && (node.SubType == ORIGIN_SUBTYPE_FIRST || node.SubType == ORIGIN_SUBTYPE_AGGREGATE)); + + /// F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every + /// relative operand of a filter, without its field-type rule. + private static void CheckRelativeShapes(object? filter, MetaData host, ReportingErrorSink sink) + { + if (filter is not IReadOnlyDictionary f) return; + void Err(string message) => sink.Push(host, ErrorCode.ERR_BAD_ATTR_FILTER, ReportingNodeLabel(host), $": {message}"); + foreach (var (key, clause) in f) + { + if (key == FILTER_COMPOSE_OR || key == FILTER_COMPOSE_AND) + { + if (clause is IReadOnlyList subs) foreach (var sub in subs) CheckRelativeShapes(sub, host, sink); + continue; + } + if (clause is not IReadOnlyDictionary ops) continue; + foreach (var (op, operand) in ops) + { + var relative = RelativeOperand(operand); + if (relative is null) continue; + var duration = relative.TryGetValue(FILTER_RELATIVE_NOW, out var dv) ? dv : null; + if (!IsExactRelativeValue(relative)) + Err($"@filter on '{key}' has a malformed relative date {JsonStringify(relative)}; a relative date is " + + "{ now: \"\" } with an optional startOf, and no other keys."); + else if (!ReportingRelativeDateOps.Contains(op)) + Err($"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under gt, gte, lt and lte."); + else if (duration is not string d || !ISO_DURATION_RE.IsMatch(d)) + Err($"@filter on '{key}' has relative date '{QuoteValue(duration)}', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."); + else if (relative.TryGetValue(FILTER_RELATIVE_START_OF, out var startOf) + && (startOf is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit))) + Err($"@filter on '{key}' has startOf '{QuoteValue(startOf)}'; startOf is one of {string.Join(", ", RELATIVE_START_OF_UNITS)}."); + } + } + } + /// True for the hosts whose @filter may carry a relative-date value. private static bool IsReportingFilterHost(MetaData node) => node.Type == TYPE_SEGMENT || @@ -1074,7 +1112,18 @@ private static bool IsReportingFilterHost(MetaData node) => /// private static void CheckNoRelativeDates(MetaData node, TypeRegistry registry, ReportingErrorSink sink) { - if (!IsReportingFilterHost(node)) + if (IsRelativeViewFilterHost(node)) + { + // `now`: a projection's and an origin's @filter lower relative dates into the view. + // Their keys resolve elsewhere, so the value's own shape is checked here. + foreach (var (attrName, value) in node.OwnAttrs()) + { + bool isFilterAttr = + registry.FindAttrSchema(node.Type, node.SubType, attrName)?.ValueType == ATTR_SUBTYPE_FILTER; + if (isFilterAttr) CheckRelativeShapes(value, node, sink); + } + } + else if (!IsReportingFilterHost(node)) { // ADR-0039: own — only locally declared filters are lowered, and the walk // visits every declared node exactly once (an inherited filter is checked diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index c9fe25c3db..febcd46165 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -781,9 +781,20 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) // Type inference against the base entity's EFFECTIVE fields (ADR-0039). var computedBase = DeriveBaseEntity(obj, root, field.Name, src, errors); if (computedBase is null) continue; + // A ref names one of the projection's own fields + // first (a passthrough, an origin.first, another computed — never itself, never + // an aggregate), else a base field. Func resolveField = name => - computedBase!.Children() + { + if (!ReferenceEquals(obj, computedBase) && name != field.Name + && obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name) is { } own) + { + var ownOrigin = own.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + return ownOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE ? null : own.SubType; + } + return computedBase!.Children() .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.SubType; + }; var inferred = ExpressionGrammar.InferExprType(expr, resolveField); if (inferred.Errors.Count > 0) { diff --git a/server/csharp/MetaObjects/SpecMetamodel/attr.json b/server/csharp/MetaObjects/SpecMetamodel/attr.json index 4c267a1947..19031ccb34 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/attr.json +++ b/server/csharp/MetaObjects/SpecMetamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index f7ac49e9a3..00f949a3e3 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -27,7 +27,7 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -51,7 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." } ] } ] diff --git a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java index e66c825a5a..d879578297 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java +++ b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java @@ -10,6 +10,8 @@ import com.metaobjects.field.DoubleField; import com.metaobjects.field.IntegerField; import com.metaobjects.field.StringField; +import com.metaobjects.field.TimestampField; +import com.metaobjects.reporting.ReportingConstants; import com.metaobjects.query.FilterOps; import com.metaobjects.registry.MetaDataRegistry; @@ -218,6 +220,8 @@ private static Object jsonElementToJava(JsonElement el) { // { "op": isNull|isNotNull|not, "arg": … } — null-test / negation // { "op": and|or, "args": [ … ] } — variadic logic // { "fn": coalesce, "args": [ … ] } — coalesce + // { "case": [ { when, then }, … ], else?, operand? } — searched, or simple with operand + // { "now": "", startOf? } — the relative-date value, as a leaf // ======================================================================= /** Expression-only op/fn names — the comparison + and/or/isNull names are the @@ -225,6 +229,13 @@ private static Object jsonElementToJava(JsonElement el) { public static final String EXPR_OP_IS_NOT_NULL = "isNotNull"; public static final String EXPR_OP_NOT = "not"; public static final String EXPR_FN_COALESCE = "coalesce"; + public static final String EXPR_CASE = "case"; + public static final String EXPR_CASE_WHEN = "when"; + public static final String EXPR_CASE_THEN = "then"; + public static final String EXPR_CASE_ELSE = "else"; + public static final String EXPR_CASE_OPERAND = "operand"; + public static final String EXPR_NOW = ReportingConstants.FILTER_RELATIVE_NOW; + public static final String EXPR_NOW_START_OF = ReportingConstants.FILTER_RELATIVE_START_OF; /** Boolean composition keys — mirror {@code FilterAttribute}'s private compose keys. */ static final String COMPOSE_AND = "and"; @@ -271,6 +282,39 @@ public static List validateExprNode(Object node) { } return out; } + if (n.containsKey(EXPR_NOW)) { + if (!(n.get(EXPR_NOW) instanceof String)) { + out.add("expression '" + EXPR_NOW + "' must be an ISO-8601 duration string"); + return out; + } + List extra = new ArrayList<>(); + for (String k : n.keySet()) if (!EXPR_NOW.equals(k) && !EXPR_NOW_START_OF.equals(k)) extra.add(k); + if (!extra.isEmpty()) { + out.add("expression '" + EXPR_NOW + "' takes only '" + EXPR_NOW_START_OF + "' beside it, not " + + String.join(", ", extra)); + } + return out; + } + if (n.containsKey(EXPR_CASE)) { + Object arms = n.get(EXPR_CASE); + if (!(arms instanceof List) || ((List) arms).isEmpty()) { + out.add("'" + EXPR_CASE + "' requires a non-empty array of { " + EXPR_CASE_WHEN + ", " + + EXPR_CASE_THEN + " } arms"); + return out; + } + for (Object arm : (List) arms) { + if (!(arm instanceof Map) || !((Map) arm).containsKey(EXPR_CASE_WHEN) + || !((Map) arm).containsKey(EXPR_CASE_THEN)) { + out.add("every '" + EXPR_CASE + "' arm must be { " + EXPR_CASE_WHEN + ", " + EXPR_CASE_THEN + " }"); + continue; + } + out.addAll(validateExprNode(((Map) arm).get(EXPR_CASE_WHEN))); + out.addAll(validateExprNode(((Map) arm).get(EXPR_CASE_THEN))); + } + if (n.containsKey(EXPR_CASE_ELSE)) out.addAll(validateExprNode(n.get(EXPR_CASE_ELSE))); + if (n.containsKey(EXPR_CASE_OPERAND)) out.addAll(validateExprNode(n.get(EXPR_CASE_OPERAND))); + return out; + } if (n.containsKey("fn")) { Object fn = n.get("fn"); if (!EXPR_FN_COALESCE.equals(fn)) { @@ -318,7 +362,7 @@ public static List validateExprNode(Object node) { out.add("unknown expression op '" + op + "'"); return out; } - out.add("expression node must be one of {field}, {value}, {op,…}, {fn,…}"); + out.add("expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"); return out; } @@ -370,6 +414,41 @@ public static InferResult inferExprType(Object node, Function re if (n.containsKey("value")) { return new InferResult(literalType(n.get("value")), List.of()); } + // now: an instant; compared with a date or local timestamp it takes that kind at lowering. + if (n.containsKey(EXPR_NOW)) return new InferResult(TimestampField.SUBTYPE_TIMESTAMP, List.of()); + if (n.containsKey(EXPR_CASE)) { + List errors = new ArrayList<>(); + InferResult operand = n.containsKey(EXPR_CASE_OPERAND) + ? inferExprType(n.get(EXPR_CASE_OPERAND), resolveField) : null; + if (operand != null) errors.addAll(operand.errors); + List results = new ArrayList<>(); + for (Object armObj : (List) n.get(EXPR_CASE)) { + Map arm = (Map) armObj; + InferResult w = inferExprType(arm.get(EXPR_CASE_WHEN), resolveField); + errors.addAll(w.errors); + if (operand == null && w.type != null && !BooleanField.SUBTYPE_BOOLEAN.equals(w.type)) { + errors.add("a searched '" + EXPR_CASE + "' needs a boolean '" + EXPR_CASE_WHEN + "', got " + w.type); + } + if (operand != null && operand.type != null && w.type != null && !w.type.equals(operand.type)) { + errors.add("a simple '" + EXPR_CASE + "' compares its " + operand.type + " '" + EXPR_CASE_OPERAND + + "' with a " + w.type + " '" + EXPR_CASE_WHEN + "'"); + } + InferResult t = inferExprType(arm.get(EXPR_CASE_THEN), resolveField); + errors.addAll(t.errors); + if (t.type != null) results.add(t.type); + } + if (n.containsKey(EXPR_CASE_ELSE)) { + InferResult e = inferExprType(n.get(EXPR_CASE_ELSE), resolveField); + errors.addAll(e.errors); + if (e.type != null) results.add(e.type); + } + String unified = results.isEmpty() ? null : results.get(0); + if (unified != null && results.stream().anyMatch(t -> !unified.equals(t))) { + errors.add("'" + EXPR_CASE + "' results have differing types (" + + String.join(", ", new LinkedHashSet<>(results)) + ")"); + } + return new InferResult(unified, errors); + } if (n.containsKey("fn")) { // coalesce List errors = new ArrayList<>(); List argTypes = new ArrayList<>(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java index 77c4439b43..543a2d1c03 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java @@ -1148,6 +1148,54 @@ && childOfType(o, ReportingConstants.TYPE_MEASURE, name) != null) { // F1 — relative-date values only on reporting hosts // --------------------------------------------------------------------------- + /** The view hosts whose {@code @filter} may carry a relative-date value too: a projection's + * and an origin.first / origin.aggregate's, which lower it into the view. */ + private static boolean isRelativeViewFilterHost(MetaData node) { + return (MetaObject.TYPE_OBJECT.equals(node.getType()) && MetaObject.SUBTYPE_PROJECTION.equals(node.getSubType())) + || (com.metaobjects.origin.MetaOrigin.TYPE_ORIGIN.equals(node.getType()) + && (com.metaobjects.origin.FirstOrigin.SUBTYPE_FIRST.equals(node.getSubType()) + || com.metaobjects.origin.AggregateOrigin.SUBTYPE_AGGREGATE.equals(node.getSubType()))); + } + + /** F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every + * relative operand of a filter, without its field-type rule. */ + private static void checkRelativeShapes(Object filter, MetaData host, ErrorSink sink) { + if (!(filter instanceof Map)) return; + for (Map.Entry entry : ((Map) filter).entrySet()) { + String key = String.valueOf(entry.getKey()); + Object clause = entry.getValue(); + if ("and".equals(key) || "or".equals(key)) { + if (clause instanceof List) for (Object sub : (List) clause) checkRelativeShapes(sub, host, sink); + continue; + } + if (!(clause instanceof Map)) continue; + for (Map.Entry opEntry : ((Map) clause).entrySet()) { + String op = String.valueOf(opEntry.getKey()); + Map relative = relativeOperand(opEntry.getValue()); + if (relative == null) continue; + Object duration = relative.get(ReportingConstants.FILTER_RELATIVE_NOW); + Object startOf = relative.get(ReportingConstants.FILTER_RELATIVE_START_OF); + String message = null; + if (!ReportingConstants.isWellFormedRelativeKeys(relative.keySet())) { + message = "@filter on '" + key + "' has a malformed relative date " + GSON.toJson(relative) + + "; a relative date is { now: \"\" } with an optional startOf, and no other keys."; + } else if (!RELATIVE_DATE_OPS.contains(op)) { + message = "@filter on '" + key + "' puts a relative date under op '" + op + + "'; relative dates are legal only under gt, gte, lt and lte."; + } else if (!(duration instanceof String) + || !ReportingConstants.ISO_DURATION_RE.matcher((String) duration).matches()) { + message = "@filter on '" + key + "' has relative date '" + quoteValue(duration) + + "', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."; + } else if (relative.containsKey(ReportingConstants.FILTER_RELATIVE_START_OF) + && (!(startOf instanceof String) || !ReportingConstants.RELATIVE_START_OF_UNITS.contains(startOf))) { + message = "@filter on '" + key + "' has startOf '" + quoteValue(startOf) + + "'; startOf is one of " + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + "."; + } + if (message != null) sink.push(host, ErrorCode.ERR_BAD_ATTR_FILTER, nodeLabel(host), ": " + message); + } + } + } + /** True for the hosts whose {@code @filter} may carry a relative-date value. */ private static boolean isReportingFilterHost(MetaData node) { return ReportingConstants.TYPE_SEGMENT.equals(node.getType()) @@ -1166,7 +1214,14 @@ private static void checkNoRelativeDates(MetaData node, ErrorSink sink) { // is visited once, at its declaration (an inherited filter is checked where it is // declared; origin.* never inherits, ADR-0029). Attrs are children in this port. List own = node.getChildren(MetaData.class, false); - if (!isReportingFilterHost(node)) { + if (isRelativeViewFilterHost(node)) { + // A projection's and an origin's @filter lower relative dates into the view. Their + // keys resolve elsewhere (projection fields, base paths, the related entity), so the + // value's own shape is checked here and the field's type where it is lowered. + for (MetaData c : own) { + if (c instanceof FilterAttribute) checkRelativeShapes(((MetaAttribute) c).getValue(), node, sink); + } + } else if (!isReportingFilterHost(node)) { for (MetaData c : own) { if (c instanceof FilterAttribute && filterContainsRelativeValue(((MetaAttribute) c).getValue())) { 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 cd3f2fd32c..4dd2daaa3e 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 @@ -3200,8 +3200,24 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, MetaObject base = deriveBaseEntity(obj, root, field.getName(), src); if (base == null) return; final MetaObject baseEntity = base; + // A ref names one of the projection's own fields first (a passthrough — joined or + // not —, an origin.first or another origin.computed), else a base field. Never + // itself, never an aggregate (it would need the grouped row). + final String selfName = field.getShortName(); ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( - expr, name -> resolvedFieldSubType(baseEntity, name)); + expr, name -> { + if (obj != baseEntity && !name.equals(selfName)) { + for (MetaField own : obj.getChildren(MetaField.class, true)) { + if (!name.equals(own.getShortName())) continue; + for (MetaData oc : own.getChildren(MetaData.class, false)) { + if (oc instanceof MetaOrigin + && AggregateOrigin.SUBTYPE_AGGREGATE.equals(oc.getSubType())) return null; + } + return own.getSubType(); + } + } + return resolvedFieldSubType(baseEntity, name); + }); if (!inferred.errors.isEmpty()) { throw new MetaDataException( ErrorMessageConstants.ERR_INVALID_ORIGIN diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java index 248282d4f1..c5bf63f1ff 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java @@ -170,8 +170,6 @@ public void everyErrorFixtureYieldsTheReferenceCodeAndMessage() throws IOExcepti "report 'acme::shop::DailyRevenue': @filter on 'purchasedAt' has relative date '90 days', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."}); expect.put("error-relative-date-non-temporal", new String[]{"ERR_BAD_ATTR_FILTER", "report 'acme::shop::DailyRevenue': @filter on 'amountCents' uses a relative date ({ now: ... }), but 'amountCents' is field.currency; relative dates apply only to field.date and field.timestamp."}); - expect.put("error-relative-date-wrong-host", new String[]{"ERR_BAD_ATTR_FILTER", - "object.projection 'acme::shop::RecentPurchase': @filter uses a relative date ({ now: ... }), which is legal only in the @filter of a segment, measure.aggregate or object.report."}); expect.put("error-report-declares-field", new String[]{"ERR_INVALID_REPORT", "report 'acme::shop::StoreTotals' declares field.long 'rowCount'; a report's fields and identity are derived from @dimensions and @measures, never declared."}); expect.put("error-report-dimension-grain", new String[]{"ERR_INVALID_REPORT", @@ -431,7 +429,7 @@ public void degenerateDurationIsRefused() throws IOException { @Test public void aFieldNamedNowIsAFieldNotARelativeDate() throws IOException { - JsonObject doc = fixtureDoc("error-relative-date-wrong-host"); + JsonObject doc = fixtureDoc("projection-filter-relative-now"); JsonObject projection = rootNode(doc, "object.projection", "RecentPurchase"); // Replace the projection's relative-date filter with one on a field literally named `now`. projection.getAsJsonArray("children").add(json("{\"field.timestamp\":{\"name\":\"now\",\"extends\":\"Purchase.purchasedAt\"}}")); diff --git a/server/python/src/metaobjects/loader/validate_reporting.py b/server/python/src/metaobjects/loader/validate_reporting.py index 065257a751..aba518559a 100644 --- a/server/python/src/metaobjects/loader/validate_reporting.py +++ b/server/python/src/metaobjects/loader/validate_reporting.py @@ -69,8 +69,10 @@ OBJECT_REPORT_ATTR_SEGMENT, OBJECT_REPORT_ATTR_SPINE, OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_REPORT, ) +from ..meta.persistence.origin.origin_constants import ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_FIRST from ..meta.core.relationship.relationship_constants import ( CARDINALITY_ONE, RELATIONSHIP_ATTR_CARDINALITY, @@ -118,6 +120,7 @@ TYPE_IDENTITY, TYPE_MEASURE, TYPE_OBJECT, + TYPE_ORIGIN, TYPE_RELATIONSHIP, TYPE_SEGMENT, TYPE_SOURCE, @@ -1170,11 +1173,70 @@ def _is_reporting_filter_host(node: MetaData) -> bool: ) +def _is_relative_view_filter_host(node: MetaData) -> bool: + """A projection and an origin.first / origin.aggregate lower relative dates into the view.""" + return (node.type == TYPE_OBJECT and node.sub_type == OBJECT_SUBTYPE_PROJECTION) or ( + node.type == TYPE_ORIGIN and node.sub_type in (ORIGIN_SUBTYPE_FIRST, ORIGIN_SUBTYPE_AGGREGATE) + ) + + +def _check_relative_shapes(filter_value: object, host: MetaData, sink: _ErrorSink) -> None: + """F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every relative + operand of a filter, without its field-type rule.""" + if not isinstance(filter_value, dict): + return + + def err(message: str) -> None: + sink.push(host, _ERR_BAD_ATTR_FILTER, _node_label(host), f": {message}") + + for key, clause in filter_value.items(): + if key in (_FILTER_COMPOSE_AND, _FILTER_COMPOSE_OR): + if isinstance(clause, list): + for sub in clause: + _check_relative_shapes(sub, host, sink) + continue + if not isinstance(clause, dict): + continue + for op, operand in clause.items(): + relative = _relative_operand(operand) + if relative is None: + continue + duration = relative.get(FILTER_RELATIVE_NOW) + if not set(relative) <= {FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF}: + err( + f"@filter on '{key}' has a malformed relative date {_js_json(relative)}; a relative date is " + f'{{ now: "" }} with an optional startOf, and no other keys.' + ) + elif op not in _RELATIVE_DATE_OPS: + err( + f"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " + f"gt, gte, lt and lte." + ) + elif not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: + err( + f"@filter on '{key}' has relative date '{_quote_value(duration)}', which is not an ISO-8601 " + f"duration (e.g. '-P7D', '-PT12H')." + ) + elif FILTER_RELATIVE_START_OF in relative: + start_of = relative[FILTER_RELATIVE_START_OF] + if not isinstance(start_of, str) or start_of not in RELATIVE_START_OF_UNITS: + err( + f"@filter on '{key}' has startOf '{_quote_value(start_of)}'; startOf is one of " + f"{', '.join(RELATIVE_START_OF_UNITS)}." + ) + + def _check_no_relative_dates(node: MetaData, sink: _ErrorSink) -> None: """F1 — walk the whole tree and refuse a ``{ now: ... }`` value in any attr.filter - outside a reporting host (a projection @filter, a dataGrid preset, an - origin.aggregate/first @filter): those hosts have no lowering for it.""" - if not _is_reporting_filter_host(node): + outside a host that lowers it (a dataGrid preset, for one). A projection's and an + origin.first / origin.aggregate's @filter lower relative dates into the view: their keys + resolve elsewhere, so only the value's own shape is checked here.""" + if _is_relative_view_filter_host(node): + # ADR-0039: own — only locally declared filters are lowered. + for attr in node.own_meta_attrs(): + if attr.sub_type == ATTR_SUBTYPE_FILTER: + _check_relative_shapes(getattr(attr, "value", None), node, sink) + elif not _is_reporting_filter_host(node): # ADR-0039: own — only locally declared filters are lowered, and the walk # visits every declared node exactly once (an inherited filter is checked # where it is declared; origin.* never inherits, ADR-0029). diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 54280e7b85..cfc9fadf01 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -25,6 +25,7 @@ from .validate_source_escapes import validate_source_escapes from .validate_reporting import validate_reporting from ..codegen.runtime.duration_wire import DURATION_RE +from ..meta.core.reporting.reporting_constants import FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF from ..meta.core.field.field_constants import ( ENUM_MEMBER_PATTERN, FIELD_ATTR_COERCE_DEFAULT, @@ -1145,6 +1146,15 @@ def ops_for_field(field: MetaData) -> frozenset[str]: EXPR_OP_IS_NOT_NULL = "isNotNull" EXPR_OP_NOT = "not" EXPR_FN_COALESCE = "coalesce" +# { case: [{ when, then }, …], else?, operand? } — searched, or simple with operand; and +# { now: "", startOf? } — the relative-date value, as a leaf. +EXPR_CASE = "case" +EXPR_CASE_WHEN = "when" +EXPR_CASE_THEN = "then" +EXPR_CASE_ELSE = "else" +EXPR_CASE_OPERAND = "operand" +EXPR_NOW = FILTER_RELATIVE_NOW +EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF # Filter-op / compose names shared with the filter vocabulary (see query-constants.ts). _FILTER_OP_EQ = "eq" @@ -1185,6 +1195,29 @@ def validate_expr_node(node: object) -> list[str]: if (v is None or isinstance(v, (str, int, float, bool))) else ["expression 'value' must be a scalar literal (string/number/boolean/null)"] ) + if EXPR_NOW in node: + if not isinstance(node[EXPR_NOW], str): + return [f"expression '{EXPR_NOW}' must be an ISO-8601 duration string"] + extra = [k for k in node if k not in (EXPR_NOW, EXPR_NOW_START_OF)] + return [] if not extra else [ + f"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {', '.join(extra)}" + ] + if EXPR_CASE in node: + arms = node[EXPR_CASE] + if not isinstance(arms, list) or not arms: + return [f"'{EXPR_CASE}' requires a non-empty array of {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }} arms"] + errs: list[str] = [] + for arm in arms: + if not isinstance(arm, dict) or EXPR_CASE_WHEN not in arm or EXPR_CASE_THEN not in arm: + errs.append(f"every '{EXPR_CASE}' arm must be {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }}") + continue + errs.extend(validate_expr_node(arm[EXPR_CASE_WHEN])) + errs.extend(validate_expr_node(arm[EXPR_CASE_THEN])) + if EXPR_CASE_ELSE in node: + errs.extend(validate_expr_node(node[EXPR_CASE_ELSE])) + if EXPR_CASE_OPERAND in node: + errs.extend(validate_expr_node(node[EXPR_CASE_OPERAND])) + return errs if "fn" in node: if node["fn"] != EXPR_FN_COALESCE: return [f"unknown expression fn '{node['fn']}'"] @@ -1210,7 +1243,7 @@ def validate_expr_node(node: object) -> list[str]: return [m for a in args for m in validate_expr_node(a)] return [f"op '{op}' requires a non-empty args array"] return [f"unknown expression op '{op}'"] - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}"] + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"] def _literal_type(v: object) -> str | None: @@ -1256,6 +1289,38 @@ def infer_expr_type( ) if "value" in n: return InferResult(_literal_type(n["value"]), []) + # now: an instant; compared with a date or local timestamp it takes that kind at lowering. + if EXPR_NOW in n: + return InferResult(FIELD_SUBTYPE_TIMESTAMP, []) + if EXPR_CASE in n: + errors: list[str] = [] + operand = infer_expr_type(n[EXPR_CASE_OPERAND], resolve_field) if EXPR_CASE_OPERAND in n else None + if operand is not None: + errors.extend(operand.errors) + results: list[str] = [] + for arm in n[EXPR_CASE]: + w = infer_expr_type(arm[EXPR_CASE_WHEN], resolve_field) + errors.extend(w.errors) + if operand is None and w.type is not None and w.type != FIELD_SUBTYPE_BOOLEAN: + errors.append(f"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.type}") + if operand is not None and operand.type is not None and w.type is not None and w.type != operand.type: + errors.append( + f"a simple '{EXPR_CASE}' compares its {operand.type} '{EXPR_CASE_OPERAND}' " + f"with a {w.type} '{EXPR_CASE_WHEN}'" + ) + t = infer_expr_type(arm[EXPR_CASE_THEN], resolve_field) + errors.extend(t.errors) + if t.type is not None: + results.append(t.type) + if EXPR_CASE_ELSE in n: + e = infer_expr_type(n[EXPR_CASE_ELSE], resolve_field) + errors.extend(e.errors) + if e.type is not None: + results.append(e.type) + unified = results[0] if results else None + if unified is not None and any(t != unified for t in results): + errors.append(f"'{EXPR_CASE}' results have differing types ({', '.join(dict.fromkeys(results))})") + return InferResult(unified, errors) if "fn" in n: # coalesce arg_results = [infer_expr_type(a, resolve_field) for a in n["args"]] @@ -2587,7 +2652,20 @@ def _validate_origin_paths( if base is None: continue - def _resolve_field(name: str, _base: MetaData = base) -> str | None: + # A ref names one of the projection's own fields first (a passthrough — joined + # or not —, an origin.first or another origin.computed), else a base field. + # Never itself, never an aggregate (it would need the grouped row). + def _resolve_field( + name: str, _base: MetaData = base, _obj: MetaData = obj, _self: str = node.name + ) -> str | None: + if _obj is not _base and name != _self: + for own in _obj.children(): + if own.type != TYPE_FIELD or own.name != name: + continue + for oc in own.own_children(): + if oc.type == TYPE_ORIGIN and oc.sub_type == ORIGIN_SUBTYPE_AGGREGATE: + return None + return own.sub_type for f in _base.children(): if f.type == TYPE_FIELD and f.name == name: return f.sub_type diff --git a/server/python/src/metaobjects/spec_metamodel/attr.json b/server/python/src/metaobjects/spec_metamodel/attr.json index 4c267a1947..19031ccb34 100644 --- a/server/python/src/metaobjects/spec_metamodel/attr.json +++ b/server/python/src/metaobjects/spec_metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index f7ac49e9a3..00f949a3e3 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -27,7 +27,7 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -51,7 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." } ] } ] diff --git a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts index 22ea90b3a4..bdd5f3e675 100644 --- a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts @@ -73,7 +73,7 @@ export const ATTR_DEFINITION: ProviderDefinition = { "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." } ] }; diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index fb6fae54bf..0e2d140d97 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -23,19 +23,29 @@ import { opsForSubType, type FilterOp, } from "../query/query-constants.js"; import { - FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_BOOLEAN, + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_TIMESTAMP, } from "../field/field-constants.js"; import { MetaAttr, type ValueError, runtimeTypeName } from "./meta-attr.js"; import { type AttrValue } from "../../shared/meta-data.js"; import { DATA_TYPE_OBJECT, type DataType } from "../../data-type.js"; import { ATTR_SUBTYPE_EXPRESSION } from "./attr-constants.js"; import { registerAttrClass } from "../../attr-class-map.js"; +import { FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF } from "../reporting/reporting-constants.js"; // --- Expression-only op/fn names (the comparison + and/or/isNull names are the // --- shared filter vocabulary above; these three are new). --- export const EXPR_OP_IS_NOT_NULL = "isNotNull"; export const EXPR_OP_NOT = "not"; export const EXPR_FN_COALESCE = "coalesce"; +// `case`: { case: [ { when, then }, ... ], else?, operand? } — searched, or simple with operand. +export const EXPR_CASE = "case"; +export const EXPR_CASE_WHEN = "when"; +export const EXPR_CASE_THEN = "then"; +export const EXPR_CASE_ELSE = "else"; +export const EXPR_CASE_OPERAND = "operand"; +// `now`: { now: "", startOf? } — the relative-date value, as a leaf. +export const EXPR_NOW = FILTER_RELATIVE_NOW; +export const EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF; const COMPARISON_OPS: ReadonlySet = new Set([ FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, @@ -50,7 +60,9 @@ export type ExprNode = | { op: string; left: ExprNode; right: ExprNode } // comparison | { op: string; arg: ExprNode } // isNull / isNotNull / not | { op: string; args: ExprNode[] } // and / or - | { fn: string; args: ExprNode[] }; // coalesce + | { fn: string; args: ExprNode[] } // coalesce + | { case: { when: ExprNode; then: ExprNode }[]; else?: ExprNode; operand?: ExprNode } // case + | { now: string; startOf?: string }; // now function isObj(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); @@ -68,6 +80,26 @@ export function validateExprNode(node: unknown): string[] { return v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? [] : ["expression 'value' must be a scalar literal (string/number/boolean/null)"]; } + if (EXPR_NOW in node) { + if (typeof node[EXPR_NOW] !== "string") return [`expression '${EXPR_NOW}' must be an ISO-8601 duration string`]; + const extra = Object.keys(node).filter((k) => k !== EXPR_NOW && k !== EXPR_NOW_START_OF); + return extra.length === 0 ? [] : [`expression '${EXPR_NOW}' takes only '${EXPR_NOW_START_OF}' beside it, not ${extra.join(", ")}`]; + } + if (EXPR_CASE in node) { + const arms = node[EXPR_CASE]; + if (!Array.isArray(arms) || arms.length === 0) return [`'${EXPR_CASE}' requires a non-empty array of { ${EXPR_CASE_WHEN}, ${EXPR_CASE_THEN} } arms`]; + const errs: string[] = []; + for (const arm of arms) { + if (!isObj(arm) || !(EXPR_CASE_WHEN in arm) || !(EXPR_CASE_THEN in arm)) { + errs.push(`every '${EXPR_CASE}' arm must be { ${EXPR_CASE_WHEN}, ${EXPR_CASE_THEN} }`); + continue; + } + errs.push(...validateExprNode(arm[EXPR_CASE_WHEN]), ...validateExprNode(arm[EXPR_CASE_THEN])); + } + if (EXPR_CASE_ELSE in node) errs.push(...validateExprNode(node[EXPR_CASE_ELSE])); + if (EXPR_CASE_OPERAND in node) errs.push(...validateExprNode(node[EXPR_CASE_OPERAND])); + return errs; + } if ("fn" in node) { if (node.fn !== EXPR_FN_COALESCE) return [`unknown expression fn '${String(node.fn)}'`]; return Array.isArray(node.args) && node.args.length >= 1 @@ -90,7 +122,7 @@ export function validateExprNode(node: unknown): string[] { } return [`unknown expression op '${op}'`]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; } /** The subtype of a scalar literal (coarse: an integer number → int, else double). */ @@ -127,6 +159,39 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st : { type: t, errors: [] }; } if ("value" in n) return { type: literalType(n.value as ExprLiteral), errors: [] }; + // now: an instant; compared with a date or local timestamp it takes that kind at lowering. + if (EXPR_NOW in n) return { type: FIELD_SUBTYPE_TIMESTAMP, errors: [] }; + if (EXPR_CASE in n) { + const errors: string[] = []; + const arms = n[EXPR_CASE] as { when: ExprNode; then: ExprNode }[]; + const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField) : undefined; + if (operand !== undefined) errors.push(...operand.errors); + const results: (string | undefined)[] = []; + for (const arm of arms) { + const w = inferExprType(arm.when, resolveField); + errors.push(...w.errors); + if (operand === undefined && w.type !== undefined && w.type !== FIELD_SUBTYPE_BOOLEAN) { + errors.push(`a searched '${EXPR_CASE}' needs a boolean '${EXPR_CASE_WHEN}', got ${w.type}`); + } + if (operand?.type !== undefined && w.type !== undefined && w.type !== operand.type) { + errors.push(`a simple '${EXPR_CASE}' compares its ${operand.type} '${EXPR_CASE_OPERAND}' with a ${w.type} '${EXPR_CASE_WHEN}'`); + } + const t = inferExprType(arm.then, resolveField); + errors.push(...t.errors); + results.push(t.type); + } + if (EXPR_CASE_ELSE in n) { + const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField); + errors.push(...e.errors); + results.push(e.type); + } + const types = results.filter((t): t is string => t !== undefined); + const unified = types[0]; + if (unified !== undefined && types.some((t) => t !== unified)) { + errors.push(`'${EXPR_CASE}' results have differing types (${[...new Set(types)].join(", ")})`); + } + return { type: unified, errors }; + } if ("fn" in n) { // coalesce const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField)); diff --git a/server/typescript/packages/metadata/src/loader/reporting-validation.ts b/server/typescript/packages/metadata/src/loader/reporting-validation.ts index af9c12c16f..f6337bb18e 100644 --- a/server/typescript/packages/metadata/src/loader/reporting-validation.ts +++ b/server/typescript/packages/metadata/src/loader/reporting-validation.ts @@ -36,9 +36,11 @@ import { TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT, + TYPE_ORIGIN, } from "../shared/base-types.js"; import { OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_REPORT, OBJECT_REPORT_ATTR_FILTER, OBJECT_REPORT_ATTR_SEGMENT, @@ -79,7 +81,7 @@ import { import { ATTR_SUBTYPE_FILTER } from "../core/attr/attr-constants.js"; import { isMetaObject, isMetaRoot, isReadOnlySource, isWritableSource } from "../shared/node-guards.js"; import { SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; -import { AGG_ALL, AGG_ANY } from "../persistence/origin/origin-constants.js"; +import { AGG_ALL, AGG_ANY, ORIGIN_SUBTYPE_FIRST, ORIGIN_SUBTYPE_AGGREGATE } from "../persistence/origin/origin-constants.js"; import { FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF, @@ -1113,6 +1115,43 @@ function checkReportMeasure( // F1 — relative-date values only on reporting hosts // --------------------------------------------------------------------------- +/** The view hosts whose `@filter` may carry a relative-date value too. */ +function isRelativeViewFilterHost(node: MetaData): boolean { + return ( + (node.type === TYPE_OBJECT && node.subType === OBJECT_SUBTYPE_PROJECTION) || + (node.type === TYPE_ORIGIN && (node.subType === ORIGIN_SUBTYPE_FIRST || node.subType === ORIGIN_SUBTYPE_AGGREGATE)) + ); +} + +/** F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every relative + * operand of a filter, without its field-type rule. */ +function checkRelativeShapes(filter: unknown, host: MetaData, sink: ErrorSink): void { + if (!isPlainObject(filter)) return; + const err = (message: string): void => sink.push(host, ERR_BAD_ATTR_FILTER, nodeLabel(host), `: ${message}`); + for (const [key, clause] of Object.entries(filter)) { + if (key === FILTER_COMPOSE_OR || key === FILTER_COMPOSE_AND) { + if (Array.isArray(clause)) for (const sub of clause) checkRelativeShapes(sub, host, sink); + continue; + } + if (!isPlainObject(clause)) continue; + for (const [op, operand] of Object.entries(clause)) { + const relative = relativeOperand(operand); + if (relative === undefined) continue; + const duration = relative[FILTER_RELATIVE_NOW]; + const startOf = relative[FILTER_RELATIVE_START_OF]; + if (!isExactRelativeValue(relative)) { + err(`@filter on '${key}' has a malformed relative date ${JSON.stringify(relative)}; a relative date is { now: "" } with an optional startOf, and no other keys.`); + } else if (!RELATIVE_DATE_OPS.includes(op)) { + err(`@filter on '${key}' puts a relative date under op '${op}'; relative dates are legal only under gt, gte, lt and lte.`); + } else if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { + err(`@filter on '${key}' has relative date '${quoteValue(duration)}', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H').`); + } else if (FILTER_RELATIVE_START_OF in relative && (typeof startOf !== "string" || !(RELATIVE_START_OF_UNITS as readonly string[]).includes(startOf))) { + err(`@filter on '${key}' has startOf '${quoteValue(startOf)}'; startOf is one of ${RELATIVE_START_OF_UNITS.join(", ")}.`); + } + } + } +} + /** True for the hosts whose `@filter` may carry a relative-date value. */ function isReportingFilterHost(node: MetaData): boolean { return ( @@ -1128,7 +1167,14 @@ function isReportingFilterHost(node: MetaData): boolean { * origin.aggregate/first @filter): those hosts have no lowering for it. */ function checkNoRelativeDates(node: MetaData, sink: ErrorSink): void { - if (!isReportingFilterHost(node)) { + if (isRelativeViewFilterHost(node)) { + // `now`: a projection's and an origin's @filter lower relative dates into the view. + // Their keys resolve elsewhere (projection fields, base paths, the related entity), so the + // value's own shape is checked here and the field's type where it is lowered. + for (const attr of node.ownMetaAttrs()) { + if (attr.subType === ATTR_SUBTYPE_FILTER) checkRelativeShapes(attr.value, node, sink); + } + } else if (!isReportingFilterHost(node)) { // ADR-0039: own — only locally declared filters are lowered, and the walk // visits every declared node exactly once (an inherited filter is checked // where it is declared; origin.* never inherits, ADR-0029). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index ac5b819ef0..0192923177 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1623,8 +1623,18 @@ export function validateOriginPaths(root: MetaData): ParseError[] { // Type inference against the base entity's EFFECTIVE fields (ADR-0039). const base = _deriveBaseEntity(obj, root, field.name, src, errors); if (base === undefined) continue; - const resolveField = (name: string): string | undefined => - base.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.subType; + // A ref names one of the projection's own fields first (a + // passthrough — joined or not —, an origin.first or another origin.computed), else a base + // field. Never itself, never an aggregate (it would need the grouped row). + const resolveField = (name: string): string | undefined => { + if (obj !== base && name !== field.name) { + const own = obj.children().find((f) => f.type === TYPE_FIELD && f.name === name); + const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (own !== undefined && ownOrigin?.subType !== ORIGIN_SUBTYPE_AGGREGATE) return own.subType; + if (own !== undefined) return undefined; + } + return base.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.subType; + }; const inferred = inferExprType(expr as ExprNode, resolveField); if (inferred.errors.length > 0) { for (const m of inferred.errors) { diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index de654e6d51..d20ab6f526 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -93,7 +93,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view)." + "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "type": "attr", @@ -168,7 +168,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time." + "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." } ] } diff --git a/server/typescript/packages/metadata/test/reporting-validation.test.ts b/server/typescript/packages/metadata/test/reporting-validation.test.ts index 579247c426..df8defd860 100644 --- a/server/typescript/packages/metadata/test/reporting-validation.test.ts +++ b/server/typescript/packages/metadata/test/reporting-validation.test.ts @@ -902,7 +902,7 @@ describe("validateReporting — relative dates", () => { expect(await codes(m)).toEqual([]); }); - test("F1: a relative value in a projection @filter is refused", async () => { + test("F1 (now): a relative value in a projection @filter is accepted", async () => { const m = edit((x) => x["metadata.root"].children.push({ "object.projection": { @@ -917,8 +917,7 @@ describe("validateReporting — relative dates", () => { }, }), ); - const msg = await single(m, "ERR_BAD_ATTR_FILTER"); - expect(msg).toContain("object.projection 'acme::shop::RecentPurchase'"); + expect(await codes(m)).toEqual([]); }); test("F1: a relative value in a dataGrid preset is refused", async () => { @@ -938,7 +937,7 @@ describe("validateReporting — relative dates", () => { expect(jsonPathOf(errors[0]!.source)).toContain("['layout.dataGrid']"); }); - test("F1: a relative value in an origin.aggregate @filter is refused", async () => { + test("F1 (now): a relative value in an origin.aggregate @filter is accepted", async () => { const m = edit((x) => x["metadata.root"].children.push({ "object.projection": { @@ -963,9 +962,7 @@ describe("validateReporting — relative dates", () => { }, }), ); - const { errors } = await loadInline(m); - expect(errors.map((e) => e.code)).toEqual(["ERR_BAD_ATTR_FILTER"]); - expect(errors[0]!.message).toContain("origin.aggregate"); + expect(await codes(m)).toEqual([]); }); test("F2: an operand with a `now` key plus other keys is refused on a reporting host", async () => { @@ -1064,12 +1061,12 @@ describe("validateReporting — relative dates", () => { expect(errors.map((e) => e.message).filter((msg) => msg.includes("relative date"))).toEqual([]); }); - test("F1: a field named `now` inside and/or does not hide a real relative value beside it", async () => { + test("F1: a field named `now` inside and/or does not hide a malformed relative value beside it", async () => { const m = edit((x) => x["metadata.root"].children.push({ "object.projection": { name: "NowView", - "@filter": { or: [{ now: { eq: 1 } }, { purchasedAt: { gte: { now: "-P7D" } } }] }, + "@filter": { or: [{ now: { eq: 1 } }, { purchasedAt: { gte: { now: "7 days ago" } } }] }, children: [ { "source.rdb": { "@kind": "view", "@view": "now_view" } }, field("long", "id", { extends: "Purchase.id" }), diff --git a/site-reference/index.html b/site-reference/index.html index f500c94a86..9ef6fbf714 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -82,7 +82,7 @@ attr.expression -A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159. +A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. types/attr.md#attrexpression diff --git a/site-reference/types/attr.html b/site-reference/types/attr.html index 0647bb695f..a4cffc35d0 100644 --- a/site-reference/types/attr.html +++ b/site-reference/types/attr.html @@ -79,7 +79,7 @@

attr.double

Allowed children

No structural children.

attr.expression

-

A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159.

+

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

Owning provider: metaobjects-core-types

Attributes

No subtype-specific attributes.

diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index 7de365aadc..f024464eb5 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -93,7 +93,7 @@

origin.aggregate

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

origin.first

metaobjects-core-types -Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. +Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: "", startOf? }) on a date or timestamp field. @of diff --git a/spec/metamodel/attr.json b/spec/metamodel/attr.json index 4c267a1947..19031ccb34 100644 --- a/spec/metamodel/attr.json +++ b/spec/metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree over a base entity's own fields (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Backs origin.computed; a filter object embeds canonically. Additive node kinds (arithmetic/case/via-joined refs) are #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity. { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration, its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." } ] } diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index f7ac49e9a3..00f949a3e3 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -27,7 +27,7 @@ { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." }, { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } ] @@ -51,7 +51,7 @@ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time." } + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field." } ] } ] From 3e60a63072c72a5b78883d8364b2aac4c57c364a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 06:26:16 -0500 Subject: [PATCH 2/7] no-mistakes(review): Fix case/now expression checks in all loaders --- AGENTS.md | 2 +- CHANGELOG.md | 11 +- docs/CONFORMANCE.md | 6 +- .../expected-errors.json | 15 ++ .../input/meta.views.json | 93 +++++++++++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.views.json | 95 +++++++++++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.views.json | 87 ++++++++++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.shop.json | 129 ++++++++++++++++++ .../providers.json | 1 + .../expected-errors.json | 25 ++++ .../input/meta.checks.json | 100 ++++++++++++++ .../providers.json | 1 + .../expected.json | 67 +++++++++ .../input/meta.views.json | 67 +++++++++ .../Core/Attr/ExpressionGrammar.cs | 23 +++- .../MetaObjects/Loader/ValidationPasses.cs | 41 +++++- .../metaobjects/attr/ExpressionAttribute.java | 14 +- .../metaobjects/loader/ValidationPhase.java | 92 ++++++++++++- .../metaobjects/loader/validation_passes.py | 115 +++++++++++++--- .../src/core/attr/meta-attr-expression.ts | 19 ++- .../metadata/src/loader/validation-passes.ts | 65 ++++++++- 27 files changed, 1062 insertions(+), 54 deletions(-) create mode 100644 fixtures/conformance/error-origin-computed-case-non-boolean-when/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-case-non-boolean-when/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-case-non-boolean-when/providers.json create mode 100644 fixtures/conformance/error-origin-computed-cycle/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-cycle/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-cycle/providers.json create mode 100644 fixtures/conformance/error-origin-computed-now-bad-duration/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-now-bad-duration/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-now-bad-duration/providers.json create mode 100644 fixtures/conformance/error-relative-date-view-host-malformed/expected-errors.json create mode 100644 fixtures/conformance/error-relative-date-view-host-malformed/input/meta.shop.json create mode 100644 fixtures/conformance/error-relative-date-view-host-malformed/providers.json create mode 100644 fixtures/conformance/error-validator-condition-now/expected-errors.json create mode 100644 fixtures/conformance/error-validator-condition-now/input/meta.checks.json create mode 100644 fixtures/conformance/error-validator-condition-now/providers.json diff --git a/AGENTS.md b/AGENTS.md index 60a3f86018..bf2ea9d6fc 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/` (461 fixtures; 38 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/` (466 fixtures; 38 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 03a431c1a4..d226abcfbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -147,7 +147,16 @@ Each item below is described in full under Added, Changed or Fixed; this list is - an `origin.computed` expression may use `now` and `case` (searched, or simple with an `operand`), and a ref in it may name another of the projection's own fields (a passthrough, an `origin.first` or another `origin.computed`, never itself or an aggregate) before a base - field (`origin-computed-case-over-joined`, `error-origin-computed-case-mixed-types`). + field (`origin-computed-case-over-joined`, `error-origin-computed-case-mixed-types`). A + simple `case` compares a literal `when` with any `operand`, so an enum or long operand maps + its codes to labels; + - the loaders refuse what a view cannot lower: a `now` whose value is not an ISO-8601 duration + or whose `startOf` is not day, week or month (`error-origin-computed-now-bad-duration`); a + searched `case` whose `when` is not boolean (`error-origin-computed-case-non-boolean-when`); + computed fields that refer to each other in a cycle (`error-origin-computed-cycle`); and a + malformed relative date in a view host's `@filter` (`error-relative-date-view-host-malformed`); + - a validator `@condition` still refuses `case` and `now` (`ERR_BAD_ATTR_VALUE`, + `error-validator-condition-now`): it becomes a database CHECK, which can hold neither. - **An int-backed enum can be an array.** `@intValueMap` together with `isArray: true` (the map on the field, or inherited from a shared enum) now loads in every port instead of diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9b61a4eacb..9c08c942db 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) | 461 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 466 | ✓ | ✓ | 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 | ✓ | — | — | — | ✓ | @@ -354,7 +354,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (461) +### `fixtures/conformance/` — metamodel loader + canonical serializer (466) | Fixture prefix | Feature doc | |---|---| @@ -716,7 +716,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 461 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 466 + yaml 16 + verify 45 + render 18 + persistence 62 + api-contract 123 + source-resolution 25 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/fixtures/conformance/error-origin-computed-case-non-boolean-when/expected-errors.json b/fixtures/conformance/error-origin-computed-case-non-boolean-when/expected-errors.json new file mode 100644 index 0000000000..fe6ab3facc --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-non-boolean-when/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection'].children[2]['field.string'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-case-non-boolean-when/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-non-boolean-when/input/meta.views.json new file mode 100644 index 0000000000..8178d9d7ae --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-non-boolean-when/input/meta.views.json @@ -0,0 +1,93 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "BadWhen", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_badwhen" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "field": "status" + }, + "then": { + "value": "open" + } + } + ], + "else": { + "value": "closed" + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-origin-computed-case-non-boolean-when/providers.json b/fixtures/conformance/error-origin-computed-case-non-boolean-when/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-non-boolean-when/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-origin-computed-cycle/expected-errors.json b/fixtures/conformance/error-origin-computed-cycle/expected-errors.json new file mode 100644 index 0000000000..16a68b392d --- /dev/null +++ b/fixtures/conformance/error-origin-computed-cycle/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection'].children[2]['field.int'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-cycle/input/meta.views.json b/fixtures/conformance/error-origin-computed-cycle/input/meta.views.json new file mode 100644 index 0000000000..9bec899e49 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-cycle/input/meta.views.json @@ -0,0 +1,95 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "Loop", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_loop" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.int": { + "name": "a", + "children": [ + { + "origin.computed": { + "@expr": { + "field": "b" + } + } + } + ] + } + }, + { + "field.int": { + "name": "b", + "children": [ + { + "origin.computed": { + "@expr": { + "field": "a" + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-origin-computed-cycle/providers.json b/fixtures/conformance/error-origin-computed-cycle/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-cycle/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-origin-computed-now-bad-duration/expected-errors.json b/fixtures/conformance/error-origin-computed-now-bad-duration/expected-errors.json new file mode 100644 index 0000000000..73dda7a463 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-now-bad-duration/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_EXPR_NODE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection'].children[2]['field.boolean'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-now-bad-duration/input/meta.views.json b/fixtures/conformance/error-origin-computed-now-bad-duration/input/meta.views.json new file mode 100644 index 0000000000..606370e8c7 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-now-bad-duration/input/meta.views.json @@ -0,0 +1,87 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "BadNow", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_badnow" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.boolean": { + "name": "started", + "children": [ + { + "origin.computed": { + "@expr": { + "op": "gte", + "left": { + "now": "7 days ago" + }, + "right": { + "field": "effectiveFrom" + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-origin-computed-now-bad-duration/providers.json b/fixtures/conformance/error-origin-computed-now-bad-duration/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-now-bad-duration/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-relative-date-view-host-malformed/expected-errors.json b/fixtures/conformance/error-relative-date-view-host-malformed/expected-errors.json new file mode 100644 index 0000000000..b990f0a8c1 --- /dev/null +++ b/fixtures/conformance/error-relative-date-view-host-malformed/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_FILTER", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.aggregate']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-relative-date-view-host-malformed/input/meta.shop.json b/fixtures/conformance/error-relative-date-view-host-malformed/input/meta.shop.json new file mode 100644 index 0000000000..fe4110c3bc --- /dev/null +++ b/fixtures/conformance/error-relative-date-view-host-malformed/input/meta.shop.json @@ -0,0 +1,129 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Program", + "children": [ + { + "source.rdb": { + "@table": "programs" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "relationship.association": { + "name": "purchases", + "@objectRef": "Purchase", + "@cardinality": "many" + } + } + ] + } + }, + { + "object.entity": { + "name": "Purchase", + "children": [ + { + "source.rdb": { + "@table": "purchases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.timestamp": { + "name": "purchasedAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "programRef", + "@references": "Program", + "@fields": [ + "programId" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "ProgramPurchaseCounts", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "program_purchase_counts" + } + }, + { + "field.long": { + "name": "id", + "extends": "Program.id" + } + }, + { + "field.int": { + "name": "recentPurchaseCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@of": "Purchase.id", + "@via": "Program.purchases", + "@filter": { + "purchasedAt": { + "gte": { + "now": "7 days ago" + } + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "Program.id" + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-relative-date-view-host-malformed/providers.json b/fixtures/conformance/error-relative-date-view-host-malformed/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-relative-date-view-host-malformed/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/error-validator-condition-now/expected-errors.json b/fixtures/conformance/error-validator-condition-now/expected-errors.json new file mode 100644 index 0000000000..d0f9cc5fe8 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-now/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[7]['validator.atLeastOne']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[8]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-condition-now/input/meta.checks.json b/fixtures/conformance/error-validator-condition-now/input/meta.checks.json new file mode 100644 index 0000000000..80d2e25ff8 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-now/input/meta.checks.json @@ -0,0 +1,100 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": { + "@table": "visits" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "storeId" + } + }, + { + "field.long": { + "name": "kioskId" + } + }, + { + "field.boolean": { + "name": "active" + } + }, + { + "field.timestamp": { + "name": "startsAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "validator.atLeastOne": { + "name": "startedByNow", + "@fields": [ + "storeId", + "kioskId" + ], + "@condition": { + "op": "lt", + "left": { + "field": "startsAt" + }, + "right": { + "now": "P0D" + } + } + } + }, + { + "validator.atLeastOne": { + "name": "caseCondition", + "@fields": [ + "storeId", + "kioskId" + ], + "@condition": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "active" + }, + "right": { + "value": true + } + }, + "then": { + "value": true + } + } + ], + "else": { + "value": false + } + } + } + } + ] + } + } + ] + } +} \ No newline at end of file diff --git a/fixtures/conformance/error-validator-condition-now/providers.json b/fixtures/conformance/error-validator-condition-now/providers.json new file mode 100644 index 0000000000..1f1aa918d4 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-now/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-db"] \ No newline at end of file diff --git a/fixtures/conformance/origin-computed-case-over-joined/expected.json b/fixtures/conformance/origin-computed-case-over-joined/expected.json index 5758a08ac8..a7a58af1fb 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/expected.json +++ b/fixtures/conformance/origin-computed-case-over-joined/expected.json @@ -76,6 +76,15 @@ "name": "effectiveFrom" } }, + { + "field.enum": { + "name": "state", + "@values": [ + "OPEN", + "CLOSED" + ] + } + }, { "identity.primary": { "name": "id", @@ -246,6 +255,64 @@ ] } }, + { + "field.string": { + "name": "stateLabel", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "state" + }, + "case": [ + { + "when": { + "value": "OPEN" + }, + "then": { + "value": "Open" + } + } + ], + "else": { + "value": "Closed" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "statusKind", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "statusId" + }, + "case": [ + { + "when": { + "value": 1 + }, + "then": { + "value": "First" + } + } + ], + "else": { + "value": "Other" + } + } + } + } + ] + } + }, { "identity.primary": { "name": "id", diff --git a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json index bf214bb6c9..8839e5b8c2 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json +++ b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json @@ -74,6 +74,15 @@ "name": "effectiveFrom" } }, + { + "field.enum": { + "name": "state", + "@values": [ + "OPEN", + "CLOSED" + ] + } + }, { "identity.primary": { "name": "id", @@ -240,6 +249,64 @@ ] } }, + { + "field.string": { + "name": "stateLabel", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "state" + }, + "case": [ + { + "when": { + "value": "OPEN" + }, + "then": { + "value": "Open" + } + } + ], + "else": { + "value": "Closed" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "statusKind", + "children": [ + { + "origin.computed": { + "@expr": { + "operand": { + "field": "statusId" + }, + "case": [ + { + "when": { + "value": 1 + }, + "then": { + "value": "First" + } + } + ], + "else": { + "value": "Other" + } + } + } + } + ] + } + }, { "identity.primary": { "name": "id", diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index f0a1f6280c..b725d514f6 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -67,12 +67,16 @@ public static class ExpressionGrammar /// The field names an expression tree references, in order of appearance. public static List FieldRefs(object? node) + => Nodes(node).Select(n => Get(n, KEY_FIELD)).OfType().ToList(); + + /// Every node of an expression tree, root first. + public static List> Nodes(object? node) { - var refs = new List(); + var nodes = new List>(); void Walk(object? x) { if (x is not IReadOnlyDictionary n) return; - if (Get(n, KEY_FIELD) is string f) refs.Add(f); + nodes.Add(n); Walk(Get(n, KEY_LEFT)); Walk(Get(n, KEY_RIGHT)); Walk(Get(n, KEY_ARG)); @@ -84,7 +88,7 @@ void Walk(object? x) if (arm is IReadOnlyDictionary a) { Walk(Get(a, EXPR_CASE_WHEN)); Walk(Get(a, EXPR_CASE_THEN)); } } Walk(node); - return refs; + return nodes; } // ------------------------------------------------------------------------- @@ -122,9 +126,13 @@ public static List ValidateExprNode(object? node) if (n.ContainsKey(EXPR_NOW)) { - if (Get(n, EXPR_NOW) is not string) return [$"expression '{EXPR_NOW}' must be an ISO-8601 duration string"]; + if (Get(n, EXPR_NOW) is not string duration || !ISO_DURATION_RE.IsMatch(duration)) + return [$"expression '{EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got {Str(Get(n, EXPR_NOW))}"]; var extra = n.Keys.Where(k => k != EXPR_NOW && k != EXPR_NOW_START_OF).ToList(); - return extra.Count == 0 ? [] : [$"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {string.Join(", ", extra)}"]; + if (extra.Count > 0) return [$"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {string.Join(", ", extra)}"]; + return n.ContainsKey(EXPR_NOW_START_OF) && (Get(n, EXPR_NOW_START_OF) is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit)) + ? [$"expression '{EXPR_NOW_START_OF}' must be one of {string.Join(", ", RELATIVE_START_OF_UNITS)}, got {Str(Get(n, EXPR_NOW_START_OF))}"] + : []; } if (n.ContainsKey(EXPR_CASE)) @@ -209,7 +217,7 @@ public static InferResult InferExprType(object? node, Func reso var name = (string)Get(n, KEY_FIELD)!; var t = resolveField(name); return t is null - ? new InferResult(null, [$"expression field '{name}' does not resolve to a base entity field"]) + ? new InferResult(null, [$"expression field '{name}' does not resolve to a projection field (not an aggregate) or a base entity field"]) : new InferResult(t, []); } @@ -234,7 +242,8 @@ public static InferResult InferExprType(object? node, Func reso errors.AddRange(w.Errors); if (operand is null && w.Type is not null && w.Type != FIELD_SUBTYPE_BOOLEAN) errors.Add($"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.Type}"); - if (operand is { Type: { } ot } && w.Type is not null && w.Type != ot) + if (operand is { Type: { } ot } && w.Type is not null && Get(arm, EXPR_CASE_WHEN) is IReadOnlyDictionary wn + && !wn.ContainsKey(KEY_VALUE) && w.Type != ot) errors.Add($"a simple '{EXPR_CASE}' compares its {ot} '{EXPR_CASE_OPERAND}' with a {w.Type} '{EXPR_CASE_WHEN}'"); var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField); errors.AddRange(t.Errors); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index febcd46165..ae82474575 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -784,17 +784,47 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) // A ref names one of the projection's own fields // first (a passthrough, an origin.first, another computed — never itself, never // an aggregate), else a base field. + // ADR-0039: own — origin.* never inherits (ADR-0029), so a field's origin is declared on it. + Func ownOriginOf = name => obj.Children() + .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.OwnChildren() + .FirstOrDefault(c => c.Type == TYPE_ORIGIN); Func resolveField = name => { if (!ReferenceEquals(obj, computedBase) && name != field.Name && obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name) is { } own) { - var ownOrigin = own.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); - return ownOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE ? null : own.SubType; + return ownOriginOf(name)?.SubType == ORIGIN_SUBTYPE_AGGREGATE ? null : own.SubType; } return computedBase!.Children() .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.SubType; }; + // A sibling computed ref is inlined by the view, so the refs must not lead back here. + Func> computedRefs = name => ownOriginOf(name) is { SubType: ORIGIN_SUBTYPE_COMPUTED } o + ? ExpressionGrammar.FieldRefs(o.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Where(r => r != name).ToList() + : []; + Func> reach = start => + { + var seen = new HashSet(StringComparer.Ordinal); + var pending = computedRefs(start); + while (pending.Count > 0) + { + var r = pending[^1]; + pending.RemoveAt(pending.Count - 1); + if (seen.Add(r)) pending.AddRange(computedRefs(r)); + } + return seen; + }; + HashSet reached = !ReferenceEquals(obj, computedBase) ? reach(field.Name) : []; + if (reached.Contains(field.Name)) + { + // One error per cycle, on its first-declared member. + var first = obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && reached.Contains(f.Name) && reach(f.Name).Contains(field.Name)); + if (first?.Name == field.Name) + errors.Add(new MetaError( + $"origin.computed on {obj.Name}.{field.Name}: @expr refers back to this field through other computed fields; a view cannot inline a cycle.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + continue; + } var inferred = ExpressionGrammar.InferExprType(expr, resolveField); if (inferred.Errors.Count > 0) { @@ -2253,6 +2283,13 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo /// private static string? ConditionProblem(object condition, MetaObject obj) { + var unrenderable = MetaObjects.Core.Attr.ExpressionGrammar.Nodes(condition) + .FirstOrDefault(n => n.ContainsKey(ExpressionGrammar.EXPR_CASE) || n.ContainsKey(ExpressionGrammar.EXPR_NOW)); + if (unrenderable is not null) + { + var kind = unrenderable.ContainsKey(ExpressionGrammar.EXPR_CASE) ? ExpressionGrammar.EXPR_CASE : ExpressionGrammar.EXPR_NOW; + return $"is not a valid expression: a condition takes no '{kind}' node, since a CHECK can hold neither a CASE nor the current time."; + } var fields = new Dictionary(StringComparer.Ordinal); foreach (var f in obj.Fields()) fields.TryAdd(f.Name, f); var inferred = MetaObjects.Core.Attr.ExpressionGrammar.InferExprType( diff --git a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java index d879578297..eaf465a138 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java +++ b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java @@ -283,8 +283,9 @@ public static List validateExprNode(Object node) { return out; } if (n.containsKey(EXPR_NOW)) { - if (!(n.get(EXPR_NOW) instanceof String)) { - out.add("expression '" + EXPR_NOW + "' must be an ISO-8601 duration string"); + Object duration = n.get(EXPR_NOW); + if (!(duration instanceof String) || !ReportingConstants.ISO_DURATION_RE.matcher((String) duration).matches()) { + out.add("expression '" + EXPR_NOW + "' must be an ISO-8601 duration string (e.g. '-P7D'), got " + duration); return out; } List extra = new ArrayList<>(); @@ -292,6 +293,10 @@ public static List validateExprNode(Object node) { if (!extra.isEmpty()) { out.add("expression '" + EXPR_NOW + "' takes only '" + EXPR_NOW_START_OF + "' beside it, not " + String.join(", ", extra)); + } else if (n.containsKey(EXPR_NOW_START_OF) + && !ReportingConstants.RELATIVE_START_OF_UNITS.contains(n.get(EXPR_NOW_START_OF))) { + out.add("expression '" + EXPR_NOW_START_OF + "' must be one of " + + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + ", got " + n.get(EXPR_NOW_START_OF)); } return out; } @@ -407,7 +412,7 @@ public static InferResult inferExprType(Object node, Function re if (t == null) { return new InferResult(null, List.of( "expression field '" + String.valueOf(n.get("field")) - + "' does not resolve to a base entity field")); + + "' does not resolve to a projection field (not an aggregate) or a base entity field")); } return new InferResult(t, List.of()); } @@ -429,7 +434,8 @@ public static InferResult inferExprType(Object node, Function re if (operand == null && w.type != null && !BooleanField.SUBTYPE_BOOLEAN.equals(w.type)) { errors.add("a searched '" + EXPR_CASE + "' needs a boolean '" + EXPR_CASE_WHEN + "', got " + w.type); } - if (operand != null && operand.type != null && w.type != null && !w.type.equals(operand.type)) { + if (operand != null && operand.type != null && w.type != null + && !((Map) arm.get(EXPR_CASE_WHEN)).containsKey("value") && !w.type.equals(operand.type)) { errors.add("a simple '" + EXPR_CASE + "' compares its " + operand.type + " '" + EXPR_CASE_OPERAND + "' with a " + w.type + " '" + EXPR_CASE_WHEN + "'"); } 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 4dd2daaa3e..a36c3b4e02 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 @@ -2454,6 +2454,13 @@ static void validateCrossFieldValidators(MetaRoot root, List * Mirrors TS conditionProblem. */ private static String conditionProblem(Object condition, java.util.Map> fields) { + for (java.util.Map n : exprNodes(condition, new ArrayList<>())) { + if (n.containsKey(ExpressionAttribute.EXPR_CASE) || n.containsKey(ExpressionAttribute.EXPR_NOW)) { + return "is not a valid expression: a condition takes no '" + + (n.containsKey(ExpressionAttribute.EXPR_CASE) ? ExpressionAttribute.EXPR_CASE : ExpressionAttribute.EXPR_NOW) + + "' node, since a CHECK can hold neither a CASE nor the current time."; + } + } ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( condition, name -> fields.containsKey(name) ? fields.get(name).getSubType() : null); if (!inferred.errors.isEmpty()) { @@ -2533,13 +2540,65 @@ private static String conditionJsonLiteral(Object value) { /** The field names an expression tree (ExpressionAttribute's Map form) references. */ private static void collectExprFieldRefs(Object node, java.util.Set out) { - if (node instanceof java.util.Map m) { + for (java.util.Map m : exprNodes(node, new ArrayList<>())) { if (m.get("field") instanceof String f) out.add(f); - for (String k : List.of("left", "right", "arg")) collectExprFieldRefs(m.get(k), out); - if (m.get("args") instanceof java.util.Collection args) for (Object a : args) collectExprFieldRefs(a, out); } } + /** Every node of an expression tree (ExpressionAttribute's Map form), root first. */ + private static List> exprNodes(Object node, List> out) { + if (node instanceof java.util.Map m) { + out.add(m); + for (String k : List.of("left", "right", "arg", ExpressionAttribute.EXPR_CASE_OPERAND, + ExpressionAttribute.EXPR_CASE_ELSE)) exprNodes(m.get(k), out); + if (m.get("args") instanceof java.util.Collection args) for (Object a : args) exprNodes(a, out); + if (m.get(ExpressionAttribute.EXPR_CASE) instanceof java.util.Collection arms) { + for (Object arm : arms) { + if (arm instanceof java.util.Map am) { + exprNodes(am.get(ExpressionAttribute.EXPR_CASE_WHEN), out); + exprNodes(am.get(ExpressionAttribute.EXPR_CASE_THEN), out); + } + } + } + } + return out; + } + + /** A field's origin. ADR-0039: own — origin.* never inherits (ADR-0029), so it is declared on the field. */ + private static MetaOrigin ownOriginOf(MetaField field) { + for (MetaData oc : field.getChildren(MetaData.class, false)) { + if (oc instanceof MetaOrigin o) return o; + } + return null; + } + + /** The projection's computed fields reachable from {@code start}'s @expr through sibling + * computed refs (a view inlines each one, so the walk must not return to its start). */ + private static java.util.Set computedReach(MetaObject obj, String start) { + java.util.Set seen = new java.util.HashSet<>(); + java.util.Deque pending = new java.util.ArrayDeque<>(computedRefs(obj, start)); + while (!pending.isEmpty()) { + String r = pending.pop(); + if (seen.add(r)) pending.addAll(computedRefs(obj, r)); + } + return seen; + } + + private static java.util.Set computedRefs(MetaObject obj, String name) { + java.util.Set refs = new java.util.HashSet<>(); + for (MetaField f : obj.getChildren(MetaField.class, true)) { + if (!name.equals(f.getShortName())) continue; + MetaOrigin o = ownOriginOf(f); + if (o != null && ComputedOrigin.SUBTYPE_COMPUTED.equals(o.getSubType()) + && o.hasMetaAttr(MetaOrigin.ATTR_EXPR, false)) { + collectExprFieldRefs(o.getMetaAttr(MetaOrigin.ATTR_EXPR, false).getValue(), refs); + } + break; + } + refs.remove(name); + return refs; + } + // ========================================================================= // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation // "increment" key draws from; on any other generation there is none, so either one is @@ -3204,15 +3263,34 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, // not —, an origin.first or another origin.computed), else a base field. Never // itself, never an aggregate (it would need the grouped row). final String selfName = field.getShortName(); + if (obj != baseEntity) { + java.util.Set reached = computedReach(obj, selfName); + if (reached.contains(selfName)) { + // One error per cycle, on its first-declared member. + for (MetaField f : obj.getChildren(MetaField.class, true)) { + if (!reached.contains(f.getShortName()) + || !computedReach(obj, f.getShortName()).contains(selfName)) continue; + if (f.getShortName().equals(selfName)) { + throw new MetaDataException( + ErrorMessageConstants.ERR_INVALID_ORIGIN + + ": origin.computed on " + obj.getName() + "." + field.getName() + + ": @expr refers back to this field through other computed fields;" + + " a view cannot inline a cycle.", + ErrorCode.ERR_INVALID_ORIGIN, src); + } + break; + } + return; + } + } ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( expr, name -> { if (obj != baseEntity && !name.equals(selfName)) { for (MetaField own : obj.getChildren(MetaField.class, true)) { if (!name.equals(own.getShortName())) continue; - for (MetaData oc : own.getChildren(MetaData.class, false)) { - if (oc instanceof MetaOrigin - && AggregateOrigin.SUBTYPE_AGGREGATE.equals(oc.getSubType())) return null; - } + MetaOrigin ownOrigin = ownOriginOf(own); + if (ownOrigin != null + && AggregateOrigin.SUBTYPE_AGGREGATE.equals(ownOrigin.getSubType())) return null; return own.getSubType(); } } diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index cfc9fadf01..8201a318a5 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -10,7 +10,7 @@ import json import math import re -from typing import Callable, NamedTuple +from typing import Any, Callable, NamedTuple from ..errors import ErrorCode, MetaError from ..source.error_source import LoaderWarning @@ -25,7 +25,12 @@ from .validate_source_escapes import validate_source_escapes from .validate_reporting import validate_reporting from ..codegen.runtime.duration_wire import DURATION_RE -from ..meta.core.reporting.reporting_constants import FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF +from ..meta.core.reporting.reporting_constants import ( + FILTER_RELATIVE_NOW, + FILTER_RELATIVE_START_OF, + ISO_DURATION_RE, + RELATIVE_START_OF_UNITS, +) from ..meta.core.field.field_constants import ( ENUM_MEMBER_PATTERN, FIELD_ATTR_COERCE_DEFAULT, @@ -1196,12 +1201,19 @@ def validate_expr_node(node: object) -> list[str]: else ["expression 'value' must be a scalar literal (string/number/boolean/null)"] ) if EXPR_NOW in node: - if not isinstance(node[EXPR_NOW], str): - return [f"expression '{EXPR_NOW}' must be an ISO-8601 duration string"] + duration = node[EXPR_NOW] + if not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: + return [f"expression '{EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got {duration!r}"] extra = [k for k in node if k not in (EXPR_NOW, EXPR_NOW_START_OF)] - return [] if not extra else [ - f"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {', '.join(extra)}" - ] + if extra: + return [f"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {', '.join(extra)}"] + start_of = node.get(EXPR_NOW_START_OF) + if EXPR_NOW_START_OF in node and not (isinstance(start_of, str) and start_of in RELATIVE_START_OF_UNITS): + return [ + f"expression '{EXPR_NOW_START_OF}' must be one of " + f"{', '.join(RELATIVE_START_OF_UNITS)}, got {start_of!r}" + ] + return [] if EXPR_CASE in node: arms = node[EXPR_CASE] if not isinstance(arms, list) or not arms: @@ -1283,7 +1295,7 @@ def infer_expr_type( if "field" in n: t = resolve_field(n["field"]) return ( - InferResult(None, [f"expression field '{n['field']}' does not resolve to a base entity field"]) + InferResult(None, [f"expression field '{n['field']}' does not resolve to a projection field (not an aggregate) or a base entity field"]) if t is None else InferResult(t, []) ) @@ -1303,7 +1315,10 @@ def infer_expr_type( errors.extend(w.errors) if operand is None and w.type is not None and w.type != FIELD_SUBTYPE_BOOLEAN: errors.append(f"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.type}") - if operand is not None and operand.type is not None and w.type is not None and w.type != operand.type: + if ( + operand is not None and operand.type is not None and w.type is not None + and "value" not in arm[EXPR_CASE_WHEN] and w.type != operand.type + ): errors.append( f"a simple '{EXPR_CASE}' compares its {operand.type} '{EXPR_CASE_OPERAND}' " f"with a {w.type} '{EXPR_CASE_WHEN}'" @@ -2662,15 +2677,30 @@ def _resolve_field( for own in _obj.children(): if own.type != TYPE_FIELD or own.name != name: continue - for oc in own.own_children(): - if oc.type == TYPE_ORIGIN and oc.sub_type == ORIGIN_SUBTYPE_AGGREGATE: - return None + own_origin = _own_origin_of(own) + if own_origin is not None and own_origin.sub_type == ORIGIN_SUBTYPE_AGGREGATE: + return None return own.sub_type for f in _base.children(): if f.type == TYPE_FIELD and f.name == name: return f.sub_type return None + reached = _computed_reach(obj, node.name) if obj is not base else set() + if node.name in reached: + # One error per cycle, on its first-declared member. + first = next( + f for f in obj.children() + if f.type == TYPE_FIELD and f.name in reached + and node.name in _computed_reach(obj, f.name) + ) + if first.name == node.name: + errors.append(MetaError( + f"origin.computed on {obj.name}.{node.name}: @expr refers back to this " + f"field through other computed fields; a view cannot inline a cycle.", + ErrorCode.ERR_INVALID_ORIGIN, envelope=src)) + continue + inferred = infer_expr_type(expr, _resolve_field) if inferred.errors: for m in inferred.errors: @@ -3938,16 +3968,58 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None # become a CHECK guard (see _condition_problem) — all ERR_BAD_ATTR_VALUE. Read RESOLVING # (ADR-0039). Mirrors TS validateCrossFieldValidators. def _expr_field_refs(node: object, out: set[str]) -> None: + for n in _expr_nodes(node): + if isinstance(n.get("field"), str): + out.add(n["field"]) + + +def _expr_nodes(node: object, out: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]: + """Every node of an attr.expression tree, root first.""" + out = [] if out is None else out if not isinstance(node, dict): - return - if isinstance(node.get("field"), str): - out.add(node["field"]) - for key in ("left", "right", "arg"): - _expr_field_refs(node.get(key), out) + return out + out.append(node) + for key in ("left", "right", "arg", EXPR_CASE_OPERAND, EXPR_CASE_ELSE): + _expr_nodes(node.get(key), out) args = node.get("args") if isinstance(args, list): for a in args: - _expr_field_refs(a, out) + _expr_nodes(a, out) + arms = node.get(EXPR_CASE) + if isinstance(arms, list): + for arm in arms: + if isinstance(arm, dict): + _expr_nodes(arm.get(EXPR_CASE_WHEN), out) + _expr_nodes(arm.get(EXPR_CASE_THEN), out) + return out + + +def _own_origin_of(field: MetaData) -> MetaData | None: + # ADR-0039: own — origin.* never inherits (ADR-0029), so a field's origin is declared on it. + return next((c for c in field.own_children() if c.type == TYPE_ORIGIN), None) + + +def _computed_reach(obj: MetaData, start: str) -> set[str]: + """The projection's computed fields reachable from ``start``'s @expr through sibling + computed refs (a view inlines each one, so the walk must not return to its start).""" + + def refs(name: str) -> set[str]: + out: set[str] = set() + field = next((f for f in obj.children() if f.type == TYPE_FIELD and f.name == name), None) + origin = _own_origin_of(field) if field is not None else None + if origin is not None and origin.sub_type == ORIGIN_SUBTYPE_COMPUTED: + _expr_field_refs(origin.attr(ORIGIN_ATTR_EXPR), out) + out.discard(name) + return out + + seen: set[str] = set() + pending = list(refs(start)) + while pending: + r = pending.pop() + if r not in seen: + seen.add(r) + pending.extend(refs(r)) + return seen # What a literal compared with a field.duration must be. @@ -3986,6 +4058,13 @@ def _condition_problem(condition: object, obj: MetaData) -> str | None: @values, for field.duration, an ISO-8601 duration; - no comparison has a null literal: ``x = NULL`` is never true, so use isNull / isNotNull. Mirrors TS conditionProblem.""" + for n in _expr_nodes(condition): + if EXPR_CASE in n or EXPR_NOW in n: + kind = EXPR_CASE if EXPR_CASE in n else EXPR_NOW + return ( + f"is not a valid expression: a condition takes no '{kind}' node, " + f"since a CHECK can hold neither a CASE nor the current time." + ) fields = {f.name: f for f in obj.fields()} inferred = infer_expr_type( condition, lambda name: fields[name].sub_type if name in fields else None diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index 0e2d140d97..2602cb707a 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -30,7 +30,9 @@ import { type AttrValue } from "../../shared/meta-data.js"; import { DATA_TYPE_OBJECT, type DataType } from "../../data-type.js"; import { ATTR_SUBTYPE_EXPRESSION } from "./attr-constants.js"; import { registerAttrClass } from "../../attr-class-map.js"; -import { FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF } from "../reporting/reporting-constants.js"; +import { + FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF, ISO_DURATION_RE, RELATIVE_START_OF_UNITS, +} from "../reporting/reporting-constants.js"; // --- Expression-only op/fn names (the comparison + and/or/isNull names are the // --- shared filter vocabulary above; these three are new). --- @@ -81,9 +83,16 @@ export function validateExprNode(node: unknown): string[] { ? [] : ["expression 'value' must be a scalar literal (string/number/boolean/null)"]; } if (EXPR_NOW in node) { - if (typeof node[EXPR_NOW] !== "string") return [`expression '${EXPR_NOW}' must be an ISO-8601 duration string`]; + const duration = node[EXPR_NOW]; + if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { + return [`expression '${EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got ${JSON.stringify(duration)}`]; + } const extra = Object.keys(node).filter((k) => k !== EXPR_NOW && k !== EXPR_NOW_START_OF); - return extra.length === 0 ? [] : [`expression '${EXPR_NOW}' takes only '${EXPR_NOW_START_OF}' beside it, not ${extra.join(", ")}`]; + if (extra.length > 0) return [`expression '${EXPR_NOW}' takes only '${EXPR_NOW_START_OF}' beside it, not ${extra.join(", ")}`]; + const startOf = node[EXPR_NOW_START_OF]; + return EXPR_NOW_START_OF in node && !(RELATIVE_START_OF_UNITS as readonly unknown[]).includes(startOf) + ? [`expression '${EXPR_NOW_START_OF}' must be one of ${RELATIVE_START_OF_UNITS.join(", ")}, got ${JSON.stringify(startOf)}`] + : []; } if (EXPR_CASE in node) { const arms = node[EXPR_CASE]; @@ -155,7 +164,7 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if ("field" in n) { const t = resolveField(n.field as string); return t === undefined - ? { type: undefined, errors: [`expression field '${String(n.field)}' does not resolve to a base entity field`] } + ? { type: undefined, errors: [`expression field '${String(n.field)}' does not resolve to a projection field (not an aggregate) or a base entity field`] } : { type: t, errors: [] }; } if ("value" in n) return { type: literalType(n.value as ExprLiteral), errors: [] }; @@ -173,7 +182,7 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if (operand === undefined && w.type !== undefined && w.type !== FIELD_SUBTYPE_BOOLEAN) { errors.push(`a searched '${EXPR_CASE}' needs a boolean '${EXPR_CASE_WHEN}', got ${w.type}`); } - if (operand?.type !== undefined && w.type !== undefined && w.type !== operand.type) { + if (operand?.type !== undefined && w.type !== undefined && !("value" in arm.when) && w.type !== operand.type) { errors.push(`a simple '${EXPR_CASE}' compares its ${operand.type} '${EXPR_CASE_OPERAND}' with a ${w.type} '${EXPR_CASE_WHEN}'`); } const t = inferExprType(arm.then, resolveField); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 0192923177..840ddc2dad 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -135,6 +135,12 @@ import { COLUMN_VALUE_AGGREGATES, } from "../persistence/origin/origin-constants.js"; import { + EXPR_CASE, + EXPR_CASE_ELSE, + EXPR_CASE_OPERAND, + EXPR_CASE_THEN, + EXPR_CASE_WHEN, + EXPR_NOW, inferExprType, validateExprNode, type ExprNode, @@ -1626,15 +1632,45 @@ export function validateOriginPaths(root: MetaData): ParseError[] { // A ref names one of the projection's own fields first (a // passthrough — joined or not —, an origin.first or another origin.computed), else a base // field. Never itself, never an aggregate (it would need the grouped row). + const ownOriginOf = (name: string): MetaData | undefined => + // ADR-0039: own — origin.* never inherits (ADR-0029), so a field's origin is declared on it. + obj.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.ownChildren().find((c) => c.type === TYPE_ORIGIN); const resolveField = (name: string): string | undefined => { if (obj !== base && name !== field.name) { const own = obj.children().find((f) => f.type === TYPE_FIELD && f.name === name); - const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); + const ownOrigin = ownOriginOf(name); if (own !== undefined && ownOrigin?.subType !== ORIGIN_SUBTYPE_AGGREGATE) return own.subType; if (own !== undefined) return undefined; } return base.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.subType; }; + // A sibling computed ref is inlined by the view, so the refs must not lead back here. + const computedRefs = (name: string): string[] => { + const o = ownOriginOf(name); + return o?.subType === ORIGIN_SUBTYPE_COMPUTED + ? expressionFieldRefs(o.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR)).filter((r) => r !== name) + : []; + }; + const reach = (start: string): Set => { + const seen = new Set(); + const pending = computedRefs(start); + for (let r = pending.pop(); r !== undefined; r = pending.pop()) { + if (!seen.has(r)) pending.push(...computedRefs(r)); + seen.add(r); + } + return seen; + }; + const reached = obj !== base ? reach(field.name) : new Set(); + if (reached.has(field.name)) { + // One error per cycle, on its first-declared member. + const first = obj.children().find((f) => f.type === TYPE_FIELD && reached.has(f.name) && reach(f.name).has(field.name)); + if (first?.name === field.name) { + errors.push(new ParseError( + `origin.computed on ${obj.name}.${field.name}: @expr refers back to this field through other computed fields; a view cannot inline a cycle.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + continue; + } const inferred = inferExprType(expr as ExprNode, resolveField); if (inferred.errors.length > 0) { for (const m of inferred.errors) { @@ -1768,16 +1804,29 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] // Read RESOLVING (ADR-0039): an entity's validators and fields include inherited ones. // --------------------------------------------------------------------------- -/** The field names an attr.expression tree references. */ -function expressionFieldRefs(node: unknown, out: string[] = []): string[] { +/** Every node of an attr.expression tree, root first. */ +function expressionNodes(node: unknown, out: Record[] = []): Record[] { if (typeof node !== "object" || node === null) return out; const n = node as Record; - if (typeof n["field"] === "string") out.push(n["field"]); - for (const key of ["left", "right", "arg"]) expressionFieldRefs(n[key], out); - for (const key of ["args"]) if (Array.isArray(n[key])) for (const a of n[key] as unknown[]) expressionFieldRefs(a, out); + out.push(n); + for (const key of ["left", "right", "arg", EXPR_CASE_OPERAND, EXPR_CASE_ELSE]) expressionNodes(n[key], out); + if (Array.isArray(n["args"])) for (const a of n["args"] as unknown[]) expressionNodes(a, out); + if (Array.isArray(n[EXPR_CASE])) { + for (const arm of n[EXPR_CASE] as unknown[]) { + if (typeof arm === "object" && arm !== null) { + expressionNodes((arm as Record)[EXPR_CASE_WHEN], out); + expressionNodes((arm as Record)[EXPR_CASE_THEN], out); + } + } + } return out; } +/** The field names an attr.expression tree references. */ +function expressionFieldRefs(node: unknown): string[] { + return expressionNodes(node).flatMap((n) => (typeof n["field"] === "string" ? [n["field"]] : [])); +} + /** What a literal compared with a field.duration must be. */ const DURATION_LITERAL_FORM = "an ISO-8601 duration (such as PT1H30M; no years or months)"; @@ -1798,6 +1847,10 @@ const _CONDITION_NUMBER_SUBTYPES = new Set([ * - no comparison has a null literal: `x = NULL` is never true, so use isNull / isNotNull. */ function conditionProblem(condition: unknown, obj: MetaObject): string | undefined { + const unrenderable = expressionNodes(condition).find((n) => EXPR_CASE in n || EXPR_NOW in n); + if (unrenderable !== undefined) { + return `is not a valid expression: a condition takes no '${EXPR_CASE in unrenderable ? EXPR_CASE : EXPR_NOW}' node, since a CHECK can hold neither a CASE nor the current time.`; + } const fields = new Map(obj.fields().map((f) => [f.name, f] as const)); const inferred = inferExprType(condition as ExprNode, (name) => fields.get(name)?.subType); if (inferred.errors.length > 0) return `is not a valid expression: ${inferred.errors.join("; ")}.`; From a506b2c4df598088181fddaca4f18aaeab3aac20 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 06:46:43 -0500 Subject: [PATCH 3/7] no-mistakes(review): Tighten expression keys and relative-date types --- AGENTS.md | 2 +- CHANGELOG.md | 11 +- docs/CONFORMANCE.md | 6 +- docs/features/reporting.md | 2 +- examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.views.json | 147 +++++++++++++ .../providers.json | 1 + .../expected-errors.json | 15 ++ .../input/meta.views.json | 145 +++++++++++++ .../providers.json | 1 + .../expected-errors.json | 25 +++ .../input/meta.shop.json | 172 +++++++++++++++ .../providers.json | 1 + .../expected.json | 197 ++++++++++++++++++ .../input/meta.views.json | 191 +++++++++++++++++ .../providers.json | 1 + .../Core/Attr/ExpressionGrammar.cs | 69 +++++- .../Loader/ValidationPasses.Reporting.cs | 106 +++++----- .../MetaObjects/Loader/ValidationPasses.cs | 15 ++ .../metaobjects/attr/ExpressionAttribute.java | 112 +++++++--- .../loader/ReportingValidation.java | 125 +++++------ .../metaobjects/loader/ValidationPhase.java | 20 ++ .../metaobjects/loader/validate_reporting.py | 130 +++++------- .../metaobjects/loader/validation_passes.py | 95 +++++++-- .../src/core/attr/meta-attr-expression.ts | 67 ++++-- .../src/loader/reporting-validation.ts | 129 ++++++------ .../metadata/src/loader/validation-passes.ts | 15 ++ 28 files changed, 1480 insertions(+), 337 deletions(-) create mode 100644 fixtures/conformance/error-origin-computed-case-unknown-key/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-case-unknown-key/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-case-unknown-key/providers.json create mode 100644 fixtures/conformance/error-origin-computed-node-mixed-keys/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-node-mixed-keys/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-node-mixed-keys/providers.json create mode 100644 fixtures/conformance/error-relative-date-non-temporal-field/expected-errors.json create mode 100644 fixtures/conformance/error-relative-date-non-temporal-field/input/meta.shop.json create mode 100644 fixtures/conformance/error-relative-date-non-temporal-field/providers.json create mode 100644 fixtures/conformance/origin-computed-literal-unifies/expected.json create mode 100644 fixtures/conformance/origin-computed-literal-unifies/input/meta.views.json create mode 100644 fixtures/conformance/origin-computed-literal-unifies/providers.json diff --git a/AGENTS.md b/AGENTS.md index bf2ea9d6fc..8b9ef83511 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/` (466 fixtures; 38 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/` (470 fixtures; 38 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 d226abcfbf..2e818d8bb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -149,12 +149,19 @@ Each item below is described in full under Added, Changed or Fixed; this list is an `origin.first` or another `origin.computed`, never itself or an aggregate) before a base field (`origin-computed-case-over-joined`, `error-origin-computed-case-mixed-types`). A simple `case` compares a literal `when` with any `operand`, so an enum or long operand maps - its codes to labels; + its codes to labels. A `case`'s results and a `coalesce`'s arguments unify a numeric literal + with any numeric field and a `now` with a date or timestamp (`origin-computed-literal-unifies`); - the loaders refuse what a view cannot lower: a `now` whose value is not an ISO-8601 duration or whose `startOf` is not day, week or month (`error-origin-computed-now-bad-duration`); a searched `case` whose `when` is not boolean (`error-origin-computed-case-non-boolean-when`); computed fields that refer to each other in a cycle (`error-origin-computed-cycle`); and a - malformed relative date in a view host's `@filter` (`error-relative-date-view-host-malformed`); + malformed relative date in a view host's `@filter` (`error-relative-date-view-host-malformed`), + or one on a field that is not a `field.date` or `field.timestamp`, where a projection's key + names its own field and an origin's names a field of its `@of` entity or `@via` terminal + (`error-relative-date-non-temporal-field`); and an expression node that carries a key its + kind does not take, such as a misspelled `else` on a `case` or a `field` node that also + carries `case` (`ERR_UNKNOWN_EXPR_NODE`, `error-origin-computed-case-unknown-key`, + `error-origin-computed-node-mixed-keys`); - a validator `@condition` still refuses `case` and `now` (`ERR_BAD_ATTR_VALUE`, `error-validator-condition-now`): it becomes a database CHECK, which can hold neither. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9c08c942db..fb4abb5df8 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) | 466 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 470 | ✓ | ✓ | 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 | ✓ | — | — | — | ✓ | @@ -354,7 +354,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (466) +### `fixtures/conformance/` — metamodel loader + canonical serializer (470) | Fixture prefix | Feature doc | |---|---| @@ -716,7 +716,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 466 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 470 + yaml 16 + verify 45 + render 18 + persistence 62 + api-contract 123 + source-resolution 25 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 0e4b993f55..00e2dc5579 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -969,7 +969,7 @@ only beside `now`. | Rule | Code | Refused | |---|---|---| -| **F1** | `ERR_BAD_ATTR_FILTER` | A relative value anywhere except the `@filter` of a `segment`, a `measure.aggregate`, an `object.report`, an `object.projection`, an `origin.first` or an `origin.aggregate`. In a `layout.dataGrid` preset it fails the load, because no lowering exists for that host. On a projection or an origin, whose filter keys resolve elsewhere, the loader checks the value's own shape (F2's operator, duration and `startOf` rules) and the field type is checked where the filter is lowered. | +| **F1** | `ERR_BAD_ATTR_FILTER` | A relative value anywhere except the `@filter` of a `segment`, a `measure.aggregate`, an `object.report`, an `object.projection`, an `origin.first` or an `origin.aggregate`. In a `layout.dataGrid` preset it fails the load, because no lowering exists for that host. On a projection or an origin, F2 applies in full: a projection's key names one of its own fields, and an origin's key names a field of its `@of` entity, or of its `@via` terminal when it has no `@of`. | | **F2** | `ERR_BAD_ATTR_FILTER` | A relative value on any field except a `field.date` or `field.timestamp`; under any operator except `gt, gte, lt, lte`; as an object that carries keys besides `now` and `startOf`; with a duration that does not match the ISO-8601 pattern `^[+-]?P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$`; or with a `startOf` other than `day`, `week` or `month`. | An operator-less `{ "occurredAt": { "now": "-P7D" } }` is read as `eq`, and `eq` is not one diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index cedd67c485..cba926bcff 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 461, + "fixtures": 470, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-origin-computed-case-unknown-key/expected-errors.json b/fixtures/conformance/error-origin-computed-case-unknown-key/expected-errors.json new file mode 100644 index 0000000000..46d5cdb5c9 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-unknown-key/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_EXPR_NODE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-case-unknown-key/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-unknown-key/input/meta.views.json new file mode 100644 index 0000000000..d7769a305c --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-unknown-key/input/meta.views.json @@ -0,0 +1,147 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "BadNodes", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_badnodes" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.int": { + "name": "misspelledElse", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "status" + }, + "right": { + "value": 0 + } + }, + "then": { + "value": 1 + } + } + ], + "elsee": { + "value": 2 + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-origin-computed-case-unknown-key/providers.json b/fixtures/conformance/error-origin-computed-case-unknown-key/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-case-unknown-key/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-origin-computed-node-mixed-keys/expected-errors.json b/fixtures/conformance/error-origin-computed-node-mixed-keys/expected-errors.json new file mode 100644 index 0000000000..46d5cdb5c9 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-node-mixed-keys/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_UNKNOWN_EXPR_NODE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-node-mixed-keys/input/meta.views.json b/fixtures/conformance/error-origin-computed-node-mixed-keys/input/meta.views.json new file mode 100644 index 0000000000..52a7b4732f --- /dev/null +++ b/fixtures/conformance/error-origin-computed-node-mixed-keys/input/meta.views.json @@ -0,0 +1,145 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "BadNodes", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_badnodes" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.int": { + "name": "fieldWithCase", + "children": [ + { + "origin.computed": { + "@expr": { + "field": "status", + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "status" + }, + "right": { + "value": 0 + } + }, + "then": { + "value": 1 + } + } + ] + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-origin-computed-node-mixed-keys/providers.json b/fixtures/conformance/error-origin-computed-node-mixed-keys/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-node-mixed-keys/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-relative-date-non-temporal-field/expected-errors.json b/fixtures/conformance/error-relative-date-non-temporal-field/expected-errors.json new file mode 100644 index 0000000000..51bab0d0a4 --- /dev/null +++ b/fixtures/conformance/error-relative-date-non-temporal-field/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_FILTER", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.aggregate']" + } + }, + { + "code": "ERR_BAD_ATTR_FILTER", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[3]['object.projection']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-relative-date-non-temporal-field/input/meta.shop.json b/fixtures/conformance/error-relative-date-non-temporal-field/input/meta.shop.json new file mode 100644 index 0000000000..6940e55857 --- /dev/null +++ b/fixtures/conformance/error-relative-date-non-temporal-field/input/meta.shop.json @@ -0,0 +1,172 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Program", + "children": [ + { + "source.rdb": { + "@table": "programs" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "relationship.association": { + "name": "purchases", + "@objectRef": "Purchase", + "@cardinality": "many" + } + } + ] + } + }, + { + "object.entity": { + "name": "Purchase", + "children": [ + { + "source.rdb": { + "@table": "purchases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "programId" + } + }, + { + "field.currency": { + "name": "amountCents" + } + }, + { + "field.timestamp": { + "name": "purchasedAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "programRef", + "@references": "Program", + "@fields": [ + "programId" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "ProgramPurchaseCounts", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "program_purchase_counts" + } + }, + { + "field.long": { + "name": "id", + "extends": "Program.id" + } + }, + { + "field.int": { + "name": "recentPurchaseCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@of": "Purchase.id", + "@via": "Program.purchases", + "@filter": { + "programId": { + "gte": { + "now": "-P7D" + } + } + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "Program.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "RecentPurchase", + "@filter": { + "amountCents": { + "gte": { + "now": "-P7D" + } + } + }, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "recent_purchases" + } + }, + { + "field.long": { + "name": "id", + "extends": "Purchase.id" + } + }, + { + "field.currency": { + "name": "amountCents", + "extends": "Purchase.amountCents" + } + }, + { + "identity.primary": { + "name": "id", + "extends": "Purchase.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-relative-date-non-temporal-field/providers.json b/fixtures/conformance/error-relative-date-non-temporal-field/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-relative-date-non-temporal-field/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/origin-computed-literal-unifies/expected.json b/fixtures/conformance/origin-computed-literal-unifies/expected.json new file mode 100644 index 0000000000..a5291fd944 --- /dev/null +++ b/fixtures/conformance/origin-computed-literal-unifies/expected.json @@ -0,0 +1,197 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": [ + "statusId" + ], + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "CaseUnify", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_case_unify" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.long": { + "name": "statusOrZero", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "status" + }, + "right": { + "value": 0 + } + }, + "then": { + "value": 0 + } + } + ], + "else": { + "field": "statusId" + } + } + } + } + ] + } + }, + { + "field.long": { + "name": "statusIdOrZero", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "statusId" + }, + { + "value": 0 + } + ] + } + } + } + ] + } + }, + { + "field.date": { + "name": "effectiveOrToday", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "effectiveFrom" + }, + { + "now": "P0D" + } + ] + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/origin-computed-literal-unifies/input/meta.views.json b/fixtures/conformance/origin-computed-literal-unifies/input/meta.views.json new file mode 100644 index 0000000000..5657b496c2 --- /dev/null +++ b/fixtures/conformance/origin-computed-literal-unifies/input/meta.views.json @@ -0,0 +1,191 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "CaseUnify", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_case_unify" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.long": { + "name": "statusOrZero", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "status" + }, + "right": { + "value": 0 + } + }, + "then": { + "value": 0 + } + } + ], + "else": { + "field": "statusId" + } + } + } + } + ] + } + }, + { + "field.long": { + "name": "statusIdOrZero", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "statusId" + }, + { + "value": 0 + } + ] + } + } + } + ] + } + }, + { + "field.date": { + "name": "effectiveOrToday", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "effectiveFrom" + }, + { + "now": "P0D" + } + ] + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/origin-computed-literal-unifies/providers.json b/fixtures/conformance/origin-computed-literal-unifies/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/origin-computed-literal-unifies/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index b725d514f6..148764a996 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -65,6 +65,22 @@ public static class ExpressionGrammar FILTER_COMPOSE_AND, FILTER_COMPOSE_OR, }; + /// Each node kind (keyed by the key that names it) and the only keys it may carry. + private static readonly (string Kind, string[] Keys)[] NodeKeys = + [ + (KEY_FIELD, [KEY_FIELD]), + (KEY_VALUE, [KEY_VALUE]), + (EXPR_NOW, [EXPR_NOW, EXPR_NOW_START_OF]), + (EXPR_CASE, [EXPR_CASE, EXPR_CASE_ELSE, EXPR_CASE_OPERAND]), + (KEY_FN, [KEY_FN, KEY_ARGS]), + (KEY_OP, [KEY_OP, KEY_LEFT, KEY_RIGHT, KEY_ARG, KEY_ARGS]), + ]; + + private static readonly HashSet NumericSubtypes = new(StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, + }; + /// The field names an expression tree references, in order of appearance. public static List FieldRefs(object? node) => Nodes(node).Select(n => Get(n, KEY_FIELD)).OfType().ToList(); @@ -110,6 +126,14 @@ public static List ValidateExprNode(object? node) return [$"expression node must be an object, got {kind}"]; } + var nodeKind = NodeKeys.FirstOrDefault(k => n.ContainsKey(k.Kind)); + if (nodeKind.Kind is not null) + { + var extraKeys = n.Keys.Where(k => !nodeKind.Keys.Contains(k)).ToList(); + if (extraKeys.Count > 0) + return [$"expression '{nodeKind.Kind}' node takes only {string.Join(", ", nodeKind.Keys)}, not {string.Join(", ", extraKeys)}"]; + } + if (n.ContainsKey(KEY_FIELD)) { return Get(n, KEY_FIELD) is string fs && fs.Length > 0 @@ -128,8 +152,6 @@ public static List ValidateExprNode(object? node) { if (Get(n, EXPR_NOW) is not string duration || !ISO_DURATION_RE.IsMatch(duration)) return [$"expression '{EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got {Str(Get(n, EXPR_NOW))}"]; - var extra = n.Keys.Where(k => k != EXPR_NOW && k != EXPR_NOW_START_OF).ToList(); - if (extra.Count > 0) return [$"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {string.Join(", ", extra)}"]; return n.ContainsKey(EXPR_NOW_START_OF) && (Get(n, EXPR_NOW_START_OF) is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit)) ? [$"expression '{EXPR_NOW_START_OF}' must be one of {string.Join(", ", RELATIVE_START_OF_UNITS)}, got {Str(Get(n, EXPR_NOW_START_OF))}"] : []; @@ -142,7 +164,8 @@ public static List ValidateExprNode(object? node) var errs = new List(); foreach (var arm in arms) { - if (arm is not IReadOnlyDictionary a || !a.ContainsKey(EXPR_CASE_WHEN) || !a.ContainsKey(EXPR_CASE_THEN)) + if (arm is not IReadOnlyDictionary a || !a.ContainsKey(EXPR_CASE_WHEN) || !a.ContainsKey(EXPR_CASE_THEN) + || a.Keys.Any(k => k != EXPR_CASE_WHEN && k != EXPR_CASE_THEN)) { errs.Add($"every '{EXPR_CASE}' arm must be {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }}"); continue; @@ -235,6 +258,7 @@ public static InferResult InferExprType(object? node, Func reso InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField) : null; if (operand is { } o) errors.AddRange(o.Errors); var results = new List(); + var resultNodes = new List(); foreach (var armObj in arms) { var arm = (IReadOnlyDictionary)armObj!; @@ -248,17 +272,18 @@ public static InferResult InferExprType(object? node, Func reso var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField); errors.AddRange(t.Errors); results.Add(t.Type); + resultNodes.Add(Get(arm, EXPR_CASE_THEN)); } if (n.ContainsKey(EXPR_CASE_ELSE)) { var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField); errors.AddRange(e.Errors); results.Add(e.Type); + resultNodes.Add(Get(n, EXPR_CASE_ELSE)); } - var types = results.Where(t => t is not null).Select(t => t!).ToList(); - string? unified = types.Count > 0 ? types[0] : null; - if (unified is not null && types.Any(t => t != unified)) - errors.Add($"'{EXPR_CASE}' results have differing types ({string.Join(", ", types.Distinct())})"); + var (unified, differing) = UnifyTypes(resultNodes, results); + if (differing is not null) + errors.Add($"'{EXPR_CASE}' results have differing types ({string.Join(", ", differing)})"); return new InferResult(unified, errors); } @@ -267,10 +292,9 @@ public static InferResult InferExprType(object? node, Func reso var args = (IReadOnlyList)Get(n, KEY_ARGS)!; var argResults = args.Select(a => InferExprType(a, resolveField)).ToList(); var errors = argResults.SelectMany(a => a.Errors).ToList(); - var argTypes = argResults.Select(a => a.Type).Where(t => t is not null).Select(t => t!).ToList(); - string? unified = argTypes.Count > 0 ? argTypes[0] : null; - if (unified is not null && argTypes.Any(t => t != unified)) - errors.Add($"'{EXPR_FN_COALESCE}' arguments have differing types ({string.Join(", ", argTypes.Distinct())})"); + var (unified, differing) = UnifyTypes(args, argResults.Select(a => a.Type).ToList()); + if (differing is not null) + errors.Add($"'{EXPR_FN_COALESCE}' arguments have differing types ({string.Join(", ", differing)})"); return new InferResult(unified, errors); } @@ -311,6 +335,29 @@ public static InferResult InferExprType(object? node, Func reso private static object? Get(IReadOnlyDictionary n, string key) => n.TryGetValue(key, out var v) ? v : null; + /// A numeric literal or a now node: it takes the type of the result it sits beside. + private static bool IsAdaptable(object? node) => + node is IReadOnlyDictionary n + && ((n.ContainsKey(KEY_VALUE) && Get(n, KEY_VALUE) is long or int or double) || n.ContainsKey(EXPR_NOW)); + + /// Whether an adaptable node takes : a number takes any numeric + /// type, now a date or timestamp. + private static bool AdaptsTo(object? node, string to) => + node is IReadOnlyDictionary n && n.ContainsKey(EXPR_NOW) + ? to == FIELD_SUBTYPE_DATE || to == FIELD_SUBTYPE_TIMESTAMP + : NumericSubtypes.Contains(to); + + /// The one type of a case's results or a coalesce's args, or every type when they do not unify. + private static (string? Type, List? Differing) UnifyTypes(IReadOnlyList nodes, IReadOnlyList types) + { + var typed = nodes.Zip(types).Where(r => r.Second is not null).Select(r => (Node: r.First, Type: r.Second!)).ToList(); + var anchor = typed.FirstOrDefault(r => !IsAdaptable(r.Node)); + string? unified = anchor.Type ?? (typed.Count > 0 ? typed[0].Type : null); + bool fits = typed.All(r => r.Type == unified + || (anchor.Type is not null && IsAdaptable(r.Node) && AdaptsTo(r.Node, anchor.Type))); + return fits ? (unified, null) : (unified, typed.Select(r => r.Type).Distinct().ToList()); + } + /// A scalar literal (string / number / boolean / null). Numbers arrive /// as long or double from DataConverter.ParseNumber. private static bool IsScalarLiteral(object? v) diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs index f653e833ca..637245e18a 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs @@ -96,7 +96,7 @@ public static IReadOnlyList ValidateReporting(MetaData root, TypeRegi } // F1 on every host that is not a reporting host. - CheckNoRelativeDates(root, registry, sink); + CheckNoRelativeDates(root, root, registry, sink); return sink.Errors.AsReadOnly(); } @@ -762,42 +762,40 @@ void Err(string message) => continue; } var relative = RelativeOperand(operand); - if (relative is null) continue; - if (!IsExactRelativeValue(relative)) - { - Err($"@filter on '{key}' has a malformed relative date {JsonStringify(relative)}; a relative date is " + - "{ now: \"\" } with an optional startOf, and no other keys."); - continue; - } - if (!ReportingTemporalFieldSubtypes.Contains(field.SubType)) - { - Err($"@filter on '{key}' uses a relative date ({{ now: ... }}), but '{key}' is field.{field.SubType}; " + - "relative dates apply only to field.date and field.timestamp."); - continue; - } - if (!ReportingRelativeDateOps.Contains(op)) - { - Err($"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " + - "gt, gte, lt and lte."); - continue; - } - var duration = relative[FILTER_RELATIVE_NOW]; - if (duration is not string d || !ISO_DURATION_RE.IsMatch(d)) - { - Err($"@filter on '{key}' has relative date '{QuoteValue(duration)}', which is not an ISO-8601 " + - "duration (e.g. '-P7D', '-PT12H')."); - continue; - } - if (relative.TryGetValue(FILTER_RELATIVE_START_OF, out var startOf) - && (startOf is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit))) - { - Err($"@filter on '{key}' has startOf '{QuoteValue(startOf)}'; startOf is one of " + - $"{string.Join(", ", RELATIVE_START_OF_UNITS)}."); - } + var problem = relative is null ? null : RelativeDateProblem(key, op, relative, field.SubType); + if (problem is not null) Err(problem); } } } + /// + /// F2 — why a relative-date operand under on is + /// refused, or null when it is well-formed: its exact shape, the field's type (when the key + /// resolves), a range op, an ISO-8601 duration and a startOf unit, in that order. + /// + private static string? RelativeDateProblem( + string key, string op, IReadOnlyDictionary relative, string? subType) + { + if (!IsExactRelativeValue(relative)) + return $"@filter on '{key}' has a malformed relative date {JsonStringify(relative)}; a relative date is " + + "{ now: \"\" } with an optional startOf, and no other keys."; + if (subType is not null && !ReportingTemporalFieldSubtypes.Contains(subType)) + return $"@filter on '{key}' uses a relative date ({{ now: ... }}), but '{key}' is field.{subType}; " + + "relative dates apply only to field.date and field.timestamp."; + if (!ReportingRelativeDateOps.Contains(op)) + return $"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " + + "gt, gte, lt and lte."; + var duration = relative[FILTER_RELATIVE_NOW]; + if (duration is not string d || !ISO_DURATION_RE.IsMatch(d)) + return $"@filter on '{key}' has relative date '{QuoteValue(duration)}', which is not an ISO-8601 " + + "duration (e.g. '-P7D', '-PT12H')."; + if (relative.TryGetValue(FILTER_RELATIVE_START_OF, out var startOf) + && (startOf is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit))) + return $"@filter on '{key}' has startOf '{QuoteValue(startOf)}'; startOf is one of " + + $"{string.Join(", ", RELATIVE_START_OF_UNITS)}."; + return null; + } + // ------------------------------------------------------------------------- // R1–R7 — object.report // ------------------------------------------------------------------------- @@ -1066,35 +1064,27 @@ private static bool IsRelativeViewFilterHost(MetaData node) => (node.Type == TYPE_OBJECT && node.SubType == OBJECT_SUBTYPE_PROJECTION) || (node.Type == TYPE_ORIGIN && (node.SubType == ORIGIN_SUBTYPE_FIRST || node.SubType == ORIGIN_SUBTYPE_AGGREGATE)); - /// F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every - /// relative operand of a filter, without its field-type rule. - private static void CheckRelativeShapes(object? filter, MetaData host, ReportingErrorSink sink) + /// F2 on every relative operand of a projection's or an origin's filter; + /// resolves a key to its field's subtype, null when it does not + /// resolve (reported elsewhere). + private static void CheckRelativeShapes( + object? filter, MetaData host, Func subTypeOf, ReportingErrorSink sink) { if (filter is not IReadOnlyDictionary f) return; - void Err(string message) => sink.Push(host, ErrorCode.ERR_BAD_ATTR_FILTER, ReportingNodeLabel(host), $": {message}"); foreach (var (key, clause) in f) { if (key == FILTER_COMPOSE_OR || key == FILTER_COMPOSE_AND) { - if (clause is IReadOnlyList subs) foreach (var sub in subs) CheckRelativeShapes(sub, host, sink); + if (clause is IReadOnlyList subs) foreach (var sub in subs) CheckRelativeShapes(sub, host, subTypeOf, sink); continue; } if (clause is not IReadOnlyDictionary ops) continue; foreach (var (op, operand) in ops) { var relative = RelativeOperand(operand); - if (relative is null) continue; - var duration = relative.TryGetValue(FILTER_RELATIVE_NOW, out var dv) ? dv : null; - if (!IsExactRelativeValue(relative)) - Err($"@filter on '{key}' has a malformed relative date {JsonStringify(relative)}; a relative date is " + - "{ now: \"\" } with an optional startOf, and no other keys."); - else if (!ReportingRelativeDateOps.Contains(op)) - Err($"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under gt, gte, lt and lte."); - else if (duration is not string d || !ISO_DURATION_RE.IsMatch(d)) - Err($"@filter on '{key}' has relative date '{QuoteValue(duration)}', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."); - else if (relative.TryGetValue(FILTER_RELATIVE_START_OF, out var startOf) - && (startOf is not string unit || !RELATIVE_START_OF_UNITS.Contains(unit))) - Err($"@filter on '{key}' has startOf '{QuoteValue(startOf)}'; startOf is one of {string.Join(", ", RELATIVE_START_OF_UNITS)}."); + var problem = relative is null ? null : RelativeDateProblem(key, op, relative, subTypeOf(key)); + if (problem is not null) + sink.Push(host, ErrorCode.ERR_BAD_ATTR_FILTER, ReportingNodeLabel(host), $": {problem}"); } } } @@ -1107,20 +1097,22 @@ private static bool IsReportingFilterHost(MetaData node) => /// /// F1 — walk the whole tree and refuse a { now: ... } value in any attr.filter - /// outside a reporting host (a projection @filter, a dataGrid preset, an - /// origin.aggregate/first @filter): those hosts have no lowering for it. + /// outside a host that lowers it (a dataGrid preset, for one), and check every relative value + /// in a projection's or an origin.aggregate/first's @filter, which lower it into the view. /// - private static void CheckNoRelativeDates(MetaData node, TypeRegistry registry, ReportingErrorSink sink) + private static void CheckNoRelativeDates(MetaData root, MetaData node, TypeRegistry registry, ReportingErrorSink sink) { if (IsRelativeViewFilterHost(node)) { - // `now`: a projection's and an origin's @filter lower relative dates into the view. - // Their keys resolve elsewhere, so the value's own shape is checked here. + // `now`: a projection's and an origin's @filter lower relative dates into the view. A + // projection's keys name its own fields; an origin's name fields of the related entity. + var target = node.Type == TYPE_ORIGIN ? OriginFilterEntity(node, root) : node; + string? SubTypeOf(string key) => target is null ? null : ReportingFieldOf(target, key)?.SubType; foreach (var (attrName, value) in node.OwnAttrs()) { bool isFilterAttr = registry.FindAttrSchema(node.Type, node.SubType, attrName)?.ValueType == ATTR_SUBTYPE_FILTER; - if (isFilterAttr) CheckRelativeShapes(value, node, sink); + if (isFilterAttr) CheckRelativeShapes(value, node, SubTypeOf, sink); } } else if (!IsReportingFilterHost(node)) @@ -1144,6 +1136,6 @@ private static void CheckNoRelativeDates(MetaData node, TypeRegistry registry, R } } // ADR-0039: own — a tree walk; each declared node is visited once, at its declaration. - foreach (var child in node.OwnChildren()) CheckNoRelativeDates(child, registry, sink); + foreach (var child in node.OwnChildren()) CheckNoRelativeDates(root, child, registry, sink); } } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index ae82474575..988ceda948 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1146,6 +1146,21 @@ private static bool IsReferenceHop(MetaData hop) /// entity they terminate at. Returned as a pair (rather than re-walking for the terminal) /// because a second walk means a second copy of the ADR-0042 package-resolution rule — /// mirrors the TS WalkedViaPath. + /// + /// The entity an origin.aggregate's or origin.first's @filter keys name: the @of + /// entity, else the @via terminal. Null when neither resolves (ValidateOriginPaths reports why). + /// + private static MetaData? OriginFilterEntity(MetaData origin, MetaData root) + { + if (origin.Parent is not { } field || field.Parent is not { } projection) return null; + // ADR-0039: own — origin.* never inherits (ADR-0029). + if (origin.OwnAttr(ORIGIN_AGGREGATE_ATTR_OF) is string of && of != "") + return ValidateFromPath(of, root, projection, field.Name, [], "", origin.Source)?.Entity; + return origin.OwnAttr(ORIGIN_AGGREGATE_ATTR_VIA) is string via && via != "" + ? ValidateViaPath(via, root, projection, field.Name, [], origin.Source)?.Terminal + : null; + } + private readonly record struct WalkedViaPath(List Hops, MetaData Terminal, IReadOnlySet Reverse); private static WalkedViaPath? ValidateViaPath( diff --git a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java index eaf465a138..ed82dd0b89 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java +++ b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java @@ -7,8 +7,13 @@ import com.google.gson.JsonSyntaxException; import com.metaobjects.DataTypes; import com.metaobjects.field.BooleanField; +import com.metaobjects.field.CurrencyField; +import com.metaobjects.field.DateField; +import com.metaobjects.field.DecimalField; import com.metaobjects.field.DoubleField; +import com.metaobjects.field.FloatField; import com.metaobjects.field.IntegerField; +import com.metaobjects.field.LongField; import com.metaobjects.field.StringField; import com.metaobjects.field.TimestampField; import com.metaobjects.reporting.ReportingConstants; @@ -254,6 +259,23 @@ private static Set orderedSet(String... names) { FilterOps.FILTER_OP_IS_NULL, EXPR_OP_IS_NOT_NULL); private static final Set VARIADIC_LOGIC_OPS = orderedSet(COMPOSE_AND, COMPOSE_OR); + /** Each node kind (keyed by the key that names it) and the only keys it may carry. */ + private static final Map> NODE_KEYS = nodeKeys(); + private static final Set NUMERIC_SUBTYPES = orderedSet( + IntegerField.SUBTYPE_INT, LongField.SUBTYPE_LONG, DoubleField.SUBTYPE_DOUBLE, FloatField.SUBTYPE_FLOAT, + DecimalField.SUBTYPE_DECIMAL, CurrencyField.SUBTYPE_CURRENCY); + + private static Map> nodeKeys() { + Map> m = new LinkedHashMap<>(); + m.put("field", List.of("field")); + m.put("value", List.of("value")); + m.put(EXPR_NOW, List.of(EXPR_NOW, EXPR_NOW_START_OF)); + m.put(EXPR_CASE, List.of(EXPR_CASE, EXPR_CASE_ELSE, EXPR_CASE_OPERAND)); + m.put("fn", List.of("fn", "args")); + m.put("op", List.of("op", "left", "right", "arg", "args")); + return java.util.Collections.unmodifiableMap(m); + } + /** * Structural well-formedness of an expression tree (known node kinds, ops, * arity). Returns an empty list when valid; each entry is a human-readable @@ -268,6 +290,17 @@ public static List validateExprNode(Object node) { } @SuppressWarnings("unchecked") Map n = (Map) node; + for (Map.Entry> kind : NODE_KEYS.entrySet()) { + if (!n.containsKey(kind.getKey())) continue; + List extra = new ArrayList<>(); + for (String k : n.keySet()) if (!kind.getValue().contains(k)) extra.add(k); + if (!extra.isEmpty()) { + out.add("expression '" + kind.getKey() + "' node takes only " + String.join(", ", kind.getValue()) + + ", not " + String.join(", ", extra)); + return out; + } + break; + } if (n.containsKey("field")) { Object f = n.get("field"); if (!(f instanceof String) || ((String) f).isEmpty()) { @@ -288,12 +321,7 @@ public static List validateExprNode(Object node) { out.add("expression '" + EXPR_NOW + "' must be an ISO-8601 duration string (e.g. '-P7D'), got " + duration); return out; } - List extra = new ArrayList<>(); - for (String k : n.keySet()) if (!EXPR_NOW.equals(k) && !EXPR_NOW_START_OF.equals(k)) extra.add(k); - if (!extra.isEmpty()) { - out.add("expression '" + EXPR_NOW + "' takes only '" + EXPR_NOW_START_OF + "' beside it, not " - + String.join(", ", extra)); - } else if (n.containsKey(EXPR_NOW_START_OF) + if (n.containsKey(EXPR_NOW_START_OF) && !ReportingConstants.RELATIVE_START_OF_UNITS.contains(n.get(EXPR_NOW_START_OF))) { out.add("expression '" + EXPR_NOW_START_OF + "' must be one of " + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + ", got " + n.get(EXPR_NOW_START_OF)); @@ -309,7 +337,7 @@ public static List validateExprNode(Object node) { } for (Object arm : (List) arms) { if (!(arm instanceof Map) || !((Map) arm).containsKey(EXPR_CASE_WHEN) - || !((Map) arm).containsKey(EXPR_CASE_THEN)) { + || !((Map) arm).containsKey(EXPR_CASE_THEN) || ((Map) arm).size() != 2) { out.add("every '" + EXPR_CASE + "' arm must be { " + EXPR_CASE_WHEN + ", " + EXPR_CASE_THEN + " }"); continue; } @@ -427,6 +455,7 @@ public static InferResult inferExprType(Object node, Function re ? inferExprType(n.get(EXPR_CASE_OPERAND), resolveField) : null; if (operand != null) errors.addAll(operand.errors); List results = new ArrayList<>(); + List resultNodes = new ArrayList<>(); for (Object armObj : (List) n.get(EXPR_CASE)) { Map arm = (Map) armObj; InferResult w = inferExprType(arm.get(EXPR_CASE_WHEN), resolveField); @@ -441,37 +470,35 @@ public static InferResult inferExprType(Object node, Function re } InferResult t = inferExprType(arm.get(EXPR_CASE_THEN), resolveField); errors.addAll(t.errors); - if (t.type != null) results.add(t.type); + results.add(t.type); + resultNodes.add(arm.get(EXPR_CASE_THEN)); } if (n.containsKey(EXPR_CASE_ELSE)) { InferResult e = inferExprType(n.get(EXPR_CASE_ELSE), resolveField); errors.addAll(e.errors); - if (e.type != null) results.add(e.type); + results.add(e.type); + resultNodes.add(n.get(EXPR_CASE_ELSE)); } - String unified = results.isEmpty() ? null : results.get(0); - if (unified != null && results.stream().anyMatch(t -> !unified.equals(t))) { - errors.add("'" + EXPR_CASE + "' results have differing types (" - + String.join(", ", new LinkedHashSet<>(results)) + ")"); + List differing = new ArrayList<>(); + String unified = unifyTypes(resultNodes, results, differing); + if (!differing.isEmpty()) { + errors.add("'" + EXPR_CASE + "' results have differing types (" + String.join(", ", differing) + ")"); } return new InferResult(unified, errors); } if (n.containsKey("fn")) { // coalesce List errors = new ArrayList<>(); List argTypes = new ArrayList<>(); - for (Object a : (List) n.get("args")) { + List args = new ArrayList<>((List) n.get("args")); + for (Object a : args) { InferResult r = inferExprType(a, resolveField); errors.addAll(r.errors); - if (r.type != null) argTypes.add(r.type); + argTypes.add(r.type); } - String unified = argTypes.isEmpty() ? null : argTypes.get(0); - if (unified != null) { - boolean differ = false; - for (String t : argTypes) if (!unified.equals(t)) { differ = true; break; } - if (differ) { - Set distinct = new LinkedHashSet<>(argTypes); - errors.add("'" + EXPR_FN_COALESCE + "' arguments have differing types (" - + String.join(", ", distinct) + ")"); - } + List differing = new ArrayList<>(); + String unified = unifyTypes(args, argTypes, differing); + if (!differing.isEmpty()) { + errors.add("'" + EXPR_FN_COALESCE + "' arguments have differing types (" + String.join(", ", differing) + ")"); } return new InferResult(unified, errors); } @@ -508,6 +535,43 @@ public static InferResult inferExprType(Object node, Function re return new InferResult(null, List.of("unknown expression op '" + op + "'")); } + /** A numeric literal or a {@code now} node: it takes the type of the result it sits beside. */ + private static boolean isAdaptable(Object node) { + Map n = (Map) node; + return (n.containsKey("value") && n.get("value") instanceof Number) || n.containsKey(EXPR_NOW); + } + + /** Whether an adaptable node takes {@code to}: a number takes any numeric type, {@code now} a date or timestamp. */ + private static boolean adaptsTo(Object node, String to) { + return ((Map) node).containsKey(EXPR_NOW) + ? DateField.SUBTYPE_DATE.equals(to) || TimestampField.SUBTYPE_TIMESTAMP.equals(to) + : NUMERIC_SUBTYPES.contains(to); + } + + /** The one type of a case's results or a coalesce's args; fills {@code differing} with every + * type when they do not unify. */ + private static String unifyTypes(List nodes, List types, List differing) { + String anchor = null; + String first = null; + for (int i = 0; i < nodes.size(); i++) { + String t = types.get(i); + if (t == null) continue; + if (first == null) first = t; + if (anchor == null && !isAdaptable(nodes.get(i))) anchor = t; + } + String unified = anchor != null ? anchor : first; + Set all = new LinkedHashSet<>(); + boolean fits = true; + for (int i = 0; i < nodes.size(); i++) { + String t = types.get(i); + if (t == null) continue; + all.add(t); + if (!t.equals(unified) && !(anchor != null && isAdaptable(nodes.get(i)) && adaptsTo(nodes.get(i), anchor))) fits = false; + } + if (!fits) differing.addAll(all); + return unified; + } + /** Coarse runtime shape label for a malformed top-level node (parity with the * TS {@code null}/{@code array}/{@code typeof} message forms). */ private static String runtimeShape(Object v) { diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java index 543a2d1c03..b9997fc75f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java @@ -163,7 +163,7 @@ static List validate(MetaRoot root) { } // F1 on every host that is not a reporting host. - checkNoRelativeDates(root, sink); + checkNoRelativeDates(root, root, sink); // Java-only: closed-set membership the TS registry enforces generically. checkClosedSets(root, sink); @@ -862,43 +862,44 @@ private static void checkFilter(Map filter, MetaData entity, String entity continue; } Map relative = relativeOperand(opEntry.getValue()); - if (relative == null) continue; - if (!ReportingConstants.isWellFormedRelativeKeys(relative.keySet())) { - err.accept("@filter on '" + key + "' has a malformed relative date " + GSON.toJson(relative) - + "; a relative date is { now: \"\" } with an optional startOf, and no other keys."); - continue; - } - if (!TEMPORAL_FIELD_SUBTYPES.contains(field.getSubType())) { - err.accept("@filter on '" + key + "' uses a relative date ({ now: ... }), but '" + key - + "' is field." + field.getSubType() - + "; relative dates apply only to field.date and field.timestamp."); - continue; - } - if (!RELATIVE_DATE_OPS.contains(op)) { - err.accept("@filter on '" + key + "' puts a relative date under op '" + op - + "'; relative dates are legal only under gt, gte, lt and lte."); - continue; - } - Object duration = relative.get(ReportingConstants.FILTER_RELATIVE_NOW); - if (!(duration instanceof String) - || !ReportingConstants.ISO_DURATION_RE.matcher((String) duration).matches()) { - err.accept("@filter on '" + key + "' has relative date '" + quoteValue(duration) - + "', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."); - continue; - } - if (relative.containsKey(ReportingConstants.FILTER_RELATIVE_START_OF)) { - Object startOf = relative.get(ReportingConstants.FILTER_RELATIVE_START_OF); - if (!(startOf instanceof String) - || !ReportingConstants.RELATIVE_START_OF_UNITS.contains(startOf)) { - err.accept("@filter on '" + key + "' has startOf '" + quoteValue(startOf) - + "'; startOf is one of " - + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + "."); - } - } + String problem = relative == null ? null : relativeDateProblem(key, op, relative, field.getSubType()); + if (problem != null) err.accept(problem); } } } + /** + * F2 — why a relative-date operand under {@code op} on {@code key} is refused, or null when + * it is well-formed: its exact shape, the field's type (when the key resolves), a range op, + * an ISO-8601 duration and a startOf unit, in that order. One mistake, one message. + */ + private static String relativeDateProblem(String key, String op, Map relative, String subType) { + if (!ReportingConstants.isWellFormedRelativeKeys(relative.keySet())) { + return "@filter on '" + key + "' has a malformed relative date " + GSON.toJson(relative) + + "; a relative date is { now: \"\" } with an optional startOf, and no other keys."; + } + if (subType != null && !TEMPORAL_FIELD_SUBTYPES.contains(subType)) { + return "@filter on '" + key + "' uses a relative date ({ now: ... }), but '" + key + + "' is field." + subType + "; relative dates apply only to field.date and field.timestamp."; + } + if (!RELATIVE_DATE_OPS.contains(op)) { + return "@filter on '" + key + "' puts a relative date under op '" + op + + "'; relative dates are legal only under gt, gte, lt and lte."; + } + Object duration = relative.get(ReportingConstants.FILTER_RELATIVE_NOW); + if (!(duration instanceof String) || !ReportingConstants.ISO_DURATION_RE.matcher((String) duration).matches()) { + return "@filter on '" + key + "' has relative date '" + quoteValue(duration) + + "', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."; + } + Object startOf = relative.get(ReportingConstants.FILTER_RELATIVE_START_OF); + if (relative.containsKey(ReportingConstants.FILTER_RELATIVE_START_OF) + && (!(startOf instanceof String) || !ReportingConstants.RELATIVE_START_OF_UNITS.contains(startOf))) { + return "@filter on '" + key + "' has startOf '" + quoteValue(startOf) + + "'; startOf is one of " + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + "."; + } + return null; + } + // --------------------------------------------------------------------------- // R1–R7 — object.report // --------------------------------------------------------------------------- @@ -1157,41 +1158,24 @@ private static boolean isRelativeViewFilterHost(MetaData node) { || com.metaobjects.origin.AggregateOrigin.SUBTYPE_AGGREGATE.equals(node.getSubType()))); } - /** F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every - * relative operand of a filter, without its field-type rule. */ - private static void checkRelativeShapes(Object filter, MetaData host, ErrorSink sink) { + /** F2 on every relative operand of a projection's or an origin's filter; {@code subTypeOf} + * resolves a key to its field's subtype, null when it does not resolve (reported elsewhere). */ + private static void checkRelativeShapes(Object filter, MetaData host, + java.util.function.Function subTypeOf, ErrorSink sink) { if (!(filter instanceof Map)) return; for (Map.Entry entry : ((Map) filter).entrySet()) { String key = String.valueOf(entry.getKey()); Object clause = entry.getValue(); - if ("and".equals(key) || "or".equals(key)) { - if (clause instanceof List) for (Object sub : (List) clause) checkRelativeShapes(sub, host, sink); + if (FILTER_COMPOSE_AND.equals(key) || FILTER_COMPOSE_OR.equals(key)) { + if (clause instanceof List) for (Object sub : (List) clause) checkRelativeShapes(sub, host, subTypeOf, sink); continue; } if (!(clause instanceof Map)) continue; for (Map.Entry opEntry : ((Map) clause).entrySet()) { - String op = String.valueOf(opEntry.getKey()); Map relative = relativeOperand(opEntry.getValue()); - if (relative == null) continue; - Object duration = relative.get(ReportingConstants.FILTER_RELATIVE_NOW); - Object startOf = relative.get(ReportingConstants.FILTER_RELATIVE_START_OF); - String message = null; - if (!ReportingConstants.isWellFormedRelativeKeys(relative.keySet())) { - message = "@filter on '" + key + "' has a malformed relative date " + GSON.toJson(relative) - + "; a relative date is { now: \"\" } with an optional startOf, and no other keys."; - } else if (!RELATIVE_DATE_OPS.contains(op)) { - message = "@filter on '" + key + "' puts a relative date under op '" + op - + "'; relative dates are legal only under gt, gte, lt and lte."; - } else if (!(duration instanceof String) - || !ReportingConstants.ISO_DURATION_RE.matcher((String) duration).matches()) { - message = "@filter on '" + key + "' has relative date '" + quoteValue(duration) - + "', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H')."; - } else if (relative.containsKey(ReportingConstants.FILTER_RELATIVE_START_OF) - && (!(startOf instanceof String) || !ReportingConstants.RELATIVE_START_OF_UNITS.contains(startOf))) { - message = "@filter on '" + key + "' has startOf '" + quoteValue(startOf) - + "'; startOf is one of " + String.join(", ", ReportingConstants.RELATIVE_START_OF_UNITS) + "."; - } - if (message != null) sink.push(host, ErrorCode.ERR_BAD_ATTR_FILTER, nodeLabel(host), ": " + message); + String problem = relative == null ? null + : relativeDateProblem(key, String.valueOf(opEntry.getKey()), relative, subTypeOf.apply(key)); + if (problem != null) sink.push(host, ErrorCode.ERR_BAD_ATTR_FILTER, nodeLabel(host), ": " + problem); } } } @@ -1206,20 +1190,25 @@ private static boolean isReportingFilterHost(MetaData node) { /** * F1 — walk the whole tree and refuse a {@code { now: ... }} value in any attr.filter - * outside a reporting host (a projection {@code @filter}, a dataGrid preset, an - * origin.aggregate/first {@code @filter}): those hosts have no lowering for it. + * outside a host that lowers it (a dataGrid preset, for one), and check every relative value + * in a projection's or an origin.aggregate/first's {@code @filter}, which lower it into the view. */ - private static void checkNoRelativeDates(MetaData node, ErrorSink sink) { + private static void checkNoRelativeDates(MetaRoot root, MetaData node, ErrorSink sink) { // ADR-0039: own — a tree walk; each declared node (and each locally declared attr) // is visited once, at its declaration (an inherited filter is checked where it is // declared; origin.* never inherits, ADR-0029). Attrs are children in this port. List own = node.getChildren(MetaData.class, false); if (isRelativeViewFilterHost(node)) { - // A projection's and an origin's @filter lower relative dates into the view. Their - // keys resolve elsewhere (projection fields, base paths, the related entity), so the - // value's own shape is checked here and the field's type where it is lowered. + // A projection's and an origin's @filter lower relative dates into the view. A + // projection's keys name its own fields; an origin's name fields of the related entity. + MetaData target = node instanceof com.metaobjects.origin.MetaOrigin + ? ValidationPhase.originFilterEntity((com.metaobjects.origin.MetaOrigin) node, root) : node; + java.util.function.Function subTypeOf = key -> { + MetaData f = target == null ? null : fieldOf(target, key); + return f == null ? null : f.getSubType(); + }; for (MetaData c : own) { - if (c instanceof FilterAttribute) checkRelativeShapes(((MetaAttribute) c).getValue(), node, sink); + if (c instanceof FilterAttribute) checkRelativeShapes(((MetaAttribute) c).getValue(), node, subTypeOf, sink); } } else if (!isReportingFilterHost(node)) { for (MetaData c : own) { @@ -1232,7 +1221,7 @@ && filterContainsRelativeValue(((MetaAttribute) c).getValue())) { } } for (MetaData c : own) { - if (!(c instanceof MetaAttribute)) checkNoRelativeDates(c, sink); + if (!(c instanceof MetaAttribute)) checkNoRelativeDates(root, c, sink); } } 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 a36c3b4e02..29d5500056 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 @@ -4482,6 +4482,26 @@ private static void checkNestedPayloadRefsValueOnly(MetaObject payload, MetaRoot */ /** FR-024 B5/B6 — the resolved target of a {@code @from}/{@code @of} ref: the * named root entity and the resolved field node on it (inherited included). */ + /** + * The entity an origin.aggregate's or origin.first's {@code @filter} keys name: the {@code @of} + * entity, else the {@code @via} terminal. Null when neither resolves (the origin pass reports why). + */ + static MetaObject originFilterEntity(com.metaobjects.origin.MetaOrigin origin, MetaRoot root) { + if (!(origin.getParent() instanceof MetaField) || !(origin.getParent().getParent() instanceof MetaObject)) return null; + MetaObject projection = (MetaObject) origin.getParent().getParent(); + String fieldName = origin.getParent().getName(); + try { + String of = origin.getOf(); + if (of != null && !of.isEmpty()) { + return validateFromOrOfPath(of, root, projection, fieldName, "", origin.getSource()).entity; + } + String via = origin.getVia(); + return via == null || via.isEmpty() ? null : validateViaPath(via, root, projection, fieldName, origin.getSource()).terminal(); + } catch (MetaDataException e) { + return null; + } + } + private static final class OriginTarget { final MetaObject entity; final MetaField field; diff --git a/server/python/src/metaobjects/loader/validate_reporting.py b/server/python/src/metaobjects/loader/validate_reporting.py index aba518559a..a42b82827d 100644 --- a/server/python/src/metaobjects/loader/validate_reporting.py +++ b/server/python/src/metaobjects/loader/validate_reporting.py @@ -213,7 +213,7 @@ def validate_reporting(root: MetaData, errors: list[MetaError]) -> None: _check_report(root, report, sink) # F1 on every host that is not a reporting host. - _check_no_relative_dates(root, sink) + _check_no_relative_dates(root, root, sink) errors.extend(sink.errors) @@ -864,40 +864,40 @@ def err(message: str) -> None: ) continue relative = _relative_operand(operand) - if relative is None: - continue - if not set(relative) <= {FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF}: - err( - f"@filter on '{key}' has a malformed relative date {_js_json(relative)}; a relative date is " - f'{{ now: "" }} with an optional startOf, and no other keys.' - ) - continue - if field.sub_type not in _TEMPORAL_FIELD_SUBTYPES: - err( - f"@filter on '{key}' uses a relative date ({{ now: ... }}), but '{key}' is field.{field.sub_type}; " - f"relative dates apply only to field.date and field.timestamp." - ) - continue - if op not in _RELATIVE_DATE_OPS: - err( - f"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " - f"gt, gte, lt and lte." - ) - continue - duration = relative[FILTER_RELATIVE_NOW] - if not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: - err( - f"@filter on '{key}' has relative date '{_quote_value(duration)}', which is not an ISO-8601 " - f"duration (e.g. '-P7D', '-PT12H')." - ) - continue - if FILTER_RELATIVE_START_OF in relative: - start_of = relative[FILTER_RELATIVE_START_OF] - if not isinstance(start_of, str) or start_of not in RELATIVE_START_OF_UNITS: - err( - f"@filter on '{key}' has startOf '{_quote_value(start_of)}'; startOf is one of " - f"{', '.join(RELATIVE_START_OF_UNITS)}." - ) + problem = None if relative is None else _relative_date_problem(key, op, relative, field.sub_type) + if problem is not None: + err(problem) + + +def _relative_date_problem(key: str, op: str, relative: dict[str, object], sub_type: str | None) -> str | None: + """F2 — why a relative-date operand under ``op`` on ``key`` is refused, or None when it is + well-formed: its exact shape, the field's type (when the key resolves), a range op, an + ISO-8601 duration and a startOf unit, in that order. One mistake, one message.""" + if not set(relative) <= {FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF}: + return ( + f"@filter on '{key}' has a malformed relative date {_js_json(relative)}; a relative date is " + f'{{ now: "" }} with an optional startOf, and no other keys.' + ) + if sub_type is not None and sub_type not in _TEMPORAL_FIELD_SUBTYPES: + return ( + f"@filter on '{key}' uses a relative date ({{ now: ... }}), but '{key}' is field.{sub_type}; " + f"relative dates apply only to field.date and field.timestamp." + ) + if op not in _RELATIVE_DATE_OPS: + return ( + f"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " + f"gt, gte, lt and lte." + ) + duration = relative[FILTER_RELATIVE_NOW] + if not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: + return ( + f"@filter on '{key}' has relative date '{_quote_value(duration)}', which is not an ISO-8601 " + f"duration (e.g. '-P7D', '-PT12H')." + ) + start_of = relative.get(FILTER_RELATIVE_START_OF) + if FILTER_RELATIVE_START_OF in relative and (not isinstance(start_of, str) or start_of not in RELATIVE_START_OF_UNITS): + return f"@filter on '{key}' has startOf '{_quote_value(start_of)}'; startOf is one of {', '.join(RELATIVE_START_OF_UNITS)}." + return None # --------------------------------------------------------------------------- @@ -1180,62 +1180,46 @@ def _is_relative_view_filter_host(node: MetaData) -> bool: ) -def _check_relative_shapes(filter_value: object, host: MetaData, sink: _ErrorSink) -> None: - """F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every relative - operand of a filter, without its field-type rule.""" +def _check_relative_shapes( + filter_value: object, host: MetaData, sub_type_of: Callable[[str], str | None], sink: _ErrorSink +) -> None: + """F2 on every relative operand of a projection's or an origin's filter; ``sub_type_of`` + resolves a key to its field's subtype, None when it does not resolve (reported elsewhere).""" if not isinstance(filter_value, dict): return - - def err(message: str) -> None: - sink.push(host, _ERR_BAD_ATTR_FILTER, _node_label(host), f": {message}") - for key, clause in filter_value.items(): if key in (_FILTER_COMPOSE_AND, _FILTER_COMPOSE_OR): if isinstance(clause, list): for sub in clause: - _check_relative_shapes(sub, host, sink) + _check_relative_shapes(sub, host, sub_type_of, sink) continue if not isinstance(clause, dict): continue for op, operand in clause.items(): relative = _relative_operand(operand) - if relative is None: - continue - duration = relative.get(FILTER_RELATIVE_NOW) - if not set(relative) <= {FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF}: - err( - f"@filter on '{key}' has a malformed relative date {_js_json(relative)}; a relative date is " - f'{{ now: "" }} with an optional startOf, and no other keys.' - ) - elif op not in _RELATIVE_DATE_OPS: - err( - f"@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under " - f"gt, gte, lt and lte." - ) - elif not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: - err( - f"@filter on '{key}' has relative date '{_quote_value(duration)}', which is not an ISO-8601 " - f"duration (e.g. '-P7D', '-PT12H')." - ) - elif FILTER_RELATIVE_START_OF in relative: - start_of = relative[FILTER_RELATIVE_START_OF] - if not isinstance(start_of, str) or start_of not in RELATIVE_START_OF_UNITS: - err( - f"@filter on '{key}' has startOf '{_quote_value(start_of)}'; startOf is one of " - f"{', '.join(RELATIVE_START_OF_UNITS)}." - ) + problem = None if relative is None else _relative_date_problem(key, op, relative, sub_type_of(key)) + if problem is not None: + sink.push(host, _ERR_BAD_ATTR_FILTER, _node_label(host), f": {problem}") -def _check_no_relative_dates(node: MetaData, sink: _ErrorSink) -> None: +def _check_no_relative_dates(root: MetaData, node: MetaData, sink: _ErrorSink) -> None: """F1 — walk the whole tree and refuse a ``{ now: ... }`` value in any attr.filter outside a host that lowers it (a dataGrid preset, for one). A projection's and an - origin.first / origin.aggregate's @filter lower relative dates into the view: their keys - resolve elsewhere, so only the value's own shape is checked here.""" + origin.first / origin.aggregate's @filter lower relative dates into the view: a projection's + keys name its own fields, an origin's name fields of the related entity.""" if _is_relative_view_filter_host(node): + from .validation_passes import origin_filter_entity + + target = origin_filter_entity(node, root) if node.type == TYPE_ORIGIN else node + + def sub_type_of(key: str) -> str | None: + field = _field_of(target, key) if target is not None else None + return field.sub_type if field is not None else None + # ADR-0039: own — only locally declared filters are lowered. for attr in node.own_meta_attrs(): if attr.sub_type == ATTR_SUBTYPE_FILTER: - _check_relative_shapes(getattr(attr, "value", None), node, sink) + _check_relative_shapes(getattr(attr, "value", None), node, sub_type_of, sink) elif not _is_reporting_filter_host(node): # ADR-0039: own — only locally declared filters are lowered, and the walk # visits every declared node exactly once (an inherited filter is checked @@ -1253,7 +1237,7 @@ def _check_no_relative_dates(node: MetaData, sink: _ErrorSink) -> None: ) # ADR-0039: own — a tree walk; each declared node is visited once, at its declaration. for child in node.own_children(): - _check_no_relative_dates(child, sink) + _check_no_relative_dates(root, child, sink) def dimension_via_terminal(root: MetaData, declaring: MetaData, via: str) -> MetaData | None: diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 8201a318a5..6c4a2bb68e 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -1178,6 +1178,20 @@ def ops_for_field(field: MetaData) -> frozenset[str]: _NULL_OPS: frozenset[str] = frozenset({_FILTER_OP_IS_NULL, EXPR_OP_IS_NOT_NULL}) _VARIADIC_LOGIC_OPS: frozenset[str] = frozenset({_FILTER_COMPOSE_AND, _FILTER_COMPOSE_OR}) +# Each node kind (keyed by the key that names it) and the only keys it may carry. +_NODE_KEYS: dict[str, tuple[str, ...]] = { + "field": ("field",), + "value": ("value",), + EXPR_NOW: (EXPR_NOW, EXPR_NOW_START_OF), + EXPR_CASE: (EXPR_CASE, EXPR_CASE_ELSE, EXPR_CASE_OPERAND), + "fn": ("fn", "args"), + "op": ("op", "left", "right", "arg", "args"), +} +_EXPR_NUMERIC_SUBTYPES: frozenset[str] = frozenset({ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +}) + def validate_expr_node(node: object) -> list[str]: """Structural well-formedness of an expression tree (known node kinds, ops, @@ -1190,6 +1204,11 @@ def validate_expr_node(node: object) -> list[str]: else type(node).__name__ ) return [f"expression node must be an object, got {kind}"] + node_kind = next((k for k in _NODE_KEYS if k in node), None) + if node_kind is not None: + extra = [k for k in node if k not in _NODE_KEYS[node_kind]] + if extra: + return [f"expression '{node_kind}' node takes only {', '.join(_NODE_KEYS[node_kind])}, not {', '.join(extra)}"] if "field" in node: f = node["field"] return [] if isinstance(f, str) and len(f) > 0 else ["expression 'field' must be a non-empty string"] @@ -1204,9 +1223,6 @@ def validate_expr_node(node: object) -> list[str]: duration = node[EXPR_NOW] if not isinstance(duration, str) or ISO_DURATION_RE.match(duration) is None: return [f"expression '{EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got {duration!r}"] - extra = [k for k in node if k not in (EXPR_NOW, EXPR_NOW_START_OF)] - if extra: - return [f"expression '{EXPR_NOW}' takes only '{EXPR_NOW_START_OF}' beside it, not {', '.join(extra)}"] start_of = node.get(EXPR_NOW_START_OF) if EXPR_NOW_START_OF in node and not (isinstance(start_of, str) and start_of in RELATIVE_START_OF_UNITS): return [ @@ -1220,7 +1236,7 @@ def validate_expr_node(node: object) -> list[str]: return [f"'{EXPR_CASE}' requires a non-empty array of {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }} arms"] errs: list[str] = [] for arm in arms: - if not isinstance(arm, dict) or EXPR_CASE_WHEN not in arm or EXPR_CASE_THEN not in arm: + if not isinstance(arm, dict) or set(arm) != {EXPR_CASE_WHEN, EXPR_CASE_THEN}: errs.append(f"every '{EXPR_CASE}' arm must be {{ {EXPR_CASE_WHEN}, {EXPR_CASE_THEN} }}") continue errs.extend(validate_expr_node(arm[EXPR_CASE_WHEN])) @@ -1270,6 +1286,33 @@ def _literal_type(v: object) -> str | None: return None # null literal +def _is_adaptable(node: object) -> bool: + """A numeric literal or a ``now`` node: it takes the type of the result it sits beside.""" + assert isinstance(node, dict) + value = node.get("value") + return ("value" in node and isinstance(value, (int, float)) and not isinstance(value, bool)) or EXPR_NOW in node + + +def _adapts_to(node: object, to: str) -> bool: + """Whether an adaptable node takes ``to``: a number takes any numeric type, ``now`` a date or timestamp.""" + assert isinstance(node, dict) + if EXPR_NOW in node: + return to in (FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP) + return to in _EXPR_NUMERIC_SUBTYPES + + +def _unify_types(nodes: list[object], types: list[str | None]) -> tuple[str | None, list[str] | None]: + """The one type of a case's results or a coalesce's args, and every type when they do not unify.""" + typed = [(node, t) for node, t in zip(nodes, types) if t is not None] + anchor = next((t for node, t in typed if not _is_adaptable(node)), None) + unified = anchor if anchor is not None else (typed[0][1] if typed else None) + fits = all( + t == unified or (anchor is not None and _is_adaptable(node) and _adapts_to(node, anchor)) + for node, t in typed + ) + return (unified, None) if fits else (unified, list(dict.fromkeys(t for _, t in typed))) + + class InferResult(NamedTuple): """The inferred field subType of an expression's root (or None if untypable), plus any type/resolution/op-legality errors (empty when it types cleanly).""" @@ -1309,7 +1352,8 @@ def infer_expr_type( operand = infer_expr_type(n[EXPR_CASE_OPERAND], resolve_field) if EXPR_CASE_OPERAND in n else None if operand is not None: errors.extend(operand.errors) - results: list[str] = [] + results: list[str | None] = [] + result_nodes: list[object] = [] for arm in n[EXPR_CASE]: w = infer_expr_type(arm[EXPR_CASE_WHEN], resolve_field) errors.extend(w.errors) @@ -1325,26 +1369,24 @@ def infer_expr_type( ) t = infer_expr_type(arm[EXPR_CASE_THEN], resolve_field) errors.extend(t.errors) - if t.type is not None: - results.append(t.type) + results.append(t.type) + result_nodes.append(arm[EXPR_CASE_THEN]) if EXPR_CASE_ELSE in n: e = infer_expr_type(n[EXPR_CASE_ELSE], resolve_field) errors.extend(e.errors) - if e.type is not None: - results.append(e.type) - unified = results[0] if results else None - if unified is not None and any(t != unified for t in results): - errors.append(f"'{EXPR_CASE}' results have differing types ({', '.join(dict.fromkeys(results))})") + results.append(e.type) + result_nodes.append(n[EXPR_CASE_ELSE]) + unified, differing = _unify_types(result_nodes, results) + if differing is not None: + errors.append(f"'{EXPR_CASE}' results have differing types ({', '.join(differing)})") return InferResult(unified, errors) if "fn" in n: # coalesce arg_results = [infer_expr_type(a, resolve_field) for a in n["args"]] errors = [e for r in arg_results for e in r.errors] - arg_types = [r.type for r in arg_results if r.type is not None] - unified = arg_types[0] if arg_types else None - if unified is not None and any(t != unified for t in arg_types): - distinct = ", ".join(dict.fromkeys(arg_types)) - errors.append(f"'{EXPR_FN_COALESCE}' arguments have differing types ({distinct})") + unified, differing = _unify_types(n["args"], [r.type for r in arg_results]) + if differing is not None: + errors.append(f"'{EXPR_FN_COALESCE}' arguments have differing types ({', '.join(differing)})") return InferResult(unified, errors) op = n["op"] @@ -1717,6 +1759,25 @@ def _validate_entity_field_ref( return (entity, field_node) +def origin_filter_entity(origin: MetaData, root: MetaData) -> MetaData | None: + """The entity an origin.aggregate's or origin.first's ``@filter`` keys name: the ``@of`` + entity, else the ``@via`` terminal. None when neither resolves (the origin pass reports why).""" + field = origin.parent + projection = field.parent if field is not None else None + if field is None or projection is None: + return None + pkg = referrer_package_of(projection) + referrer = f"{projection.fqn()}::{field.name}" + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + of_ref = origin.attr(ORIGIN_ATTR_OF) + if isinstance(of_ref, str) and of_ref: + target = _validate_entity_field_ref(of_ref, ORIGIN_ATTR_OF, "", root, pkg, [], origin, referrer) + return target[0] if target is not None else None + via = origin.attr(ORIGIN_ATTR_VIA) + walked = _validate_via_path(via, "", root, pkg, [], origin, referrer) if isinstance(via, str) and via else None + return walked.terminal if walked is not None else None + + class WalkedViaPath(NamedTuple): """A fully-walked ``@via`` path: the relationship hop nodes in path order, plus the entity they terminate at. Returned as a pair (rather than re-walking diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index 2602cb707a..f2e19e538a 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -23,7 +23,8 @@ import { opsForSubType, type FilterOp, } from "../query/query-constants.js"; import { - FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_TIMESTAMP, + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, } from "../field/field-constants.js"; import { MetaAttr, type ValueError, runtimeTypeName } from "./meta-attr.js"; import { type AttrValue } from "../../shared/meta-data.js"; @@ -55,6 +56,20 @@ const COMPARISON_OPS: ReadonlySet = new Set([ const NULL_OPS: ReadonlySet = new Set([FILTER_OP_IS_NULL, EXPR_OP_IS_NOT_NULL]); const VARIADIC_LOGIC_OPS: ReadonlySet = new Set([FILTER_COMPOSE_AND, FILTER_COMPOSE_OR]); +/** Each node kind (keyed by the key that names it) and the only keys it may carry. */ +const NODE_KEYS: ReadonlyMap = new Map([ + ["field", ["field"]], + ["value", ["value"]], + [EXPR_NOW, [EXPR_NOW, EXPR_NOW_START_OF]], + [EXPR_CASE, [EXPR_CASE, EXPR_CASE_ELSE, EXPR_CASE_OPERAND]], + ["fn", ["fn", "args"]], + ["op", ["op", "left", "right", "arg", "args"]], +]); +const ARM_KEYS: readonly string[] = [EXPR_CASE_WHEN, EXPR_CASE_THEN]; +const NUMERIC_SUBTYPES: ReadonlySet = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); + export type ExprLiteral = string | number | boolean | null; export type ExprNode = | { field: string } @@ -74,6 +89,9 @@ function isObj(v: unknown): v is Record { * Returns [] when valid. No entity/type context — see `inferExprType` for typing. */ export function validateExprNode(node: unknown): string[] { if (!isObj(node)) return [`expression node must be an object, got ${node === null ? "null" : Array.isArray(node) ? "array" : typeof node}`]; + const kind = [...NODE_KEYS.entries()].find(([k]) => k in node); + const extra = kind === undefined ? [] : Object.keys(node).filter((k) => !kind[1].includes(k)); + if (kind !== undefined && extra.length > 0) return [`expression '${kind[0]}' node takes only ${kind[1].join(", ")}, not ${extra.join(", ")}`]; if ("field" in node) { return typeof node.field === "string" && node.field.length > 0 ? [] : ["expression 'field' must be a non-empty string"]; } @@ -87,8 +105,6 @@ export function validateExprNode(node: unknown): string[] { if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { return [`expression '${EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got ${JSON.stringify(duration)}`]; } - const extra = Object.keys(node).filter((k) => k !== EXPR_NOW && k !== EXPR_NOW_START_OF); - if (extra.length > 0) return [`expression '${EXPR_NOW}' takes only '${EXPR_NOW_START_OF}' beside it, not ${extra.join(", ")}`]; const startOf = node[EXPR_NOW_START_OF]; return EXPR_NOW_START_OF in node && !(RELATIVE_START_OF_UNITS as readonly unknown[]).includes(startOf) ? [`expression '${EXPR_NOW_START_OF}' must be one of ${RELATIVE_START_OF_UNITS.join(", ")}, got ${JSON.stringify(startOf)}`] @@ -99,7 +115,7 @@ export function validateExprNode(node: unknown): string[] { if (!Array.isArray(arms) || arms.length === 0) return [`'${EXPR_CASE}' requires a non-empty array of { ${EXPR_CASE_WHEN}, ${EXPR_CASE_THEN} } arms`]; const errs: string[] = []; for (const arm of arms) { - if (!isObj(arm) || !(EXPR_CASE_WHEN in arm) || !(EXPR_CASE_THEN in arm)) { + if (!isObj(arm) || !(EXPR_CASE_WHEN in arm) || !(EXPR_CASE_THEN in arm) || Object.keys(arm).some((k) => !ARM_KEYS.includes(k))) { errs.push(`every '${EXPR_CASE}' arm must be { ${EXPR_CASE_WHEN}, ${EXPR_CASE_THEN} }`); continue; } @@ -142,6 +158,28 @@ function literalType(v: ExprLiteral): string | undefined { return undefined; // null literal } +/** A numeric literal or a `now` node: it takes the type of the result it sits beside. */ +function isAdaptable(node: unknown): boolean { + const n = node as Record; + return ("value" in n && typeof n.value === "number") || EXPR_NOW in n; +} + +/** Whether an adaptable node takes `to`: a number takes any numeric type, `now` a date or timestamp. */ +function adaptsTo(node: unknown, to: string): boolean { + return EXPR_NOW in (node as Record) + ? to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP + : NUMERIC_SUBTYPES.has(to); +} + +/** The one type of a case's results or a coalesce's args, or `differing` when they do not unify. */ +function unifyTypes(nodes: readonly unknown[], types: readonly (string | undefined)[]): { type: string | undefined; differing?: string[] } { + const typed = nodes.flatMap((node, i) => { const type = types[i]; return type === undefined ? [] : [{ node, type }]; }); + const anchor = typed.find((r) => !isAdaptable(r.node)); + const unified = (anchor ?? typed[0])?.type; + const fits = typed.every((r) => r.type === unified || (anchor !== undefined && isAdaptable(r.node) && adaptsTo(r.node, anchor.type))); + return fits ? { type: unified } : { type: unified, differing: [...new Set(typed.map((r) => r.type))] }; +} + export interface InferResult { /** The inferred field subType of the expression's root, or undefined if untypable. */ type: string | undefined; @@ -176,6 +214,7 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField) : undefined; if (operand !== undefined) errors.push(...operand.errors); const results: (string | undefined)[] = []; + const resultNodes: unknown[] = []; for (const arm of arms) { const w = inferExprType(arm.when, resolveField); errors.push(...w.errors); @@ -188,29 +227,29 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st const t = inferExprType(arm.then, resolveField); errors.push(...t.errors); results.push(t.type); + resultNodes.push(arm.then); } if (EXPR_CASE_ELSE in n) { const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField); errors.push(...e.errors); results.push(e.type); + resultNodes.push(n[EXPR_CASE_ELSE]); } - const types = results.filter((t): t is string => t !== undefined); - const unified = types[0]; - if (unified !== undefined && types.some((t) => t !== unified)) { - errors.push(`'${EXPR_CASE}' results have differing types (${[...new Set(types)].join(", ")})`); + const unified = unifyTypes(resultNodes, results); + if (unified.differing !== undefined) { + errors.push(`'${EXPR_CASE}' results have differing types (${unified.differing.join(", ")})`); } - return { type: unified, errors }; + return { type: unified.type, errors }; } if ("fn" in n) { // coalesce const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField)); const errors = argResults.flatMap((a) => a.errors); - const argTypes = argResults.map((a) => a.type).filter((t): t is string => t !== undefined); - const unified = argTypes[0]; - if (unified !== undefined && argTypes.some((t) => t !== unified)) { - errors.push(`'${EXPR_FN_COALESCE}' arguments have differing types (${[...new Set(argTypes)].join(", ")})`); + const unified = unifyTypes(n.args as ExprNode[], argResults.map((a) => a.type)); + if (unified.differing !== undefined) { + errors.push(`'${EXPR_FN_COALESCE}' arguments have differing types (${unified.differing.join(", ")})`); } - return { type: unified, errors }; + return { type: unified.type, errors }; } const op = n.op as string; diff --git a/server/typescript/packages/metadata/src/loader/reporting-validation.ts b/server/typescript/packages/metadata/src/loader/reporting-validation.ts index f6337bb18e..7970ce151b 100644 --- a/server/typescript/packages/metadata/src/loader/reporting-validation.ts +++ b/server/typescript/packages/metadata/src/loader/reporting-validation.ts @@ -79,6 +79,7 @@ import { opsForField, } from "../core/query/query-constants.js"; import { ATTR_SUBTYPE_FILTER } from "../core/attr/attr-constants.js"; +import { originFilterEntity } from "./validation-passes.js"; import { isMetaObject, isMetaRoot, isReadOnlySource, isWritableSource } from "../shared/node-guards.js"; import { SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; import { AGG_ALL, AGG_ANY, ORIGIN_SUBTYPE_FIRST, ORIGIN_SUBTYPE_AGGREGATE } from "../persistence/origin/origin-constants.js"; @@ -165,7 +166,7 @@ export function validateReporting(root: MetaData): ParseError[] { } // F1 on every host that is not a reporting host. - checkNoRelativeDates(root, sink); + checkNoRelativeDates(root, root, sink); return sink.errors; } @@ -812,49 +813,52 @@ function checkFilter( continue; } const relative = relativeOperand(operand); - if (relative === undefined) continue; - if (!isExactRelativeValue(relative)) { - err( - `@filter on '${key}' has a malformed relative date ${JSON.stringify(relative)}; a relative date is ` + - `{ now: "" } with an optional startOf, and no other keys.`, - ); - continue; - } - if (!TEMPORAL_FIELD_SUBTYPES.includes(field.subType)) { - err( - `@filter on '${key}' uses a relative date ({ now: ... }), but '${key}' is field.${field.subType}; ` + - `relative dates apply only to field.date and field.timestamp.`, - ); - continue; - } - if (!RELATIVE_DATE_OPS.includes(op)) { - err( - `@filter on '${key}' puts a relative date under op '${op}'; relative dates are legal only under ` + - `gt, gte, lt and lte.`, - ); - continue; - } - const duration = relative[FILTER_RELATIVE_NOW]; - if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { - err( - `@filter on '${key}' has relative date '${quoteValue(duration)}', which is not an ISO-8601 ` + - `duration (e.g. '-P7D', '-PT12H').`, - ); - continue; - } - if (FILTER_RELATIVE_START_OF in relative) { - const startOf = relative[FILTER_RELATIVE_START_OF]; - if (typeof startOf !== "string" || !(RELATIVE_START_OF_UNITS as readonly string[]).includes(startOf)) { - err( - `@filter on '${key}' has startOf '${quoteValue(startOf)}'; startOf is one of ` + - `${RELATIVE_START_OF_UNITS.join(", ")}.`, - ); - } - } + const problem = relative === undefined ? undefined : relativeDateProblem(key, op, relative, field.subType); + if (problem !== undefined) err(problem); } } } +/** + * F2 — why a relative-date operand under `op` on `key` is refused, or undefined when it is + * well-formed: its exact shape, the field's type (when the key resolves), a range op, an + * ISO-8601 duration and a startOf unit, in that order. One mistake, one message. + */ +function relativeDateProblem( + key: string, + op: string, + relative: Record, + subType: string | undefined, +): string | undefined { + if (!isExactRelativeValue(relative)) { + return ( + `@filter on '${key}' has a malformed relative date ${JSON.stringify(relative)}; a relative date is ` + + `{ now: "" } with an optional startOf, and no other keys.` + ); + } + if (subType !== undefined && !TEMPORAL_FIELD_SUBTYPES.includes(subType)) { + return ( + `@filter on '${key}' uses a relative date ({ now: ... }), but '${key}' is field.${subType}; ` + + `relative dates apply only to field.date and field.timestamp.` + ); + } + if (!RELATIVE_DATE_OPS.includes(op)) { + return `@filter on '${key}' puts a relative date under op '${op}'; relative dates are legal only under gt, gte, lt and lte.`; + } + const duration = relative[FILTER_RELATIVE_NOW]; + if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { + return ( + `@filter on '${key}' has relative date '${quoteValue(duration)}', which is not an ISO-8601 ` + + `duration (e.g. '-P7D', '-PT12H').` + ); + } + const startOf = relative[FILTER_RELATIVE_START_OF]; + if (FILTER_RELATIVE_START_OF in relative && (typeof startOf !== "string" || !(RELATIVE_START_OF_UNITS as readonly string[]).includes(startOf))) { + return `@filter on '${key}' has startOf '${quoteValue(startOf)}'; startOf is one of ${RELATIVE_START_OF_UNITS.join(", ")}.`; + } + return undefined; +} + // --------------------------------------------------------------------------- // R1–R7 — object.report // --------------------------------------------------------------------------- @@ -1123,31 +1127,25 @@ function isRelativeViewFilterHost(node: MetaData): boolean { ); } -/** F2's value rules (exact shape, range op, ISO-8601 duration, startOf unit) on every relative - * operand of a filter, without its field-type rule. */ -function checkRelativeShapes(filter: unknown, host: MetaData, sink: ErrorSink): void { +/** F2 on every relative operand of a projection's or an origin's filter; `subTypeOf` resolves a + * key to its field's subtype, undefined when it does not resolve (reported elsewhere). */ +function checkRelativeShapes( + filter: unknown, + host: MetaData, + subTypeOf: (key: string) => string | undefined, + sink: ErrorSink, +): void { if (!isPlainObject(filter)) return; - const err = (message: string): void => sink.push(host, ERR_BAD_ATTR_FILTER, nodeLabel(host), `: ${message}`); for (const [key, clause] of Object.entries(filter)) { if (key === FILTER_COMPOSE_OR || key === FILTER_COMPOSE_AND) { - if (Array.isArray(clause)) for (const sub of clause) checkRelativeShapes(sub, host, sink); + if (Array.isArray(clause)) for (const sub of clause) checkRelativeShapes(sub, host, subTypeOf, sink); continue; } if (!isPlainObject(clause)) continue; for (const [op, operand] of Object.entries(clause)) { const relative = relativeOperand(operand); - if (relative === undefined) continue; - const duration = relative[FILTER_RELATIVE_NOW]; - const startOf = relative[FILTER_RELATIVE_START_OF]; - if (!isExactRelativeValue(relative)) { - err(`@filter on '${key}' has a malformed relative date ${JSON.stringify(relative)}; a relative date is { now: "" } with an optional startOf, and no other keys.`); - } else if (!RELATIVE_DATE_OPS.includes(op)) { - err(`@filter on '${key}' puts a relative date under op '${op}'; relative dates are legal only under gt, gte, lt and lte.`); - } else if (typeof duration !== "string" || !ISO_DURATION_RE.test(duration)) { - err(`@filter on '${key}' has relative date '${quoteValue(duration)}', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H').`); - } else if (FILTER_RELATIVE_START_OF in relative && (typeof startOf !== "string" || !(RELATIVE_START_OF_UNITS as readonly string[]).includes(startOf))) { - err(`@filter on '${key}' has startOf '${quoteValue(startOf)}'; startOf is one of ${RELATIVE_START_OF_UNITS.join(", ")}.`); - } + const problem = relative === undefined ? undefined : relativeDateProblem(key, op, relative, subTypeOf(key)); + if (problem !== undefined) sink.push(host, ERR_BAD_ATTR_FILTER, nodeLabel(host), `: ${problem}`); } } } @@ -1163,16 +1161,17 @@ function isReportingFilterHost(node: MetaData): boolean { /** * F1 — walk the whole tree and refuse a `{ now: ... }` value in any attr.filter - * outside a reporting host (a projection @filter, a dataGrid preset, an - * origin.aggregate/first @filter): those hosts have no lowering for it. + * outside a host that lowers it (a dataGrid preset, for one), and check every relative value + * in a projection's or an origin.aggregate/first's @filter, which lower it into the view. */ -function checkNoRelativeDates(node: MetaData, sink: ErrorSink): void { +function checkNoRelativeDates(root: MetaData, node: MetaData, sink: ErrorSink): void { if (isRelativeViewFilterHost(node)) { - // `now`: a projection's and an origin's @filter lower relative dates into the view. - // Their keys resolve elsewhere (projection fields, base paths, the related entity), so the - // value's own shape is checked here and the field's type where it is lowered. + // `now`: a projection's and an origin's @filter lower relative dates into the view. A + // projection's keys name its own fields; an origin's name fields of the related entity. + const target = node.type === TYPE_ORIGIN ? originFilterEntity(node, root) : node; + const subTypeOf = (key: string): string | undefined => (target === undefined ? undefined : fieldOf(target, key)?.subType); for (const attr of node.ownMetaAttrs()) { - if (attr.subType === ATTR_SUBTYPE_FILTER) checkRelativeShapes(attr.value, node, sink); + if (attr.subType === ATTR_SUBTYPE_FILTER) checkRelativeShapes(attr.value, node, subTypeOf, sink); } } else if (!isReportingFilterHost(node)) { // ADR-0039: own — only locally declared filters are lowered, and the walk @@ -1191,5 +1190,5 @@ function checkNoRelativeDates(node: MetaData, sink: ErrorSink): void { } } // ADR-0039: own — a tree walk; each declared node is visited once, at its declaration. - for (const child of node.ownChildren()) checkNoRelativeDates(child, sink); + for (const child of node.ownChildren()) checkNoRelativeDates(root, child, sink); } diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 840ddc2dad..738e114741 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -692,6 +692,21 @@ function _validateFromPath( return { entity: sourceObj, field: sourceField }; } +/** + * The entity an origin.aggregate's or origin.first's `@filter` keys name: the `@of` entity, + * else the `@via` terminal. Undefined when neither resolves (validateOriginPaths reports why). + */ +export function originFilterEntity(origin: MetaData, root: MetaData): MetaData | undefined { + const field = origin.parent; + const projection = field?.parent; + if (field === undefined || projection === undefined) return undefined; + // ADR-0039: own — origin.* never inherits (ADR-0029). + const of_ = origin.ownAttr(ORIGIN_AGGREGATE_ATTR_OF); + if (typeof of_ === "string" && of_ !== "") return _validateFromPath(of_, root, projection, field.name, origin.source, [])?.entity; + const via = origin.ownAttr(ORIGIN_AGGREGATE_ATTR_VIA); + return typeof via === "string" && via !== "" ? _validateViaPath(via, root, projection, field.name, origin.source, [])?.terminal : undefined; +} + /** A fully-walked `@via` path: the relationship hop nodes in path order, and * the TERMINAL entity reached after the last hop. Both fall out of one walk, * so they are returned together — recovering the terminal with a second walk From a49a6a32c7538b0481e0d56171304bafbedd6240 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 06:49:21 -0500 Subject: [PATCH 4/7] no-mistakes(review): apply reviewer inline fixes --- .../csharp/MetaObjects/Loader/ValidationPasses.cs | 14 +++++++------- .../com/metaobjects/loader/ValidationPhase.java | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 988ceda948..f5c98fd4eb 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1139,13 +1139,6 @@ private static bool IsReferenceHop(MetaData hop) // Origin helper: _validateViaPath // ------------------------------------------------------------------------- - /// Validate an explicit `@via` "Entity.rel[.rel...]" path. Returns the walked - /// relationship hop nodes (in path order) on full success — FR-024 B5 runs - /// the cardinality checks over them — or null when any error was pushed. - /// A fully-walked @via path: the relationship hop nodes in path order, plus the - /// entity they terminate at. Returned as a pair (rather than re-walking for the terminal) - /// because a second walk means a second copy of the ADR-0042 package-resolution rule — - /// mirrors the TS WalkedViaPath. /// /// The entity an origin.aggregate's or origin.first's @filter keys name: the @of /// entity, else the @via terminal. Null when neither resolves (ValidateOriginPaths reports why). @@ -1161,6 +1154,13 @@ private static bool IsReferenceHop(MetaData hop) : null; } + /// Validate an explicit `@via` "Entity.rel[.rel...]" path. Returns the walked + /// relationship hop nodes (in path order) on full success — FR-024 B5 runs + /// the cardinality checks over them — or null when any error was pushed. + /// A fully-walked @via path: the relationship hop nodes in path order, plus the + /// entity they terminate at. Returned as a pair (rather than re-walking for the terminal) + /// because a second walk means a second copy of the ADR-0042 package-resolution rule — + /// mirrors the TS WalkedViaPath. private readonly record struct WalkedViaPath(List Hops, MetaData Terminal, IReadOnlySet Reverse); private static WalkedViaPath? ValidateViaPath( 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 29d5500056..05fbbb388d 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 @@ -4480,8 +4480,6 @@ private static void checkNestedPayloadRefsValueOnly(MetaObject payload, MetaRoot * * @param projection the projection node that owns the field carrying the origin */ - /** FR-024 B5/B6 — the resolved target of a {@code @from}/{@code @of} ref: the - * named root entity and the resolved field node on it (inherited included). */ /** * The entity an origin.aggregate's or origin.first's {@code @filter} keys name: the {@code @of} * entity, else the {@code @via} terminal. Null when neither resolves (the origin pass reports why). @@ -4502,6 +4500,8 @@ static MetaObject originFilterEntity(com.metaobjects.origin.MetaOrigin origin, M } } + /** FR-024 B5/B6 — the resolved target of a {@code @from}/{@code @of} ref: the + * named root entity and the resolved field node on it (inherited included). */ private static final class OriginTarget { final MetaObject entity; final MetaField field; From cfaf3bc340aa1c923380845431c07440617b1389 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 16:38:06 -0500 Subject: [PATCH 5/7] no-mistakes(review): apply reviewer inline fixes --- server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs | 3 ++- server/csharp/MetaObjects/Loader/ValidationPasses.cs | 1 + .../main/java/com/metaobjects/loader/ReportingValidation.java | 2 +- server/python/src/metaobjects/loader/validate_reporting.py | 2 +- .../packages/metadata/src/loader/reporting-validation.ts | 3 ++- .../packages/metadata/src/loader/validation-passes.ts | 1 + 6 files changed, 8 insertions(+), 4 deletions(-) diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs index 637245e18a..71350ffe87 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs @@ -1108,6 +1108,7 @@ private static void CheckNoRelativeDates(MetaData root, MetaData node, TypeRegis // projection's keys name its own fields; an origin's name fields of the related entity. var target = node.Type == TYPE_ORIGIN ? OriginFilterEntity(node, root) : node; string? SubTypeOf(string key) => target is null ? null : ReportingFieldOf(target, key)?.SubType; + // ADR-0039: own — only locally declared filters are lowered (origin.* never inherits, ADR-0029). foreach (var (attrName, value) in node.OwnAttrs()) { bool isFilterAttr = @@ -1131,7 +1132,7 @@ private static void CheckNoRelativeDates(MetaData root, MetaData node, TypeRegis ErrorCode.ERR_BAD_ATTR_FILTER, ReportingNodeLabel(node), $": @{attrName} uses a relative date ({{ now: ... }}), which is legal only in the " + - "@filter of a segment, measure.aggregate or object.report."); + "@filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first."); } } } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index f5c98fd4eb..57214fa874 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -799,6 +799,7 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.SubType; }; // A sibling computed ref is inlined by the view, so the refs must not lead back here. + // ADR-0039: own — origin.* never inherits (ADR-0029), so @expr is declared on the origin. Func> computedRefs = name => ownOriginOf(name) is { SubType: ORIGIN_SUBTYPE_COMPUTED } o ? ExpressionGrammar.FieldRefs(o.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Where(r => r != name).ToList() : []; diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java index b9997fc75f..88789141f7 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java @@ -1216,7 +1216,7 @@ private static void checkNoRelativeDates(MetaRoot root, MetaData node, ErrorSink && filterContainsRelativeValue(((MetaAttribute) c).getValue())) { sink.push(node, ErrorCode.ERR_BAD_ATTR_FILTER, nodeLabel(node), ": @" + c.getShortName() + " uses a relative date ({ now: ... }), which is legal only in " - + "the @filter of a segment, measure.aggregate or object.report."); + + "the @filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first."); } } } diff --git a/server/python/src/metaobjects/loader/validate_reporting.py b/server/python/src/metaobjects/loader/validate_reporting.py index a42b82827d..6038697431 100644 --- a/server/python/src/metaobjects/loader/validate_reporting.py +++ b/server/python/src/metaobjects/loader/validate_reporting.py @@ -1233,7 +1233,7 @@ def sub_type_of(key: str) -> str | None: _ERR_BAD_ATTR_FILTER, _node_label(node), f": @{attr.name} uses a relative date ({{ now: ... }}), which is legal only in the " - f"@filter of a segment, measure.aggregate or object.report.", + f"@filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first.", ) # ADR-0039: own — a tree walk; each declared node is visited once, at its declaration. for child in node.own_children(): diff --git a/server/typescript/packages/metadata/src/loader/reporting-validation.ts b/server/typescript/packages/metadata/src/loader/reporting-validation.ts index 7970ce151b..0fa6a949c5 100644 --- a/server/typescript/packages/metadata/src/loader/reporting-validation.ts +++ b/server/typescript/packages/metadata/src/loader/reporting-validation.ts @@ -1170,6 +1170,7 @@ function checkNoRelativeDates(root: MetaData, node: MetaData, sink: ErrorSink): // projection's keys name its own fields; an origin's name fields of the related entity. const target = node.type === TYPE_ORIGIN ? originFilterEntity(node, root) : node; const subTypeOf = (key: string): string | undefined => (target === undefined ? undefined : fieldOf(target, key)?.subType); + // ADR-0039: own — only locally declared filters are lowered (origin.* never inherits, ADR-0029). for (const attr of node.ownMetaAttrs()) { if (attr.subType === ATTR_SUBTYPE_FILTER) checkRelativeShapes(attr.value, node, subTypeOf, sink); } @@ -1184,7 +1185,7 @@ function checkNoRelativeDates(root: MetaData, node: MetaData, sink: ErrorSink): ERR_BAD_ATTR_FILTER, nodeLabel(node), `: @${attr.name} uses a relative date ({ now: ... }), which is legal only in the ` + - `@filter of a segment, measure.aggregate or object.report.`, + `@filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first.`, ); } } diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 738e114741..d6e19de579 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1662,6 +1662,7 @@ export function validateOriginPaths(root: MetaData): ParseError[] { // A sibling computed ref is inlined by the view, so the refs must not lead back here. const computedRefs = (name: string): string[] => { const o = ownOriginOf(name); + // ADR-0039: own — origin.* never inherits (ADR-0029), so @expr is declared on the origin. return o?.subType === ORIGIN_SUBTYPE_COMPUTED ? expressionFieldRefs(o.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR)).filter((r) => r !== name) : []; From f657f1f1a367c133e15cee88ad90fe60e955ad89 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 16:40:15 -0500 Subject: [PATCH 6/7] no-mistakes(review): Reject fractional literals beside integer-backed fields --- AGENTS.md | 2 +- docs/CONFORMANCE.md | 6 +- examples/showcase/site-payload.json | 2 +- fixtures/conformance/ERROR-CODES.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.views.json | 137 ++++++++++++++++++ .../providers.json | 1 + .../Core/Attr/ExpressionGrammar.cs | 15 +- .../metaobjects/attr/ExpressionAttribute.java | 10 +- .../metaobjects/loader/validation_passes.py | 7 +- .../src/core/attr/meta-attr-expression.ts | 9 +- 11 files changed, 184 insertions(+), 22 deletions(-) create mode 100644 fixtures/conformance/error-origin-computed-literal-fractional/expected-errors.json create mode 100644 fixtures/conformance/error-origin-computed-literal-fractional/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-computed-literal-fractional/providers.json diff --git a/AGENTS.md b/AGENTS.md index 8b9ef83511..72567644f8 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/` (470 fixtures; 38 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/` (471 fixtures; 38 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index fb4abb5df8..565a911200 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) | 470 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 471 | ✓ | ✓ | 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 | ✓ | — | — | — | ✓ | @@ -354,7 +354,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (470) +### `fixtures/conformance/` — metamodel loader + canonical serializer (471) | Fixture prefix | Feature doc | |---|---| @@ -716,7 +716,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 470 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 471 + yaml 16 + verify 45 + render 18 + persistence 62 + api-contract 123 + source-resolution 25 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the `cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index cba926bcff..cf58472f9d 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 470, + "fixtures": 471, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index c526c39bf5..19b3594d42 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -52,7 +52,7 @@ "ERR_TEMPLATE_NOT_STATIC": "Build-time verify (ADR-0061, Jinja bodies, Python and TypeScript): a template reference the check cannot settle statically — a computed attribute or include name, a dynamic subscript, a call, a tag outside the supported set. Reported rather than passed; path = the expression or tag.", "ERR_TEMPLATE_SYNTAX": "Build-time verify: the template body, or a template it includes or imports, does not parse. Jinja bodies (ADR-0061, Python and TypeScript): path = the parser's message, which is engine-specific. Mustache bodies (every port): an unbalanced section (a close with no open, a close naming another section, a section never closed); path = the section's name.", "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", - "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate or object.report (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", + "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", diff --git a/fixtures/conformance/error-origin-computed-literal-fractional/expected-errors.json b/fixtures/conformance/error-origin-computed-literal-fractional/expected-errors.json new file mode 100644 index 0000000000..412ce723c2 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-literal-fractional/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.long'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-computed-literal-fractional/input/meta.views.json b/fixtures/conformance/error-origin-computed-literal-fractional/input/meta.views.json new file mode 100644 index 0000000000..19b9e3d505 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-literal-fractional/input/meta.views.json @@ -0,0 +1,137 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.entity": { + "name": "Status", + "children": [ + { + "source.rdb": { + "@table": "statuses" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "name" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + }, + { + "object.entity": { + "name": "Case", + "children": [ + { + "source.rdb": { + "@table": "cases" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "statusId" + } + }, + { + "field.int": { + "name": "priorType" + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.int": { + "name": "status" + } + }, + { + "field.date": { + "name": "effectiveFrom" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + }, + { + "identity.reference": { + "name": "statusId", + "@fields": "statusId", + "@references": "acme::views::Status" + } + } + ] + } + }, + { + "object.projection": { + "name": "FracCoalesce", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_frac_coalesce" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Case.id" + } + }, + { + "field.long": { + "name": "x", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "coalesce", + "args": [ + { + "field": "statusId" + }, + { + "value": 1.5 + } + ] + } + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Case.id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-origin-computed-literal-fractional/providers.json b/fixtures/conformance/error-origin-computed-literal-fractional/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-origin-computed-literal-fractional/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index 148764a996..d29e1028f7 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -340,12 +340,15 @@ private static bool IsAdaptable(object? node) => node is IReadOnlyDictionary n && ((n.ContainsKey(KEY_VALUE) && Get(n, KEY_VALUE) is long or int or double) || n.ContainsKey(EXPR_NOW)); - /// Whether an adaptable node takes : a number takes any numeric - /// type, now a date or timestamp. - private static bool AdaptsTo(object? node, string to) => - node is IReadOnlyDictionary n && n.ContainsKey(EXPR_NOW) - ? to == FIELD_SUBTYPE_DATE || to == FIELD_SUBTYPE_TIMESTAMP - : NumericSubtypes.Contains(to); + /// Whether an adaptable node takes : a whole number any numeric + /// type, a fractional number only double, float or decimal, now a date or timestamp. + private static bool AdaptsTo(object? node, string to) + { + var n = (IReadOnlyDictionary)node!; + if (n.ContainsKey(EXPR_NOW)) return to == FIELD_SUBTYPE_DATE || to == FIELD_SUBTYPE_TIMESTAMP; + if (LiteralType(Get(n, KEY_VALUE)) == FIELD_SUBTYPE_INT) return NumericSubtypes.Contains(to); + return to == FIELD_SUBTYPE_DOUBLE || to == FIELD_SUBTYPE_FLOAT || to == FIELD_SUBTYPE_DECIMAL; + } /// The one type of a case's results or a coalesce's args, or every type when they do not unify. private static (string? Type, List? Differing) UnifyTypes(IReadOnlyList nodes, IReadOnlyList types) diff --git a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java index ed82dd0b89..60c858ff28 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java +++ b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java @@ -541,11 +541,13 @@ private static boolean isAdaptable(Object node) { return (n.containsKey("value") && n.get("value") instanceof Number) || n.containsKey(EXPR_NOW); } - /** Whether an adaptable node takes {@code to}: a number takes any numeric type, {@code now} a date or timestamp. */ + /** Whether an adaptable node takes {@code to}: a whole number any numeric type, a fractional number only + * double, float or decimal, {@code now} a date or timestamp. */ private static boolean adaptsTo(Object node, String to) { - return ((Map) node).containsKey(EXPR_NOW) - ? DateField.SUBTYPE_DATE.equals(to) || TimestampField.SUBTYPE_TIMESTAMP.equals(to) - : NUMERIC_SUBTYPES.contains(to); + Map n = (Map) node; + if (n.containsKey(EXPR_NOW)) return DateField.SUBTYPE_DATE.equals(to) || TimestampField.SUBTYPE_TIMESTAMP.equals(to); + if (IntegerField.SUBTYPE_INT.equals(literalType(n.get("value")))) return NUMERIC_SUBTYPES.contains(to); + return DoubleField.SUBTYPE_DOUBLE.equals(to) || FloatField.SUBTYPE_FLOAT.equals(to) || DecimalField.SUBTYPE_DECIMAL.equals(to); } /** The one type of a case's results or a coalesce's args; fills {@code differing} with every diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 6c4a2bb68e..8ff9af3e8e 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -1294,11 +1294,14 @@ def _is_adaptable(node: object) -> bool: def _adapts_to(node: object, to: str) -> bool: - """Whether an adaptable node takes ``to``: a number takes any numeric type, ``now`` a date or timestamp.""" + """Whether an adaptable node takes ``to``: a whole number any numeric type, a fractional number only + double, float or decimal, ``now`` a date or timestamp.""" assert isinstance(node, dict) if EXPR_NOW in node: return to in (FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP) - return to in _EXPR_NUMERIC_SUBTYPES + if _literal_type(node["value"]) == FIELD_SUBTYPE_INT: + return to in _EXPR_NUMERIC_SUBTYPES + return to in (FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL) def _unify_types(nodes: list[object], types: list[str | None]) -> tuple[str | None, list[str] | None]: diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index f2e19e538a..9f04e4a97c 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -164,11 +164,12 @@ function isAdaptable(node: unknown): boolean { return ("value" in n && typeof n.value === "number") || EXPR_NOW in n; } -/** Whether an adaptable node takes `to`: a number takes any numeric type, `now` a date or timestamp. */ +/** Whether an adaptable node takes `to`: a whole number any numeric type, a fractional number only double, float or decimal, `now` a date or timestamp. */ function adaptsTo(node: unknown, to: string): boolean { - return EXPR_NOW in (node as Record) - ? to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP - : NUMERIC_SUBTYPES.has(to); + const n = node as Record; + if (EXPR_NOW in n) return to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP; + if (literalType(n.value as ExprLiteral) === FIELD_SUBTYPE_INT) return NUMERIC_SUBTYPES.has(to); + return to === FIELD_SUBTYPE_DOUBLE || to === FIELD_SUBTYPE_FLOAT || to === FIELD_SUBTYPE_DECIMAL; } /** The one type of a case's results or a coalesce's args, or `differing` when they do not unify. */ From 57bfba75232163be4910fb7c174cd775eb283f39 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 12 Nov 2026 17:26:41 -0500 Subject: [PATCH 7/7] no-mistakes(document): Fixed stale expression-grammar docs: error-code entry and @condition refusal note. --- docs/features/migrations-and-drift.md | 1 + fixtures/conformance/ERROR-CODES.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 3d414db849..540b7ecfe8 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -430,6 +430,7 @@ attributes shape it, all database-only (no generated code reads them): it out. - **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, `exactlyOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. + It refuses `case` and `now` (`ERR_BAD_ATTR_VALUE`): a database CHECK can hold neither. The rule holds only where the condition does: the CHECK is `(NOT condition) OR (rule)`, with the negation folded in (`kind = 'Owned'` becomes `kind <> 'Owned'`). It is checked at load (`ERR_BAD_ATTR_VALUE`): every field it names is a field of the entity, it is a boolean diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 19b3594d42..60e4bd240c 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -96,7 +96,7 @@ "ERR_INVALID_REPORT": "FR-044: an object.report is invalid: @from does not resolve to an object.entity (R1); a @dimensions item names no dimension of @from, omits the grain of a time dimension, uses a grain the dimension does not declare, gives a grain to an attribute dimension, or repeats (R2); a @measures item resolves to no measure at all (R3); the report declares a field.* or identity.* child (R4) or a writable source (R5); two items derive the same report field name (R6); or @segment names no segment of @from (R7).", "ERR_REPORT_FOREIGN_MEASURE": "FR-044: an object.report lists a measure (bare or dotted) that belongs to an entity other than @from (R3). All measures of a report come from @from; combining two fact tables is a second report.", "ERR_COMPUTED_TYPE_MISMATCH": "#195: an origin.computed @expr tree's inferred root type does not equal the carrying field's declared field.. A computed column's type is DERIVED from its expression, never asserted (no @convert escape), so a mismatch is a hard load error (sibling of ERR_PASSTHROUGH_TYPE_MISMATCH).", - "ERR_UNKNOWN_EXPR_NODE": "#195: an origin.computed @expr tree contains a node whose kind/op/fn is not in the closed expression grammar (field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce). Fail-closed per ADR-0023; the detail names the offending token.", + "ERR_UNKNOWN_EXPR_NODE": "#195: an origin.computed @expr tree contains a node whose kind/op/fn is not in the closed expression grammar (field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now), or a node carries a key its kind does not take (a misspelled `else`, or a `field` node that also carries `case`). Fail-closed per ADR-0023; the detail names the offending token.", "ERR_SQL_BODY_WITH_UNMANAGED": "#208: a source.rdb declares both @sql (author-supplied body) and @unmanaged (DDL owned elsewhere). The two markers are the mutually exclusive non-default states of one DDL-ownership axis — contradictory on a single source.", "ERR_SQL_BODY_ON_WRITABLE_KIND": "#208: a source.rdb declares @sql with a writable @kind (\"table\", the default). A hand-written CREATE TABLE would bypass the column-diff machinery; tables are fully modeled or @unmanaged, never opaque-bodied.", "ERR_ORIGIN_UNDER_SQL_BODY": "#208: a host object whose read source carries @sql also declares an origin.*-bearing (derived) field, or (on object.projection) an @filter (#207) — two sources of truth for the same body (the synthesized derivation/outer-WHERE vs. the author's verbatim SQL). Fail-closed.",