diff --git a/changelog.d/core-references-into-data.md b/changelog.d/core-references-into-data.md new file mode 100644 index 0000000000..dbd13b074f --- /dev/null +++ b/changelog.d/core-references-into-data.md @@ -0,0 +1,14 @@ +- **Core's four references are declared in data in every port.** `relationship.* @objectRef`, + `identity.reference @references` and `field.object` / `field.map @objectRef` now carry the + reference facet (`ref`) in `spec/metamodel/relationship.json`, `identity.json` and `field.json`, + and every port (TypeScript, C#, Java and Kotlin, Python, Rust) reads them from there instead of + declaring them in its own code. Each keeps its error code (`ERR_INVALID_RELATIONSHIP`, + `ERR_INVALID_REFERENCE`, `ERR_UNRESOLVED_OBJECT_REF`), so a model of core types loads, and + fails, exactly as before. An extension subtype that inherits a core type's reference attribute + now gets the same reference check, which it did not before: a provider subtype that takes + `relationship.base`'s `@objectRef` (in TypeScript, through `extendsBase`) raises + `ERR_INVALID_RELATIONSHIP` for a dangling target, and in Java a custom subtype inheriting + `relationship.base`, `field.object`, `field.map` or `identity.reference` raises that type's code + on every registry path. The registry manifest + (`fixtures/registry-conformance/expected-registry.json`) now writes `ref` on those seven + attributes; `metamodelVersion` does not move. diff --git a/changelog.d/csharp-reference-facet.md b/changelog.d/csharp-reference-facet.md index c9a7d8be5c..fd0fd0e977 100644 --- a/changelog.d/csharp-reference-facet.md +++ b/changelog.d/csharp-reference-facet.md @@ -1,16 +1,15 @@ -- **The C# loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of - a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript loader: the - spec reader validates the facet and carries it to `AttrSchema.Ref`, the lookup is typed by the - target, a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked - for in the referrer's own containers first, and a value that names nothing - (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another - system (the facet's own code) is refused. A canonical value is the path the lookup walked, and - a value whose canonical spelling would not look up the same target is kept as written. The - registry manifest writes `ref` only on an attribute that has one. No definition file uses the - facet yet, so no registry, manifest or generated output changes. A provider's own code that is - not an `ErrorCode` member now keeps its spelling in `MetaError.ProviderCode` (`Code` stays - `ERR_UNKNOWN`; `CodeName` gives either). A parent-relative `@references` value - (`..::Address.id`) now resolves its owner instead of reading the `..` as one. +- **The C# loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of a + provider definition, `spec/metamodel-definitions.md`), matching the TypeScript loader: the spec + reader validates the facet and carries it to `AttrSchema.Ref`, the lookup is typed by the target, + a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked for in the + referrer's own containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong + kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is + refused. A canonical value is the path the lookup walked, and a value whose canonical spelling + would not look up the same target is kept as written. The registry manifest writes `ref` only on + an attribute that has one. A provider's own code that is not an `ErrorCode` member now keeps its + spelling in `MetaError.ProviderCode` (`Code` stays `ERR_UNKNOWN`; `CodeName` gives either). A + parent-relative `@references` value (`..::Address.id`) now resolves its owner instead of reading + the `..` as one. Upgrading: C# `ReferenceDescriptor` is now `(Attr, Facet)`. A provider that sets `TypeDefinition.References` in code builds `new ReferenceDescriptor(attr, new ReferenceFacet(...))`. diff --git a/changelog.d/java-reference-facet.md b/changelog.d/java-reference-facet.md index c17d49cd4c..9c5f5b17d6 100644 --- a/changelog.d/java-reference-facet.md +++ b/changelog.d/java-reference-facet.md @@ -1,22 +1,20 @@ -- **The Java loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of - a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript and C# - loaders; Kotlin runs on it. The spec reader validates the facet and carries it to the attr's - `ChildRequirement.getRef()` (or `CommonAttributeDef.ref()`). The lookup is typed by the target. - A dotted value resolves `System.child` and `pkg::System.child`, and a bare value is looked for - in the referrer's own containers first. A value that names nothing (`ERR_REF_UNRESOLVED`), the - wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is - refused. A canonical value is the path the lookup walked; a value whose canonical spelling - would not look up the same target is kept as written. The registry manifest writes `ref` only - on an attribute that has one. No definition file uses the facet yet, so no registry, manifest - or generated output changes. A provider's own code that is not an `ErrorCode` member now keeps - its spelling in `MetaDataException.getProviderCode()` (`getCode()` stays `ERR_UNKNOWN`; +- **The Java loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of a + provider definition, `spec/metamodel-definitions.md`), matching the TypeScript and C# loaders; + Kotlin runs on it. The spec reader validates the facet and carries it to the attr's + `ChildRequirement.getRef()` (or `CommonAttributeDef.ref()`). The lookup is typed by the target. A + dotted value resolves `System.child` and `pkg::System.child`, and a bare value is looked for in + the referrer's own containers first. A value that names nothing (`ERR_REF_UNRESOLVED`), the wrong + kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is + refused. A canonical value is the path the lookup walked; a value whose canonical spelling would + not look up the same target is kept as written. The registry manifest writes `ref` only on an + attribute that has one. A provider's own code that is not an `ErrorCode` member now keeps its + spelling in `MetaDataException.getProviderCode()` (`getCode()` stays `ERR_UNKNOWN`; `getCodeName()` gives either). A parent-relative `@references` value (`..::Address.id`) now resolves its owner instead of reading the `..` as one. As in TypeScript, an `@objectRef` or - `@references` value whose `..::` climbs above the root package now raises - `ERR_BAD_ATTR_VALUE` instead of the reference's own code, and an inherited one is checked in - the package of the node that declares it, not the inheritor's. A dotted `extends` whose owner is a - top-level node other than an object (`acme::Parcels.base`) now resolves, as it does in - TypeScript and C#. + `@references` value whose `..::` climbs above the root package now raises `ERR_BAD_ATTR_VALUE` + instead of the reference's own code, and an inherited one is checked in the package of the node + that declares it, not the inheritor's. A dotted `extends` whose owner is a top-level node other + than an object (`acme::Parcels.base`) now resolves, as it does in TypeScript and C#. Upgrading: Java `ReferenceDescriptor` is now `(attr, facet)`. A provider that attaches references to its type definition in code builds diff --git a/changelog.d/python-reference-facet.md b/changelog.d/python-reference-facet.md index 2af98b6899..b009878184 100644 --- a/changelog.d/python-reference-facet.md +++ b/changelog.d/python-reference-facet.md @@ -1,14 +1,13 @@ -- **The Python loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry - of a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript and C# - loaders: the spec reader validates the facet and carries it to `AttrSchema.ref`, the lookup is - typed by the target, a dotted value resolves `System.child` and `pkg::System.child`, a bare - value is looked for in the referrer's own containers first, and a value that names nothing - (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another - system (the facet's own code) is refused. A canonical value is the path the lookup walked, and - a value whose canonical spelling would not look up the same target is kept as written. The - registry manifest writes `ref` only on an attribute that has one. No definition file uses the - facet yet, so no registry, manifest or generated output changes. A provider's own code that is - not an `ErrorCode` member now keeps its spelling in `MetaError.provider_code` (`code` stays +- **The Python loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of + a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript and C# loaders: + the spec reader validates the facet and carries it to `AttrSchema.ref`, the lookup is typed by + the target, a dotted value resolves `System.child` and `pkg::System.child`, a bare value is + looked for in the referrer's own containers first, and a value that names nothing + (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another system + (the facet's own code) is refused. A canonical value is the path the lookup walked, and a value + whose canonical spelling would not look up the same target is kept as written. The registry + manifest writes `ref` only on an attribute that has one. A provider's own code that is not an + `ErrorCode` member now keeps its spelling in `MetaError.provider_code` (`code` stays `ERR_UNKNOWN`; `code_name` gives either), and the CLI and `build_shared_model` report that spelling. diff --git a/changelog.d/rust-reference-facet.md b/changelog.d/rust-reference-facet.md index beb13f17ca..5d44d4d0fb 100644 --- a/changelog.d/rust-reference-facet.md +++ b/changelog.d/rust-reference-facet.md @@ -1,22 +1,21 @@ -- **The Rust loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of - a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript, C# and Java - loaders. The spec reader in `providers.rs` validates the facet (refusing a bad facet, or one on - a structural child) and carries it to `AttrSchema::reference`. The registered walk enforces it +- **The Rust loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of a + provider definition, `spec/metamodel-definitions.md`), matching the TypeScript, C# and Java + loaders. The spec reader in `providers.rs` validates the facet (refusing a bad facet, or one on a + structural child) and carries it to `AttrSchema::reference`. The registered walk enforces it through a kind-typed symbol table: a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own containers first, and a - value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) - or a node of another system (the facet's own code) is refused, with `sameSystem` judged on the - path the lookup walked. The reference pass writes a canonical value as that walked path, and - keeps a value as written when its canonical spelling would not look up the same target. The - registry manifest writes `ref` only on an attribute that has one. No definition file uses the - facet yet, so no registry, manifest or generated output changes. A provider's own code that is - not in the shared catalogue keeps its spelling in `MetaError::provider_code` (`code` stays - `ERR_UNKNOWN`; `MetaError::code_name()` gives either, and the error prints under it). A - parent-relative `@references` value (`..::Address.id`) now resolves its owner instead of - reading the `..` as one. A root-level node and a same-named node in a package, declared in one - document, are now two nodes rather than one merged node, as in every other port and the - loader's cross-file merge; this closes the last ledgered `yaml-conformance` fixture - (`yaml-ref-root-escape`), so Rust passes 19 of 19. + value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or + a node of another system (the facet's own code) is refused, with `sameSystem` judged on the path + the lookup walked. The reference pass writes a canonical value as that walked path, and keeps a + value as written when its canonical spelling would not look up the same target. The registry + manifest writes `ref` only on an attribute that has one. A provider's own code that is not in the + shared catalogue keeps its spelling in `MetaError::provider_code` (`code` stays `ERR_UNKNOWN`; + `MetaError::code_name()` gives either, and the error prints under it). A parent-relative + `@references` value (`..::Address.id`) now resolves its owner instead of reading the `..` as one. + A root-level node and a same-named node in a package, declared in one document, are now two nodes + rather than one merged node, as in every other port and the loader's cross-file merge; this + closes the last ledgered `yaml-conformance` fixture (`yaml-ref-root-escape`), so Rust passes 19 + of 19. Upgrading: Rust `ReferenceDescriptor` is now `{ attr, facet }`. A provider that sets `TypeDefinition::references` in code builds `ReferenceDescriptor { attr, facet: ReferenceFacet { .. } }`, diff --git a/changelog.d/typescript-reference-facet-reader.md b/changelog.d/typescript-reference-facet-reader.md index e4fca6fec3..35b49d2c8e 100644 --- a/changelog.d/typescript-reference-facet-reader.md +++ b/changelog.d/typescript-reference-facet-reader.md @@ -1,13 +1,12 @@ -- **The TypeScript loader reads and enforces the reference facet** (`ref` on a `type: "attr"` - entry of a provider definition, `spec/metamodel-definitions.md`). A reference attribute can now - say in data what it may name (target type, admitted subtypes, same system), and the loader - checks it with no code per provider: the lookup is typed by the target, a dotted value resolves +- **The TypeScript loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry + of a provider definition, `spec/metamodel-definitions.md`). A reference attribute can now say in + data what it may name (target type, admitted subtypes, same system), and the loader checks it + with no code per provider: the lookup is typed by the target, a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is refused. The registry manifest writes `ref` only on an attribute that has one. The two default codes are in `fixtures/conformance/ERROR-CODES.json` and in the TypeScript, Python, Java and C# error-code - catalogs. No definition file uses the facet yet, so no registry, manifest or generated output - changes. A provider that sets `TypeDefinition.references` in code: the descriptor's + catalogs. A provider that sets `TypeDefinition.references` in code: the descriptor's `targetSubType` is now `targetSubTypes` (a list), `dottedFieldPath` is now `fieldPath`, and `errorCode` is optional. diff --git a/fixtures/registry-conformance/README.md b/fixtures/registry-conformance/README.md index 68097854a4..6a2681198c 100644 --- a/fixtures/registry-conformance/README.md +++ b/fixtures/registry-conformance/README.md @@ -281,8 +281,10 @@ still fails everywhere. An attr whose definition entry carries the reference facet (`spec/metamodel-definitions.md`) carries `"ref"` in the manifest, after any `ports` and before `description`: `targetType`, then `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (only when `true`), `errorCode` and -`wrongSystemCode` (only when present). An attr with no facet writes no `ref`, so the canonical -does not change until a definition file uses one. +`wrongSystemCode` (only when present). An attr with no facet writes no `ref`. In the core +definitions the facet is on core's four older references (`relationship.* @objectRef`, +`identity.reference @references`, `field.object` and `field.map @objectRef`), each naming its +existing error code. ### EXCLUDED from v1 — deferred follow-ons (documented, not silent) diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index fc2ca761fb..fa91431504 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -2065,6 +2065,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_UNRESOLVED_OBJECT_REF" + }, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." }, { @@ -2225,6 +2229,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_UNRESOLVED_OBJECT_REF" + }, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." }, { @@ -3146,6 +3154,11 @@ "valueType": "string", "isArray": false, "required": true, + "ref": { + "targetType": "object", + "fieldPath": true, + "errorCode": "ERR_INVALID_REFERENCE" + }, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." } ], @@ -4425,6 +4438,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + }, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, { @@ -4496,6 +4513,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + }, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, { @@ -4566,6 +4587,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + }, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, { @@ -4637,6 +4662,10 @@ "valueType": "string", "isArray": false, "required": false, + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + }, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, { diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs index 4658fe2cac..733cb8af8e 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs @@ -202,12 +202,37 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr() Assert.Equal(["b", "a"], facet!.TargetSubTypes!); } - [Fact] - public void No_shipped_definition_file_uses_the_facet_yet() + // The seven attributes that carry a facet in the core definitions. Only core's four older + // references carry one (spec/metamodel-definitions.md, "Existing references keep their + // codes"), each naming its existing code. + private static readonly string[] CoreFacets = + [ + "field.map @objectRef object False ERR_UNRESOLVED_OBJECT_REF", + "field.object @objectRef object False ERR_UNRESOLVED_OBJECT_REF", + "identity.reference @references object True ERR_INVALID_REFERENCE", + "relationship.aggregation @objectRef object False ERR_INVALID_RELATIONSHIP", + "relationship.association @objectRef object False ERR_INVALID_RELATIONSHIP", + "relationship.base @objectRef object False ERR_INVALID_RELATIONSHIP", + "relationship.composition @objectRef object False ERR_INVALID_RELATIONSHIP", + ]; + + [Fact] + public void The_core_definitions_declare_exactly_the_four_core_references() { var registry = Provider.ComposeRegistry(CoreTypes.LibraryProviders); + var found = new List(); foreach (var id in registry.AllTypes()) - Assert.All(registry.AttrsOf(id.Type, id.SubType), a => Assert.Null(a.Ref)); + { + foreach (var a in registry.AttrsOf(id.Type, id.SubType)) + { + if (a.Ref is not { } f) continue; + Assert.Null(f.TargetSubTypes); + Assert.False(f.SameSystem); + found.Add($"{id.Type}.{id.SubType} @{a.Name} {f.TargetType} {f.FieldPath} {f.ErrorCode}"); + } + } + found.Sort(StringComparer.Ordinal); + Assert.Equal(CoreFacets, found); Assert.All(registry.GetCommonAttrs(), a => Assert.Null(a.Ref)); } @@ -668,8 +693,10 @@ public void The_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fix } [Fact] - public void A_registry_with_no_facet_writes_no_ref_key() + public void An_attribute_with_no_facet_writes_no_ref_key() { - Assert.DoesNotContain("\"ref\"", RegistryManifest.Emit(Provider.ComposeRegistry(CoreTypes.LibraryProviders))); + // One "ref" per facet in the core definitions, and none anywhere else. + var manifest = RegistryManifest.Emit(Provider.ComposeRegistry(CoreTypes.LibraryProviders)); + Assert.Equal(CoreFacets.Length, manifest.Split("\"ref\"").Length - 1); } } diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 53a6506ce3..a11faa87a3 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -557,42 +557,10 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) RelationshipSchema.RelationshipAttrs.ToList())); } - // Declare the core cross-references ON their TypeDefinitions — the loader's - // registry-derived validation resolves them (a dangling target fails the load). - // Mirrors the TS/Java realization (config-on-the-type). - foreach (string subType in RELATIONSHIP_SUBTYPES) - { - var rdef = registry.Find(TYPE_RELATIONSHIP, subType); - if (rdef is not null) - { - rdef.References = [new MetaObjects.Validation.ReferenceDescriptor( - RELATIONSHIP_ATTR_OBJECT_REF, - new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, ErrorCode: "ERR_INVALID_RELATIONSHIP"))]; - } - } - var idRefDef = registry.Find(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE); - if (idRefDef is not null) - { - idRefDef.References = [new MetaObjects.Validation.ReferenceDescriptor( - IDENTITY_REFERENCE_ATTR_REFERENCES, - new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, FieldPath: true, ErrorCode: "ERR_INVALID_REFERENCE"))]; - } - - // ADR-0042 — a field.object / field.map @objectRef must resolve (a dangling target - // fails the load, closing the gap that surfaced downstream as a misleading runtime - // error; #191). The required-attr pass owns absence (ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF); - // this descriptor fires only when @objectRef is PRESENT but resolves to nothing → - // ERR_UNRESOLVED_OBJECT_REF. Mirrors the TS core-types.ts registration. - foreach (string subType in new[] { FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP }) - { - var fdef = registry.Find(TYPE_FIELD, subType); - if (fdef is not null) - { - fdef.References = [new MetaObjects.Validation.ReferenceDescriptor( - FIELD_ATTR_OBJECT_REF, - new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, ErrorCode: "ERR_UNRESOLVED_OBJECT_REF"))]; - } - } + // The core cross-references (relationship.* @objectRef, identity.reference + // @references, field.object / field.map @objectRef) are reference facets in their + // spec/metamodel definition files, each naming its existing code + // (spec/metamodel-definitions.md, "Existing references keep their codes"). // index — 1 subtype (lookup). Non-unique lookup indexes for query-performance. // Distinct from identity.secondary (which enforces uniqueness). A single diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index 46a2f064ce..7b497d901f 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -112,7 +112,7 @@ "whenToUse": "A field holds a nested structured value (or an array of them). Set @objectRef + @storage so the shape is typed and persisted (flattened/jsonb) instead of an untyped blob.", "rules": "Set @objectRef to the nested object's name (or FQN). @storage selects physical layout — flattened expands into prefixed parent columns (isArray must be false), jsonb stores the structured value (or array when isArray=true) in one jsonb column, subdocument emits no Postgres column. Defaults to single-jsonb-column when @storage is absent.", "children": [ - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { @@ -125,7 +125,7 @@ "rules": "Keys are always strings. Set exactly one of @valueType (a scalar value subtype: string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid) or @objectRef (a value-object name or FQN). Stored as a single jsonb column holding the JSON object — never a native array; isArray does not apply.", "children": [ { "type": "attr", "subType": "string", "name": "valueType", "min": 0, "max": 1, "description": "Scalar value subtype for a scalar-valued map (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). Mutually exclusive with @objectRef; exactly one of the two must be set." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { diff --git a/server/csharp/MetaObjects/SpecMetamodel/identity.json b/server/csharp/MetaObjects/SpecMetamodel/identity.json index d7ec0ebec0..4c7bbe8d67 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/identity.json +++ b/server/csharp/MetaObjects/SpecMetamodel/identity.json @@ -29,7 +29,7 @@ "whenToUse": "This entity holds a foreign key to another. Declare it to generate the FK constraint + typed navigation, instead of a loose id field you join on by hand.", "children": [ { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, - { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." }, + { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity.", "ref": { "targetType": "object", "fieldPath": true, "errorCode": "ERR_INVALID_REFERENCE" } }, { "type": "attr", "subType": "boolean", "name": "enforce", "min": 0, "max": 1, "description": "When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level." } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/relationship.json b/server/csharp/MetaObjects/SpecMetamodel/relationship.json index 0fd2d5b1a9..308c5a130d 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/relationship.json +++ b/server/csharp/MetaObjects/SpecMetamodel/relationship.json @@ -8,7 +8,7 @@ "rules": "@cardinality is an open string at the metamodel level ('one'/'many', and Java-canonical composite forms such as 'many-to-one'); @objectRef names the target entity. M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. @onDelete/@onUpdate carry referential actions (cascade/set-null/restrict/no-action).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -24,7 +24,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Association is a plain reference — the target's lifecycle is independent (default @onDelete restrict).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -40,7 +40,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Aggregation is shared/independent — the target outlives the parent (default @onDelete set-null).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -56,7 +56,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Composition is owned lifecycle — the children do not outlive the parent (default @onDelete cascade).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/MapField.java b/server/java/metadata/src/main/java/com/metaobjects/field/MapField.java index 4dc5c8f10d..97ce14413c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/MapField.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/MapField.java @@ -66,14 +66,9 @@ public static void registerTypes(MetaDataRegistry registry) { // re-declaring them here. FR-033 strict-attr scoping keeps exactly // @valueType + @objectRef on field.map (per spec/metamodel/field.json), // so the manifest byte-matches the frozen registry fixture. - .inheritsFrom(TYPE_FIELD, SUBTYPE_BASE) - // ADR-0042 — a value-object-valued map's @objectRef is a cross-reference - // to a real object; the loader's registry-derived validation resolves it - // package-locally (dangling target = load error). Fires only when - // @objectRef is present (a scalar-valued map uses @valueType instead). - .reference(new com.metaobjects.validation.ReferenceDescriptor( - MetaObject.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of( - MetaObject.TYPE_OBJECT, "ERR_UNRESOLVED_OBJECT_REF"))); + .inheritsFrom(TYPE_FIELD, SUBTYPE_BASE); + // ADR-0042 — @objectRef's reference facet (ERR_UNRESOLVED_OBJECT_REF) is + // declared in spec/metamodel/field.json and applied by the spec reader. }); log.debug("Registered MapField type with unified registry"); diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/ObjectField.java b/server/java/metadata/src/main/java/com/metaobjects/field/ObjectField.java index d11bf00fa3..3f622cfb0b 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/ObjectField.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/ObjectField.java @@ -66,15 +66,9 @@ public static void registerTypes(MetaDataRegistry registry) { // prefix. Scoped to field.object; description enriched from spec db.json. .optionalAttributeWithConstraints(ATTR_FLATTENED_COLUMN_PREFIX) .ofType(com.metaobjects.attr.StringAttribute.SUBTYPE_STRING) - .asSingle() - // ADR-0042 — @objectRef is a cross-reference to a real object (the - // nested value's shape); the loader's registry-derived validation - // resolves it package-locally (dangling target = load error). Fires - // only when @objectRef is present (absence is - // ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF's job). - .reference(new com.metaobjects.validation.ReferenceDescriptor( - MetaObject.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of( - MetaObject.TYPE_OBJECT, "ERR_UNRESOLVED_OBJECT_REF"))); + .asSingle(); + // ADR-0042 — @objectRef's reference facet (ERR_UNRESOLVED_OBJECT_REF) is + // declared in spec/metamodel/field.json and applied by the spec reader. }); log.debug("Registered ObjectField type with unified registry"); diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java index fb59d667e7..c1474f2a62 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java +++ b/server/java/metadata/src/main/java/com/metaobjects/identity/ReferenceIdentity.java @@ -58,11 +58,8 @@ public static void registerTypes(MetaDataRegistry registry) { // @fields + @references are REQUIRED on identity.reference (cross-port canonical). def.requiredAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.requiredAttributeWithConstraints(ATTR_REFERENCES).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); - // @references is a cross-reference to a real object (FK target) — the loader's - // registry-derived validation resolves it; "Entity.field" forms resolve the entity. - def.reference(new com.metaobjects.validation.ReferenceDescriptor( - ATTR_REFERENCES, new com.metaobjects.validation.ReferenceFacet( - com.metaobjects.object.MetaObject.TYPE_OBJECT, null, true, false, "ERR_INVALID_REFERENCE", null))); + // @references's reference facet (fieldPath, ERR_INVALID_REFERENCE) is declared in + // spec/metamodel/identity.json and applied by the spec reader. def.optionalAttributeWithConstraints(ATTR_ENFORCE).ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); // RDB-physical FK constraint-name override contributed by the db provider // (db.json extends identity.reference). Description sourced from the embedded diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java index aa6ef6ccf2..f72f68be3a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/MetaDataRegistry.java @@ -1148,6 +1148,10 @@ public synchronized void applySpecDescriptions(com.metaobjects.registry.spec.Spe // @maxLength on field.boolean) now → ERR_UNKNOWN_ATTR. Types NOT declared in // the JSON keep their attrs untouched (no JSON-sourced strict set exists). applyStrictAttrScoping(reader); + + // Pass 6 — the reference facets, the same step the core bootstrap runs, so an extension + // subtype inherits its ancestor's reference check whatever order Pass 2 re-inherited in. + applySpecReferences(reader); } /** @@ -1627,6 +1631,83 @@ private static String directKey(ChildRequirement req) { return key; } + /** + * Put the reference facet the spec definitions declare onto each attr requirement, direct + * and inherited, of every registered type — and nothing else. The core bootstrap runs this + * so a registry that never goes through {@link #applySpecDescriptions} (the SPI singleton, + * {@link #createWithCoreProviders()}) still enforces the core references, and + * {@link #applySpecDescriptions} runs it last so every path ends the same. + * + *

An extension subtype the spec does not declare inherits its parent's definition data, + * so an inherited requirement takes the facet of the nearest declared ancestor: a custom + * subtype inheriting {@code relationship.base} gets {@code @objectRef}'s + * {@code ERR_INVALID_RELATIONSHIP} check, as in the TypeScript reference. The lookup walks + * the parent chain rather than trusting the inherited copy, because a subtype an SPI provider + * registers during bootstrap took that copy before this pass applied the facet.

+ */ + private void applySpecReferences(com.metaobjects.registry.spec.SpecMetamodelReader reader) { + for (Map.Entry entry : new ArrayList<>(typeDefinitions.entrySet())) { + MetaDataTypeId id = entry.getKey(); + TypeDefinition def = entry.getValue(); + boolean directChanged = false; + Map directReqs = new LinkedHashMap<>(); + for (ChildRequirement req : def.getDirectChildRequirements()) { + ChildRequirement withRef = withSpecRef(req, id, reader); + directChanged |= withRef != req; + directReqs.put(directKey(req), withRef); + } + Map inherited = new LinkedHashMap<>(); + for (Map.Entry e : def.getInheritedChildRequirements().entrySet()) { + inherited.put(e.getKey(), withInheritedSpecRef(e.getValue(), id, def, reader)); + } + TypeDefinition target = def; + if (directChanged) { + target = new TypeDefinition( + def.getImplementationClass(), id.type(), id.subType(), def.getDescription(), + directReqs, def.getParentType(), def.getParentSubType(), + def.getRules(), def.getExample(), def.getWhenToUse(), def.getParents()); + target.setMaxOccurs(def.getMaxOccurs()); + target.setDefaultName(def.getDefaultName()); + target.setReferences(def.getReferences()); + target.setValidator(def.getValidator()); + typeDefinitions.put(id, target); + } + target.populateInheritedRequirements(inherited); + } + } + + /** + * As {@link #withSpecRef} for an inherited requirement: a type the spec declares is judged + * by its own definition only; an undeclared extension subtype takes the facet of its nearest + * declared ancestor. + */ + private ChildRequirement withInheritedSpecRef(ChildRequirement req, MetaDataTypeId id, TypeDefinition def, + com.metaobjects.registry.spec.SpecMetamodelReader reader) { + MetaDataTypeId owner = id; + TypeDefinition current = def; + java.util.Set seen = new java.util.HashSet<>(); + while (!reader.isDeclared(owner.type(), owner.subType()) && current != null && current.hasParent() + && seen.add(owner)) { + owner = new MetaDataTypeId(current.getParentType(), current.getParentSubType()); + current = typeDefinitions.get(owner); + } + return withSpecRef(req, owner, reader); + } + + private static ChildRequirement withSpecRef(ChildRequirement req, MetaDataTypeId id, + com.metaobjects.registry.spec.SpecMetamodelReader reader) { + if (!MetaAttribute.TYPE_ATTR.equals(req.getExpectedType()) + || req.getName() == null || "*".equals(req.getName())) { + return req; + } + com.metaobjects.registry.spec.SpecMetamodelReader.AttrEntry doc = + reader.attrDoc(id.type(), id.subType(), req.getName()); + if (doc == null || doc.ref() == null || doc.ref().equals(req.getRef())) { + return req; + } + return req.withRef(doc.ref()); + } + /** * FR-033 (sub-step B1) — re-describe a definition's INHERITED attr requirements * against the definition's OWN {@code (type, subType)}, so a JSON description that @@ -1918,6 +1999,7 @@ private void ensureInitialized() { synchronized (this) { if (!initialized) { loadServiceProviders(); + applySpecReferences(com.metaobjects.registry.spec.SpecMetamodelReader.load()); initialized = true; } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/relationship/AggregationRelationship.java b/server/java/metadata/src/main/java/com/metaobjects/relationship/AggregationRelationship.java index a159724da6..3500270281 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/relationship/AggregationRelationship.java +++ b/server/java/metadata/src/main/java/com/metaobjects/relationship/AggregationRelationship.java @@ -19,12 +19,9 @@ public static void registerTypes(MetaDataRegistry registry) { registry.registerType(AggregationRelationship.class, def -> def .type(TYPE_RELATIONSHIP).subType(SUBTYPE_AGGREGATION) .description("Aggregation relationship - parent has shared ownership (shared lifecycle)") + // @objectRef's reference facet (ERR_INVALID_RELATIONSHIP) is declared in + // spec/metamodel/relationship.json and applied by the spec reader. .inheritsFrom(TYPE_RELATIONSHIP, SUBTYPE_BASE) - // @objectRef is a cross-reference to a real object (the relationship target); - // the loader's registry-derived validation resolves it (dangling = load error). - .reference(new com.metaobjects.validation.ReferenceDescriptor( - MetaRelationship.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of( - com.metaobjects.object.MetaObject.TYPE_OBJECT, "ERR_INVALID_RELATIONSHIP"))) ); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/relationship/AssociationRelationship.java b/server/java/metadata/src/main/java/com/metaobjects/relationship/AssociationRelationship.java index a36c8f9762..5346443810 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/relationship/AssociationRelationship.java +++ b/server/java/metadata/src/main/java/com/metaobjects/relationship/AssociationRelationship.java @@ -19,12 +19,9 @@ public static void registerTypes(MetaDataRegistry registry) { registry.registerType(AssociationRelationship.class, def -> def .type(TYPE_RELATIONSHIP).subType(SUBTYPE_ASSOCIATION) .description("Association relationship - parent references independent child (independent lifecycle)") + // @objectRef's reference facet (ERR_INVALID_RELATIONSHIP) is declared in + // spec/metamodel/relationship.json and applied by the spec reader. .inheritsFrom(TYPE_RELATIONSHIP, SUBTYPE_BASE) - // @objectRef is a cross-reference to a real object (the relationship target); - // the loader's registry-derived validation resolves it (dangling = load error). - .reference(new com.metaobjects.validation.ReferenceDescriptor( - MetaRelationship.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of( - com.metaobjects.object.MetaObject.TYPE_OBJECT, "ERR_INVALID_RELATIONSHIP"))) ); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/relationship/CompositionRelationship.java b/server/java/metadata/src/main/java/com/metaobjects/relationship/CompositionRelationship.java index 086606137e..96c192f440 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/relationship/CompositionRelationship.java +++ b/server/java/metadata/src/main/java/com/metaobjects/relationship/CompositionRelationship.java @@ -19,12 +19,9 @@ public static void registerTypes(MetaDataRegistry registry) { registry.registerType(CompositionRelationship.class, def -> def .type(TYPE_RELATIONSHIP).subType(SUBTYPE_COMPOSITION) .description("Composition relationship - parent exclusively owns child (dependent lifecycle)") + // @objectRef's reference facet (ERR_INVALID_RELATIONSHIP) is declared in + // spec/metamodel/relationship.json and applied by the spec reader. .inheritsFrom(TYPE_RELATIONSHIP, SUBTYPE_BASE) - // @objectRef is a cross-reference to a real object (the relationship target); - // the loader's registry-derived validation resolves it (dangling = load error). - .reference(new com.metaobjects.validation.ReferenceDescriptor( - MetaRelationship.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of( - com.metaobjects.object.MetaObject.TYPE_OBJECT, "ERR_INVALID_RELATIONSHIP"))) ); } diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/validation/DownstreamValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/validation/DownstreamValidationTest.java index 483fda1eef..8c416dc50e 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/validation/DownstreamValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/validation/DownstreamValidationTest.java @@ -12,7 +12,6 @@ import java.util.List; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -31,20 +30,23 @@ private MetaDataLoader newLoader() { } @Test - public void coreCrossReferencesLiveOnTheirTypeDefinitions() { - // The descriptors are carried by the type's registration, not hardcoded in a pass. - TypeDefinition rel = getSharedRegistry().getTypeDefinition("relationship", "composition"); + public void coreCrossReferencesLiveOnTheirDefinitionAttributes() { + // The core references are reference facets in spec/metamodel/*.json, carried by the + // attribute's requirement on the type's registration — not hardcoded in a pass. + com.metaobjects.registry.MetaDataRegistry loaderRegistry = + com.metaobjects.registry.RegistryManifest.defaultLoaderRegistry(); + TypeDefinition rel = loaderRegistry.getTypeDefinition("relationship", "composition"); assertNotNull("relationship.composition is registered", rel); - assertFalse("relationship.composition declares its @objectRef cross-reference", - rel.getReferences().isEmpty()); - assertEquals("objectRef", rel.getReferences().get(0).attr()); + assertNotNull("relationship.composition declares its @objectRef cross-reference", + rel.getChildRequirement("objectRef").getRef()); + assertEquals("ERR_INVALID_RELATIONSHIP", rel.getChildRequirement("objectRef").getRef().errorCode()); - TypeDefinition idRef = getSharedRegistry().getTypeDefinition("identity", "reference"); + TypeDefinition idRef = loaderRegistry.getTypeDefinition("identity", "reference"); assertNotNull("identity.reference is registered", idRef); - assertFalse("identity.reference declares its @references cross-reference", - idRef.getReferences().isEmpty()); + assertNotNull("identity.reference declares its @references cross-reference", + idRef.getChildRequirement("references").getRef()); assertTrue("identity.reference resolves the entity segment of a dotted path", - idRef.getReferences().get(0).facet().fieldPath()); + idRef.getChildRequirement("references").getRef().fieldPath()); } @Test diff --git a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java index a6fe085818..e6fb739776 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java @@ -38,9 +38,10 @@ * resolves {@code System.child} and {@code pkg::System.child}, the lookup is kind-typed, and * the registry manifest writes the facet only when an attr has one. * - *

No shipped definition file uses the facet yet, so these tests compose a test provider - * with a small system vocabulary of its own: the types are registered in code, and the - * reference attributes come from a provider definition read by the spec reader. Mirrors the + *

Most of these tests compose a test provider with a small system vocabulary of its own: + * the types are registered in code, and the reference attributes come from a provider + * definition read by the spec reader. The last group checks core's own four references, which + * the shipped definition files declare. Mirrors the * TS {@code test/reference-facet.test.ts} and the C# {@code ReferenceFacetTests} case for * case.

*/ @@ -289,15 +290,35 @@ public void theReaderCarriesAFacetOnATypesEntryAttr() { assertEquals(List.of("b", "a"), facet.targetSubTypes()); } + /** The seven attributes that carry a facet in the core definitions. Only core's four + * older references carry one (spec/metamodel-definitions.md, "Existing references keep + * their codes"), each naming its existing code. */ + private static final List CORE_FACETS = List.of( + "field.map @objectRef object false ERR_UNRESOLVED_OBJECT_REF", + "field.object @objectRef object false ERR_UNRESOLVED_OBJECT_REF", + "identity.reference @references object true ERR_INVALID_REFERENCE", + "relationship.aggregation @objectRef object false ERR_INVALID_RELATIONSHIP", + "relationship.association @objectRef object false ERR_INVALID_RELATIONSHIP", + "relationship.base @objectRef object false ERR_INVALID_RELATIONSHIP", + "relationship.composition @objectRef object false ERR_INVALID_RELATIONSHIP"); + @Test - public void noShippedDefinitionFileUsesTheFacetYet() { + public void theCoreDefinitionsDeclareExactlyTheFourCoreReferences() { MetaDataRegistry registry = RegistryManifest.defaultLoaderRegistry(); + List found = new java.util.ArrayList<>(); for (MetaDataTypeId id : registry.getRegisteredTypes()) { TypeDefinition def = registry.getTypeDefinition(id.type(), id.subType()); for (ChildRequirement req : def.getChildRequirements()) { - assertNull(id + " @" + req.getName(), req.getRef()); + ReferenceFacet f = req.getRef(); + if (f == null) continue; + assertNull(f.targetSubTypes()); + assertFalse(f.sameSystem()); + found.add(id.type() + "." + id.subType() + " @" + req.getName() + " " + f.targetType() + + " " + f.fieldPath() + " " + f.errorCode()); } } + java.util.Collections.sort(found); + assertEquals(CORE_FACETS, found); for (CommonAttributeDef common : registry.getCommonAttributes()) { assertNull(common.name(), common.ref()); } @@ -633,6 +654,160 @@ public void aWrongKindObjectReferenceStillSuggestsTheObjectInAnotherPackage() { assertTrue(message(r, 0), message(r, 0).contains("An object named \"Address\" exists in: common::Address.")); } + @Test + public void anIsolatedCoreRegistryStillEnforcesTheCoreReferences() { + // createWithCoreProviders() never runs applySpecDescriptions; the four core references + // must reach it anyway (spec/metamodel-definitions.md, "Existing references keep their codes"). + String text = """ + metadata.root: + package: shop + children: + - object.entity: + name: Order + children: + - field.long: { name: id } + - field.long: { name: customerId } + - field.object: { name: shipTo, objectRef: Missing } + - field.map: { name: lines, objectRef: Missing } + - identity.primary: { name: pk, fields: [ id ] } + - identity.reference: { name: customerRef, fields: [ customerId ], references: Missing } + - relationship.association: { name: customer, objectRef: Missing, cardinality: one } + """; + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "isolatedCore"); + loader.setTypeRegistry(MetaDataRegistry.createWithCoreProviders()); + loader.init(); + List errors = new ArrayList<>(); + try { + loader.load(List.of(new InMemoryStringSource(text, "order.yaml", MetaDataSource.MetaDataFormat.YAML))); + } catch (MetaDataException e) { + errors.add(e); + } + errors.addAll(loader.getErrors()); + // One error per offending node, each with its own code: field.object and field.map share + // ERR_UNRESOLVED_OBJECT_REF, so a distinct-code check would pass with either facet missing. + Map expected = Map.of( + "shipTo", "ERR_UNRESOLVED_OBJECT_REF", + "lines", "ERR_UNRESOLVED_OBJECT_REF", + "customerRef", "ERR_INVALID_REFERENCE", + "customer", "ERR_INVALID_RELATIONSHIP"); + assertEquals(errors.stream().map(e -> e.getCodeName().orElse("") + ": " + e.getMessage()).toList().toString(), + expected.size(), errors.size()); + for (Map.Entry node : expected.entrySet()) { + List about = errors.stream() + .filter(e -> e.getMessage().contains("\"Order." + node.getKey() + "\"")) + .toList(); + assertEquals(node.getKey() + " in " + errors, 1, about.stream() + .filter(e -> e.getCodeName().orElse("").equals(node.getValue())).count()); + } + } + + // ---- An extension subtype inherits its core parent's reference check, on every path ---- + + /** A custom relationship subtype, as a downstream provider would register one. */ + public static final class CustomRelationship extends com.metaobjects.relationship.MetaRelationship { + public CustomRelationship(String subType, String name) { super(subType, name); } + @Override public String getLifecycle() { return "independent"; } + @Override public boolean isOwning() { return false; } + @Override public boolean isReferencing() { return true; } + } + + /** A custom field subtype inheriting field.object. */ + public static final class CustomObjectField extends com.metaobjects.field.MetaField { + public CustomObjectField(String subType, String name) { + super(subType, name, com.metaobjects.DataTypes.OBJECT); + } + } + + /** Registers relationship.custom (inherits relationship.base) and field.custom (inherits field.object). */ + static final MetaDataTypeProvider INHERITING = new MetaDataTypeProvider() { + @Override public String getProviderId() { return "test-inheriting-core-references"; } + @Override public String[] getDependencies() { return new String[]{"relationship-types", "field-types"}; } + @Override public String getDescription() { return "Test-only: extension subtypes of core types."; } + @Override public void registerTypes(MetaDataRegistry registry) { registerInheriting(registry); } + }; + + private static void registerInheriting(MetaDataRegistry registry) { + registry.registerType(CustomRelationship.class, def -> def + .type("relationship").subType("custom").description("A test relationship.") + .inheritsFrom("relationship", "base")); + registry.registerType(CustomObjectField.class, def -> def + .type("field").subType("custom").description("A test object field.") + .inheritsFrom("field", "object")); + } + + private static final String INHERITING_MODEL = """ + metadata.root: + package: shop + children: + - object.entity: + name: Order + children: + - field.long: { name: id } + - field.custom: { name: shipTo, objectRef: Missing } + - identity.primary: { name: pk, fields: [ id ] } + - relationship.custom: { name: customer, objectRef: Missing, cardinality: one } + """; + + private static List loadWith(MetaDataRegistry registry) { + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "inheritingCore"); + loader.setTypeRegistry(registry); + loader.init(); + List errors = new ArrayList<>(); + try { + loader.load(List.of(new InMemoryStringSource(INHERITING_MODEL, "order.yaml", + MetaDataSource.MetaDataFormat.YAML))); + } catch (MetaDataException e) { + errors.add(e); + } + for (MetaDataException e : loader.getErrors()) if (!errors.contains(e)) errors.add(e); + return errors.stream().map(e -> e.getCodeName().orElse("") + ": " + e.getMessage()).sorted().toList(); + } + + private static void assertInheritedChecks(List errors) { + assertEquals(errors.toString(), 2, errors.size()); + assertTrue(errors.toString(), errors.get(0).startsWith("ERR_INVALID_RELATIONSHIP")); + assertTrue(errors.toString(), errors.get(1).startsWith("ERR_UNRESOLVED_OBJECT_REF")); + } + + @Test + public void anExtensionSubtypeRegisteredDuringTheSpiBootstrapInheritsTheCoreReferences() { + // The getInstance() bootstrap: an SPI provider registers the extension subtypes while the + // providers load, before the reference facets are applied. getInstance() is the process + // singleton other tests read, so this runs the same bootstrap on a private registry whose + // service registry adds the test provider to the SPI set. + com.metaobjects.registry.ServiceRegistry spi = new com.metaobjects.registry.ServiceRegistry() { + private final com.metaobjects.registry.ServiceRegistry base = + com.metaobjects.registry.ServiceRegistryFactory.getDefault(); + @Override @SuppressWarnings("unchecked") public java.util.Collection getServices(Class c) { + List all = new ArrayList<>(base.getServices(c)); + if (c == MetaDataTypeProvider.class) all.add((T) INHERITING); + return all; + } + @Override public void registerService(Class c, T s) { base.registerService(c, s); } + @Override public boolean unregisterService(Class c, T s) { return base.unregisterService(c, s); } + @Override public String getDescription() { return "test SPI with an extension provider"; } + @Override public void close() { } + }; + MetaDataRegistry registry = new MetaDataRegistry(spi); + registry.validateConsistency(); // runs the same lazy bootstrap getInstance() runs + assertTrue(registry.isRegistered("relationship", "custom")); + assertInheritedChecks(loadWith(registry)); + } + + @Test + public void anExtensionSubtypeRegisteredOnACoreRegistryInheritsTheCoreReferences() { + MetaDataRegistry registry = MetaDataRegistry.createWithCoreProviders(); + registerInheriting(registry); + assertInheritedChecks(loadWith(registry)); + } + + @Test + public void anExtensionSubtypeComposedIntoALoaderRegistryInheritsTheCoreReferences() { + assertInheritedChecks(loadWith(RegistryManifest.composeLoaderRegistry(List.of(INHERITING)))); + } + @Test public void aParentRelativeReferencesValueStillSuggestsTheObjectInAnotherPackage() { // ADR-0059 §2: `..::Address.id` from `acme::shop` names `acme::Address`; only `common::Address` exists. @@ -711,7 +886,9 @@ public void theManifestWritesRefOnlyOnAnAttributeThatHasOneInTheFixedKeyOrder() } @Test - public void aRegistryWithNoFacetWritesNoRefKey() { - assertFalse(RegistryManifest.emit(RegistryManifest.defaultLoaderRegistry()).contains("\"ref\"")); + public void anAttributeWithNoFacetWritesNoRefKey() { + // One "ref" per facet in the core definitions, and none anywhere else. + String manifest = RegistryManifest.emit(RegistryManifest.defaultLoaderRegistry()); + assertEquals(CORE_FACETS.size(), manifest.split("\"ref\"", -1).length - 1); } } diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 08cec7a19a..1bfe01f1aa 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -175,7 +175,6 @@ ) from .provider import Provider from .registry import AttrSchema, ChildRule, NodeFactory, TypeDefinition, TypeRegistry -from .validation_types import ReferenceDescriptor, ReferenceFacet from .shared.base_types import ( SUBTYPE_BASE, SUBTYPE_ROOT, @@ -223,7 +222,6 @@ def _register_subtypes( factory: NodeFactory, child_rules: list[ChildRule] | None = None, attrs: list[AttrSchema] | None = None, - references: list[ReferenceDescriptor] | None = None, ) -> None: """Register one TypeDefinition per subtype. Centralises loop boilerplate only — all type knowledge (subtypes tuple, node class, child rules) stays with the caller.""" @@ -235,7 +233,6 @@ def _register_subtypes( factory=factory, child_rules=list(child_rules) if child_rules else [], attrs=list(attrs) if attrs else [], - references=list(references) if references else [], ) ) @@ -488,22 +485,10 @@ def _register_subtypes( ) break -# ADR-0042 — a field.object / field.map @objectRef must RESOLVE (a dangling target -# fails the load, closing the gap #191 surfaced as a misleading downstream error). -# The required-attr pass owns absence (ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF); this -# reference descriptor fires only when @objectRef is present but resolves to nothing -# → ERR_UNRESOLVED_OBJECT_REF. Mirrors the TS core-types.ts registerCoreTypeDefs. -for _def in core_provider._defs: # noqa: SLF001 (provider build-time enrichment) - if _def.type == TYPE_FIELD and _def.sub_type in ( - fc.FIELD_SUBTYPE_OBJECT, - fc.FIELD_SUBTYPE_MAP, - ): - _def.references.append( - ReferenceDescriptor( - FIELD_ATTR_OBJECT_REF, - ReferenceFacet(TYPE_OBJECT, error_code="ERR_UNRESOLVED_OBJECT_REF"), - ) - ) +# ADR-0042 — a field.object / field.map @objectRef must RESOLVE: its reference facet +# (ERR_UNRESOLVED_OBJECT_REF) is declared in spec/metamodel/field.json and applied by +# the spec reader, as are identity.reference @references (ERR_INVALID_REFERENCE) and +# relationship.* @objectRef (ERR_INVALID_RELATIONSHIP). # field.enum — dedicated registration with required @values attr. # Inherits every common field attr (column / required / unique / default / @@ -625,11 +610,6 @@ def _register_subtypes( AttrSchema(name=IDENTITY_REFERENCE_ATTR_ENFORCE, value_type=ATTR_SUBTYPE_BOOLEAN, required=False), ], child_rules=[ChildRule(TYPE_ATTR, "*")], - # @references is a cross-reference to a real object (FK target) — the loader's - # registry-derived validation resolves it; "Entity.field" resolves the entity head. - references=[ReferenceDescriptor( - IDENTITY_REFERENCE_ATTR_REFERENCES, - ReferenceFacet(TYPE_OBJECT, field_path=True, error_code="ERR_INVALID_REFERENCE"))], ) ) @@ -688,11 +668,6 @@ def _register_subtypes( factory=MetaRelationship, child_rules=[ChildRule(TYPE_ATTR, "*")], attrs=_RELATIONSHIP_ATTRS, - # @objectRef is a cross-reference to a real object (the relationship target); the - # loader's registry-derived validation resolves it (dangling target = load error). - references=[ReferenceDescriptor( - RELATIONSHIP_ATTR_OBJECT_REF, - ReferenceFacet(TYPE_OBJECT, error_code="ERR_INVALID_RELATIONSHIP"))], ) # source.* — base (no attrs) + rdb (paradigm subtype with @table/@kind/@role/@schema). diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index 46a2f064ce..7b497d901f 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -112,7 +112,7 @@ "whenToUse": "A field holds a nested structured value (or an array of them). Set @objectRef + @storage so the shape is typed and persisted (flattened/jsonb) instead of an untyped blob.", "rules": "Set @objectRef to the nested object's name (or FQN). @storage selects physical layout — flattened expands into prefixed parent columns (isArray must be false), jsonb stores the structured value (or array when isArray=true) in one jsonb column, subdocument emits no Postgres column. Defaults to single-jsonb-column when @storage is absent.", "children": [ - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { @@ -125,7 +125,7 @@ "rules": "Keys are always strings. Set exactly one of @valueType (a scalar value subtype: string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid) or @objectRef (a value-object name or FQN). Stored as a single jsonb column holding the JSON object — never a native array; isArray does not apply.", "children": [ { "type": "attr", "subType": "string", "name": "valueType", "min": 0, "max": 1, "description": "Scalar value subtype for a scalar-valued map (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). Mutually exclusive with @objectRef; exactly one of the two must be set." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { diff --git a/server/python/src/metaobjects/spec_metamodel/identity.json b/server/python/src/metaobjects/spec_metamodel/identity.json index d7ec0ebec0..4c7bbe8d67 100644 --- a/server/python/src/metaobjects/spec_metamodel/identity.json +++ b/server/python/src/metaobjects/spec_metamodel/identity.json @@ -29,7 +29,7 @@ "whenToUse": "This entity holds a foreign key to another. Declare it to generate the FK constraint + typed navigation, instead of a loose id field you join on by hand.", "children": [ { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, - { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." }, + { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity.", "ref": { "targetType": "object", "fieldPath": true, "errorCode": "ERR_INVALID_REFERENCE" } }, { "type": "attr", "subType": "boolean", "name": "enforce", "min": 0, "max": 1, "description": "When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level." } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/relationship.json b/server/python/src/metaobjects/spec_metamodel/relationship.json index 0fd2d5b1a9..308c5a130d 100644 --- a/server/python/src/metaobjects/spec_metamodel/relationship.json +++ b/server/python/src/metaobjects/spec_metamodel/relationship.json @@ -8,7 +8,7 @@ "rules": "@cardinality is an open string at the metamodel level ('one'/'many', and Java-canonical composite forms such as 'many-to-one'); @objectRef names the target entity. M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. @onDelete/@onUpdate carry referential actions (cascade/set-null/restrict/no-action).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -24,7 +24,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Association is a plain reference — the target's lifecycle is independent (default @onDelete restrict).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -40,7 +40,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Aggregation is shared/independent — the target outlives the parent (default @onDelete set-null).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -56,7 +56,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Composition is owned lifecycle — the children do not outlive the parent (default @onDelete cascade).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, diff --git a/server/python/tests/unit/test_reference_facet.py b/server/python/tests/unit/test_reference_facet.py index 4cdce8be2d..76ecd0f81e 100644 --- a/server/python/tests/unit/test_reference_facet.py +++ b/server/python/tests/unit/test_reference_facet.py @@ -258,10 +258,32 @@ def test_the_reader_carries_a_facet_on_a_types_entry_attr() -> None: assert entry.ref.target_sub_types == ("b", "a") -def test_no_shipped_definition_file_uses_the_facet_yet() -> None: +# The seven attributes that carry a facet in the core definitions. Only core's four older +# references carry one (spec/metamodel-definitions.md, "Existing references keep their codes"), +# each naming its existing code. +_CORE_FACETS = sorted( + [ + ("field", "map", "objectRef", False, "ERR_UNRESOLVED_OBJECT_REF"), + ("field", "object", "objectRef", False, "ERR_UNRESOLVED_OBJECT_REF"), + ("identity", "reference", "references", True, "ERR_INVALID_REFERENCE"), + ("relationship", "aggregation", "objectRef", False, "ERR_INVALID_RELATIONSHIP"), + ("relationship", "association", "objectRef", False, "ERR_INVALID_RELATIONSHIP"), + ("relationship", "base", "objectRef", False, "ERR_INVALID_RELATIONSHIP"), + ("relationship", "composition", "objectRef", False, "ERR_INVALID_RELATIONSHIP"), + ] +) + + +def test_the_core_definitions_declare_exactly_the_four_core_references() -> None: registry = compose_registry(list(core_providers)) + found = [] for definition in registry._defs.values(): # noqa: SLF001 (no public iterator) - assert all(a.ref is None for a in definition.attrs), definition.key() + for a in definition.attrs: + if a.ref is not None: + assert a.ref.target_type == "object" + assert a.ref.target_sub_types is None and not a.ref.same_system + found.append((definition.type, definition.sub_type, a.name, a.ref.field_path, a.ref.error_code)) + assert sorted(found) == _CORE_FACETS assert all(a.ref is None for a in registry.get_common_attrs()) @@ -664,5 +686,7 @@ def test_the_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_ ) -def test_a_registry_with_no_facet_writes_no_ref_key() -> None: - assert '"ref"' not in emit_registry_manifest(compose_registry(list(core_providers))) +def test_an_attribute_with_no_facet_writes_no_ref_key() -> None: + # One "ref" per facet in the core definitions, and none anywhere else. + manifest = emit_registry_manifest(compose_registry(list(core_providers))) + assert manifest.count('"ref"') == len(_CORE_FACETS) diff --git a/server/rust/metaobjects/data/metamodel/field.json b/server/rust/metaobjects/data/metamodel/field.json index 46a2f064ce..7b497d901f 100644 --- a/server/rust/metaobjects/data/metamodel/field.json +++ b/server/rust/metaobjects/data/metamodel/field.json @@ -112,7 +112,7 @@ "whenToUse": "A field holds a nested structured value (or an array of them). Set @objectRef + @storage so the shape is typed and persisted (flattened/jsonb) instead of an untyped blob.", "rules": "Set @objectRef to the nested object's name (or FQN). @storage selects physical layout — flattened expands into prefixed parent columns (isArray must be false), jsonb stores the structured value (or array when isArray=true) in one jsonb column, subdocument emits no Postgres column. Defaults to single-jsonb-column when @storage is absent.", "children": [ - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { @@ -125,7 +125,7 @@ "rules": "Keys are always strings. Set exactly one of @valueType (a scalar value subtype: string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid) or @objectRef (a value-object name or FQN). Stored as a single jsonb column holding the JSON object — never a native array; isArray does not apply.", "children": [ { "type": "attr", "subType": "string", "name": "valueType", "min": 0, "max": 1, "description": "Scalar value subtype for a scalar-valued map (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). Mutually exclusive with @objectRef; exactly one of the two must be set." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { diff --git a/server/rust/metaobjects/data/metamodel/identity.json b/server/rust/metaobjects/data/metamodel/identity.json index d7ec0ebec0..4c7bbe8d67 100644 --- a/server/rust/metaobjects/data/metamodel/identity.json +++ b/server/rust/metaobjects/data/metamodel/identity.json @@ -29,7 +29,7 @@ "whenToUse": "This entity holds a foreign key to another. Declare it to generate the FK constraint + typed navigation, instead of a loose id field you join on by hand.", "children": [ { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, - { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." }, + { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity.", "ref": { "targetType": "object", "fieldPath": true, "errorCode": "ERR_INVALID_REFERENCE" } }, { "type": "attr", "subType": "boolean", "name": "enforce", "min": 0, "max": 1, "description": "When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level." } ] } diff --git a/server/rust/metaobjects/data/metamodel/relationship.json b/server/rust/metaobjects/data/metamodel/relationship.json index 0fd2d5b1a9..308c5a130d 100644 --- a/server/rust/metaobjects/data/metamodel/relationship.json +++ b/server/rust/metaobjects/data/metamodel/relationship.json @@ -8,7 +8,7 @@ "rules": "@cardinality is an open string at the metamodel level ('one'/'many', and Java-canonical composite forms such as 'many-to-one'); @objectRef names the target entity. M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. @onDelete/@onUpdate carry referential actions (cascade/set-null/restrict/no-action).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -24,7 +24,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Association is a plain reference — the target's lifecycle is independent (default @onDelete restrict).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -40,7 +40,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Aggregation is shared/independent — the target outlives the parent (default @onDelete set-null).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -56,7 +56,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Composition is owned lifecycle — the children do not outlive the parent (default @onDelete cascade).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index d01239908b..2829a3a181 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -21,8 +21,8 @@ use crate::errors::{ MetaError, }; use crate::registry::{ - AttrSchema, ChildRule, ChildSubType, ReferenceDescriptor, ReferenceFacet, SUBTYPE_BASE, - TypeDefinition, TypeRegistry, WILDCARD, + AttrSchema, ChildRule, ChildSubType, ReferenceFacet, SUBTYPE_BASE, TypeDefinition, + TypeRegistry, WILDCARD, }; pub const CORE_TYPES_ID: &str = "metaobjects-core-types"; @@ -718,26 +718,10 @@ fn register_core(registry: &mut TypeRegistry) -> Result<(), MetaError> { registry.register(def)?; } } - let reference = |attr: &str, field_path: bool, code: &str| ReferenceDescriptor { - attr: attr.to_string(), - facet: ReferenceFacet { - field_path, - ..ReferenceFacet::of("object", code) - }, - }; - for sub in registry.all_sub_types_of("relationship") { - if let Some(def) = registry.find_mut("relationship", &sub) { - def.references = vec![reference("objectRef", false, "ERR_INVALID_RELATIONSHIP")]; - } - } - if let Some(def) = registry.find_mut("identity", "reference") { - def.references = vec![reference("references", true, "ERR_INVALID_REFERENCE")]; - } - for sub in ["object", "map"] { - if let Some(def) = registry.find_mut("field", sub) { - def.references = vec![reference("objectRef", false, "ERR_UNRESOLVED_OBJECT_REF")]; - } - } + // The core references (relationship.* @objectRef, identity.reference @references, + // field.object / field.map @objectRef) are reference facets in the vendored + // data/metamodel definition files, each naming its existing code + // (spec/metamodel-definitions.md, "Existing references keep their codes"). registry.set_default_sub_type("metadata", "root")?; registry.set_default_sub_type("object", "entity")?; Ok(()) diff --git a/server/rust/metaobjects/src/validate/refs_tests.rs b/server/rust/metaobjects/src/validate/refs_tests.rs index 55b3c0af01..63570875c6 100644 --- a/server/rust/metaobjects/src/validate/refs_tests.rs +++ b/server/rust/metaobjects/src/validate/refs_tests.rs @@ -323,20 +323,70 @@ fn the_reader_carries_a_facet_on_a_types_entry_attr() { ); } +/// The seven attributes that carry a facet in the core definitions, with what each says. +/// Only core's four older references carry one (spec/metamodel-definitions.md, "Existing +/// references keep their codes"), each naming its existing code. +fn core_facets() -> Vec { + let mut v: Vec = [ + ("field.map @objectRef", false, ERR_UNRESOLVED_OBJECT_REF), + ("field.object @objectRef", false, ERR_UNRESOLVED_OBJECT_REF), + ( + "identity.reference @references", + true, + ERR_INVALID_REFERENCE, + ), + ( + "relationship.aggregation @objectRef", + false, + ERR_INVALID_RELATIONSHIP, + ), + ( + "relationship.association @objectRef", + false, + ERR_INVALID_RELATIONSHIP, + ), + ( + "relationship.base @objectRef", + false, + ERR_INVALID_RELATIONSHIP, + ), + ( + "relationship.composition @objectRef", + false, + ERR_INVALID_RELATIONSHIP, + ), + ] + .iter() + .map(|(at, field_path, code)| format!("{at} object {field_path} {code}")) + .collect(); + v.sort(); + v +} + #[test] -fn no_shipped_definition_file_uses_the_facet_yet() { +fn the_core_definitions_declare_exactly_the_four_core_references() { let r = crate::providers::default_registry().unwrap(); + let mut found = Vec::new(); for def in r.all() { for a in &def.attributes { - assert!( - a.reference.is_none(), - "{}.{} @{}", - def.type_name, - def.sub_type, - a.name - ); + if let Some(f) = &a.reference { + assert!( + f.target_sub_types.is_none() && !f.same_system && f.wrong_system_code.is_none() + ); + found.push(format!( + "{}.{} @{} {} {} {}", + def.type_name, + def.sub_type, + a.name, + f.target_type, + f.field_path, + f.error_code.as_deref().unwrap_or("-") + )); + } } } + found.sort(); + assert_eq!(found, core_facets()); assert!(r.common_attrs().iter().all(|a| a.reference.is_none())); } @@ -897,9 +947,10 @@ fn the_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_key_or } #[test] -fn a_registry_with_no_facet_writes_no_ref_key() { +fn an_attribute_with_no_facet_writes_no_ref_key() { let manifest = emit_manifest(&crate::providers::default_registry().unwrap()); - assert!(!manifest.contains("\"ref\"")); + // One `"ref"` per facet in the core definitions, and none anywhere else. + assert_eq!(manifest.matches("\"ref\"").count(), core_facets().len()); } #[test] diff --git a/server/typescript/packages/metadata/src/core-types.ts b/server/typescript/packages/metadata/src/core-types.ts index 75daf7235b..015c51729e 100644 --- a/server/typescript/packages/metadata/src/core-types.ts +++ b/server/typescript/packages/metadata/src/core-types.ts @@ -79,7 +79,7 @@ import { } from "./shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; import { OBJECT_SUBTYPES, OBJECT_SUBTYPE_ENTITY } from "./core/object/object-constants.js"; -import { FIELD_SUBTYPES, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_ATTR_OBJECT_REF } from "./core/field/field-constants.js"; +import { FIELD_SUBTYPES } from "./core/field/field-constants.js"; import { ATTR_SUBTYPES } from "./core/attr/attr-constants.js"; import { VALIDATOR_SUBTYPES, @@ -95,9 +95,8 @@ import { IDENTITY_SUBTYPE_PRIMARY, IDENTITY_SUBTYPE_SECONDARY, IDENTITY_SUBTYPE_REFERENCE, - IDENTITY_REFERENCE_ATTR_REFERENCES, } from "./core/identity/identity-constants.js"; -import { RELATIONSHIP_SUBTYPES, RELATIONSHIP_ATTR_OBJECT_REF } from "./core/relationship/relationship-constants.js"; +import { RELATIONSHIP_SUBTYPES } from "./core/relationship/relationship-constants.js"; import { LAYOUT_SUBTYPES } from "./presentation/layout/layout-constants.js"; import { SOURCE_SUBTYPES } from "./persistence/source/source-constants.js"; import { @@ -495,42 +494,10 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { registry.register(indexDef); } - // Declare the core cross-references ON their TypeDefinitions, so the loader's - // registry-derived validation resolves them generically (a dangling target fails the - // load). Set on the concrete subtypes the parser produces. (Production moves these into - // the embedded spec/metamodel JSON once every port's spec reader carries the field.) - for (const subType of RELATIONSHIP_SUBTYPES) { - const def = registry.find(TYPE_RELATIONSHIP, subType); - if (def) { - def.references = [ - { attr: RELATIONSHIP_ATTR_OBJECT_REF, targetType: TYPE_OBJECT, errorCode: "ERR_INVALID_RELATIONSHIP" }, - ]; - } - } - const idRefDef = registry.find(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE); - if (idRefDef) { - idRefDef.references = [ - { - attr: IDENTITY_REFERENCE_ATTR_REFERENCES, - targetType: TYPE_OBJECT, - fieldPath: true, - errorCode: "ERR_INVALID_REFERENCE", - }, - ]; - } - // ADR-0042 — a field.object / field.map @objectRef must resolve (a dangling - // target fails the load, closing the gap that surfaced downstream as a - // misleading ERR_VAR_NOT_ON_PAYLOAD; #191). The required-attr pass owns - // absence (ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF); this descriptor fires only - // when @objectRef is present but resolves to nothing → ERR_UNRESOLVED_OBJECT_REF. - for (const subType of [FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP]) { - const def = registry.find(TYPE_FIELD, subType); - if (def) { - def.references = [ - { attr: FIELD_ATTR_OBJECT_REF, targetType: TYPE_OBJECT, errorCode: "ERR_UNRESOLVED_OBJECT_REF" }, - ]; - } - } + // The core cross-references (relationship.* @objectRef, identity.reference + // @references, field.object / field.map @objectRef) are declared as reference + // facets in their spec/metamodel definition files, each naming its existing code + // (spec/metamodel-definitions.md, "Existing references keep their codes"). // Default subTypes for YAML authoring sugar: a bare `metadata:` / `object:` // key resolves to these. `metadata` has exactly one subtype (root) so the diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index cc1f081144..3af2c5ae31 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -208,7 +208,11 @@ export const FIELD_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." + "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization.", + "ref": { + "targetType": "object", + "errorCode": "ERR_UNRESOLVED_OBJECT_REF" + } } ] }, @@ -235,7 +239,11 @@ export const FIELD_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." + "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set.", + "ref": { + "targetType": "object", + "errorCode": "ERR_UNRESOLVED_OBJECT_REF" + } } ] }, diff --git a/server/typescript/packages/metadata/src/core/identity/identity-definition.embedded.ts b/server/typescript/packages/metadata/src/core/identity/identity-definition.embedded.ts index 42842932cf..b3396a9671 100644 --- a/server/typescript/packages/metadata/src/core/identity/identity-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/identity/identity-definition.embedded.ts @@ -79,7 +79,12 @@ export const IDENTITY_DEFINITION: ProviderDefinition = { "name": "references", "min": 1, "max": 1, - "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." + "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity.", + "ref": { + "targetType": "object", + "fieldPath": true, + "errorCode": "ERR_INVALID_REFERENCE" + } }, { "type": "attr", diff --git a/server/typescript/packages/metadata/src/core/relationship/relationship-definition.embedded.ts b/server/typescript/packages/metadata/src/core/relationship/relationship-definition.embedded.ts index 40ab7f3627..956eff5515 100644 --- a/server/typescript/packages/metadata/src/core/relationship/relationship-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/relationship/relationship-definition.embedded.ts @@ -29,7 +29,11 @@ export const RELATIONSHIP_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." + "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + } }, { "type": "attr", @@ -106,7 +110,11 @@ export const RELATIONSHIP_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." + "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + } }, { "type": "attr", @@ -183,7 +191,11 @@ export const RELATIONSHIP_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." + "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + } }, { "type": "attr", @@ -260,7 +272,11 @@ export const RELATIONSHIP_DEFINITION: ProviderDefinition = { "name": "objectRef", "min": 0, "max": 1, - "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." + "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", + "ref": { + "targetType": "object", + "errorCode": "ERR_INVALID_RELATIONSHIP" + } }, { "type": "attr", diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts index 22bd083c63..b9b8358c1d 100644 --- a/server/typescript/packages/metadata/test/definition-schema.test.ts +++ b/server/typescript/packages/metadata/test/definition-schema.test.ts @@ -62,15 +62,35 @@ describe("definition schema — the existing definition files", () => { }); } - test("no existing definition file uses the reference facet yet", () => { + test("the core definition files declare exactly the four core references, each with its existing code", () => { + // spec/metamodel-definitions.md, "Existing references keep their codes": the four + // references core once declared in code live in the definition files, and no other + // core attribute is a reference yet. + const found: string[] = []; for (const file of definitionFiles) { const doc = JSON.parse(readFileSync(join(specDir, file), "utf-8")) as { - types?: { children?: object[] }[]; - extends?: { children?: object[] }[]; + types?: { type: string; subType: string; children?: { name?: string; ref?: unknown }[] }[]; + extends?: { type: string; subType?: string; children?: { name?: string; ref?: unknown }[] }[]; }; - const children = [...(doc.types ?? []), ...(doc.extends ?? [])].flatMap((t) => t.children ?? []); - expect(children.filter((c) => "ref" in c)).toEqual([]); + for (const t of [...(doc.types ?? []), ...(doc.extends ?? [])]) { + for (const c of t.children ?? []) { + if (c.ref !== undefined) found.push(`${t.type}.${t.subType ?? "*"} @${c.name} ${JSON.stringify(c.ref)}`); + } + } } + const relationship = JSON.stringify({ targetType: "object", errorCode: "ERR_INVALID_RELATIONSHIP" }); + const objectRef = JSON.stringify({ targetType: "object", errorCode: "ERR_UNRESOLVED_OBJECT_REF" }); + expect(found.sort()).toEqual( + [ + `field.map @objectRef ${objectRef}`, + `field.object @objectRef ${objectRef}`, + `identity.reference @references ${JSON.stringify({ targetType: "object", fieldPath: true, errorCode: "ERR_INVALID_REFERENCE" })}`, + `relationship.aggregation @objectRef ${relationship}`, + `relationship.association @objectRef ${relationship}`, + `relationship.base @objectRef ${relationship}`, + `relationship.composition @objectRef ${relationship}`, + ].sort(), + ); }); }); diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index eafd131b4b..cc79f20ab6 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -20,7 +20,7 @@ import { } from "../src/provider-data.js"; import { TypeId, type TypeRegistry } from "../src/registry.js"; import { MetaData } from "../src/shared/meta-data.js"; -import { buildRegistryManifest, emitRegistryManifest } from "../src/registry-manifest.js"; +import { buildRegistryManifest } from "../src/registry-manifest.js"; import { refTarget } from "../src/naming-refs.js"; import { canonicalSerialize } from "../src/serializer-json.js"; import type { ReferenceFacet } from "../src/validation-types.js"; @@ -552,8 +552,22 @@ describe("reference facet — the registry manifest", () => { }); }); - it("a registry with no facet writes no `ref` key", () => { - const text = emitRegistryManifest(composeRegistry([...coreProviders])); - expect(text).not.toContain(`"ref"`); + it("an attribute with no facet writes no `ref` key", () => { + const manifest = buildRegistryManifest(composeRegistry([...coreProviders])); + const withRef = manifest.types.flatMap((t) => + t.attrs.filter((a) => a.ref !== undefined).map((a) => `${t.type}.${t.subType} @${a.name}`), + ); + // Only the four core references (spec/metamodel-definitions.md) carry a facet. + expect(withRef.sort()).toEqual([ + "field.map @objectRef", + "field.object @objectRef", + "identity.reference @references", + "relationship.aggregation @objectRef", + "relationship.association @objectRef", + "relationship.base @objectRef", + "relationship.composition @objectRef", + ]); + const plain = manifest.types.find((t) => t.type === "relationship" && t.subType === "association")!; + expect(Object.keys(plain.attrs.find((a) => a.name === "cardinality")!)).not.toContain("ref"); }); }); diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 058a1f857b..483590eef8 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -68,12 +68,13 @@ Rules on where the facet may appear: provider's to document; the two default codes and every code core uses are in `fixtures/conformance/ERROR-CODES.json`. -**Existing references keep their codes.** Core declares four references in TypeScript code -today (`core-types.ts`: `relationship.* @objectRef` raises `ERR_INVALID_RELATIONSHIP`, -`identity.reference @references` raises `ERR_INVALID_REFERENCE`, and `field.object` and -`field.map @objectRef` raise `ERR_UNRESOLVED_OBJECT_REF`). When they move into the definition -files, each one names its code in `errorCode`, so no fixture or adopter sees a different code. -The two default codes apply to references that are new with the facet. +**Existing references keep their codes.** Core's four older references are declared with the +facet in the definition files: `relationship.* @objectRef` raises `ERR_INVALID_RELATIONSHIP` +(`relationship.json`), `identity.reference @references` raises `ERR_INVALID_REFERENCE` +(`identity.json`, with `fieldPath`), and `field.object` and `field.map @objectRef` raise +`ERR_UNRESOLVED_OBJECT_REF` (`field.json`). They were declared in each port's code before 1.4.0; +each names its old code in `errorCode`, so no fixture or adopter sees a different code. The two +default codes apply to references that are new with the facet. **The manifest.** The registry manifest (`fixtures/registry-conformance/`) writes `ref` on an attribute only when the attribute has one, after `ports` and before `description`. Its keys come @@ -192,15 +193,15 @@ facet that sets `sameSystem` before then can never pass and no definition file s ## Status -The format and the schema are specified here. No definition file uses `ref` yet. +The format and the schema are specified here. The four core references above use `ref`; no +other definition file does yet. Ports whose spec reader reads and enforces `ref`: TypeScript, C#, Java, Kotlin, Python, Rust. +Each reads the four core references from the definition files (in Rust, from its vendored copy in +`data/metamodel/`) and declares none of them in code. -A port joins that line in its own change, while no definition file uses the facet, so no -registry output changes. A port on the line writes the facet in its registry manifest as -described above. The two default codes are in `fixtures/conformance/ERROR-CODES.json` and its +The two default codes are in `fixtures/conformance/ERROR-CODES.json` and its vendored Rust copy, and in the TypeScript, Python, Java (Kotlin shares it) and C# error-code catalogs. Rust lists only the codes it raises, so its reader change adds them there. The two -worked cases become conformance fixtures, and the four existing core references move from code -into the definition files keeping their codes, in the change that first registers vocabulary -using the facet. +worked cases become conformance fixtures in the change that first registers new vocabulary using +the facet (the four core references above are not new vocabulary). diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index 46a2f064ce..7b497d901f 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -112,7 +112,7 @@ "whenToUse": "A field holds a nested structured value (or an array of them). Set @objectRef + @storage so the shape is typed and persisted (flattened/jsonb) instead of an untyped blob.", "rules": "Set @objectRef to the nested object's name (or FQN). @storage selects physical layout — flattened expands into prefixed parent columns (isArray must be false), jsonb stores the structured value (or array when isArray=true) in one jsonb column, subdocument emits no Postgres column. Defaults to single-jsonb-column when @storage is absent.", "children": [ - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { @@ -125,7 +125,7 @@ "rules": "Keys are always strings. Set exactly one of @valueType (a scalar value subtype: string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid) or @objectRef (a value-object name or FQN). Stored as a single jsonb column holding the JSON object — never a native array; isArray does not apply.", "children": [ { "type": "attr", "subType": "string", "name": "valueType", "min": 0, "max": 1, "description": "Scalar value subtype for a scalar-valued map (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). Mutually exclusive with @objectRef; exactly one of the two must be set." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." } + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set.", "ref": { "targetType": "object", "errorCode": "ERR_UNRESOLVED_OBJECT_REF" } } ] }, { diff --git a/spec/metamodel/identity.json b/spec/metamodel/identity.json index d7ec0ebec0..4c7bbe8d67 100644 --- a/spec/metamodel/identity.json +++ b/spec/metamodel/identity.json @@ -29,7 +29,7 @@ "whenToUse": "This entity holds a foreign key to another. Declare it to generate the FK constraint + typed navigation, instead of a loose id field you join on by hand.", "children": [ { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, - { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." }, + { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity.", "ref": { "targetType": "object", "fieldPath": true, "errorCode": "ERR_INVALID_REFERENCE" } }, { "type": "attr", "subType": "boolean", "name": "enforce", "min": 0, "max": 1, "description": "When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level." } ] } diff --git a/spec/metamodel/relationship.json b/spec/metamodel/relationship.json index 0fd2d5b1a9..308c5a130d 100644 --- a/spec/metamodel/relationship.json +++ b/spec/metamodel/relationship.json @@ -8,7 +8,7 @@ "rules": "@cardinality is an open string at the metamodel level ('one'/'many', and Java-canonical composite forms such as 'many-to-one'); @objectRef names the target entity. M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. @onDelete/@onUpdate carry referential actions (cascade/set-null/restrict/no-action).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -24,7 +24,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Association is a plain reference — the target's lifecycle is independent (default @onDelete restrict).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -40,7 +40,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Aggregation is shared/independent — the target outlives the parent (default @onDelete set-null).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, @@ -56,7 +56,7 @@ "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Composition is owned lifecycle — the children do not outlive the parent (default @onDelete cascade).", "children": [ { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, - { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car').", "ref": { "targetType": "object", "errorCode": "ERR_INVALID_RELATIONSHIP" } }, { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." },