diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index c2ae2489a4..1adc6c31c6 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -31,7 +31,7 @@ Preserve the following contracts exactly across all language ports: - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) - Storage attrs: `@storage` on `field.object` (with `@objectRef`) — values `flattened` / `jsonb` / `subdocument`. Unifies "owned types" (flattened storage) and "structured JSONB" (jsonb storage). Defaults to single-jsonb-column when absent (back-compat). -- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript, C#, Java (OMDB) and Kotlin (Exposed) persist it on every engine, Python on Postgres only; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). +- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript, C#, Java (OMDB), Kotlin (Exposed) and Python persist it on every engine; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). - Documentation common attrs (any node): `description`, `title`, `notes`, `deprecated`, `replacedBy`, `seeAlso`, `aliases`. Registered via the cross-language `commonAttrs` registry hook (`registerCommonAttrs` / `RegisterCommonAttrs` / `register_common_attrs` / Java `MetaDataRegistry.registerCommonAttribute` — wired in all four ports). `notes` is the internal-only rationale slot — never emitted to user-facing doc-gen (JSDoc / XML-doc / Postgres `COMMENT ON` / Mermaid prose). **The `description` / `notes` split is by CONTENT KIND, not audience** — an audience split invites writing the same content twice at two levels of politeness. `description` states what the element IS and COVERS (scope and boundary, derivable from the model); `notes` states what you had to look OUTSIDE the model to learn (evidence, citations, what breaks if it changes). Mechanical test: a sentence belongs in `notes` exactly when it would have to change because the IMPLEMENTATION changed while the model did not. `title` is a noun phrase, `summary` a one-line sentence. TS doc-gen ships all three tiers; C# ships XML-doc + COMMENT ON. See `docs/superpowers/specs/2026-05-24-documentation-provider-design.md`. **Wire format:** diff --git a/CHANGELOG.md b/CHANGELOG.md index 664bd0207b..e2c9f54863 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,29 @@ here.** Python had none. `Renderer` now strips standalone comment lines before mustache.java parses them. A template with such a line renders differently in Java, so a prompt body with one changes bytes (and its prompt-cache prefix) on upgrade. The `render-standalone-*` fixtures pin the whitespace rules. +- **Python: the entity model generator writes through the code writer (ADR-0063).** The model + modules (`.py` with `Create` and `Patch`), the shared `enums.py` and the + `_duration_wire.py` banner are built on a `PyWriter`, and `ruff` no longer runs over them, so the + bytes no longer depend on whether `ruff` is installed. Over 1,561 model modules generated from the + repository's fixtures, 1,146 are byte-identical, and the other 415 match once both versions are + put through the same `ruff` import sort and format. What moves: the standard-library and + third-party imports share one section (no blank line between `import datetime` and + `from pydantic import ...`, the writer's import order); a `Field(...)` too long for its line puts + one keyword per line; and a `field.duration` annotation too long for its line breaks inside + `Annotated[...]`. `PyWriter.gap()` asked for before the first body line now gives the two blank + lines PEP 8 sets after the imports and before a top-level class (a new `py-gap-after-imports` + writer-conformance case). For subclasses of `EntityModelGenerator` (not a stability contract, + ADR-0063 item 7): `_emit_field_lines`, `_emit_create_lines` and `_emit_patch_lines` return writer + pieces without indentation (`"name: int | None = None"`) instead of indented strings, + `_emit_cross_field_rules` returns a step that writes the method onto the writer (or `None`) instead + of lines, a new `_write_model` writes one class, and `render_entity_model` returns the finished + module rather than text for `ruff` to tidy. +- **Python: `@union` and `@grain` projections are checked at load.** A union member whose fields + differ in name, subtype, array-ness, `@column` or enum shape, a member that is the projection + itself or declares its own `@union`, `@unionAll` without `@union`, a `@grain` that does not name a + base-entity `field.object` jsonb array with `@objectRef`, an aggregate in a `@grain` view, and a + malformed `@grainOrdinal` are now `ERR_BAD_ATTR_VALUE`, as in TypeScript and C#. Python passes the + `error-projection-union-shape` and `error-projection-grain-not-object-array` fixtures. - **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone when the project keeps a hash manifest. It now does the same on the path with no manifest (output written outside the project, or a program that runs the generators with no state directory), which @@ -178,6 +201,28 @@ here.** included every filterable text field, and an int-backed (`@intValueMap`) enum is an integer column, so Postgres refused the ILIKE. Search now covers only fields whose operator band includes `like`. +- **Python: a primitive array persists on SQLite and MySQL.** The `ObjectManagerDb`'s SQLite and + MySQL dialects bound no list, so an `isArray` string, number, date, uuid or enum field could not be + written there. The column the TypeScript-owned schema gives it (`TEXT` on SQLite, `JSON` on MySQL) + now holds a JSON array, an int-backed enum's as its integers (`[5,0]`), and each element reads back + through the scalar decode. `roundtrip-int-enum-array` runs on both engines instead of being deferred. + A `field.date`, `field.time` or `field.timestamp` array was refused on write on every engine, + Postgres included (the list was parsed as one value); it is now parsed element by element. +- **Python: an unrestricted `routes` is no longer refused for objects it writes no router for.** + `metaobjects gen` refused a config that limits `filter-allowlist` (or `entity`) to some packages + while `routes` is left unlimited, whenever another package held an abstract or sourceless object, + saying `routes` covered it. `routes` writes nothing for those objects, so only the objects it + routes count now. A routed object's model still imports the abstract base it `extends`, the value + objects its fields reference and its M:N targets, so limiting `entity` away from one of those is + still refused. So is the concrete subtype of a routed discriminator base, whose `Create` and + `Patch` models the base's router imports. +- **Python: `metaobjects eject --force` no longer rewrites an identical copy.** It compares each file + with the reference before writing, and one that already matches is left alone and reported + `unchanged`. +- **Python: a reverse finder over a flattened value-object member is named by its flat key.** A + reference whose `@fields` names a member such as `address.countryId` emitted a method name with a + dot in it, which is not Python. It is now `find_plans_by_address_country`, as TypeScript names it, + so the generated finder name changes for such a model on upgrade. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` @@ -869,8 +914,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the only int-backed enum, projection and report-row enum arrays get the element converter (they read stored ints as ordinals before), and a non-required int-backed enum array is nullable. - - Python: ObjectManager maps elements on write, read and filter operands on Postgres. Its - SQLite and MySQL dialects store no primitive array, so the new scenario is deferred there. + - Python: ObjectManager maps elements on write, read and filter operands, on Postgres, SQLite + and MySQL (the last two store a JSON array of numbers). - Java: OMDB stores an int-backed enum array as a native `integer[]` on Postgres and a JSON array of numbers on SQLite, MySQL and Derby; a member with no declared integer is refused on write, and a stored integer with no member fails the read. Kotlin: the Exposed table generator emits an diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 7d8211268b..00d7319826 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -68,7 +68,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 67 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 11 Python) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 68 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 12 Python) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 0edcfb714b..b06f07283b 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -292,7 +292,7 @@ sharing the enum keeps its integer `CHECK`. The generated type is the port's lis | C# | Postgres, SQLite, MySQL | the element converter of an EF Core primitive collection; a non-required array is `IList?` | | Java | Postgres, SQLite, MySQL, Derby | the OMDB codec (`JdbcCodecs`; `PostgresDriver.nativeArrayElementType` on Postgres). A member with no declared integer is refused on write with an `SQLException` naming the field. A repository you write yourself maps each element through the generated enum's `dbValue()` and `fromDbValue(int)` | | Kotlin | Postgres, SQLite, MySQL | the generated `portableIntEnumArray(name, { toInt }, { fromInt })` column, emitted into `MetaIntEnumArrayColumnType.kt` only in a package that has such a column. Its two lambdas are generated `when` expressions, so a member with no integer is a compile error | -| Python | Postgres only | the codec in `metaobjects.runtime.values`, called by `ObjectManagerDb`. SQLite and MySQL store no primitive array in this runtime, so an enum array of either kind is Postgres-only there | +| Python | Postgres, SQLite, MySQL | the codec in `metaobjects.runtime.values`, called by `ObjectManagerDb`; the SQLite and MySQL dialects bind the array as JSON text and decode each element | The `roundtrip-int-enum-array` persistence scenario ([fixtures/persistence-conformance/README.md](../../fixtures/persistence-conformance/README.md#int-backed-enum-array-scenario)) diff --git a/docs/ports/python.md b/docs/ports/python.md index b9146d0b01..6e1d4413ac 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -171,7 +171,11 @@ never disagree about what was generated. A target whose `generators` is empty wr nothing and says so. With no `metaobjects.config.yaml` at all, `gen` and `verify --codegen` fail with exit 2 and write nothing: there is no list to run. `routes` needs `entity` and `filter-allowlist` beside it (the router imports both), and `metaobjects gen` warns when one -is missing. +is missing. A `packages` or `entities` limit on either one is refused when it leaves out an +object the routed objects import: for `filter-allowlist`, the routed objects; for `entity`, the +routed objects and the models they import (the abstract base each `extends`, the value objects +they reference, their M:N targets, and the concrete subtypes of a routed discriminator base). An +abstract or sourceless object that `routes` writes no router for needs neither. The 1.0 form `metaobjects gen --out --generators ` is not read: the metadata directory is `metadata` and each output directory is a target's `outDir`. @@ -429,8 +433,10 @@ A declared name wins over the pluralizer. Either one is snake_cased with an acro split, so `FAQs` becomes `faqs`, not `fa_qs`. The router, the API docs, the M:N routes and the collision check all read one function, `collection_segment`. The same name also gives the reverse finders: `@collectionName: CaseHistory` on an object turns -`find__by_` into `find_case_history_by_` (and `..._in`). A project that sets -neither keeps every route and finder name it has today. The shared cases are in +`find__by_` into `find_case_history_by_` (and `..._in`). A reference whose +`@fields` names a member of a flattened value object (`address.countryId`) takes that member's +flat key in ``, so the finder is `find_plans_by_address_country`, as TypeScript names it. A +project that sets neither keeps every route and finder name it has today. The shared cases are in `fixtures/naming-conformance/collection-segments.json`. ### Page size and undeclared body keys: the `api` block @@ -781,10 +787,13 @@ that file's root package, so `package` on such a node is already the full A `field.enum` with `@intValueMap` (own or inherited from a shared abstract enum) is stored as its declared integers while `ObjectManager` callers pass and receive member symbols. The codec in `metaobjects.runtime.values` (called by `ObjectManagerDb`) encodes on every write and on filter operands, and decodes on -every read. On an `isArray: true` field it does this for each element, on Postgres only (see +every read. On an `isArray: true` field it does this for each element, on every engine (see [Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays)); a null element stays a null element. An int that has no member raises `ValueError` on read, whether it is a scalar or an -array element. +array element. On SQLite and MySQL, which have no array type, the column is `TEXT` / `JSON` holding a +JSON array (`[5,0]`). This holds for every primitive array (strings, numbers, dates, uuids): each +element is written as the JSON form of what the scalar column binds and read back through the scalar +decode. ### Run-time validation @@ -1053,10 +1062,12 @@ already have it. The `[email]` extra is needed as soon as any field carries generator types that field `EmailStr`, which imports `email-validator` when the class is defined. Without it the generated module fails at import, not at `gen`. -**Note on emitted output.** Both generators run `ruff_format(content)` on the -file before writing, so the literal emitted layout may reflow whitespace -slightly vs the snippets above. Function signatures, class definitions, and -import lines are stable. +**Note on emitted output.** The entity generator lays its modules out with the +Python code writer (ADR-0063); no formatter runs over them, so what is written does +not depend on whether `ruff` is installed. The output-parser generator still runs +`ruff_format(content)` on the file until it is converted, so its literal layout may +reflow whitespace slightly vs the snippets above. Function signatures, class +definitions, and import lines are stable. ## Capability snapshot diff --git a/fixtures/writer-conformance/cases/py-gap-after-imports.json b/fixtures/writer-conformance/cases/py-gap-after-imports.json new file mode 100644 index 0000000000..a819cc6a16 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-gap-after-imports.json @@ -0,0 +1,24 @@ +{ + "description": "gap() asked for before the first body line puts two blank lines between the imports and the body, so a class or def right after the imports gets the two PEP 8 sets before a top-level definition; without it the sections stay one blank line apart.", + "dialect": "python", + "ops": [ + ["header", "# @generated by MetaObjects."], + ["use", "annotations", "__future__"], + ["use", "BaseModel", "pydantic"], + ["gap"], + ["open", "class A(BaseModel):"], + ["line", "x: int"], + ["dedent"] + ], + "expected": [ + "# @generated by MetaObjects.", + "", + "from __future__ import annotations", + "", + "from pydantic import BaseModel", + "", + "", + "class A(BaseModel):", + " x: int" + ] +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 8475365aeb..8f289a98d5 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -968,11 +968,17 @@ def _unmet_requires_by_selection( if entry is None: continue inner_filter = getattr(gen, "filter", None) - covered = [o for o in objects if not callable(inner_filter) or inner_filter(o)] + written = [o for o in objects if not callable(inner_filter) or inner_filter(o)] for dep, dep_token in zip(gens, tokens): if dep_token not in entry.requires or not isinstance(dep, SelectedGenerator): continue - gap = sorted(o.name for o in covered if not dep.selects(o)) + # Only what the written objects import from the required generator: `routes` writes + # nothing for an abstract or sourceless object, so limiting `filter-allowlist` away + # from one leaves nothing dangling, while a routed object's model still imports its + # abstract base. + needs = entry.covers.get(dep_token, lambda o, _objects: (o,)) + needed = {id(n): n for o in written for n in needs(o, objects)} + gap = sorted(n.name for n in needed.values() if not dep.selects(n)) if gap: errors.append( f"generator {token!r} requires {dep_token!r}, which is limited away from " diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 359a1f422e..3f14a45b92 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -56,18 +56,6 @@ import wiring itself (`from ._entity import `), which still needs path-resolution/import-base machinery; the config's per-target `outDir` is the prerequisite that is now in place. -## TPH body discriminator: 400, not a silent drop - -**Status:** known divergence, out of scope for the 1.2.x input patch. - -A per-subtype write route (`POST /api/auths/bridge`) validates the request body with -that subtype's model, whose discriminator accepts only the route's own value. A body -that names another subtype (`"type": "Coupon"`) is answered `400 {"error":"validation"}`. -Nothing is stored, so this is not a security hole, but the other ports drop the key -and create the row with the route's subtype. The shared -`tph-input-foreign-discriminator-dropped` scenario asserts the drop, and this port's -runner skips it with this reason (`tests/integration/test_api_contract_tph_generated.py`). - ## FR-015 stored-procedure callables are NOT generated by this port **Contract.** FR-015 gives a `source.rdb @kind: storedProc` / `tableFunction` a generated diff --git a/server/python/src/metaobjects/codegen/eject.py b/server/python/src/metaobjects/codegen/eject.py index f4df97c42f..51ddcddf14 100644 --- a/server/python/src/metaobjects/codegen/eject.py +++ b/server/python/src/metaobjects/codegen/eject.py @@ -147,8 +147,14 @@ def eject(names: list[str], root: Path, *, force: bool = False) -> EjectResult: for n in names: entry = known[n] target = owned_path(root, n) - target.write_text(ejected_source(entry), encoding="utf-8") - out.append(f"ejected {n} -> {target.relative_to(root)}") + source = ejected_source(entry) + # `--force` over a copy that already IS the reference writes nothing: an unchanged + # file is never rewritten. + if target.exists() and target.read_bytes() == source.encode("utf-8"): + out.append(f"unchanged {n} -> {target.relative_to(root)} (already the reference)") + else: + target.write_text(source, encoding="utf-8") + out.append(f"ejected {n} -> {target.relative_to(root)}") out.append(f" wire it: replace \"{n}\" in `generators` with {owned_token(entry)}") for module in entry.runtime: rt = runtime_path(root, module) diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index 1cabf29c37..c5385ff2eb 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -23,12 +23,13 @@ import re import tempfile from dataclasses import dataclass, field +from collections.abc import Iterable from typing import Callable, Mapping from metaobjects.codegen.generator import Generator from metaobjects.codegen.project_config import DEFAULT_REQUIREMENT_WITNESS_MODULE, ApiDocsConfig from metaobjects.codegen.generators.api_docs_generator import api_docs_generator -from metaobjects.codegen.generators.entity_model import entity_model +from metaobjects.codegen.generators.entity_model import entity_model, model_import_closure from metaobjects.codegen.generators.extractor_generator import extractor_generator from metaobjects.codegen.generators.filter_allowlist_generator import ( filter_allowlist_generator, @@ -55,6 +56,8 @@ from metaobjects.codegen.generators.shared_model_generator import shared_model_generator from metaobjects.codegen.generators.template_generator import template_generator from metaobjects.codegen.generators.trace_helper_generator import trace_helper_generator +from metaobjects.codegen.runtime.shared_predicates import emits_router +from metaobjects.meta.core.object.meta_object import MetaObject from metaobjects.render.verify import InMemoryProvider GeneratorTier = str # "native" | "neutral" @@ -241,6 +244,15 @@ class GeneratorEntry: #: Not gated cross-port (the manifest carries no such column); surfaced by ``--list`` #: and warned about by :func:`unsatisfied_requires`. requires: tuple[str, ...] = () + #: Per required generator, the objects of the target that one of this generator's objects + #: imports from it: ``(object, every object in the target) -> objects``. Limiting a required + #: generator away from one of those leaves a dangling import, limiting it away from any other + #: object does not. A required generator with no entry here is needed for the object itself. + #: ``routes`` writes nothing for an abstract or sourceless object, so a limit that leaves + #: those out is no gap, unless a routed object's model imports it. + covers: Mapping[str, Callable[[MetaObject, list[MetaObject]], Iterable[MetaObject]]] = field( + default_factory=dict + ) #: The settings an ``options:`` mapping on this generator's ``generators`` entry may carry. #: A generator that lists none refuses any. options: tuple[GeneratorOption, ...] = () @@ -362,6 +374,10 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: # FIELDS/OPS constants from _filter_allowlist; without either the # generated package fails at import (ModuleNotFoundError). requires=("entity", "filter-allowlist"), + covers={ + "entity": lambda o, objects: model_import_closure(o, objects) if emits_router(o) else (), + "filter-allowlist": lambda o, _objects: (o,) if emits_router(o) else (), + }, source=router_generator, runtime=_ROUTER_RUNTIME + (_EXPORT_RUNTIME,) + _SHARED_PREDICATES + (_FR010_FIELD_MAPPING, _M2M_CODEGEN), ), diff --git a/server/python/src/metaobjects/codegen/generators/entity_model.py b/server/python/src/metaobjects/codegen/generators/entity_model.py index 025d884a62..dc9e416350 100644 --- a/server/python/src/metaobjects/codegen/generators/entity_model.py +++ b/server/python/src/metaobjects/codegen/generators/entity_model.py @@ -10,6 +10,7 @@ from __future__ import annotations import re +from collections.abc import Callable from pathlib import Path from metaobjects.meta.core.field.meta_field import MetaField @@ -46,11 +47,11 @@ ) from metaobjects.shared.base_types import TYPE_ORIGIN, TYPE_VALIDATOR from metaobjects.codegen.config import GenConfig -from metaobjects.codegen.constants import GENERATED_MARKER, generated_header +from metaobjects.codegen.constants import GENERATED_MARKER, generated_header_lines from metaobjects.codegen.type_map import field_is_array, py_type_for -from metaobjects.codegen.format import ruff_format +from metaobjects.codegen.writer import CodeWriter, Piece, PyWriter, call, flat, group, str_lit from metaobjects.codegen.generator import EmittedFile, GenContext, Generator, per_entity -from metaobjects.codegen.generators.tph_plan import tph_subtype_binding +from metaobjects.codegen.generators.tph_plan import tph_plan_for, tph_subtype_binding from metaobjects.codegen.import_path import ( ModuleScope, import_line, @@ -98,10 +99,11 @@ def _is_int(value: object) -> bool: #: numbers, clock text and calendar spans, never sees a value; in JSON the canonical form is #: written (Pydantic writes ``PT5400S`` for 90 minutes). A Python-mode dump keeps the native #: ``timedelta``. -DURATION_TYPE = ( - "Annotated[datetime.timedelta, BeforeValidator(parse_duration_input), " - 'PlainSerializer(format_duration, return_type=str, when_used="json")]' -) +DURATION_TYPE: Piece = group("Annotated[", [ + "datetime.timedelta", + "BeforeValidator(parse_duration_input)", + 'PlainSerializer(format_duration, return_type=str, when_used="json")', +], "]") #: The generated package's copy of the duration codec, emitted beside the models when any of #: them has a ``field.duration`` (:func:`duration_wire_module`). A copy rather than an import of #: the installed ``metaobjects``, so the generated package runs on its own, as an owned router's @@ -131,10 +133,13 @@ def duration_wire_module() -> EmittedFile: """The ``_duration_wire.py`` module a model with a ``field.duration`` imports its codec from: ``codegen/runtime/duration_wire.py``, verbatim, under a generated header.""" src = _RUNTIME_SOURCE_DIR / "duration_wire.py" + banner = CodeWriter().line( + f"# {GENERATED_MARKER} — DO NOT EDIT. Copied from codegen/runtime/duration_wire.py: " + "edit that file and regenerate." + ) return EmittedFile( path=f"{DURATION_WIRE_MODULE}.py", - content=f"# {GENERATED_MARKER} — DO NOT EDIT. Copied from codegen/runtime/duration_wire.py: " - "edit that file and regenerate.\n" + src.read_text(encoding="utf-8"), + content=banner.to_string() + src.read_text(encoding="utf-8"), ) @@ -304,19 +309,48 @@ def _validator_constraints(field: MetaField, *, wire: bool) -> dict[str, object] def _constraint_parts(constraints: dict[str, object]) -> list[str]: - """The ``Field(...)`` constraint kwargs rendered in the stable, deterministic order.""" - return [_constraint_source(k, constraints[k]) for k in _CONSTRAINT_ORDER if k in constraints] + """The ``Field(...)`` constraint kwargs, one per keyword, in the stable order.""" + return [kw for k in _CONSTRAINT_ORDER if k in constraints for kw in _constraint_source(k, constraints[k])] -def _constraint_source(key: str, value: object) -> str: +def _constraint_source(key: str, value: object) -> list[str]: + """The keyword argument(s) one constraint becomes.""" if isinstance(value, _AsciiPattern): # json_schema_extra overrides the schema ``pattern`` (the compiled one carries the # Python-only ``\\Z`` anchor) with an ECMA-262-valid form for OpenAPI consumers. - return ( - f"{key}=re.compile({str(value)!r}, re.ASCII), " - f"json_schema_extra={{'pattern': {value.schema_pattern!r}}}" - ) - return f"{key}={value!r}" + return [ + f"{key}=re.compile({str_lit(str(value))}, re.ASCII)", + f"json_schema_extra={{{str_lit('pattern')}: {str_lit(value.schema_pattern)}}}", + ] + return [f"{key}={py_literal(value)}"] + + +def py_literal(value: object) -> str: + """*value* as Python source: strings double-quoted (:func:`str_lit`), lists and dicts + spelled item by item, anything else by ``repr``.""" + if isinstance(value, str): + return str_lit(str(value)) + if isinstance(value, list): + return "[" + ", ".join(py_literal(v) for v in value) + "]" + if isinstance(value, dict): + return "{" + ", ".join(f"{py_literal(k)}: {py_literal(v)}" for k, v in value.items()) + "}" + return repr(value) + + +def _member(name: str, annotation: Piece, value: Piece | None) -> Piece: + """A model member: ``name: annotation`` with its ``= value`` when it has one.""" + declaration = (f"{name}: ", annotation) + return declaration if value is None else (*declaration, " = ", value) + + +def _optional(type_expr: Piece) -> Piece: + return (type_expr, " | None") + + +def _field_call(parts: list[str], default: str | None = None) -> Piece: + """``Field(default=..., )``: one breakable list, so a member too long for the + line puts each keyword on its own line.""" + return call("Field", parts if default is None else [f"default={default}", *parts]) def _type_expr_for_field( @@ -326,8 +360,8 @@ def _type_expr_for_field( *, wire: bool, scope: ModuleScope = ModuleScope(), -) -> tuple[str, str | None]: - """The Python annotation text for *field* (arrays wrapped in ``list[...]``) plus the +) -> tuple[Piece, str | None]: + """The Python annotation for *field* (arrays wrapped in ``list[...]``) plus the shared-enum class name when the field resolves to one (used to render an enum default). Collects any required imports into *imports*. Shared by the create-model and patch-model emitters so both carry byte-identical typing. @@ -350,6 +384,7 @@ def _type_expr_for_field( else None ) enum_type_name: str | None = None + type_expr: Piece if shared is not None: type_name, enum_import = fr019.enum_type_and_import(shared, config, scope) imports.add(enum_import) @@ -371,13 +406,14 @@ def _type_expr_for_field( if field.sub_type == fc.FIELD_SUBTYPE_DURATION: # `wire.durations: native` leaves Pydantic's own timedelta handling in place, both ways; # `iso` holds the field to the ISO-8601 wire rule. + duration_type: Piece if wire_of(field).durations == WIRE_DURATIONS_ISO: imports.update(duration_imports(scope)) duration_type = DURATION_TYPE else: imports.add("import datetime") duration_type = "datetime.timedelta" - type_expr = f"list[{duration_type}]" if field_is_array(field) else duration_type + type_expr = ("list[", duration_type, "]") if field_is_array(field) else duration_type if field.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): # A field.object (-> VO) and a field.map with @objectRef (-> dict[str, VO]) both # reference a value-object; import its model so the emitted annotation resolves. @@ -419,36 +455,21 @@ def origin_guaranteed_non_null(field: MetaField) -> bool: return False -def _with_type_checking(imports: list[str]) -> list[str]: - """Add ``TYPE_CHECKING`` to the emitted ``typing`` import. - - Folded into the existing ``from typing import ...`` when there is one, rather than - emitted as a second line from the same module — two imports of one module is - something every linter in the ecosystem flags, and generated code an adopter has to - silence is generated code they stop trusting. - """ - for i, imp in enumerate(imports): - if imp.startswith("from typing import "): - names = sorted({*imp[len("from typing import ") :].split(", "), "TYPE_CHECKING"}) - return [*imports[:i], f"from typing import {', '.join(names)}", *imports[i + 1 :]] - return sorted([*imports, "from typing import TYPE_CHECKING"]) - - def _literal_default_expr(field: MetaField, enum_type_name: str | None) -> str: """The Python source of a literal @default: the list an array default spells, an enum member (Type.MEMBER, UPPER_CASE), or the value's own literal.""" default_raw = field.attrs().get(fc.FIELD_ATTR_DEFAULT) if field_is_array(field): - return repr(array_default(field)) + return py_literal(array_default(field)) if enum_type_name is not None: return f"{enum_type_name}.{str(default_raw).upper()}" - return repr(default_raw) + return py_literal(default_raw) def _field_line( field: MetaField, imports: set[str], config: GenConfig, scope: ModuleScope = ModuleScope() -) -> tuple[str, bool]: - """Return (source line, uses_field). Collects required imports into *imports*.""" +) -> tuple[Piece, bool]: + """Return (member, uses_field). Collects required imports into *imports*.""" type_expr, enum_type_name = _type_expr_for_field(field, imports, config, wire=False, scope=scope) required = field.attrs().get(fc.FIELD_ATTR_REQUIRED) is True # A server-side expression default (now(), gen_random_uuid(), CURRENT_TIMESTAMP) @@ -467,19 +488,20 @@ def _field_line( # origin.computed stay the conservative nullable default. mandatory = required or origin_guaranteed_non_null(field) # A field is Optional only when it is neither mandatory nor carries a @default. - annotation = type_expr if (mandatory or has_default) else f"{type_expr} | None" + annotation = type_expr if (mandatory or has_default) else _optional(type_expr) + value: Piece | None if has_default and uses_field: - assignment = f" = Field(default={default_expr}, {', '.join(parts)})" + value = _field_call(parts, default_expr) elif has_default: - assignment = f" = {default_expr}" + value = default_expr elif mandatory and uses_field: - assignment = f" = Field({', '.join(parts)})" + value = _field_call(parts) elif mandatory: - assignment = "" + value = None elif uses_field: - assignment = f" = Field(default=None, {', '.join(parts)})" + value = _field_call(parts, "None") else: - assignment = " = None" + value = "None" # Pydantic field name = field.name, ALWAYS. `@column` is the physical column name, # a different axis: it is what the persistence layer binds to, never what the model @@ -494,7 +516,7 @@ def _field_line( # lever for it: `columnNamingStrategy` applied to field.name is, because @column is # free-form — `callPurpose` + `@column: purpose_code` used to emit a field # `purpose_code`, which is neither the wire name nor derived from the field name. - return f" {field.name}: {annotation}{assignment}", uses_field + return _member(field.name, annotation, value), uses_field def _primary_identity_field_names(entity: MetaObject) -> list[str]: @@ -608,8 +630,8 @@ def _equals_literal(raw: object, when_field: MetaField, imports: set[str]) -> st return repr(float(text)) if sub in _DECIMAL_SUBTYPES and _NUMERIC_LITERAL.match(text): imports.add("from decimal import Decimal") - return f"Decimal({text!r})" - return repr(text) + return f"Decimal({str_lit(text)})" + return str_lit(text) # --- @condition: a rule is checked only where its condition is TRUE ----------- @@ -617,25 +639,37 @@ def _equals_literal(raw: object, when_field: MetaField, imports: set[str]) -> st # three-valued logic) lets the record through. The condition is generated as a small Python # expression of type ``bool | None`` (``None`` is SQL NULL); the helpers below are declared # inside the generated method, so the generated model imports nothing from MetaObjects. -_HELPER_CMP = ( - " def _cmp(a: object, b: object) -> int | None:\n" - " if a is None or b is None:\n" - " return None\n" - " try:\n" - " return (a > b) - (a < b) # type: ignore[operator]\n" - " except TypeError:\n" - " return None\n" -) -_HELPER_TRI = ( - " def _all(*v: bool | None) -> bool | None:\n" - " return False if False in v else None if None in v else True\n" - "\n" - " def _any(*v: bool | None) -> bool | None:\n" - " return True if True in v else None if None in v else False\n" - "\n" - " def _not(v: bool | None) -> bool | None:\n" - " return None if v is None else not v\n" -) +#: A piece of the generated model written straight onto the writer. +WriteStep = Callable[[PyWriter], None] + + +def _write_helper_cmp(w: PyWriter) -> None: + w.text(""" + def _cmp(a: object, b: object) -> int | None: + if a is None or b is None: + return None + try: + return (a > b) - (a < b) # type: ignore[operator] + except TypeError: + return None + """) + + +def _write_helper_tri(w: PyWriter) -> None: + w.text(""" + def _all(*v: bool | None) -> bool | None: + return False if False in v else None if None in v else True + + def _any(*v: bool | None) -> bool | None: + return True if True in v else None if None in v else False + + def _not(v: bool | None) -> bool | None: + return None if v is None else not v + """) + + +_HELPER_CMP: WriteStep = _write_helper_cmp +_HELPER_TRI: WriteStep = _write_helper_tri _CONDITION_HELPERS = (_HELPER_CMP, _HELPER_TRI) _NUMERIC_SUBTYPES = (*_INT_SUBTYPES, *_FLOAT_SUBTYPES, *_DECIMAL_SUBTYPES) EXPR_OP_IS_NULL, EXPR_OP_AND, EXPR_OP_OR = "isNull", "and", "or" @@ -682,7 +716,7 @@ class _ConditionBuilder: def __init__(self, by_name: dict[str, MetaField], imports: set[str]) -> None: self.by_name = by_name self.imports = imports - self.helpers: set[str] = set() + self.helpers: set[WriteStep] = set() def _node_field(self, node: object) -> MetaField | None: if not isinstance(node, dict): @@ -728,8 +762,8 @@ def _literal(self, value: object, kind: str, field: MetaField | None) -> str | N parser = _TEMPORAL_PARSERS.get(field.sub_type) if parser is not None: self.imports.add("import datetime") - return f"{parser}({value!r})" - return repr(value) + return f"{parser}({str_lit(value)})" + return py_literal(value) def value(self, node: object, kind: str, ref: MetaField | None) -> str | None: if not isinstance(node, dict): @@ -788,17 +822,45 @@ def condition(self, node: object) -> str | None: return None +def _raise_if(condition: str, label: str) -> WriteStep: + """``if : raise ValueError(