Skip to content

Commit 65a2b0a

Browse files
committed
fix(python): keep a projection's by-id route when it has an id field (FR-044)
1 parent f884621 commit 65a2b0a

4 files changed

Lines changed: 125 additions & 51 deletions

File tree

‎server/python/src/metaobjects/codegen/instance_artifacts.py‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
field was read by nothing and entity_model never consulted it, so `GenConfig` now
88
refuses to accept a value it cannot honour.
99
"""
10-
from metaobjects.meta.core.identity.identity_constants import IDENTITY_ATTR_FIELDS
1110
from metaobjects.meta.core.object.meta_object import MetaObject
1211
from metaobjects.meta.core.object.object_constants import OBJECT_SUBTYPE_REPORT
1312
from metaobjects.meta.core.reporting.report_read_model import report_read_source
@@ -65,18 +64,26 @@ def is_served_report(obj: MetaObject) -> bool:
6564

6665

6766
def has_item_route(entity: MetaObject) -> bool:
68-
"""Whether a read-only object is addressable by key: it has a primary identity over
69-
EXACTLY ONE field. A report has no identity at all, and a keyless projection has none
70-
either, so neither gets a ``/{id}`` route or a ``find_by_id`` on its repository seam
71-
(FR-044 open question 4). A composite identity has no single path parameter to bind."""
72-
identity = entity.primary_identity()
73-
if identity is None:
67+
"""Whether a read-only object gets a ``/{id}`` route, a ``find_by_id`` on its
68+
repository seam and the three item-verb refusals (FR-044 open question 4, as ruled).
69+
70+
Answer 4 removes only what could never serve a row, so the rule is:
71+
72+
* a report (the declared node or its read model) NEVER has one, even if a derived
73+
field is named ``id``: it has no identity, and a row of it is not addressable;
74+
* otherwise it has one when it declares a primary identity (a single field, or a
75+
composite one, which binds its FIRST field exactly as before this change), or when
76+
it declares NO primary identity and has an effective field named ``id`` (the
77+
default key ``pk_field_name`` falls back to);
78+
* otherwise (no identity and no ``id`` field) the route could only bind an ``int`` it
79+
cannot honour, so it is not generated.
80+
81+
Every projection whose router had a usable item route before FR-044 renders
82+
byte-identically. ADR-0039: ``children()`` / ``fields()`` resolve, so an inherited
83+
identity or ``id`` field counts.
84+
"""
85+
if entity.sub_type == OBJECT_SUBTYPE_REPORT:
7486
return False
75-
fields = identity.get_meta_attr(IDENTITY_ATTR_FIELDS) # ADR-0039: resolving (identity attr)
76-
if isinstance(fields, str):
77-
names = [n for n in (p.strip() for p in fields.split(",")) if n]
78-
elif isinstance(fields, (list, tuple)):
79-
names = [n for n in fields if isinstance(n, str) and n]
80-
else:
81-
names = []
82-
return len(names) == 1
87+
if entity.primary_identity() is not None:
88+
return True
89+
return any(f.name == "id" for f in entity.fields())

‎server/python/tests/codegen/test_projection_compile.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def _view_projection(*, keyed: bool = True) -> MetaObject:
4141
src = MetaSource(TYPE_SOURCE, SOURCE_SUBTYPE_RDB, "")
4242
src.set_attr(SOURCE_ATTR_KIND, SOURCE_KIND_VIEW, sub_type="string")
4343
o.add_child(src)
44-
o.add_child(_f("id", fc.FIELD_SUBTYPE_INT, required=True))
44+
# A keyless projection has neither a primary identity nor a field named `id`: only
45+
# then is there nothing a by-id route could bind.
46+
o.add_child(_f("id" if keyed else "code", fc.FIELD_SUBTYPE_INT, required=True))
4547
o.add_child(_f("weekCount", fc.FIELD_SUBTYPE_INT)) # non-required derived field
4648
if keyed:
4749
identity = MetaIdentity(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY, "pk")
@@ -94,9 +96,10 @@ def test_projection_router_is_read_only() -> None:
9496

9597

9698
def test_keyless_projection_router_has_no_item_routes() -> None:
97-
"""FR-044 open question 4: a projection with no single-field identity has no item
98-
address, so it gets GET list and the collection POST refusal only, and its repository
99-
seam has no ``find_by_id``. (Before, it bound an ``id: int`` it could not honour.)"""
99+
"""FR-044 open question 4 (as ruled): a projection with no primary identity AND no
100+
``id`` field has no item address, so it gets GET list and the collection POST refusal
101+
only, and its repository seam has no ``find_by_id``. (Before, it bound an ``id: int``
102+
it could not honour.)"""
100103
src = render_router(_view_projection(keyed=False))
101104
assert src is not None
102105
compile(src, "<ProgramSummary router>", "exec")

‎server/python/tests/codegen/test_report_router.py‎

Lines changed: 95 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,103 @@ def test_served_report_predicate_follows_table_a() -> None:
4848
assert is_served_report(report_read_model(_obj(root, "InvoiceStatusTotals"), root))
4949

5050

51-
def test_only_an_object_with_a_single_field_identity_has_an_item_route() -> None:
51+
def _projection(*, identity: list[str] | None, id_field: bool) -> MetaObject:
52+
from metaobjects.meta.core.field.meta_field import MetaField
53+
from metaobjects.meta.core.identity.identity_constants import (
54+
IDENTITY_ATTR_FIELDS,
55+
IDENTITY_SUBTYPE_PRIMARY,
56+
)
57+
from metaobjects.meta.core.identity.meta_identity import MetaIdentity
58+
from metaobjects.meta.persistence.source.meta_source import MetaSource
59+
from metaobjects.meta.persistence.source.source_constants import (
60+
SOURCE_ATTR_KIND,
61+
SOURCE_KIND_VIEW,
62+
SOURCE_SUBTYPE_RDB,
63+
)
64+
from metaobjects.shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_SOURCE
65+
66+
obj = MetaObject(TYPE_OBJECT, "projection", "Summary")
67+
obj.package = "acme::test"
68+
src = MetaSource(TYPE_SOURCE, SOURCE_SUBTYPE_RDB, "")
69+
src.set_attr(SOURCE_ATTR_KIND, SOURCE_KIND_VIEW, sub_type="string")
70+
obj.add_child(src)
71+
names = (["id"] if id_field else []) + ["code", "other"]
72+
for n in names:
73+
obj.add_child(MetaField(TYPE_FIELD, "int", n))
74+
if identity is not None:
75+
ident = MetaIdentity(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY, "pk")
76+
ident.set_attr(IDENTITY_ATTR_FIELDS, identity)
77+
obj.add_child(ident)
78+
return obj
79+
80+
81+
def _has_item_surface(src: str) -> bool:
82+
return (
83+
'@router.get("/{summary_id}")' in src
84+
and "def find_by_id(" in src
85+
and src.count('"error": "method_not_allowed",') == 4
86+
)
87+
88+
89+
def test_a_report_never_has_an_item_route_even_with_a_derived_field_named_id() -> None:
5290
root = _load()
91+
model = report_read_model(_obj(root, "InvoiceStatusTotals"), root)
92+
assert not has_item_route(model)
93+
assert not has_item_route(_obj(root, "InvoiceStatusTotals")) # the declared node too
5394
assert has_item_route(_obj(root, "Invoice"))
54-
assert not has_item_route(report_read_model(_obj(root, "InvoiceStatusTotals"), root))
95+
# A derived field named `id`: build a report whose dimension is `Invoice.id`.
96+
import json
97+
98+
from metaobjects.loader.meta_data_loader import MetaDataLoader
99+
from metaobjects.loader.sources import InMemoryStringSource
100+
101+
meta = json.loads((_CORPUS / "meta.json").read_text())
102+
meta["metadata.root"]["children"].append({"object.report": {
103+
"name": "ById", "@from": "Invoice", "@dimensions": ["id"], "@measures": ["invoices"],
104+
"children": [{"source.rdb": {"@kind": "view", "@view": "v_by_id"}}],
105+
}})
106+
# A dimension named after the key column: `Invoice.id` needs a dimension node.
107+
inv = next(c["object.entity"] for c in meta["metadata.root"]["children"] if "object.entity" in c)
108+
inv["children"].append({"dimension.attribute": {"name": "id", "@of": "Invoice.id"}})
109+
result = MetaDataLoader().load([InMemoryStringSource(json.dumps(meta), "meta.json")])
110+
assert not result.errors, [e.message for e in result.errors]
111+
by_id = _obj(result.root, "ById")
112+
read_model = report_read_model(by_id, result.root)
113+
assert "id" in [f.name for f in read_model.fields()]
114+
assert not has_item_route(read_model)
115+
src = render_router(read_model)
116+
assert src is not None and "find_by_id" not in src and "{" not in "".join(
117+
ln for ln in src.splitlines() if ln.startswith("@router.")
118+
)
119+
120+
121+
def test_a_projection_with_a_single_field_identity_has_the_item_surface() -> None:
122+
p = _projection(identity=["id"], id_field=True)
123+
assert has_item_route(p)
124+
assert _has_item_surface(render_router(p))
125+
126+
127+
def test_a_projection_with_an_id_field_and_no_identity_has_the_item_surface() -> None:
128+
p = _projection(identity=None, id_field=True)
129+
assert has_item_route(p)
130+
assert _has_item_surface(render_router(p))
131+
132+
133+
def test_a_composite_identity_keeps_its_item_route_bound_to_the_first_field() -> None:
134+
p = _projection(identity=["code", "other"], id_field=False)
135+
assert has_item_route(p)
136+
assert _has_item_surface(render_router(p))
137+
138+
139+
def test_a_projection_with_no_identity_and_no_id_field_is_keyless() -> None:
140+
p = _projection(identity=None, id_field=False)
141+
assert not has_item_route(p)
142+
src = render_router(p)
143+
assert src is not None
144+
decorators = re.findall(r'@router\.(\w+)\(("[^"]*")', src)
145+
assert decorators == [("get", '""'), ("post", '""')], decorators
146+
assert "find_by_id" not in src
147+
assert src.count('"error": "method_not_allowed",') == 1
55148

56149

57150
def test_report_router_has_the_collection_routes_and_no_item_route() -> None:
@@ -97,18 +190,3 @@ def test_run_gen_serves_three_reports_and_nothing_for_the_sourceless_one(tmp_pat
97190
assert f"{snake}_names.py" in files
98191
assert not any(f.startswith("invoice_days") for f in files)
99192
assert not any("invoice_days" in f for f in files)
100-
101-
102-
def test_a_composite_identity_has_no_single_path_parameter() -> None:
103-
from metaobjects.meta.core.identity.identity_constants import (
104-
IDENTITY_ATTR_FIELDS,
105-
IDENTITY_SUBTYPE_PRIMARY,
106-
)
107-
from metaobjects.meta.core.identity.meta_identity import MetaIdentity
108-
from metaobjects.shared.base_types import TYPE_IDENTITY
109-
110-
obj = MetaObject(TYPE_OBJECT, "projection", "Pair")
111-
identity = MetaIdentity(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY, "pk")
112-
identity.set_attr(IDENTITY_ATTR_FIELDS, ["a", "b"])
113-
obj.add_child(identity)
114-
assert not has_item_route(obj)

‎server/python/tests/codegen/test_router_generator.py‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,14 @@
1717
from metaobjects.codegen.runtime.filter_parser import parse_filter
1818
from metaobjects.meta.core.field.meta_field import MetaField
1919
from metaobjects.meta.core.field import field_constants as fc
20-
from metaobjects.meta.core.identity.identity_constants import (
21-
IDENTITY_ATTR_FIELDS,
22-
IDENTITY_SUBTYPE_PRIMARY,
23-
)
24-
from metaobjects.meta.core.identity.meta_identity import MetaIdentity
2520
from metaobjects.meta.core.object.meta_object import MetaObject
2621
from metaobjects.meta.persistence.source.meta_source import MetaSource
2722
from metaobjects.meta.persistence.source.source_constants import (
2823
SOURCE_ATTR_KIND,
2924
SOURCE_KIND_VIEW,
3025
SOURCE_SUBTYPE_RDB,
3126
)
32-
from metaobjects.shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_OBJECT, TYPE_SOURCE
27+
from metaobjects.shared.base_types import TYPE_FIELD, TYPE_OBJECT, TYPE_SOURCE
3328

3429

3530
def _entity(
@@ -39,7 +34,6 @@ def _entity(
3934
source_kind: str | None = "table",
4035
package: str | None = None,
4136
subtype: str = "entity",
42-
pk: bool = False,
4337
) -> MetaObject:
4438
o = MetaObject(TYPE_OBJECT, subtype, name)
4539
o.package = package
@@ -50,12 +44,6 @@ def _entity(
5044
o.add_child(src)
5145
for f in fields:
5246
o.add_child(f)
53-
if pk:
54-
# A single-field primary identity: what makes a read-only object addressable by
55-
# key (FR-044: a keyless one gets no item route).
56-
identity = MetaIdentity(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY, "pk")
57-
identity.set_attr(IDENTITY_ATTR_FIELDS, ["id"])
58-
o.add_child(identity)
5947
return o
6048

6149

@@ -142,7 +130,6 @@ def test_view_kind_gets_a_read_only_router() -> None:
142130
[_f("id", fc.FIELD_SUBTYPE_INT, required=True)],
143131
source_kind=SOURCE_KIND_VIEW,
144132
package="acme::blog",
145-
pk=True,
146133
)
147134
out = render_router(view)
148135
assert out is not None
@@ -179,7 +166,6 @@ def test_projection_subtype_gets_a_read_only_router() -> None:
179166
source_kind=SOURCE_KIND_VIEW,
180167
package="acme::sales",
181168
subtype="projection",
182-
pk=True,
183169
)
184170
out = render_router(proj)
185171
assert out is not None

0 commit comments

Comments
 (0)