diff --git a/CHANGELOG.md b/CHANGELOG.md index 071a1f1458..2a7ba7d7fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1038,6 +1038,56 @@ Each item below is described in full under Security, Added, Changed or Fixed; th with a written, shrink-only allowlist) now holds Java generator source to it. No shipped Java generator uses the writer yet, so generated output does not change in this release. +- **A code writer for Python generators: `CodeWriter` and `PyWriter` in `metaobjects.codegen.writer`** + (ADR-0063). The Python port of the writer contract in `spec/code-writer.md`: the language-neutral + core (lines, blocks, blank-line requests, snippets, fit-or-break lists), run against the shared + `core` cases of `fixtures/writer-conformance/`, plus a Python dialect with its own eleven cases (imports + collected and sorted as `__future__`, absolute, relative; docstrings; suites that end by dedenting; + `gap()` for the two blank lines between top-level definitions). It is on the engine surface an + ejected generator may import (`eject.engineSurface.python.engine`). A layout check + (`tests/codegen/test_layout_ratchet.py`) parses generator source with `ast` and fails on a string + holding a line break, a string that starts with indentation, a join on a newline or an indentation + built by repeating a space; every file that still types its layout is on an allowlist that only + shrinks. The `output-prompt`, `report-export` and `filter-allowlist` generators now write through it + and no longer call `ruff`; the others convert one at a time, and `ruff_format` stays exported for + owned generators that call it. + +- **Python publishes a shared model (FR-023).** A `shared-model` generator, wired in + `metaobjects.config.yaml` like any other (`metaobjects gen --list` names its options), writes + `.metaobjects.json` and `metaobjects.pkg.json` for a consumer's `deps sync`: `name` and + `include` (required), `exclude`, `requirements`, `files` (relative to the project root; default + every metadata file of the project) and `version` (default: the nearest `pyproject.toml` or + `package.json` version, a declared input of the run). It was TypeScript, Java, Kotlin and C# + only, so a Python project ran a TypeScript generator for it. The bytes are the other ports': the + Python test runs all 15 cases of `fixtures/shared-model-conformance/` (nine publish, six + refusal), where it ran only the nine documents before. The engine is `metaobjects.shared_model` + (`build_shared_model`, `render_shared_model_files`, `SharedModelError` carrying the refusal + reason). A `generators` entry's `options` also gain a list kind, for `include`, `exclude` and + `files`. +- **Python: the `ObjectManager` splits into an abstract `ObjectManager` and a concrete + `ObjectManagerDb` (breaking).** `ObjectManager(root, driver)` no longer constructs: it raises a + `TypeError` naming `ObjectManagerDb(root, driver)`, and there is no shim. `ObjectManager` is + now the store-neutral contract (the Java `ObjectManager` / `ObjectManagerDB` shape) that + generated and hand-written code can be typed against; `ObjectManagerDb` is the DB-API + implementation on Postgres, SQLite and MySQL, with the same SQL and the same rows as before. + New with the split: `with om.transaction():` (every write in the block commits together or + rolls back together; a nested block joins the outer one), persistence listeners + (`om.add_listener(PersistenceListener)`, before and after each create, update and delete), and + `metaobjects.runtime.values`, the write and read value codecs as a public module. The drivers + (`DbApiDriver`, `PostgresDriver`, `SqliteDriver`, `MySqlDriver`) now live in + `metaobjects.runtime.drivers` and keep their `metaobjects.runtime` exports. Upgrade note: + [docs/features/migrations/python-object-manager-split.md](docs/features/migrations/python-object-manager-split.md). +- **Python: per-generator package and entity selection and generator options in + `metaobjects.config.yaml`.** A `generators` entry written as a mapping now takes `packages`, + `entities` and `options` beside `name` and `handEdits`. `packages` and `entities` limit that one + generator to part of its target; `options` hands the generator its own settings, in camelCase, + as snake_case keyword arguments. They work for a packaged generator (`report-export` takes + `maxRows`, `xmlNulls` and `csvBom`; `routes` takes `reportMaxRows`; `metaobjects gen --list` names + them) and for a team's own `module:symbol` one, whose factory or class receives them (or, if it + takes the build context, reads `ctx.options`). A package or entity the target does not hold, an + option a generator does not take, and options on a generator instance are refused with a message + that lists what is accepted, never ignored. `metaobjects-config.schema.json` carries the keys. + - **Select objects to regenerate in every port.** C# `dotnet meta gen --entities A,B` (and `verify --codegen --entities`) and, for Java and Kotlin, `mvn metaobjects:generate -Dmeta.entities=A,B` regenerate only the named objects' files, like TypeScript's @@ -1897,6 +1947,15 @@ Each item below is described in full under Security, Added, Changed or Fixed; th is kept: the services wrap it. The `.csproj` the name is read from is an input of `dotnet meta gen`'s skip key (ADR-0064), so renaming the assembly renders again. +- **Python: the `output-prompt`, `report-export` and `filter-allowlist` generators lay out their own + output** (ADR-0063). The bytes no longer depend on whether `ruff` is installed or on its version. + The files read the same, with these differences: a module docstring closes on its own line, a + broken call or set literal ends with a trailing comma, `import x` lines come before `from x import` + lines in a section, and a literal that fits 88 columns stays on one line. If you subclass + `FilterAllowlistGenerator`, `_emit_constants` now writes onto a `PyWriter` it is handed instead of + returning source lines; an override of `OutputPromptGenerator._emit_format_spec` may return text or + a writer piece. + ### Deprecated - **C#: `ValueObjectNames.Names(root)`.** A value object is never renamed, so it now returns the @@ -1905,6 +1964,16 @@ Each item below is described in full under Security, Added, Changed or Fixed; th ### Fixed +- **Python: an `origin.computed` `@expr` and a validator `@condition` accept every expression + function and the `cast` node.** The Python loader knew only `coalesce`, so a projection that used + `lower`, `greatest`, `splitPart`, `concat`, `nullif`, `length` or `{ cast, as }` was refused with + `ERR_UNKNOWN_EXPR_NODE` while the TypeScript, C#, Java and Kotlin loaders accepted it. It now + validates the same fifteen functions (arity, parameter kinds, result type), checks a cast + against the same table of what can become what (an enum stored as an integer casts to `int`, an + object never casts, a boolean casts only to `int`), and refuses in a CHECK `@condition` anything + only a view can hold (a cast, a function other than `coalesce`, a dotted path). Python-written + models are unaffected unless they used these nodes, which never loaded. + - **A credential is never filterable or sortable, in every port.** A field that declares a `view.password` and that a model also marked `@filterable` or `@sortable` was on the generated filter and sort allowlists, so a client could learn its value by probing (`filter[pinHash][eq]=...`, diff --git a/agent-context/skills/metaobjects-runtime-ui/references/python.md b/agent-context/skills/metaobjects-runtime-ui/references/python.md index de1d4870bf..dc5efe21aa 100644 --- a/agent-context/skills/metaobjects-runtime-ui/references/python.md +++ b/agent-context/skills/metaobjects-runtime-ui/references/python.md @@ -1,33 +1,40 @@ # Python server runtime -The Python runtime tier is the **`metaobjects.runtime.ObjectManager`** — a +The Python runtime tier is **`metaobjects.runtime.ObjectManagerDb`** — a metadata-driven query/CRUD engine that reads the same metadata at runtime and drives -persistence with no per-entity ORM boilerplate. It is the cross-port analog of Java's -OMDB: a method-based API (`find_by_id` / `find_many` / `count` / `create` / `update` / +persistence with no per-entity ORM boilerplate. It is the DB-API implementation of the +abstract `ObjectManager` contract and the cross-port analog of Java's `ObjectManagerDB` +(OMDB): a method-based API (`find_by_id` / `find_many` / `count` / `create` / `update` / `delete` / `relate`) that compiles a Filter dict to parameterized SQL and runs it via a pluggable driver. It is **pure data-access** (CRUD / query / codec); schema is owned by the Node `meta` migration tool, not the runtime. ## Contents -- Construct an `ObjectManager` +- Construct an `ObjectManagerDb` - CRUD + query - Return-type contract - Serving the REST contract - Physical names in your repository implementation -## Construct an `ObjectManager` +## Construct an `ObjectManagerDb` -`ObjectManager(root, driver)` takes a loaded metadata `root` plus a `PostgresDriver` -wrapping any DB-API 2 connection (pg8000 / psycopg): +`ObjectManagerDb(root, driver)` takes a loaded metadata `root` plus a driver +(`PostgresDriver`, `SqliteDriver` or `MySqlDriver`) wrapping any DB-API 2 connection +(pg8000 / psycopg for Postgres). `ObjectManager` is the abstract contract: constructing it +raises a `TypeError` naming `ObjectManagerDb`, so annotate hand-written code that only calls +the methods with `ObjectManager` and construct `ObjectManagerDb`: ```python import pg8000 from metaobjects import load_directory -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver result = load_directory("metaobjects") # same canonical JSON every port reads conn = pg8000.connect(...) # any DB-API 2 connection -om = ObjectManager(result.root, PostgresDriver(conn)) +om = ObjectManagerDb(result.root, PostgresDriver(conn)) + +with om.transaction(): # one commit for every write in the block + om.create("Author", {"name": "Ada"}) # a raise inside rolls all of it back ``` ## CRUD + query diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index cb308ba111..9aabdda1cd 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -50,7 +50,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/source-resolution-conformance/`](../fixtures/source-resolution-conformance/) | 28 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | -| [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (serializer arm: the 9 publish cases' document bytes; no publisher) | +| [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 5 | ✓ (the emitter is TS-owned) | — | — | — | — | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | @@ -66,7 +66,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) | 50 cases (31 core + 10 TypeScript + 9 Java) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 61 cases (31 core + 10 TypeScript + 9 Java + 11 Python) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | — (writer not built yet) | ✓ (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) | — | — | — | — | @@ -668,9 +668,8 @@ unless `requirements` is set, and the order of `files` does not change the bytes the manifest records the toolchain's `metamodelVersion`, so they do not move with it. **TypeScript runs all 15**, in `codegen-ts/test/shared-model-conformance.test.ts`. **Python runs -the serializer arm**: for each publish case it loads `files`, takes the nodes the pinned manifest -lists, and `serialize_shared_document` must reproduce the artifact byte for byte (and the sha256 -the manifest records). Python has no publisher, so selection and the refusals are TypeScript's. +all 15**, in `tests/conformance/test_shared_model_conformance.py`, against `metaobjects.shared_model`, +the engine its `shared-model` generator calls. **Java runs all 15**, in `metadata`'s `SharedModelConformanceTest` against the `SharedModel` engine the `shared-model` generator calls; **Kotlin** runs through that same engine and Maven goals and adds only `KotlinSharedModelGeneratorTest`. **C# runs all 15**, in `SharedModelConformanceTests`. diff --git a/docs/features/cli.md b/docs/features/cli.md index e92f5254ac..63efac777f 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -476,7 +476,13 @@ targets: # or an owned copy as "module:symbol". Nothing runs that is not listed. admin: outDir: src/generated/admin - generators: [entity] + generators: + - entity + - name: filter-allowlist # an entry may be a mapping: a generator limited to part of the target + packages: [shop::catalog] + entities: [Book] + - name: report-export # and given its own settings + options: {maxRows: 5000, xmlNulls: nil, csvBom: true} entities: [Author, Book] # optional allowlist; omit = every entity docs: outDir: docs/python # a directory of its own: another port's pages here read as drift @@ -489,6 +495,21 @@ targets: `--target ` scopes the run to a single target; `--generators ` narrows it to the declared entries named (an owned entry matches its registry name too) and refuses a name no target declares. A target whose `generators` is empty writes nothing and says so. +- **A `generators` entry may be a mapping** `{name, handEdits, packages, entities, options}`: + - `packages` (metadata packages such as `shop::catalog`) and `entities` (short object names) + limit that one generator to part of the target, inside the target's own `entities`. The + selection narrows what the generator is given, so a whole-model file it writes (shared enums, + a report writer) is built from the selected objects only. A name the target holds no object + for is refused, not skipped: a typo there would otherwise drop the generator's output and + the run would still report success. + - `options` are the generator's own settings, keyed in the camelCase every key in this file + uses (`maxRows`) and handed to the generator as snake_case keyword arguments (`max_rows`). + `metaobjects gen --list` names the options each packaged generator takes (`report-export`: + `maxRows`, `xmlNulls`, `csvBom`; `routes`: `reportMaxRows`); an option a generator does not + take is refused and the message lists the ones it does. A team's own generator (`module:symbol`) + gets them the same way: as keyword arguments to its factory or class (a `**options` factory + takes any), or, for a factory that takes the build context, as `ctx.options`, exactly as + written. A factory that takes none, and a ready-made generator instance, refuse them. - **`metaobjects verify --codegen`** — also run by bare `verify`, which adds `--templates` (see above) — regenerates the same list in memory (the exact `gen` pipeline, including the cross-target duplicate-output-path guard) and diffs each **unique diff --git a/docs/features/entities.md b/docs/features/entities.md index f31c4b276f..cc5c370043 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -314,7 +314,7 @@ public partial class AppDbContext : DbContext `metaobjects.codegen` emits one Pydantic `BaseModel` per entity (not a `@dataclass`), with a `Create` and a `Patch` input model beside it, plus a shipped FastAPI `APIRouter` (`router_generator`, FR-008 §2.3) and a shipped -`ObjectManager` runtime (`metaobjects.runtime.object_manager`) for CRUD +`ObjectManagerDb` runtime (`metaobjects.runtime.object_manager_db`, the DB-API implementation of the abstract `ObjectManager`) for CRUD against the same metadata. ```python @@ -345,9 +345,9 @@ class AuthorPatch(BaseModel): ``` ```python -from metaobjects.runtime.object_manager import ObjectManager +from metaobjects.runtime import ObjectManagerDb -om = ObjectManager(root, driver) # driver wraps a DB-API 2 connection +om = ObjectManagerDb(root, driver) # driver wraps a DB-API 2 connection; ObjectManager is the abstract contract row = om.create("Author", {"name": "Ada", "bio": None}) found = om.find_by_id("Author", row["id"]) ``` diff --git a/docs/features/metadata-dependencies.md b/docs/features/metadata-dependencies.md index 694a3183b6..c7ab4697da 100644 --- a/docs/features/metadata-dependencies.md +++ b/docs/features/metadata-dependencies.md @@ -88,7 +88,7 @@ dependency lock records what that version's shared model was when you last synce Because the snapshot is committed, only the machine that runs `sync` needs the package installed. CI, `meta gen`, `meta migrate` and every other port load the snapshot. -**What a Java or .NET publisher packs.** The `shared-model` generator writes +**What a Java or .NET publisher packs** (a Python publisher: see "A Python package" below). The `shared-model` generator writes `metaobjects.pkg.json` and `.metaobjects.json` into its output directory; the build that packages your library puts that directory at `metaobjects/` in the package. In Maven that is a resource with a target path (`shared @@ -504,8 +504,7 @@ publisher reachable. ## Publishing a dependency: `sharedModelFile()` -A publisher wires the `shared-model` generator (TypeScript, Java, Kotlin and C#; Python -consumes only) to select a subset of its own metadata by the same include/exclude scope-pattern +A publisher wires the `shared-model` generator (TypeScript, Java, Kotlin, C# and Python) to select a subset of its own metadata by the same include/exclude scope-pattern grammar `scope` already uses, and emit it as one canonical-JSON artifact plus a manifest: @@ -603,14 +602,24 @@ already do. Consumers declare `{ "name": "acme-billing", "npm": "@acme/billing-model", "dir": "metaobjects" }`. -**A Python package.** The generator is TypeScript, so a Python project runs it with the -Node `meta` it already uses for schema work. - -1. Point the target inside the importable package, and make sure the build ships the - JSON files as package data: - - ```ts - targets: { shared: { outDir: "src/acme_scheduling/metaobjects" } }, +**A Python package.** A Python project runs its own `shared-model` generator +(`metaobjects gen`); the Node `meta` writes the same bytes, so a project that still publishes +with it sees no change. + +1. Point the target inside the importable package, wire the generator in + `metaobjects.config.yaml`, and make sure the build ships the JSON files as package data: + + ```yaml + targets: + shared: + outDir: src/acme_scheduling/metaobjects + generators: + - name: shared-model + options: + name: acme-scheduling + include: ["acme::scheduling::**"] + # exclude, requirements and files are optional; files are relative to the project + # root. version defaults to the pyproject.toml [project] version below. ``` ```toml @@ -625,12 +634,11 @@ Node `meta` it already uses for schema work. acme_scheduling = ["metaobjects/*.json"] ``` - With no `version` option and no `package.json` version nearer the project root, the - generator stamps `pyproject.toml`'s static `[project]` version. If the Node project - has its own `package.json` version, or the Python package lives elsewhere in the - repository, pass `version` explicitly so the manifest carries the version consumers - install. -2. Bump the version, run `meta gen`, then build and upload as usual + With no `version` option, the Python generator stamps the nearest `pyproject.toml` + `[project]` version (or `package.json` version) at or above the project root. If the Python + package lives elsewhere in the repository, pass `version` explicitly so the manifest + carries the version consumers install. With no version found, the run fails. +2. Bump the version, run `metaobjects gen`, then build and upload as usual (`python -m build`, then `twine upload` or `uv publish`). `unzip -l dist/*.whl` shows the two files if the package data is right. @@ -684,18 +692,16 @@ Then `meta deps sync` as for any other installed package. Nothing about the regi reaches `.metaobjects/`: the lock records the transport (`npm`/`python` + `dir`), never a URL. -**TypeScript, Java, Kotlin and C# publish; TypeScript, Python, Java, Kotlin and C# consume.** +**TypeScript, Python, Java, Kotlin and C# publish and consume.** TypeScript, Python, Java, Kotlin and C# can *consume* a dependency (load its snapshot, extend it, overlay it). Java reads it at every rung of the Maven plugin's source ladder (``/``, the neutral config, the default directory), and Kotlin inherits that through the same plugin and loader, so a Spring or Kotlin build consumes a shared model with no -extra configuration. Java, Kotlin and C# can also *publish*: each ships a `shared-model` +extra configuration. Java, Kotlin, C# and Python can also *publish*: each ships a `shared-model` generator (Java and Kotlin through the Maven plugin's `metaobjects:generate`, C# through -`dotnet meta gen`; all three ejectable) that writes the artifact and manifest, byte-identical to -the TypeScript one and gated by `fixtures/shared-model-conformance/`. The Node `meta deps sync` -stays the only writer of the lock and the snapshot, in every port. A Python project that wants -to publish a shared model runs a TypeScript `sharedModelFile()` generator against its own -metadata. +`dotnet meta gen`, Python through `metaobjects gen`; all four ejectable) that writes the artifact +and manifest, byte-identical to the TypeScript one and gated by `fixtures/shared-model-conformance/`. +The Node `meta deps sync` stays the only writer of the lock and the snapshot, in every port. **C#.** `dotnet meta` reads `dependencies` from `.metaobjects/config.json` at every rung of its source ladder — C# has no native config surface, so the explicit `` form reads the @@ -831,7 +837,6 @@ but **not** built yet — do not assume any of the following exists: - **A runtime `ObjectManager` scope predicate.** Nothing at runtime refuses to serve an imported entity — "what's imported" is a load-time/codegen concept today, not a runtime one. -- **Python as a publisher** — Java, Kotlin and C# publish; Python consumes only. - **A JVM classpath read with `"commit": false`** — a Java or Kotlin build reading a dependency's artifact straight off the classpath with no committed snapshot. The committed snapshot is the only shipped path. @@ -873,7 +878,7 @@ but **not** built yet — do not assume any of the following exists: `include` / `exclude` / `files` / `requirements`, and the refusals (an empty selection, a requirement claiming a node outside the selection, a closure failure naming every `referrer → target` pair, vocabulary a consumer's toolchain does not ship). TypeScript, Java - (Kotlin through the same engine) and C# run all of it; Python runs the serializer arm. + (Kotlin through the same engine), C# and Python run all of it. ## See also diff --git a/docs/features/migrations/python-object-manager-split.md b/docs/features/migrations/python-object-manager-split.md new file mode 100644 index 0000000000..f3e846a5bc --- /dev/null +++ b/docs/features/migrations/python-object-manager-split.md @@ -0,0 +1,49 @@ +# Migration — the Python `ObjectManager` splits into `ObjectManager` and `ObjectManagerDb` (`1.3.0`) + +**Breaking, Python only, and by hand.** The class you constructed with +`ObjectManager(root, driver)` is now `ObjectManagerDb(root, driver)`. `ObjectManager` is the +abstract contract (the Java `ObjectManager` / `ObjectManagerDB` shape), and constructing it +raises a `TypeError` that names the replacement. There is no shim: an alias that quietly kept +the old constructor working would keep code written against a concrete class, which is the +coupling the split removes. + +## What to change + +| Before | After | +|---|---| +| `from metaobjects.runtime import ObjectManager` then `ObjectManager(root, driver)` | `from metaobjects.runtime import ObjectManagerDb` then `ObjectManagerDb(root, driver)` | +| `from metaobjects.runtime.object_manager import ObjectManager` | `from metaobjects.runtime.object_manager_db import ObjectManagerDb` (a type annotation that should accept any manager keeps `ObjectManager`) | +| `from metaobjects.runtime.object_manager import DbApiDriver, PostgresDriver, SelectResult` | the same names from `metaobjects.runtime` or `metaobjects.runtime.drivers` | +| `metaobjects.runtime.object_manager._coerce_write_value`, `_decode_read_value`, `_coerce_key_value`, `_coerce_filter_value` (private) | `metaobjects.runtime.values.coerce_write_value`, `decode_read_value`, `coerce_key_value`, `coerce_filter_value` (public) | + +Nothing else about the constructor changed: the driver and the loaded root are the same, and so +is every method (`create`, `insert_preserving`, `update`, `delete`, `find_by_id`, `find_many`, +`count`, `relate`, `validate`, `primary_key_field`). Hand-written code that only calls those +methods should be typed against `ObjectManager`, so it runs against any manager. + +A search that finds every site: `grep -rn "ObjectManager(" .` + +## What is new + +* **Transactions.** `with om.transaction(): ...` holds every write in the block on the + connection and commits once when the outermost block ends, or rolls all of it back when the + block raises. A block inside a block joins it (no savepoint). A write outside any block still + commits on its own, as before. `DbApiDriver.transaction()` is the same thing one level down, + for code that holds a driver and no manager. +* **Listeners.** `om.add_listener(listener)` registers a `PersistenceListener` (override only + the methods you need: `on_before_create` / `on_after_create`, `..._update`, `..._delete`). + A `before` method may raise to refuse the write. Inside a transaction an `after` method runs + before the commit, so an exception from it rolls the transaction back. +* **A contract other stores can implement.** Subclass `ObjectManager`, supply `find_many`, + `count`, `relate`, `transaction`, `_insert_row`, `_update_row` and `_delete_row`, and the + base class does the rest (report refusal, `@autoSet` stamping, listeners, `find_by_id`, + `validate`). +* **The value codecs are a module.** `metaobjects.runtime.values` holds the write and read + conversion (decimals, uuids, temporals, durations, int-backed enums, arrays of value + objects) and `@autoSet` stamping, with no SQL in it. + +## What did not change + +Reads and writes return the same rows, with the same SQL, on Postgres, SQLite and MySQL. The +persistence, API-contract and query conformance corpora run unmodified against +`ObjectManagerDb`. diff --git a/docs/features/reporting.md b/docs/features/reporting.md index 9bcc947696..7f56862391 100644 --- a/docs/features/reporting.md +++ b/docs/features/reporting.md @@ -608,7 +608,7 @@ A measure with no `@of` must declare a `@filter` or a `@segment` (rule M0); ever |---|---| | TypeScript | `ObjectManager` reads a view-backed report through a detached read model: `list` and `count`, with filter, sort and limit on the derived fields. | | Java | OMDB, the same read. | -| Python | `ObjectManager`, the same read. | +| Python | `ObjectManagerDb`, the same read. | | C# | codegen writes a keyless EF Core row class per view-backed report and maps it with `HasNoKey().ToView(...)` plus a `DbSet`. | | Kotlin | codegen writes an Exposed table object per view-backed report. | @@ -656,7 +656,7 @@ same default everywhere, set where each port sets its other generator options: | TypeScript | `routesFile({ reportMaxRows: 500 })` (and `routesFileHono`), or `reportMaxRows` on `mountReadOnlyCrudRoutes` in an owned routes file | | C# | `new RoutesGenerator { ReportMaxRows = 500 }` | | Java, Kotlin | the `reportMaxRows` generator arg (`500` in the plugin's ``) | -| Python | `router_generator(report_max_rows=500)` | +| Python | `RouterGenerator(report_max_rows=500)`, or `options: {reportMaxRows: 500}` on the `routes` entry in `metaobjects.config.yaml` | A page bound that is not usable is refused, never ignored: `limit` below 1, a negative `offset` or a value that is not an integer answers `400 { "error": "pagination.invalid_value", "param": ... }`, @@ -805,7 +805,7 @@ Postgres and MySQL, which hold the declared precision, and its `-15` twin everyw | C# (EF Core) | ✓ | ✓ | ✓ (Pomelo) | n/a | | Kotlin (Exposed) | ✓ | ✓ | ✓ | n/a | | Java (OMDB) | ✓ | ✓ | ✓ | n/a | -| Python (`ObjectManager`) | ✓ (pg8000) | ✓ (`sqlite3`) | ✓ (PyMySQL) | n/a | +| Python (`ObjectManagerDb`) | ✓ (pg8000) | ✓ (`sqlite3`) | ✓ (PyMySQL) | n/a | Each engine reads the artifact TypeScript produced for it: `canonical/schema.sqlite.sql` is the output of `meta migrate --dialect sqlite`, and `canonical/schema.mysql.sql` is the diff --git a/docs/ports/python.md b/docs/ports/python.md index 12f5c40b2e..3aaf7509e1 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -246,6 +246,16 @@ row-model field that can be null is `T | None = None`; a measure with `@default` report with no view source, or an abstract one, generates nothing. The contract is in [reporting](../features/reporting.md#how-a-report-is-served). +**Publishing a shared model.** The `shared-model` generator (FR-023) writes `.metaobjects.json` +and `metaobjects.pkg.json` for a consumer's `deps sync`, byte-identical to the other ports' and gated +by `fixtures/shared-model-conformance/` (all 15 cases). Options on its `generators` entry: `name`, +`include` (required), `exclude`, `requirements`, `files` (relative to the project root; default every +metadata file of the project) and `version` (default: the nearest `pyproject.toml` or `package.json` +version, recorded as a declared input so bumping it regenerates). The engine is +`metaobjects.shared_model` (`build_shared_model`, `render_shared_model_files`); a selection that is +empty, not closed or needs non-core vocabulary raises `SharedModelError` and fails the run. See +[metadata-dependencies.md](../features/metadata-dependencies.md#publishing-a-dependency-sharedmodelfile). + **Report export.** Add the standalone `report-export` generator to a target and the served report's list route answers `?format=csv|json|xml` ([contract](../features/api-contract.md#report-export)). It writes one shared `report_export_writer.py` (standard library only: `csv` quoting by hand, @@ -770,7 +780,7 @@ 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.object_manager` encodes on every write and on filter operands, and decodes on +`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 the array is an `integer[]` holding the ints in order: `["PUBLISHED", "DRAFT"]` is stored as `{5,0}`. An empty array stays empty, a null array stays null, and a null element stays a null element. An int that @@ -1057,6 +1067,7 @@ import lines are stable. | Entities + fields | Yes | | Relationships + FK | Loader-level yes; relationship-navigation codegen is on the roadmap | | Source kinds (table / view / storedProc) | Loader-level yes; codegen for non-`table` kinds is in progress | +| View expression functions (projection and report views) | Partial: the loader accepts the view functions and the cast node. Not yet: a dotted path in `origin.computed` `@expr`, a scalar `origin.aggregate` on a computed field, a path operand in `origin.first` `@filter`, `origin.passthrough` through a path, and a derived field on an entity with a read source. The `projection-view-vocabulary-rc21` fixture stays in the ledger | | `field.currency` / `field.enum` / `field.object` + `@storage` | Loader-level yes; codegen for `field.object` `flattened` storage is in progress | | Templates + render (FR-004) | Yes (`metaobjects.render`; Mustache, and Jinja with the `jinja` extra) | | Payload-VO codegen | Yes — the `entity` generator's model for each value object IS the payload type (ADR-0056); no separate payload generator | @@ -1067,7 +1078,7 @@ import lines are stable. | API reference docs | Yes — `api-docs` in a target's `generators`, options in the top-level `apiDocs` block (`apiSubDir`, `projectName`, `modelBaseUrl`); `metaobjects docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#python)) | | Requirement gate + requirement tests | Yes (`metaobjects verify`, on every run; `requirement-tests` emits pytest and is ejectable) | | Business-rules gate (ADR-0066, experimental) | Yes (`metaobjects verify`, on every run; see [business rules](../features/business-rules.md)) | -| Runtime metadata | Yes (`metaobjects.runtime.ObjectManager` — DB-API 2 drivers: Postgres via pg8000/psycopg, `SqliteDriver` over the standard library's `sqlite3`, `MySqlDriver` over PyMySQL with the `mysql` extra) + loader API + render engine | +| Runtime metadata | Yes (`metaobjects.runtime.ObjectManagerDb` — DB-API 2 drivers: Postgres via pg8000/psycopg, `SqliteDriver` over the standard library's `sqlite3`, `MySqlDriver` over PyMySQL with the `mysql` extra) + loader API + render engine | ## Conformance status (as of 2026-05-27) diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-runtime-ui/references/python.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-runtime-ui/references/python.md index de1d4870bf..dc5efe21aa 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-runtime-ui/references/python.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-runtime-ui/references/python.md @@ -1,33 +1,40 @@ # Python server runtime -The Python runtime tier is the **`metaobjects.runtime.ObjectManager`** — a +The Python runtime tier is **`metaobjects.runtime.ObjectManagerDb`** — a metadata-driven query/CRUD engine that reads the same metadata at runtime and drives -persistence with no per-entity ORM boilerplate. It is the cross-port analog of Java's -OMDB: a method-based API (`find_by_id` / `find_many` / `count` / `create` / `update` / +persistence with no per-entity ORM boilerplate. It is the DB-API implementation of the +abstract `ObjectManager` contract and the cross-port analog of Java's `ObjectManagerDB` +(OMDB): a method-based API (`find_by_id` / `find_many` / `count` / `create` / `update` / `delete` / `relate`) that compiles a Filter dict to parameterized SQL and runs it via a pluggable driver. It is **pure data-access** (CRUD / query / codec); schema is owned by the Node `meta` migration tool, not the runtime. ## Contents -- Construct an `ObjectManager` +- Construct an `ObjectManagerDb` - CRUD + query - Return-type contract - Serving the REST contract - Physical names in your repository implementation -## Construct an `ObjectManager` +## Construct an `ObjectManagerDb` -`ObjectManager(root, driver)` takes a loaded metadata `root` plus a `PostgresDriver` -wrapping any DB-API 2 connection (pg8000 / psycopg): +`ObjectManagerDb(root, driver)` takes a loaded metadata `root` plus a driver +(`PostgresDriver`, `SqliteDriver` or `MySqlDriver`) wrapping any DB-API 2 connection +(pg8000 / psycopg for Postgres). `ObjectManager` is the abstract contract: constructing it +raises a `TypeError` naming `ObjectManagerDb`, so annotate hand-written code that only calls +the methods with `ObjectManager` and construct `ObjectManagerDb`: ```python import pg8000 from metaobjects import load_directory -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver result = load_directory("metaobjects") # same canonical JSON every port reads conn = pg8000.connect(...) # any DB-API 2 connection -om = ObjectManager(result.root, PostgresDriver(conn)) +om = ObjectManagerDb(result.root, PostgresDriver(conn)) + +with om.transaction(): # one commit for every write in the block + om.create("Author", {"name": "Ada"}) # a raise inside rolls all of it back ``` ## CRUD + query diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index ebdba74ce3..7a946f6216 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -202,7 +202,7 @@ "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "java", "kotlin", "csharp"] + "ports": ["typescript", "java", "kotlin", "csharp", "python"] }, "form": { "concept": "Per-entity React form component over the generated Zod schema.", @@ -554,7 +554,9 @@ "metaobjects.codegen.requirement_hooks", "metaobjects.codegen.requirement_walk", "metaobjects.codegen.type_map", - "metaobjects.codegen.value_objects" + "metaobjects.codegen.value_objects", + "metaobjects.codegen.writer", + "metaobjects.shared_model" ] }, "rust": { diff --git a/fixtures/shared-model-conformance/README.md b/fixtures/shared-model-conformance/README.md index f81c9fa186..1626fc7019 100644 --- a/fixtures/shared-model-conformance/README.md +++ b/fixtures/shared-model-conformance/README.md @@ -85,9 +85,9 @@ attribute `secretHandling` of type string, not required). - **TypeScript** — all of it: select, closure, serialize, core-vocabulary re-load, manifest, and every refusal (`codegen-ts/test/shared-model-conformance.test.ts`). -- **Python** — the **serializer arm** only: load `files`, take exactly the nodes the pinned - manifest lists, and `serialize_shared_document` must reproduce the artifact byte for byte (and the - manifest's sha256). Python has no publisher (`server/python/tests/conformance/test_shared_model_conformance.py`). +- **Python** — all of it, in `server/python/tests/conformance/test_shared_model_conformance.py`, + against `metaobjects.shared_model` (`build_shared_model`, `render_shared_model_files`), the engine + the `shared-model` generator calls. The test registers the `secret-handling` provider itself. - **Java** — all of it, in `server/java/metadata` (`SharedModelConformanceTest`, against the `SharedModel` engine that the `shared-model` generator in `codegen-base` calls). - **Kotlin** — inherits the Java engine and the Maven goals; `KotlinSharedModelGeneratorTest` pins diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index c31bdc4319..5b94dc4ae0 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,7 +7,7 @@ format are in [`spec/code-writer.md`](../../spec/code-writer.md). - `cases/*.json` with `"dialect": "core"` pin the language-neutral core: indentation, blocks, blank-line requests, snippets, fit-or-break lists, line endings and the error codes. Every port's writer runs them with the options the case states. -- Cases with a language dialect (`"dialect": "typescript"`, `"dialect": "java"`) pin that +- Cases with a language dialect (`"dialect": "typescript"`, `"java"` or `"python"`) pin that language's writer: import collection and ordering, doc comments and its defaults. A runner skips the dialects that are not its own. @@ -15,7 +15,8 @@ Runners: - TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts` (`core` and `typescript`). - Java, `server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java` (`core` and `java`). +- Python, `server/python/tests/codegen/test_writer_conformance.py` (`core` and `python`). - Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core`). -The ports without a writer yet (C#, Kotlin, Python) run the `core` cases when their writers +The ports without a writer yet (C#, Kotlin) run the `core` cases when their writers land, and add cases for their own dialect beside these. diff --git a/fixtures/writer-conformance/cases/py-defaults.json b/fixtures/writer-conformance/cases/py-defaults.json new file mode 100644 index 0000000000..95b6e67f0e --- /dev/null +++ b/fixtures/writer-conformance/cases/py-defaults.json @@ -0,0 +1,70 @@ +{ + "description": "The Python dialect indents four spaces, breaks at 88 columns and puts a comma after the last item of a broken list.", + "dialect": "python", + "ops": [ + [ + "open", + "class A:" + ], + [ + "line", + "NAMES = ", + { + "list": { + "open": "[", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"", + "\"n14\"", + "\"n15\"", + "\"n16\"", + "\"n17\"", + "\"n18\"", + "\"n19\"" + ], + "close": "]" + } + } + ], + [ + "dedent" + ] + ], + "expected": [ + "class A:", + " NAMES = [", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\",", + " \"n14\",", + " \"n15\",", + " \"n16\",", + " \"n17\",", + " \"n18\",", + " \"n19\",", + " ]" + ] +} diff --git a/fixtures/writer-conformance/cases/py-doc-docstring.json b/fixtures/writer-conformance/cases/py-doc-docstring.json new file mode 100644 index 0000000000..e64ba77a7d --- /dev/null +++ b/fixtures/writer-conformance/cases/py-doc-docstring.json @@ -0,0 +1,49 @@ +{ + "description": "A one-entry docstring that fits is one line; more entries, or one that does not fit, make a block with the closing quotes on their own line. An empty entry is a blank line. Backslashes and triple quotes are escaped.", + "dialect": "python", + "ops": [ + [ + "open", + "def f():" + ], + [ + "doc", + "The value." + ], + [ + "line", + "pass" + ], + [ + "dedent" + ], + [ + "open", + "def g():" + ], + [ + "doc", + "First line.", + "", + "See \\d and \"\"\"." + ], + [ + "line", + "pass" + ], + [ + "dedent" + ] + ], + "expected": [ + "def f():", + " \"\"\"The value.\"\"\"", + " pass", + "def g():", + " \"\"\"First line.", + "", + " See \\\\d and \\\"\\\"\\\".", + " \"\"\"", + " pass" + ] +} diff --git a/fixtures/writer-conformance/cases/py-doc-trailing-quote.json b/fixtures/writer-conformance/cases/py-doc-trailing-quote.json new file mode 100644 index 0000000000..072a959b03 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-doc-trailing-quote.json @@ -0,0 +1,47 @@ +{ + "description": "A double quote at the end of a one-line docstring is escaped, so it does not join the closing quotes. In a block the closing quotes are on their own line, so the text is left as it is.", + "dialect": "python", + "ops": [ + [ + "open", + "def f():" + ], + [ + "doc", + "Says \"hi\"" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ], + [ + "open", + "def g():" + ], + [ + "doc", + "First.", + "Ends with a quote\"" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ] + ], + "expected": [ + "def f():", + " \"\"\"Says \"hi\\\"\"\"\"", + " pass", + "def g():", + " \"\"\"First.", + " Ends with a quote\"", + " \"\"\"", + " pass" + ] +} diff --git a/fixtures/writer-conformance/cases/py-error-dedent-without-open.json b/fixtures/writer-conformance/cases/py-error-dedent-without-open.json new file mode 100644 index 0000000000..7f69178ecd --- /dev/null +++ b/fixtures/writer-conformance/cases/py-error-dedent-without-open.json @@ -0,0 +1,14 @@ +{ + "description": "A dedent with no suite open is an unbalanced close.", + "dialect": "python", + "ops": [ + [ + "line", + "x = 1" + ], + [ + "dedent" + ] + ], + "error": "ERR_WRITER_UNBALANCED_CLOSE" +} diff --git a/fixtures/writer-conformance/cases/py-gap-between-top-level-definitions.json b/fixtures/writer-conformance/cases/py-gap-between-top-level-definitions.json new file mode 100644 index 0000000000..d91bd6b61c --- /dev/null +++ b/fixtures/writer-conformance/cases/py-gap-between-top-level-definitions.json @@ -0,0 +1,52 @@ +{ + "description": "gap() asks for two blank lines; a dedent keeps a pending request, so the gap survives the end of a suite. blank() after a gap does not shrink it.", + "dialect": "python", + "ops": [ + [ + "open", + "def a():" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ], + [ + "gap" + ], + [ + "open", + "def b():" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ], + [ + "gap" + ], + [ + "blank" + ], + [ + "line", + "c = 1" + ] + ], + "expected": [ + "def a():", + " pass", + "", + "", + "def b():", + " pass", + "", + "", + "c = 1" + ] +} diff --git a/fixtures/writer-conformance/cases/py-header-imports-body.json b/fixtures/writer-conformance/cases/py-header-imports-body.json new file mode 100644 index 0000000000..da61d4d02e --- /dev/null +++ b/fixtures/writer-conformance/cases/py-header-imports-body.json @@ -0,0 +1,26 @@ +{ + "description": "Header lines print first, then the imports, then the body, with one blank line between each section.", + "dialect": "python", + "ops": [ + [ + "header", + "# @generated by MetaObjects." + ], + [ + "use", + "annotations", + "__future__" + ], + [ + "line", + "x = 1" + ] + ], + "expected": [ + "# @generated by MetaObjects.", + "", + "from __future__ import annotations", + "", + "x = 1" + ] +} diff --git a/fixtures/writer-conformance/cases/py-imports-alias.json b/fixtures/writer-conformance/cases/py-imports-alias.json new file mode 100644 index 0000000000..0b78a24008 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-imports-alias.json @@ -0,0 +1,27 @@ +{ + "description": "An aliased import prints `Exported as Local`, and a module imported under an alias prints `import m as a`.", + "dialect": "python", + "ops": [ + [ + "line", + "x = np.zeros(UUID4)" + ], + [ + "useAs", + "uuid4", + "uuid", + "UUID4" + ], + [ + "useModule", + "numpy", + "np" + ] + ], + "expected": [ + "import numpy as np", + "from uuid import uuid4 as UUID4", + "", + "x = np.zeros(UUID4)" + ] +} diff --git a/fixtures/writer-conformance/cases/py-imports-collected-and-sorted.json b/fixtures/writer-conformance/cases/py-imports-collected-and-sorted.json new file mode 100644 index 0000000000..875856533f --- /dev/null +++ b/fixtures/writer-conformance/cases/py-imports-collected-and-sorted.json @@ -0,0 +1,61 @@ +{ + "description": "Imports used anywhere in the body print first: __future__, then absolute modules, then relative ones, with a blank line between the sections. In a section the plain `import m` lines come first, then the `from m import` lines, each in code-point order; names in code-point order.", + "dialect": "python", + "ops": [ + [ + "line", + "x = 1" + ], + [ + "use", + "Path", + "pathlib" + ], + [ + "use", + "annotations", + "__future__" + ], + [ + "use", + "BaseModel", + "pydantic" + ], + [ + "use", + "Field", + "pydantic" + ], + [ + "use", + "helper", + ".helper" + ], + [ + "use", + "Alpha", + "..alpha" + ], + [ + "useModule", + "json" + ], + [ + "useModule", + "zlib" + ] + ], + "expected": [ + "from __future__ import annotations", + "", + "import json", + "import zlib", + "from pathlib import Path", + "from pydantic import BaseModel, Field", + "", + "from ..alpha import Alpha", + "from .helper import helper", + "", + "x = 1" + ] +} diff --git a/fixtures/writer-conformance/cases/py-imports-conflict.json b/fixtures/writer-conformance/cases/py-imports-conflict.json new file mode 100644 index 0000000000..a276e4f518 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-imports-conflict.json @@ -0,0 +1,17 @@ +{ + "description": "One local name imported from two modules is an error, not a silent shadow.", + "dialect": "python", + "ops": [ + [ + "use", + "Row", + "a" + ], + [ + "use", + "Row", + "b" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} diff --git a/fixtures/writer-conformance/cases/py-imports-long-list-breaks.json b/fixtures/writer-conformance/cases/py-imports-long-list-breaks.json new file mode 100644 index 0000000000..126f18d443 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-imports-long-list-breaks.json @@ -0,0 +1,46 @@ +{ + "description": "An import line past 88 columns breaks into a parenthesised list, one name per line with a trailing comma; one name never breaks.", + "dialect": "python", + "ops": [ + [ + "line", + "x = 1" + ], + [ + "use", + "AlphaAlphaAlpha", + "a_rather_long_module_name.with.a.long.path" + ], + [ + "use", + "BetaBetaBeta", + "a_rather_long_module_name.with.a.long.path" + ], + [ + "use", + "GammaGammaGamma", + "a_rather_long_module_name.with.a.long.path" + ], + [ + "use", + "DeltaDeltaDelta", + "a_rather_long_module_name.with.a.long.path" + ], + [ + "use", + "Only", + "another_rather_long_module_name.with.a.long.path.that.is.even.longer.than.the.first.one" + ] + ], + "expected": [ + "from a_rather_long_module_name.with.a.long.path import (", + " AlphaAlphaAlpha,", + " BetaBetaBeta,", + " DeltaDeltaDelta,", + " GammaGammaGamma,", + ")", + "from another_rather_long_module_name.with.a.long.path.that.is.even.longer.than.the.first.one import Only", + "", + "x = 1" + ] +} diff --git a/fixtures/writer-conformance/cases/py-suite-open-at-end-ends-there.json b/fixtures/writer-conformance/cases/py-suite-open-at-end-ends-there.json new file mode 100644 index 0000000000..308f703ea0 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-suite-open-at-end-ends-there.json @@ -0,0 +1,18 @@ +{ + "description": "A suite still open when the file is finished ends there: Python needs no closing token.", + "dialect": "python", + "ops": [ + [ + "open", + "def f():" + ], + [ + "line", + "pass" + ] + ], + "expected": [ + "def f():", + " pass" + ] +} diff --git a/server/python/README.md b/server/python/README.md index b1f293e1c5..1fdb287fe7 100644 --- a/server/python/README.md +++ b/server/python/README.md @@ -45,7 +45,7 @@ The primary public API is the **loader** (`load_directory` / `load_uris` / distribution also ships the Python implementations of the other pillars used by the CLI and tooling: `codegen` (Pydantic + FastAPI emit — reference generators you own: `metaobjects eject ` copies one into your repo), `render` (Mustache, or Jinja with -`pip install metaobjects[jinja]` — ADR-0061 — + payload-VO + verify), and `runtime` (a DB-API 2 `ObjectManager` — pg8000 / psycopg on Postgres, the standard library's `sqlite3` on SQLite, PyMySQL on MySQL 8 (`pip install metaobjects[mysql]`) — no SQLAlchemy). +`pip install metaobjects[jinja]` — ADR-0061 — + payload-VO + verify), and `runtime` (an abstract `ObjectManager` and its DB-API 2 implementation `ObjectManagerDb` — pg8000 / psycopg on Postgres, the standard library's `sqlite3` on SQLite, PyMySQL on MySQL 8 (`pip install metaobjects[mysql]`) — no SQLAlchemy). Schema migrations are owned by the TypeScript `meta` CLI (ADR-0015); there is **no `migrate` module** in this distribution. @@ -54,7 +54,7 @@ Schema migrations are owned by the TypeScript `meta` CLI (ADR-0015); there is Table and column names are one project setting, `naming` in `.metaobjects/config.json` (`columns` and `tables`, each `snake_case` by default or `literal`). `metaobjects gen` and `verify` read it, and so do `load_directory`, `load_uris` and `load_string(..., project_dir=...)`: -they search upward from the metadata directory for that file, so the `ObjectManager` queries the +they search upward from the metadata directory for that file, so the `ObjectManagerDb` queries the names the code was generated for. If you keep a database whose columns are named exactly like the fields, add `"naming": { "columns": "literal" }`. With no config file found the loader warns once and uses `snake_case`; `metaobjects.naming.attach_naming(root, project_dir)` sets it explicitly and diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 0f82b625dd..8475365aeb 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -64,7 +64,7 @@ import re import sys from pathlib import Path -from typing import Any, Callable +from typing import Any, Callable, Mapping from metaobjects import MetaDataLoader from metaobjects.errors import ErrorCode, MetaError, ParseError @@ -126,11 +126,17 @@ from metaobjects.codegen.project_config import ( CONFIG_FILENAME, ConfigError, + GeneratorSettings, ProjectConfig, TargetConfig, load_project_config, ) -from metaobjects.codegen.generator import Generator, generator_cacheable, generator_extra_inputs +from metaobjects.codegen.generator import ( + Generator, + SelectedGenerator, + generator_cacheable, + generator_extra_inputs, +) from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model from metaobjects.codegen.generators.extractor_generator import extractor_generator @@ -151,6 +157,7 @@ RequirementTestsOptions, get_generator, list_generators, + resolve_options, unsatisfied_requires, ) from metaobjects.codegen.project_import import import_project_symbol @@ -160,7 +167,7 @@ from metaobjects.codegen.generators.render_helper_generator import ( _derive_payload_field_tree, ) -from metaobjects.codegen.value_objects import bound_payload_vo +from metaobjects.codegen.value_objects import bound_payload_vo, pkg_of from metaobjects.meta.template import template_constants as tc from metaobjects.naming import ( COLUMN_NAMING_STRATEGIES, @@ -803,6 +810,24 @@ def _refuse_column_naming_flag(args: argparse.Namespace) -> str | None: return "error: " + removed_naming_source_message("--column-naming", flag) +def _build_context_for_project( + template_root: str, + config: ProjectConfig, + collection: Collection, + providers: list[object], +) -> GeneratorBuildContext: + """The context every generator factory of ``gen`` and ``verify --codegen`` is built with: + the template root, the project's directory and its own metadata files (never a dependency's + artifact), and the consumer providers the run loaded the model with. One definition, so the + two commands build a generator identically.""" + return GeneratorBuildContext( + template_root, + project_root=str(project_root_for(config.metadata_dir())), + source_files=tuple(str(p) for p in collection.own_files), + providers=tuple(providers), + ) + + def _template_root_for_config(args: argparse.Namespace, config: ProjectConfig) -> tuple[str, str | None]: """``(template root, refusal)`` for a config-driven run: ``templates`` in the config, else :func:`_template_root_for`. A ``--templates`` (``gen``) or ``--prompts`` (``verify``) that @@ -823,6 +848,7 @@ def _template_root_for_config(args: argparse.Namespace, config: ProjectConfig) - def _resolve_generators( names: str, ctx: GeneratorBuildContext | None = None, owned_root: Path | None = None, + settings: Mapping[str, GeneratorSettings] | None = None, ) -> tuple[list[Generator], list[str]]: """Resolve a comma-separated list of STABLE generator names via the registry. @@ -838,17 +864,24 @@ def _resolve_generators( absent entirely: the registry hardcoded ``template_root="templates"``, so ``--templates`` reached the template-spec pass and nothing else, and selecting ``render-helper`` read a directory the user had never named. + + *settings* is a target's ``generator_settings``: an entry's ``options`` are checked against + what the generator takes and reach its factory, packaged or owned. An option it does not + take is an error, not a silent drop. """ if ctx is None: ctx = GeneratorBuildContext() + settings = settings or {} requested = [n.strip() for n in names.split(",") if n.strip()] gens: list[Generator] = [] errors: list[str] = [] selected: list[str] = [] for n in requested: entry = get_generator(n) + raw_options = settings[n].options if n in settings else {} if entry is None and (":" in n or "." in n): - gen, err = owned.build_owned(n, owned_root or Path.cwd(), ctx) + gen, err = owned.build_owned( + n, owned_root or Path.cwd(), dataclasses.replace(ctx, options=raw_options)) if err is not None: errors.append(err) continue @@ -859,7 +892,11 @@ def _resolve_generators( known = ", ".join(sorted(GENERATOR_REGISTRY)) errors.append(f"unknown generator {n!r}; known: {known}") continue - gens.append(entry.factory(ctx)) + kwargs, option_errors = resolve_options(n, entry.options, raw_options) + if option_errors: + errors.extend(option_errors) + continue + gens.append(entry.factory(dataclasses.replace(ctx, options=kwargs))) selected.append(n) if not errors and not gens: errors.append("no generators selected (empty --generators list)") @@ -869,6 +906,81 @@ def _resolve_generators( return gens, errors +def _apply_generator_selection( + gens: list[Generator], target: TargetConfig, root: MetaData, +) -> tuple[list[Generator], list[str]]: + """Limit each generator to the ``packages`` / ``entities`` its entry declares. + + ``gens`` is in the order of ``target.generators`` (one generator per entry). A name that + matches nothing in the model is refused, the way an unknown option is: a typo here would + otherwise drop a generator's output and the run would still report success.""" + if not target.generator_settings: + return gens, [] + # ADR-0039 sanctioned own: top-level object scan on the loader ROOT (never extended). + objects = [ + c for c in root.own_children() if c.type == TYPE_OBJECT and isinstance(c, MetaObject) + ] + in_target = [o for o in objects if target.entities is None or o.name in target.entities] + known_entities = {o.name for o in in_target} + known_packages = {pkg_of(o) for o in in_target} + out: list[Generator] = [] + errors: list[str] = [] + for gen, token in zip(gens, target.generators or []): + picked = target.generator_settings.get(token) + if picked is None or not picked.selects: + out.append(gen) + continue + missing_entities = sorted(set(picked.entities or ()) - known_entities) + missing_packages = sorted(set(picked.packages or ()) - known_packages) + if missing_entities: + errors.append( + f"generator {token!r}: entities {missing_entities} name no object in this target; " + f"it declares {sorted(known_entities)}" + ) + if missing_packages: + errors.append( + f"generator {token!r}: packages {missing_packages} hold no object in this target; " + f"it has {sorted(known_packages)}" + ) + if missing_entities or missing_packages: + continue + out.append(SelectedGenerator( + gen, + frozenset(picked.packages) if picked.packages is not None else None, + frozenset(picked.entities) if picked.entities is not None else None, + )) + if not errors: + errors.extend(_unmet_requires_by_selection(out, target.generators or [], in_target)) + return out, errors + + +def _unmet_requires_by_selection( + gens: list[Generator], tokens: list[str], objects: list[MetaObject], +) -> list[str]: + """One error per generator that covers an object a generator it ``requires`` is selected away from. + + ``routes`` imports the filter allowlist of every object it routes; limit ``filter-allowlist`` + to one entity and the other routers import a module nobody wrote, which ``gen`` would only + show as an ImportError in the generated package.""" + errors: list[str] = [] + for gen, token in zip(gens, tokens): + entry = get_generator(token) + 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)] + 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)) + if gap: + errors.append( + f"generator {token!r} requires {dep_token!r}, which is limited away from " + f"{gap}; limit {token!r} to the same packages/entities, or lift the limit" + ) + return errors + + def _parse_entities(value: str | None) -> list[str] | None: """Parse a comma-separated ``--entities`` value into a name list (``None`` = no filter = generate every entity). Blank names are dropped.""" @@ -1190,6 +1302,8 @@ def _cmd_list(_args: argparse.Namespace) -> int: if verdict is not None: for path, status in verdict[1]: print(f" runtime {path.as_posix()} [{status}]") + for option in entry.options: + print(f" option {option.name}: {option.description}") for path, status in owned.runtime_status(root): print(f"runtime {path.as_posix()} [owned — {status}]") return 0 @@ -1674,10 +1788,15 @@ def selected(gen: Generator, token: str) -> bool: continue if t.generators: gens, gen_errors = _resolve_generators( - ",".join(t.generators), ctx, owned_root=config.config_dir) + ",".join(t.generators), ctx, owned_root=config.config_dir, + settings=t.generator_settings) if gen_errors: errors.extend(f"target '{t.name}': {m}" for m in gen_errors) continue + gens, select_errors = _apply_generator_selection(gens, t, root) + if select_errors: + errors.extend(f"target '{t.name}': {m}" for m in select_errors) + continue overwrite = frozenset( g.name for g, tok in zip(gens, t.generators) if tok in t.overwrite_hand_edits ) @@ -2085,7 +2204,7 @@ def _cmd_gen_config_run(args: argparse.Namespace, state: _SkipState) -> int: refused_out=refused, select=collection.in_scope, in_ledger=collection.in_ledger, - build_ctx=GeneratorBuildContext(template_root), + build_ctx=_build_context_for_project(template_root, config, collection, providers), column_naming=column_naming, selection=selection, targeted_out=targeted, @@ -2511,7 +2630,7 @@ def compare(naming: str) -> tuple[list[str], list[_DirReport]]: regen = dict( select=collection.in_scope, in_ledger=collection.in_ledger, - build_ctx=GeneratorBuildContext(template_root), + build_ctx=_build_context_for_project(template_root, config, collection, providers), # R31: the `names` generator's constants are strategy-dependent, so the regen # must use the strategy `gen` wrote with, or every constant reads as drift. column_naming=naming, diff --git a/server/python/src/metaobjects/codegen/constants.py b/server/python/src/metaobjects/codegen/constants.py index 7399300483..634084cedb 100644 --- a/server/python/src/metaobjects/codegen/constants.py +++ b/server/python/src/metaobjects/codegen/constants.py @@ -1,9 +1,28 @@ """Codegen-wide constants. The @generated marker drives the overwrite policy.""" from __future__ import annotations +from .writer import CodeWriter + GENERATED_MARKER = "@generated by metaobjects" +def generated_header_lines(entity_name: str, fqn: str) -> list[str]: + """The three banner lines of every emitted module, without line endings. A generator + on :class:`~metaobjects.codegen.writer.PyWriter` passes them to ``header(...)``.""" + return [ + f"# {GENERATED_MARKER} — DO NOT EDIT.", + f"# Source metadata: {entity_name} ({fqn})", + f"# Extend in your own module (e.g. {entity_name}_extra.py) — nothing imports it for you.", + ] + + +def _as_text(lines: list[str]) -> str: + w = CodeWriter() + for ln in lines: + w.line(ln) + return w.to_string() + + def generated_header(entity_name: str, fqn: str) -> str: """Line-1 header for every emitted module. Detected by the overwrite policy. @@ -15,11 +34,7 @@ def generated_header(entity_name: str, fqn: str) -> str: convention as it actually works. Keep this line and ``codegen-ts/src/constants.ts``'s ``sidecarLine`` saying the same thing. """ - return ( - f"# {GENERATED_MARKER} — DO NOT EDIT.\n" - f"# Source metadata: {entity_name} ({fqn})\n" - f"# Extend in your own module (e.g. {entity_name}_extra.py) — nothing imports it for you.\n" - ) + return _as_text(generated_header_lines(entity_name, fqn)) def generated_package_init() -> str: @@ -31,7 +46,9 @@ def generated_package_init() -> str: the overwrite policy re-writes it on regen and refuses to clobber a hand-authored ``__init__.py`` (which lacks the marker). """ - return ( - f"# {GENERATED_MARKER} — DO NOT EDIT.\n" - f"# Package marker so the generated output directory is importable.\n" + return _as_text( + [ + f"# {GENERATED_MARKER} — DO NOT EDIT.", + "# Package marker so the generated output directory is importable.", + ] ) diff --git a/server/python/src/metaobjects/codegen/eject.py b/server/python/src/metaobjects/codegen/eject.py index 39f613418a..f4df97c42f 100644 --- a/server/python/src/metaobjects/codegen/eject.py +++ b/server/python/src/metaobjects/codegen/eject.py @@ -49,6 +49,7 @@ GENERATOR_REGISTRY, GeneratorBuildContext, GeneratorEntry, + snake_case_option, ) from metaobjects.codegen.project_import import import_project_symbol @@ -372,15 +373,39 @@ def build_owned(spec: str, root: Path, ctx: GeneratorBuildContext) -> tuple[Gene required = [p for p in params.values() if p.default is inspect.Parameter.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)] + # `options:` on the entry reach a factory as keyword arguments (camelCase key -> + # snake_case name). A factory that takes the build context reads them from + # `ctx.options` as written instead; one that takes neither is refused the options. + takes_ctx = len(required) == 1 and "template_root" not in params + kwargs: dict[str, object] = {} + if ctx.options and not takes_ctx: + kwargs = {snake_case_option(k): v for k, v in ctx.options.items()} + if not any(p.kind is p.VAR_KEYWORD for p in params.values()): + named = { + n for n, p in params.items() + if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY) + } + unknown = sorted(k for k in ctx.options if snake_case_option(k) not in named) + if unknown: + takes = ", ".join(sorted(named)) or "none" + return None, ( + f"generator {spec!r}: {symbol}() takes no option(s) " + f"{', '.join(repr(k) for k in unknown)}; it takes: {takes}" + ) try: if "template_root" in params: - obj = obj(template_root=ctx.template_root or tempfile.gettempdir()) - elif len(required) == 1: + obj = obj(template_root=ctx.template_root or tempfile.gettempdir(), **kwargs) + elif takes_ctx: obj = obj(ctx) else: - obj = obj() + obj = obj(**kwargs) except Exception as exc: return None, f"generator {spec!r}: factory {symbol}() raised: {exc}" + elif ctx.options: + return None, ( + f"generator {spec!r}: {symbol!r} is a generator instance, which takes no options; " + "make it a factory or a class so the options reach it" + ) if not hasattr(obj, "generate") or not hasattr(obj, "name"): return None, f"generator {spec!r}: {symbol!r} is not a generator (needs name and generate)" return obj, None diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 19fe33addb..e240580736 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -72,6 +72,53 @@ class Generator(Protocol): def generate(self, ctx: GenContext) -> list[EmittedFile]: ... +class SelectedGenerator: + """A generator limited to some packages and objects: the ``packages`` / ``entities`` of its + ``generators`` entry in ``metaobjects.config.yaml``. + + It is the wrapped generator with one thing changed, its ``filter`` (the predicate the + runner reads into ``ctx.matches``): the wrapped generator's own filter, if it has one, + AND-ed with the selection. So the selection can only narrow, and it narrows a whole-model + file the generator writes (shared enums, a report writer) the same way as a per-object + one: the file is built from the objects the generator is selected for. Every other + attribute (``name``, ``cacheable``, ``declared_extra_inputs``, whatever an owned + generator adds) is the wrapped generator's. + """ + + def __init__( + self, + inner: "Generator", + packages: frozenset[str] | None, + entities: frozenset[str] | None, + ) -> None: + self._inner = inner + self._packages = packages + self._entities = entities + # Bound per instance, not defined on the class: this wrapper is not a generator of its + # own (no registry entry builds one, nothing ejects it), and the generator census + # counts every class that has a `generate` method. + self.generate = inner.generate + + def __getattr__(self, attr: str) -> object: + # Only reached for what this class does not define: delegate to the wrapped generator. + return getattr(self._inner, attr) + + @property + def inner(self) -> "Generator": + return self._inner + + def selects(self, entity: MetaObject) -> bool: + from metaobjects.codegen.value_objects import pkg_of + + return (self._entities is None or entity.name in self._entities) and ( + self._packages is None or pkg_of(entity) in self._packages + ) + + def filter(self, entity: MetaObject) -> bool: + inner_filter = getattr(self._inner, "filter", None) + return self.selects(entity) and (not callable(inner_filter) or bool(inner_filter(entity))) + + def generator_cacheable(gen: object) -> bool: """Whether a run that includes ``gen`` may be skipped when nothing changed.""" return bool(getattr(gen, "cacheable", True)) diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index b1cc10dc62..1cabf29c37 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -20,9 +20,10 @@ """ from __future__ import annotations +import re import tempfile -from dataclasses import dataclass -from typing import Callable +from dataclasses import dataclass, field +from typing import Callable, Mapping from metaobjects.codegen.generator import Generator from metaobjects.codegen.project_config import DEFAULT_REQUIREMENT_WITNESS_MODULE, ApiDocsConfig @@ -51,6 +52,7 @@ RUNTIME_MODULES as _ROUTER_RUNTIME, router_generator, ) +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.render.verify import InMemoryProvider @@ -75,6 +77,92 @@ GeneratorLayer = str # one of GENERATOR_LAYERS +@dataclass(frozen=True) +class GeneratorOption: + """One setting a packaged generator takes in ``options:`` on its ``generators`` entry. + + ``name`` is the camelCase key the config file uses (every key in that file is camelCase); + the generator receives it as the snake_case keyword argument :attr:`kwarg`. ``kind`` is + ``integer``, ``boolean``, ``string`` or ``stringList`` (a list of non-empty strings); + ``choices`` closes a string, ``minimum`` bounds an integer.""" + + name: str + kind: str + description: str + choices: tuple[str, ...] | None = None + minimum: int | None = None + #: A generator that cannot run without it: ``resolve_options`` refuses an entry that + #: leaves it out, naming it, instead of the run failing (or doing nothing) later. + required: bool = False + + @property + def kwarg(self) -> str: + return snake_case_option(self.name) + + def coerce(self, value: object) -> tuple[object, str | None]: + """``(value, None)`` when ``value`` is acceptable, else ``(None, why)``.""" + if self.kind == "boolean": + if isinstance(value, bool): + return value, None + return None, "must be true or false" + if self.kind == "integer": + if isinstance(value, bool) or not isinstance(value, int): + return None, "must be a whole number" + if self.minimum is not None and value < self.minimum: + return None, f"must be at least {self.minimum}" + return value, None + if self.kind == "stringList": + if ( + not isinstance(value, list) + or not all(isinstance(v, str) and v for v in value) + ): + return None, "must be a list of non-empty strings" + if self.required and not value: + return None, "must list at least one name" + return tuple(value), None + if not isinstance(value, str) or not value: + return None, "must be a non-empty string" + if self.choices is not None and value not in self.choices: + return None, f"must be one of {', '.join(self.choices)}" + return value, None + + +_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])([A-Z])") + + +def snake_case_option(name: str) -> str: + """``maxRows`` -> ``max_rows``: how an option key of the config file becomes the keyword + argument a generator takes. A key with no capital is returned as it is.""" + return _CAMEL_BOUNDARY.sub(r"_\1", name).lower() + + +def resolve_options( + generator: str, accepted: tuple[GeneratorOption, ...], raw: Mapping[str, object] +) -> tuple[dict[str, object], list[str]]: + """Check a ``generators`` entry's ``options`` against what the packaged generator takes. + + Returns ``(keyword arguments, errors)``. A name the generator does not take is an error + that lists the names it does, so a misspelling names its own fix.""" + errors: list[str] = [] + known = {o.name: o for o in accepted} + kwargs: dict[str, object] = {} + for key, value in raw.items(): + option = known.get(key) + if option is None: + takes = ", ".join(sorted(known)) if known else "none" + errors.append(f"generator {generator!r} takes no option {key!r}; options: {takes}") + continue + coerced, why = option.coerce(value) + if why is not None: + errors.append(f"generator {generator!r} option {key!r} {why}, got {value!r}") + continue + kwargs[option.kwarg] = coerced + for option in accepted: + if option.required and option.name not in raw: + errors.append(f"generator {generator!r} needs the option {option.name!r}: {option.description}") + return kwargs, errors + + @dataclass(frozen=True) class RequirementTestsOptions: """The ``requirementTests`` config block, RESOLVED: ``renderer`` and ``filter`` are the @@ -115,6 +203,21 @@ class GeneratorBuildContext: #: The ``apiDocs`` block of ``metaobjects.config.yaml``. ``None`` = no block (or #: ``--list``): the ``api-docs`` generator uses its defaults. api_docs: ApiDocsConfig | None = None + #: The ``options`` of the ``generators`` entry being built, already checked and renamed to + #: the keyword arguments the generator takes (``maxRows`` -> ``max_rows``). Empty when the + #: entry has none, and for ``--list``. A team's own factory that takes this context reads + #: the entry's options here exactly as written. + options: Mapping[str, object] = field(default_factory=dict) + #: The project directory (the one holding ``.metaobjects/``), absolute. ``None`` for + #: ``--list``. A generator that reads a file the model does not name (the shared-model + #: publisher's ``files`` and version) resolves it here. + project_root: str | None = None + #: The project's OWN metadata files, absolute (never a dependency's artifact). ``None`` + #: for ``--list``. The shared-model publisher's default ``files``. + source_files: tuple[str, ...] | None = None + #: The consumer providers the run loaded the project with (``providers:`` of the config and + #: ``--provider``), so a generator that loads files of its own sees the same vocabulary. + providers: tuple[object, ...] = () @dataclass(frozen=True) @@ -138,6 +241,9 @@ 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, ...] = () + #: The settings an ``options:`` mapping on this generator's ``generators`` entry may carry. + #: A generator that lists none refuses any. + options: tuple[GeneratorOption, ...] = () #: The packaged factory an adopter copies with ``metaobjects eject`` (ADR-0034 #: Amendment 3). Its module is the file copied; its name is the ``module:symbol`` #: symbol the copy is wired by. ``None`` = not ejectable (the ``template`` primitive @@ -245,7 +351,13 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: description="Per-entity REST endpoint surface (controllers / routes / router).", tier="native", layer="api", - factory=lambda _ctx: router_generator(), + factory=lambda ctx: router_generator(**ctx.options), + options=( + GeneratorOption( + "reportMaxRows", "integer", minimum=1, + description="The row cap of a served report's list route.", + ), + ), # The router imports Create/Patch from the entity module and the # FIELDS/OPS constants from _filter_allowlist; without either the # generated package fails at import (ModuleNotFoundError). @@ -262,9 +374,38 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: ), tier="native", layer="api", - factory=lambda _ctx: report_export_generator(), + factory=lambda ctx: report_export_generator(**ctx.options), + options=( + GeneratorOption( + "maxRows", "integer", minimum=1, + description="The most rows one export holds (default 100000).", + ), + GeneratorOption( + "xmlNulls", "string", choices=("empty", "nil"), + description="How XML writes a null: an empty element, or xsi:nil.", + ), + GeneratorOption( + "csvBom", "boolean", description="Start a CSV with a byte order mark (default false).", + ), + ), source=report_export_generator, ), + "shared-model": GeneratorEntry( + name="shared-model", + description="A publisher's flattened shared-model artifact plus the manifest that pins it, for a consumer's `deps sync` (FR-023).", + tier="native", + layer="capability", + factory=shared_model_generator, + options=( + GeneratorOption("name", "string", required=True, description="The dependency key a consumer syncs under; also the artifact's basename."), + GeneratorOption("include", "stringList", required=True, description="Scope patterns of the top-level nodes to publish, e.g. acme::common::**."), + GeneratorOption("exclude", "stringList", description="Scope patterns removed from the selection after include."), + GeneratorOption("requirements", "boolean", description="Also publish the selected requirement.* nodes (default false)."), + GeneratorOption("files", "stringList", description="Which of the project's metadata files may contribute, relative to the project root (default: all of them)."), + GeneratorOption("version", "string", description="The published version (default: the nearest pyproject.toml or package.json version)."), + ), + source=shared_model_generator, + ), "output-parser": GeneratorEntry( name="output-parser", description="Per-template response parser: a strict parse that rejects a reply not matching the @responseRef shape, plus a tolerant, never-raising extract_lenient.", diff --git a/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py b/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py index 54043d43c9..8a15bb2539 100644 --- a/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py +++ b/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py @@ -34,8 +34,8 @@ from __future__ import annotations from metaobjects.apidocs.naming import snake_case as _snake_case -from metaobjects.codegen.constants import generated_header -from metaobjects.codegen.format import ruff_format +from metaobjects.codegen.constants import generated_header_lines +from metaobjects.codegen.writer import PyWriter, call, group, str_lit from metaobjects.codegen.name_claims import claimed_module_path from metaobjects.codegen.value_objects import pkg_of from metaobjects.codegen.generator import EmittedFile, GenContext, Generator, per_entity @@ -253,29 +253,26 @@ def add(f: MetaField) -> None: def _emit_constants( self, + w: PyWriter, fields_const: str, ops_const: str, ops_by_field: dict[str, tuple[str, ...]], - ) -> list[str]: - """The ``_FILTER_FIELDS`` frozenset + ``_FILTER_OPS_BY_FIELD`` - dict literal lines. Override to change the emitted data-structure shape.""" - lines: list[str] = [] + ) -> None: + """Write the ``_FILTER_FIELDS`` frozenset + ``_FILTER_OPS_BY_FIELD`` + dict literal onto ``w``. Override to change the emitted data-structure shape.""" if not ops_by_field: - lines.append(f"{fields_const}: frozenset[str] = frozenset()") - lines.append("") - lines.append(f"{ops_const}: dict[str, frozenset[str]] = {{}}") - else: - lines.append(f"{fields_const}: frozenset[str] = frozenset({{") - for name in ops_by_field: - lines.append(f' "{name}",') - lines.append("})") - lines.append("") - lines.append(f"{ops_const}: dict[str, frozenset[str]] = {{") - for name, ops in ops_by_field.items(): - ops_literal = ", ".join(f'"{op}"' for op in ops) - lines.append(f' "{name}": frozenset({{{ops_literal}}}),') - lines.append("}") - return lines + w.line(f"{fields_const}: frozenset[str] = frozenset()") + w.blank() + w.line(f"{ops_const}: dict[str, frozenset[str]] = {{}}") + return + names = group("{", [str_lit(n) for n in ops_by_field], "}") + w.line(f"{fields_const}: frozenset[str] = ", call("frozenset", [names])) + w.blank() + entries = [ + [str_lit(name), ": ", call("frozenset", [group("{", [str_lit(op) for op in ops], "}")])] + for name, ops in ops_by_field.items() + ] + w.line(f"{ops_const}: dict[str, frozenset[str]] = ", group("{", entries, "}")) def render_filter_allowlist( self, entity: MetaObject, object_index: dict[str, MetaObject] | None = None @@ -312,18 +309,17 @@ def render_filter_allowlist( ops_by_field = self._compute_filterable_ops(entity, object_index) - parts: list[str] = [] - parts.append( - generated_header(short_name, _effective_fqn(entity)).rstrip() + "\n" - + f'"""GENERATED — per-entity FR-009 filter allowlist for {short_name}.\n\n' - f"{fields_const} lists the filterable field names; {ops_const}\n" - f'constrains the operator vocabulary for each field by its subtype."""\n' + w = PyWriter() + w.header(*generated_header_lines(short_name, _effective_fqn(entity))) + w.module_doc( + f"GENERATED — per-entity FR-009 filter allowlist for {short_name}.", + "", + f"{fields_const} lists the filterable field names; {ops_const}", + "constrains the operator vocabulary for each field by its subtype.", ) - parts.append("from __future__ import annotations") - parts.append("") - parts.extend(self._emit_constants(fields_const, ops_const, ops_by_field)) - parts.append("") - return "\n".join(parts) + w.use_future() + self._emit_constants(w, fields_const, ops_const, ops_by_field) + return w.to_string() def generate(self, ctx: GenContext) -> list[EmittedFile]: index = build_object_index(ctx.entities) @@ -339,7 +335,7 @@ def emit(entity: MetaObject, c: GenContext) -> list[EmittedFile]: c.claims, c.config, pkg_of(entity), f"{snake}_filter_allowlist", entity.resolution_key(), ), - content=ruff_format(source), + content=source, ) ] diff --git a/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py b/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py index fc19de4e92..e74001827e 100644 --- a/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py +++ b/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py @@ -24,8 +24,8 @@ from collections.abc import Callable from metaobjects.apidocs.naming import snake_case as _snake_case -from metaobjects.codegen.constants import generated_header -from metaobjects.codegen.format import ruff_format +from metaobjects.codegen.constants import generated_header_lines +from metaobjects.codegen.writer import Piece, PyWriter, str_lit from metaobjects.codegen.name_claims import claimed_module_path from metaobjects.codegen.value_objects import pkg_of from metaobjects.codegen.generator import EmittedFile, GenContext, Generator @@ -43,10 +43,11 @@ def _emit_format_spec( payload: MetaObject, template: MetaData, root_name: str -) -> str: - """The baked ``OutputFormatSpec`` literal. Module-level back-compat shim; the - override seam is :meth:`OutputPromptGenerator._emit_format_spec`.""" - return ofs.spec_literal(payload, template, root_name) +) -> Piece: + """The baked ``OutputFormatSpec`` literal, as a writer piece (it breaks one field per + line when it does not fit). Module-level back-compat shim; the override seam is + :meth:`OutputPromptGenerator._emit_format_spec`, which may return plain text too.""" + return ofs.spec_piece(payload, template, root_name) def render_output_prompt( @@ -78,7 +79,7 @@ def render_output_prompt( # fragment and extract() agree on the root element/object. root_name = payload.name emit_spec = generator._emit_format_spec if generator is not None else _emit_format_spec - spec_literal = emit_spec(payload, template, root_name) + spec_literal = emit_spec(payload, template, root_name) # a str or a writer piece fqn = ( f"{payload.package}::{template_name}" @@ -86,38 +87,30 @@ def render_output_prompt( else template_name ) - lines: list[str] = [ - generated_header(template_name, fqn), - "from __future__ import annotations\n", - "from metaobjects.render import (", - " PROMPT_OVERRIDES_NONE,", - " FieldKind,", - " Format,", - " OutputFormatSpec,", - " PromptField,", - " PromptOverrides,", - " PromptStyle,", - " render_output_format,", - ")", + w = PyWriter() + w.header(*generated_header_lines(template_name, fqn)) + w.use_future() + for name in ( + "PROMPT_OVERRIDES_NONE", "FieldKind", "Format", "OutputFormatSpec", "PromptField", + "PromptOverrides", "PromptStyle", "render_output_format", + ): + w.use(name, "metaobjects.render") + w.line("# FR-010 artifact 1 — the baked response-format descriptor for this prompt.") + w.line("_SPEC: OutputFormatSpec = ", spec_literal) + w.gap() + w.open(f"def {render_fn}(overrides: PromptOverrides | None = None) -> str:") + w.doc( + 'The response-format instruction fragment ("produce your answer like this").', "", - "", - "# FR-010 artifact 1 — the baked response-format descriptor for this prompt.", - f"_SPEC: OutputFormatSpec = {spec_literal}", - "", - "", - f"def {render_fn}(overrides: PromptOverrides | None = None) -> str:", - ' """The response-format instruction fragment ("produce your answer like this").', - "", - " A comment-free guide / inline / example-only fragment teaching an LLM how to", - " shape its answer. Pass ``overrides`` to swap the style or override a field's", - ' example / instruction at render time."""', - " return render_output_format(_SPEC, overrides or PROMPT_OVERRIDES_NONE)", - "", - "", - f'__all__ = ["{render_fn}"]', - "", - ] - return "\n".join(lines) + "A comment-free guide / inline / example-only fragment teaching an LLM how to", + "shape its answer. Pass ``overrides`` to swap the style or override a field's", + "example / instruction at render time.", + ) + w.line("return render_output_format(_SPEC, overrides or PROMPT_OVERRIDES_NONE)") + w.dedent() + w.gap() + w.line(f"__all__ = [{str_lit(render_fn)}]") + return w.to_string() class OutputPromptGenerator: @@ -133,7 +126,7 @@ def __init__(self, *, filter: Callable[[MetaObject], bool] | None = None) -> Non def _emit_format_spec( self, payload: MetaObject, template: MetaData, root_name: str - ) -> str: + ) -> Piece: """EXTENSION SEAM — the baked ``OutputFormatSpec`` literal. Defaults to the module-level :func:`_emit_format_spec`; override to inject custom field examples / instructions / style into the prompt fragment descriptor.""" @@ -164,7 +157,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: ctx.claims, ctx.config, pkg_of(tmpl), f"{_snake_case(tmpl.name)}_response_format", tmpl.resolution_key(), ), - content=ruff_format(content), + content=content, ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/report_export_generator.py b/server/python/src/metaobjects/codegen/generators/report_export_generator.py index 3d74154c6f..9c137522a8 100644 --- a/server/python/src/metaobjects/codegen/generators/report_export_generator.py +++ b/server/python/src/metaobjects/codegen/generators/report_export_generator.py @@ -37,10 +37,10 @@ from __future__ import annotations from metaobjects.apidocs.naming import snake_case as _snake_case -from metaobjects.codegen.constants import generated_header -from metaobjects.codegen.format import ruff_format +from metaobjects.codegen.constants import generated_header_lines +from metaobjects.codegen.writer import PyWriter, call, group, str_lit from metaobjects.codegen.generator import EmittedFile, GenContext, Generator -from metaobjects.codegen.import_path import ModuleScope, import_line +from metaobjects.codegen.import_path import ModuleScope from metaobjects.codegen.instance_artifacts import is_served_report from metaobjects.codegen.name_claims import claimed_module_path from metaobjects.codegen.value_objects import pkg_of @@ -65,102 +65,6 @@ _STRING_SUBTYPES = frozenset({fc.FIELD_SUBTYPE_STRING, fc.FIELD_SUBTYPE_ENUM, fc.FIELD_SUBTYPE_URI}) _JSON_SUBTYPES = frozenset({fc.FIELD_SUBTYPE_MAP, fc.FIELD_SUBTYPE_OBJECT}) -_WRITER_SOURCE = '''\ -"""GENERATED shared writers for report export: CSV and XML. Standard library only. - -Rows are lists of dicts in wire form (what the JSON export writes). A column is -``ExportColumn(name, kind)``: ``"string"`` cells get the formula-injection guard in CSV, -``"scalar"`` cells never do, ``"json"`` cells (arrays, maps, objects) are written as compact JSON. -""" -from __future__ import annotations - -import json -import re -from collections.abc import Iterable, Mapping, Sequence -from dataclasses import dataclass -from typing import Any -from xml.sax.saxutils import escape, quoteattr - -#: The export cap: more rows than this is ``400 export_too_large``, never a truncated body. -EXPORT_MAX_ROWS = {max_rows} -#: Write a UTF-8 byte order mark before the CSV header row. -EXPORT_CSV_BOM = {csv_bom} -#: How a null is written in XML: ``"empty"`` (an empty element) or ``"nil"`` (``xsi:nil="true"``). -EXPORT_XML_NULLS = "{xml_nulls}" - -XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance" - -#: A string cell starting with one of these is prefixed with an apostrophe. -_INJECTION_START = ("=", "+", "-", "@", "\\t", "\\r") -#: Characters XML 1.0 cannot carry at all. -_XML_ILLEGAL = re.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\ufffe\\uffff]") - - -@dataclass(frozen=True) -class ExportColumn: - name: str - kind: str # "string" | "scalar" | "json" - - -def wire_text(value: Any) -> str: - """The text of one wire-form value: null is empty, a boolean is true/false.""" - if value is None: - return "" - if isinstance(value, bool): - return "true" if value else "false" - if isinstance(value, (dict, list)): - return json.dumps(value, separators=(",", ":"), ensure_ascii=False) - return str(value) - - -def csv_cell(text: str, guard: bool) -> str: - """One CSV field: the injection guard (string cells only), then quoting.""" - if guard and text.startswith(_INJECTION_START): - text = "'" + text - if any(c in text for c in '",\\r\\n'): - return '"' + text.replace('"', '""') + '"' - return text - - -def write_csv(columns: Sequence[ExportColumn], rows: Iterable[Mapping[str, Any]]) -> str: - """RFC 4180: a header row of the column names, CRLF after every record including the last.""" - out = ["\\ufeff" if EXPORT_CSV_BOM else ""] - out.append(",".join(csv_cell(c.name, False) for c in columns) + "\\r\\n") - for row in rows: - out.append( - ",".join(csv_cell(wire_text(row.get(c.name)), c.kind == "string") for c in columns) - + "\\r\\n" - ) - return "".join(out) - - -def xml_text(text: str) -> str: - """Element text: illegal characters replaced, & < > escaped, CR and LF as references.""" - return escape(_XML_ILLEGAL.sub("\\ufffd", text), {{"\\r": " ", "\\n": " "}}) - - -def write_xml(root: str, columns: Sequence[ExportColumn], rows: Iterable[Mapping[str, Any]]) -> str: - """``value......``: no declaration, no indentation.""" - nil = EXPORT_XML_NULLS == "nil" - out = [f"<{{root}}" + (f" xmlns:xsi={{quoteattr(XSI_NAMESPACE)}}" if nil else "")] - body: list[str] = [] - for row in rows: - body.append("") - for c in columns: - value = row.get(c.name) - if value is None: - body.append(f'<{{c.name}} xsi:nil="true"/>' if nil else f"<{{c.name}}/>") - else: - body.append(f"<{{c.name}}>{{xml_text(wire_text(value))}}") - body.append("") - if body: - out.append(">" + "".join(body) + f"") - else: - out.append("/>") - return "".join(out) -''' - - def _column_kind(field: MetaField) -> str: if field_is_array(field) or field.sub_type in _JSON_SUBTYPES: return "json" @@ -187,31 +91,149 @@ def __init__( self.csv_bom = csv_bom def render_writer(self) -> str: - return _WRITER_SOURCE.format( - max_rows=self.max_rows, csv_bom=repr(bool(self.csv_bom)), xml_nulls=self.xml_nulls + """The shared module: the options as constants, then the CSV and XML writers, which + are fixed runtime code written as snippets.""" + w = PyWriter() + w.header(*generated_header_lines("report-export", "metaobjects::report-export")) + w.module_doc( + "GENERATED shared writers for report export: CSV and XML. Standard library only.", + "", + "Rows are lists of dicts in wire form (what the JSON export writes). A column is", + '``ExportColumn(name, kind)``: ``"string"`` cells get the formula-injection guard in CSV,', + '``"scalar"`` cells never do, ``"json"`` cells (arrays, maps, objects) are written as ' + "compact JSON.", + ) + w.use_future() + w.use_module("json") + w.use_module("re") + for name in ("Iterable", "Mapping", "Sequence"): + w.use(name, "collections.abc") + w.use("dataclass", "dataclasses") + w.use("Any", "typing") + w.use("escape", "xml.sax.saxutils") + w.use("quoteattr", "xml.sax.saxutils") + w.line("#: The export cap: more rows than this is ``400 export_too_large``, never a truncated body.") + w.line(f"EXPORT_MAX_ROWS = {self.max_rows}") + w.line("#: Write a UTF-8 byte order mark before the CSV header row.") + w.line(f"EXPORT_CSV_BOM = {bool(self.csv_bom)!r}") + w.line('#: How a null is written in XML: ``"empty"`` (an empty element) or ``"nil"`` (``xsi:nil="true"``).') + w.line(f"EXPORT_XML_NULLS = {str_lit(self.xml_nulls)}") + w.blank() + w.line('XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"') + w.blank() + w.line("#: A string cell starting with one of these is prefixed with an apostrophe.") + w.line('_INJECTION_START = ("=", "+", "-", "@", "\\t", "\\r")') + w.line("#: Characters XML 1.0 cannot carry at all.") + w.line('_XML_ILLEGAL = re.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\ufffe\\uffff]")') + w.gap() + w.text( + r''' + @dataclass(frozen=True) + class ExportColumn: + name: str + kind: str # "string" | "scalar" | "json" + ''' ) + w.gap() + w.text( + r''' + def wire_text(value: Any) -> str: + """The text of one wire-form value: null is empty, a boolean is true/false.""" + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (dict, list)): + return json.dumps(value, separators=(",", ":"), ensure_ascii=False) + return str(value) + ''' + ) + w.gap() + w.text( + r''' + def csv_cell(text: str, guard: bool) -> str: + """One CSV field: the injection guard (string cells only), then quoting.""" + if guard and text.startswith(_INJECTION_START): + text = "'" + text + if any(c in text for c in '",\r\n'): + return '"' + text.replace('"', '""') + '"' + return text + ''' + ) + w.gap() + w.text( + r''' + def write_csv(columns: Sequence[ExportColumn], rows: Iterable[Mapping[str, Any]]) -> str: + """RFC 4180: a header row of the column names, CRLF after every record including the last.""" + out = ["\ufeff" if EXPORT_CSV_BOM else ""] + out.append(",".join(csv_cell(c.name, False) for c in columns) + "\r\n") + for row in rows: + out.append( + ",".join(csv_cell(wire_text(row.get(c.name)), c.kind == "string") for c in columns) + + "\r\n" + ) + return "".join(out) + ''' + ) + w.gap() + w.text( + r''' + def xml_text(text: str) -> str: + """Element text: illegal characters replaced, & < > escaped, CR and LF as references.""" + return escape(_XML_ILLEGAL.sub("\ufffd", text), {"\r": " ", "\n": " "}) + ''' + ) + w.gap() + w.text( + r''' + def write_xml(root: str, columns: Sequence[ExportColumn], rows: Iterable[Mapping[str, Any]]) -> str: + """``value......``: no declaration, no indentation.""" + nil = EXPORT_XML_NULLS == "nil" + out = [f"<{root}" + (f" xmlns:xsi={quoteattr(XSI_NAMESPACE)}" if nil else "")] + body: list[str] = [] + for row in rows: + body.append("") + for c in columns: + value = row.get(c.name) + if value is None: + body.append(f'<{c.name} xsi:nil="true"/>' if nil else f"<{c.name}/>") + else: + body.append(f"<{c.name}>{xml_text(wire_text(value))}") + body.append("") + if body: + out.append(">" + "".join(body) + f"") + else: + out.append("/>") + return "".join(out) + ''' + ) + return w.to_string() def render_report(self, report: MetaObject, scope: ModuleScope = ModuleScope()) -> str: """The export module of one served report: its columns in derived-field order.""" - cols = ",\n".join( - f' ExportColumn("{f.name}", "{_column_kind(f)}")' for f in report.fields() + w = PyWriter() + w.header(*generated_header_lines(report.name, report.resolution_key())) + w.module_doc(f"GENERATED — CSV and XML export of the {report.name} report.") + w.use_future() + w.use("Iterable", "collections.abc") + w.use("Mapping", "collections.abc") + w.use("Any", "typing") + for name in ("ExportColumn", "write_csv", "write_xml"): + w.use(name, scope.root(WRITER_MODULE)) + w.line(f"EXPORT_ROOT = {str_lit(report.name)}") + cols = [ + call("ExportColumn", [str_lit(f.name), str_lit(_column_kind(f))]) + for f in report.fields() if not is_credential_field(f) # #484: an export names no credential column - ) - return ( - generated_header(report.name, report.resolution_key()) - + '"""GENERATED — CSV and XML export of the ' - + f'{report.name} report."""\n' - + "from __future__ import annotations\n\n" - + "from collections.abc import Iterable, Mapping\n" - + "from typing import Any\n\n" - + import_line(scope.root(WRITER_MODULE), "ExportColumn", "write_csv", "write_xml") + "\n\n" - + f'EXPORT_ROOT = "{report.name}"\n' - + f"EXPORT_COLUMNS = (\n{cols},\n)\n\n\n" - + "def export_csv(rows: Iterable[Mapping[str, Any]]) -> str:\n" - + " return write_csv(EXPORT_COLUMNS, rows)\n\n\n" - + "def export_xml(rows: Iterable[Mapping[str, Any]]) -> str:\n" - + " return write_xml(EXPORT_ROOT, EXPORT_COLUMNS, rows)\n" - ) + ] + w.line("EXPORT_COLUMNS = ", group("[", cols, "]")) + w.gap() + w.open("def export_csv(rows: Iterable[Mapping[str, Any]]) -> str:") + w.line("return write_csv(EXPORT_COLUMNS, rows)") + w.dedent().gap() + w.open("def export_xml(rows: Iterable[Mapping[str, Any]]) -> str:") + w.line("return write_xml(EXPORT_ROOT, EXPORT_COLUMNS, rows)") + return w.to_string() def generate(self, ctx: GenContext) -> list[EmittedFile]: reports = [e for e in ctx.entities if ctx.matches(e) and is_served_report(e)] @@ -220,10 +242,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: files = [ EmittedFile( path=f"{WRITER_MODULE}.py", - content=ruff_format( - generated_header("report-export", "metaobjects::report-export") - + self.render_writer() - ), + content=self.render_writer(), ) ] for report in reports: @@ -235,10 +254,8 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: ctx.claims, ctx.config, pkg_of(report), f"{_snake_case(report.name)}_export", report.resolution_key(), ), - content=ruff_format( - self.render_report( - report, ModuleScope(ctx.config.output_layout, pkg_of(report)) - ) + content=self.render_report( + report, ModuleScope(ctx.config.output_layout, pkg_of(report)) ), ) ) diff --git a/server/python/src/metaobjects/codegen/generators/shared_model_generator.py b/server/python/src/metaobjects/codegen/generators/shared_model_generator.py new file mode 100644 index 0000000000..9cecb23109 --- /dev/null +++ b/server/python/src/metaobjects/codegen/generators/shared_model_generator.py @@ -0,0 +1,175 @@ +"""``shared-model``: a publisher's flattened shared-model artifact and the manifest that pins it +(FR-023 §4.3), the pair a consumer's ``deps sync`` copies into its own repo and verifies. + +Emits two files into the target's out dir: ``.metaobjects.json`` (one canonical-JSON +``metadata.root`` document holding the selected top-level nodes) and ``metaobjects.pkg.json`` +(the manifest: name, version, ``metamodelVersion``, the artifact's file name and sha256, and the +sorted packages and nodes). The selection, the closure check and both files' bytes are +:mod:`metaobjects.shared_model`'s; this module only decides which files may contribute and +which version is published, which is why an owned copy changes those and nothing a consumer +checks. The bytes are pinned by ``fixtures/shared-model-conformance`` and identical across ports. + +Options (``options:`` of the ``generators`` entry; the generator receives them as keyword +arguments): + +* ``name`` (required): the dependency key a consumer syncs under, and the artifact's basename. +* ``include`` (required): scope patterns (``acme::platform::**``) of the top-level nodes to + publish. ``exclude`` is applied after it. ``template.*`` is never published. +* ``requirements`` (default ``False``): also publish the selected ``requirement.*`` nodes, so a + consumer can inherit them. +* ``files``: which of the project's own metadata files may contribute, relative to the project + root. Default: every metadata file of the project (a dependency's artifact is never one). +* ``version``: the published version. Default: the ``version`` of the nearest ``pyproject.toml`` + ``[project]`` table or ``package.json`` at or above the project root. + +The files load on their own, as a consumer loads the artifact, so a file that extends a +shipped library's node cannot be among them: name the files that stand alone in ``files``. + +A selection that cannot be published (empty, not closed under references, or needing +vocabulary a consumer's toolchain does not ship) fails the run naming why. +""" +from __future__ import annotations + +import json +import tomllib +from pathlib import Path +from typing import TYPE_CHECKING, Sequence + +from metaobjects.codegen.generator import EmittedFile, GenContext +from metaobjects.shared_model import ( + SharedModelError, + build_shared_model, + render_shared_model_files, +) + +if TYPE_CHECKING: # the registry imports this module; the context is only an annotation here + from metaobjects.codegen.generator_registry import GeneratorBuildContext + + +def _nearest_version(start: Path) -> tuple[str, Path] | None: + """``(version, file it came from)`` for the nearest ``pyproject.toml`` ``[project]`` version + or ``package.json`` ``version`` walking up from *start*; ``None`` when there is none.""" + for directory in (start, *start.parents): + pyproject = directory / "pyproject.toml" + if pyproject.is_file(): + try: + version = tomllib.loads(pyproject.read_text(encoding="utf-8")).get("project", {}).get("version") + except (tomllib.TOMLDecodeError, OSError): + version = None # not a version source: keep walking up + if isinstance(version, str): + return version, pyproject + package_json = directory / "package.json" + if package_json.is_file(): + try: + version = json.loads(package_json.read_text(encoding="utf-8")).get("version") + except (ValueError, OSError, AttributeError): + version = None + if isinstance(version, str): + return version, package_json + return None + + +class SharedModelGenerator: + """Emits the shared-model artifact and manifest once per run.""" + + name = "shared-model" + + def __init__( + self, + name: str | None = None, + include: Sequence[str] = (), + exclude: Sequence[str] = (), + requirements: bool = False, + files: Sequence[str] | None = None, + version: str | None = None, + project_root: str | None = None, + source_files: Sequence[str] | None = None, + providers: Sequence[object] = (), + ) -> None: + self.model_name = name + self.include = tuple(include) + self.exclude = tuple(exclude) + self.requirements = requirements + self.files = tuple(files) if files is not None else None + self.version = version + self.project_root = Path(project_root) if project_root else None + self.source_files = tuple(source_files) if source_files is not None else None + self.providers = tuple(providers) + + @property + def declared_extra_inputs(self) -> tuple[str, ...]: + """The files this generator reads that the model does not name (ADR-0064): the + configured ``files`` and the file the version comes from, project-relative.""" + if self.project_root is None: + return () + paths = [self.project_root / f for f in self.files or ()] + if self.version is None: + found = _nearest_version(self.project_root) + if found is not None: + paths.append(found[1]) + out: list[str] = [] + for p in paths: + try: + out.append(p.resolve().relative_to(self.project_root.resolve()).as_posix()) + except ValueError: + continue # outside the project: not a project-relative input + return tuple(out) + + def generate(self, ctx: GenContext) -> list[EmittedFile]: + if not self.model_name or not self.include: + # Built with no settings (the registry sweeps every generator this way): nothing + # to publish. A config entry that leaves `name` or `include` out never gets here, + # because `resolve_options` refuses it first (both options are required). + return [] + if self.files is not None: + if self.project_root is None: + raise ValueError(f"shared-model({self.model_name!r}): 'files' needs a project root to resolve against") + files = [self.project_root / f for f in self.files] + else: + files = [Path(f) for f in self.source_files or ()] + if not files: + raise ValueError( + f"shared-model({self.model_name!r}): no source files to load; pass option 'files' " + "or run through `metaobjects gen`, which supplies the project's own files." + ) + model = build_shared_model( + self.model_name, + files, + self.include, + self.exclude, + requirements=self.requirements, + providers=self.providers, + ) + version = self.version + if version is None: + found = _nearest_version(self.project_root or Path.cwd()) + if found is None: + raise ValueError( + f"shared-model({self.model_name!r}): no version available; pass option 'version', " + "or run in a project with a pyproject.toml or package.json version at or above " + "the project root." + ) + version = found[0] + rendered = render_shared_model_files(model, version) + return [EmittedFile(path=p, content=c) for p, c in (rendered.artifact, rendered.manifest)] + + +def shared_model_generator(ctx: GeneratorBuildContext) -> SharedModelGenerator: + """Generator factory for ``shared-model``: takes the build context, which carries the + entry's options, the project root, the project's own files and the run's providers. See the + module docstring for the options.""" + options = ctx.options + return SharedModelGenerator( + name=options.get("name"), # type: ignore[arg-type] + include=options.get("include", ()), # type: ignore[arg-type] + exclude=options.get("exclude", ()), # type: ignore[arg-type] + requirements=bool(options.get("requirements", False)), + files=options.get("files"), # type: ignore[arg-type] + version=options.get("version"), # type: ignore[arg-type] + project_root=ctx.project_root, + source_files=ctx.source_files, + providers=ctx.providers, + ) + + +__all__ = ["SharedModelError", "SharedModelGenerator", "shared_model_generator"] diff --git a/server/python/src/metaobjects/codegen/metaobjects-config.schema.json b/server/python/src/metaobjects/codegen/metaobjects-config.schema.json index 050f134dd5..2ed564a94d 100644 --- a/server/python/src/metaobjects/codegen/metaobjects-config.schema.json +++ b/server/python/src/metaobjects/codegen/metaobjects-config.schema.json @@ -108,12 +108,28 @@ "enum": ["keep", "overwrite"], "default": "keep", "description": "What a hand edit to this generator's output gets. keep (the default) refuses the edited file, and an edited file no generator emits any more. overwrite regenerates over the edit and deletes such an orphan, naming each one." + }, + "packages": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 }, + "description": "Metadata packages (e.g. \"acme::sales\") this generator emits for. Omit for every package in the target. A package the target holds no object of is refused." + }, + "entities": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 }, + "description": "Short object names this generator emits for, inside the target's own `entities`. Omit for every object. A name the target does not hold is refused." + }, + "options": { + "type": "object", + "description": "The generator's own settings, in camelCase; a generator receives them as snake_case keyword arguments (maxRows -> max_rows). A setting the generator does not take is refused. `metaobjects gen --list` names each packaged generator's." } } } ] }, - "description": "Generators to run: stable names (see `metaobjects gen --list`), or {name, handEdits} mappings. Required: there is no default suite, so a target that names none generates nothing and `verify --codegen` checks nothing." + "description": "Generators to run: stable names (see `metaobjects gen --list`), or {name, handEdits, packages, entities, options} mappings. Required: there is no default suite, so a target that names none generates nothing and `verify --codegen` checks nothing." }, "entities": { "type": "array", diff --git a/server/python/src/metaobjects/codegen/project_config.py b/server/python/src/metaobjects/codegen/project_config.py index 03e4b00477..bcb96096f5 100644 --- a/server/python/src/metaobjects/codegen/project_config.py +++ b/server/python/src/metaobjects/codegen/project_config.py @@ -23,7 +23,7 @@ from __future__ import annotations import re -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path import yaml # type: ignore[import-untyped] # PyYAML ships no type stubs @@ -70,8 +70,9 @@ TARGET_KEYS: tuple[str, ...] = ("outDir", "generators", "entities", "templateSpec") #: Every key a mapping entry of a target's ``generators`` list may carry: the generator's -#: name and its ``handEdits`` setting. Same contract as above. -GENERATOR_ENTRY_KEYS: tuple[str, ...] = ("name", "handEdits") +#: name, its ``handEdits`` setting, the ``packages`` and ``entities`` it is limited to, and its +#: ``options``. Same contract as above. +GENERATOR_ENTRY_KEYS: tuple[str, ...] = ("name", "handEdits", "packages", "entities", "options") #: The values ``handEdits`` accepts, the same in every port. ``keep`` (the default) refuses #: a generated file edited by hand, and an edited file no generator emits any more; @@ -123,6 +124,29 @@ class ConfigError(ValueError): """ +@dataclass(frozen=True) +class GeneratorSettings: + """What a ``generators`` entry written as a mapping says about ONE generator, beyond its name. + + ``packages`` and ``entities`` limit what THIS generator emits for, inside the target's own + ``entities`` (a name outside the target is outside both). ``options`` are the generator's + own settings, in the camelCase this file uses for every key; they reach the generator as + snake_case keyword arguments, and a name the generator does not take is refused when the + generator is built (here only the SHAPE is checked: this loader never imports the engine). + """ + + #: Metadata packages (``acme::sales``) the generator emits for; ``None`` => every package. + packages: tuple[str, ...] | None = None + #: Short object names the generator emits for; ``None`` => every object in the target. + entities: tuple[str, ...] | None = None + #: The generator's own settings, as written. + options: dict[str, object] = field(default_factory=dict) + + @property + def selects(self) -> bool: + return self.packages is not None or self.entities is not None + + @dataclass(frozen=True) class TargetConfig: """One named run-spec: where to write + which generators/entities to run. @@ -148,6 +172,9 @@ class TargetConfig: #: The ``generators`` entries (as written in ``generators``) declared with #: ``handEdits: overwrite``. Every other entry keeps hand edits. overwrite_hand_edits: frozenset[str] = frozenset() + #: Per generator entry, by the entry's name: its ``packages`` / ``entities`` / ``options``. + #: An entry written as a bare name, or with none of the three, has no row. + generator_settings: dict[str, GeneratorSettings] = field(default_factory=dict) #: ``gen --entities``: the entities this RUN writes, within ``entities``. Never read #: from the file. ``entities`` stays the target's model, so a whole-model file (shared #: enums, the duration codec, the report writers) still renders from all of it. @@ -275,20 +302,51 @@ def _require_str_list(value: object, ctx: str) -> list[str]: return list(value) -def _parse_generator_entries(value: object, ctx: str) -> tuple[list[str], frozenset[str]]: - """A target's ``generators``: each entry a name, or a mapping ``{name, handEdits}``. +def _parse_name_list(value: object, ctx: str, key: str) -> tuple[str, ...]: + if ( + not isinstance(value, list) or not value + or not all(isinstance(x, str) and x for x in value) + ): + raise ConfigError(f"{ctx}: '{key}' must be a non-empty list of non-empty strings.") + return tuple(dict.fromkeys(value)) + - Returns the names in order and the ones declared ``handEdits: overwrite``.""" +def _parse_generator_options(value: object, ctx: str) -> dict[str, object]: + if not isinstance(value, dict) or not all(isinstance(k, str) and k for k in value): + raise ConfigError(f"{ctx}: 'options' must be a mapping of option name to value.") + return dict(value) + + +def _parse_generator_entries( + value: object, ctx: str +) -> tuple[list[str], frozenset[str], dict[str, GeneratorSettings]]: + """A target's ``generators``: each entry a name, or a mapping + ``{name, handEdits, packages, entities, options}``. + + Returns the names in order, the ones declared ``handEdits: overwrite``, and the + per-generator settings of each entry that carries any.""" if not isinstance(value, list): - raise ConfigError(f"{ctx} must be a list of generator names or {{name, handEdits}} mappings.") + raise ConfigError(f"{ctx} must be a list of generator names or {{name, ...}} mappings.") names: list[str] = [] overwrite: set[str] = set() + settings: dict[str, GeneratorSettings] = {} + configured: set[str] = set() + + def reject_repeat(name: str, carries: bool) -> None: + if name in names and (carries or name in configured): + raise ConfigError( + f"{ctx}: generator {name!r} is listed twice and one entry carries " + f"packages, entities, options or handEdits; settings are per generator name, " + f"so merge them into one entry." + ) + for entry in value: if isinstance(entry, str): + reject_repeat(entry, False) names.append(entry) continue if not isinstance(entry, dict): - raise ConfigError(f"{ctx}: each entry must be a generator name or a {{name, handEdits}} mapping.") + raise ConfigError(f"{ctx}: each entry must be a generator name or a {{name, ...}} mapping.") _reject_unknown_keys(entry, GENERATOR_ENTRY_KEYS, ctx) name = entry.get("name") if not isinstance(name, str) or not name: @@ -299,10 +357,23 @@ def _parse_generator_entries(value: object, ctx: str) -> tuple[list[str], frozen f"{ctx}: entry {name!r} has handEdits {hand_edits!r}; expected one of " f"{', '.join(HAND_EDITS_VALUES)}." ) + entry_ctx = f"{ctx}: entry {name!r}" + packages = _parse_name_list(entry["packages"], entry_ctx, "packages") if "packages" in entry else None + entities = _parse_name_list(entry["entities"], entry_ctx, "entities") if "entities" in entry else None + options = _parse_generator_options(entry["options"], entry_ctx) if "options" in entry else {} + carries = ( + packages is not None or entities is not None or bool(options) + or hand_edits == HAND_EDITS_OVERWRITE + ) + reject_repeat(name, carries) names.append(name) + if carries: + configured.add(name) if hand_edits == HAND_EDITS_OVERWRITE: overwrite.add(name) - return names, frozenset(overwrite) + if packages is not None or entities is not None or options: + settings[name] = GeneratorSettings(packages=packages, entities=entities, options=options) + return names, frozenset(overwrite), settings def _parse_requirement_tests(raw: object, ctx: str) -> RequirementTestsConfig: @@ -454,8 +525,9 @@ def load_project_config(path: Path) -> ProjectConfig: raise ConfigError(f"{ctx} must declare a non-empty 'outDir' string.") generators = spec.get("generators") overwrite_hand_edits: frozenset[str] = frozenset() + generator_settings: dict[str, GeneratorSettings] = {} if generators is not None: - generators, overwrite_hand_edits = _parse_generator_entries( + generators, overwrite_hand_edits, generator_settings = _parse_generator_entries( generators, f"{ctx} 'generators'") entities = spec.get("entities") if entities is not None: @@ -467,6 +539,7 @@ def load_project_config(path: Path) -> ProjectConfig: TargetConfig( name=str(name), out_dir=out_dir, generators=generators, entities=entities, template_spec=template_spec, overwrite_hand_edits=overwrite_hand_edits, + generator_settings=generator_settings, ) ) diff --git a/server/python/src/metaobjects/codegen/runtime/output_format_spec_emitter.py b/server/python/src/metaobjects/codegen/runtime/output_format_spec_emitter.py index be0193de5d..75a0e86e59 100644 --- a/server/python/src/metaobjects/codegen/runtime/output_format_spec_emitter.py +++ b/server/python/src/metaobjects/codegen/runtime/output_format_spec_emitter.py @@ -10,6 +10,7 @@ from __future__ import annotations from . import fr010_field_mapping as fm +from metaobjects.codegen.writer import Piece, call, flat, kwarg, seq from metaobjects.codegen.generators.find_inbound import is_xml, response_format_of from metaobjects.meta.core.field import field_constants as fc from metaobjects.meta.meta_data import MetaData @@ -38,7 +39,7 @@ def _opt_string_attr(field: MetaData, attr_name: str) -> str: return fm.py_string_literal(v) if isinstance(v, str) else "None" -def _prompt_field_literal(field: MetaData) -> str: +def _prompt_field_piece(field: MetaData) -> Piece: name = field.name req = "True" if fm.is_required(field) else "False" array = "True" if fm.is_array(field) else "False" @@ -46,12 +47,12 @@ def _prompt_field_literal(field: MetaData) -> str: if field.sub_type == fc.FIELD_SUBTYPE_OBJECT: # FR-010: nested prompt deferred — emit a FieldKind.OBJECT placeholder (nested # defaults to None on PromptField). The note lives HERE, not in the returned - # literal: spec_literal joins every field onto ONE line, and a Python '#' inline - # comment would swallow the rest of that line — including the closing `])` — so a - # nested-object payload emitted invalid Python (unterminated list) and crashed - # `gen` + `verify --codegen`. The other ports use `/* */` block comments, which - # are inline-safe; Python has none, so the literal must carry no comment. - return f'PromptField("{name}", FieldKind.OBJECT, {req}, array={array})' + # literal: a Python '#' inline comment would swallow the rest of its line, + # including a closing bracket, so the literal must carry no comment. The other + # ports use `/* */` block comments, which are inline-safe; Python has none. + return call( + "PromptField", [f'"{name}"', "FieldKind.OBJECT", req, kwarg("array", array)] + ) example = _opt_string_attr(field, fc.FIELD_ATTR_EXAMPLE) instruction = _opt_string_attr(field, fc.FIELD_ATTR_INSTRUCTION) @@ -59,25 +60,41 @@ def _prompt_field_literal(field: MetaData) -> str: if field.sub_type == fc.FIELD_SUBTYPE_ENUM: values_lit = fm.string_list_literal(fm.enum_values(field)) enum_doc_lit = fm.properties_map_literal(field.attrs().get(fc.FIELD_ATTR_ENUM_DOC)) - return ( - f'PromptField("{name}", FieldKind.ENUM, {req}, array={array}, ' - f"enum_values={values_lit}, enum_doc={enum_doc_lit}, " - f"example={example}, instruction={instruction})" + return call( + "PromptField", + [ + f'"{name}"', "FieldKind.ENUM", req, kwarg("array", array), + kwarg("enum_values", values_lit), kwarg("enum_doc", enum_doc_lit), + kwarg("example", example), kwarg("instruction", instruction), + ], ) kind = fm.scalar_kind(field.sub_type) or "STRING" - return ( - f'PromptField("{name}", FieldKind.{kind}, {req}, array={array}, ' - f"example={example}, instruction={instruction})" + return call( + "PromptField", + [ + f'"{name}"', f"FieldKind.{kind}", req, kwarg("array", array), + kwarg("example", example), kwarg("instruction", instruction), + ], ) -def spec_literal(vo: MetaData, template: MetaData, root_name: str) -> str: - """Emit ``OutputFormatSpec(Format.X, "rootName", PromptStyle.X, [PromptField(...), …])``.""" - format_enum = _format_enum(template) - style_enum = _prompt_style_enum(template) - field_lits = [_prompt_field_literal(f) for f in fm.fields(vo)] - body = ", ".join(field_lits) - return ( - f'OutputFormatSpec({format_enum}, "{root_name}", {style_enum}, [{body}])' +def spec_piece(vo: MetaData, template: MetaData, root_name: str) -> Piece: + """The ``OutputFormatSpec(...)`` literal as a writer piece: a generator on + :class:`~metaobjects.codegen.writer.PyWriter` writes it, and it breaks one field per + line when it does not fit.""" + return call( + "OutputFormatSpec", + [ + _format_enum(template), + f'"{root_name}"', + _prompt_style_enum(template), + seq([_prompt_field_piece(f) for f in fm.fields(vo)]), + ], ) + + +def spec_literal(vo: MetaData, template: MetaData, root_name: str) -> str: + """Emit ``OutputFormatSpec(Format.X, "rootName", PromptStyle.X, [PromptField(...), …])`` + on one line. The string form an owned generator's extension seam returns.""" + return flat(spec_piece(vo, template, root_name)) diff --git a/server/python/src/metaobjects/codegen/writer/__init__.py b/server/python/src/metaobjects/codegen/writer/__init__.py new file mode 100644 index 0000000000..0d5aed0867 --- /dev/null +++ b/server/python/src/metaobjects/codegen/writer/__init__.py @@ -0,0 +1,22 @@ +"""The code writer every Python generator writes through (ADR-0063).""" +from .code_writer import ( + ERR_WRITER_IMPORT_CONFLICT, + ERR_WRITER_NEWLINE_IN_LINE, + ERR_WRITER_UNBALANCED_CLOSE, + ERR_WRITER_UNCLOSED_BLOCK, + ERR_WRITER_UNKNOWN_PIECE, + CodeWriter, + Group, + Piece, + WriterError, + flat, + group, +) +from .py_writer import PyWriter, call, kwarg, mapping, seq, str_lit + +__all__ = [ + "CodeWriter", "PyWriter", "Group", "Piece", "WriterError", "flat", "group", "call", + "kwarg", "mapping", "seq", "str_lit", + "ERR_WRITER_IMPORT_CONFLICT", "ERR_WRITER_NEWLINE_IN_LINE", "ERR_WRITER_UNBALANCED_CLOSE", + "ERR_WRITER_UNCLOSED_BLOCK", "ERR_WRITER_UNKNOWN_PIECE", +] diff --git a/server/python/src/metaobjects/codegen/writer/code_writer.py b/server/python/src/metaobjects/codegen/writer/code_writer.py new file mode 100644 index 0000000000..c1263e76a7 --- /dev/null +++ b/server/python/src/metaobjects/codegen/writer/code_writer.py @@ -0,0 +1,244 @@ +"""The language-neutral code writer (ADR-0063; contract: ``spec/code-writer.md``). + +A generator says WHAT a line contains; the writer decides WHERE it sits. It builds the file +in memory and returns a string, so nothing here touches the disk and no formatter runs over +the result. It never parses the text it is handed: it lays out the structure the generator +gave it — lines, blocks, blank-line requests and breakable lists. + +This module and the dialect beside it are the ONLY codegen source allowed to type layout +(newlines, indentation). ``tests/codegen/test_layout_ratchet.py`` holds every other +generator module to that. +""" +from __future__ import annotations + +import re +from collections.abc import Callable +from dataclasses import dataclass +from typing import Union + +#: Error codes a writer raises. Shared by every port's writer (spec/code-writer.md). +ERR_WRITER_UNBALANCED_CLOSE = "ERR_WRITER_UNBALANCED_CLOSE" +ERR_WRITER_UNCLOSED_BLOCK = "ERR_WRITER_UNCLOSED_BLOCK" +ERR_WRITER_NEWLINE_IN_LINE = "ERR_WRITER_NEWLINE_IN_LINE" +ERR_WRITER_IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT" +ERR_WRITER_UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE" + + +class WriterError(Exception): + """A writer failure: one of the shared codes plus a message for people.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(f"{code}: {message}") + self.code = code + + +@dataclass(frozen=True) +class Group: + """A bracketed, comma-separated list. Printed on one line when the line fits the + width; otherwise opener, one item per line (each followed by a comma) and closer.""" + + open: str + items: tuple["Piece", ...] + close: str + #: ``{ a, b }`` (True) versus ``[a, b]`` or ``f(a, b)`` (False) on one line. + pad: bool = False + + +#: An expression fragment: text, a breakable list, or a concatenation of fragments. +Piece = Union[str, Group, tuple, list] + + +def group(open_: str, items: "list[Piece] | tuple[Piece, ...]", close: str, pad: bool = False) -> Group: + """A list with no padding inside its brackets (``[a, b]``, ``f(a, b)``) by default.""" + return Group(open_, tuple(items), close, pad) + + +_ANY_LINE_BREAK = re.compile(r"\r\n?|\n") +_NEWLINE = "\n" + + +def flat(p: Piece) -> str: + """A piece printed on one line.""" + if isinstance(p, str): + return p + if isinstance(p, Group): + if not p.items: + return p.open + p.close + inner = ", ".join(flat(i) for i in p.items) + return f"{p.open} {inner} {p.close}" if p.pad else p.open + inner + p.close + return "".join(flat(x) for x in p) + + +def _last_group(p: Piece) -> tuple[str, Group, str] | None: + """Split a piece around its LAST non-empty list: (text before, the list, text after).""" + if isinstance(p, str): + return None + if isinstance(p, Group): + return None if not p.items else ("", p, "") + parts = list(p) + for i in range(len(parts) - 1, -1, -1): + hit = _last_group(parts[i]) + if hit is not None: + return (flat(parts[:i]) + hit[0], hit[1], hit[2] + flat(parts[i + 1 :])) + return None + + +class CodeWriter: + """The core writer. Built to be extended (ADR-0063): every method is public or + protected-by-convention, so a dialect or an adopter's subclass overrides the one step it + needs (``piece``, ``break_at``, ``fits``). These methods are not a stability contract.""" + + def __init__(self, indent: str = " ", width: int = 88, trailing_comma: bool = True) -> None: + self.indent = indent + self.width = width + self.trailing_comma = trailing_comma + self._out: list[str] = [] + #: The text of each line that opened a block still open, outermost first. + self._openers: list[str] = [] + self._want_blank = 0 + #: True at the start of the file and right after a block opens. + self._at_block_start = True + + # ── the public surface ─────────────────────────────────────────────────────────── + + def line(self, *parts: object) -> "CodeWriter": + """One line at the current indent. The parts are concatenated; when the line does + not fit the width, the LAST non-empty list in it is printed one item per line. A + line whose text is empty is a blank-line request.""" + return self._put(self.piece(parts)) + + def blank(self) -> "CodeWriter": + """Ask for one blank line before whatever is written next. Requests never stack.""" + self._want_blank = max(self._want_blank, 1) + return self + + def open(self, *parts: object) -> "CodeWriter": + """Write the line that opens a block, then indent.""" + return self._open_piece(self.piece(parts)) + + def close(self, *parts: object) -> "CodeWriter": + """Dedent, then write the line that closes the block.""" + return self._close_piece(self.piece(parts)) + + def block(self, head: object, body: Callable[[], None], tail: object = "}") -> "CodeWriter": + """``open(head)``, the body, then ``close(tail)``: the indent cannot be left + unbalanced.""" + self.open(head) + body() + return self.close(tail) + + def text(self, snippet: str) -> "CodeWriter": + """A multi-line snippet written as it should read. Its common left margin is + removed and it is re-indented to the current level; a blank line in it is a + blank-line request. Every line is re-indented, including lines inside a multi-line + string literal.""" + lines = _ANY_LINE_BREAK.split(snippet) + if len(lines) > 1 and lines[0].strip() == "": + lines.pop(0) + if lines and lines[-1].strip() == "": + lines.pop() + margin = min( + (len(ln) - len(ln.lstrip()) for ln in lines if ln.strip() != ""), default=0 + ) + for ln in lines: + if ln.strip() == "": + self.blank() + else: + self._put(ln[margin:]) + return self + + def to_string(self) -> str: + """The finished file: ``\\n`` line endings, no trailing whitespace, one final + newline (none when empty). Raises if a block is still open.""" + body = self._body() + return "" if body == "" else body + _NEWLINE + + def __str__(self) -> str: + return self.to_string() + + # ── the steps a dialect or subclass overrides ──────────────────────────────────── + + def piece(self, p: object) -> Piece: + """Turn one argument of ``line()`` into a writer piece. A dialect overrides this to + accept its own fragment types and calls ``super`` for the rest.""" + if isinstance(p, str): + return p + if isinstance(p, Group): + items = tuple(self.piece(i) for i in p.items) + if all(a is b for a, b in zip(items, p.items)): + return p + return Group(p.open, items, p.close, p.pad) + if isinstance(p, (list, tuple)): + return tuple(self.piece(x) for x in p) + raise WriterError(ERR_WRITER_UNKNOWN_PIECE, f"cannot write {_describe(p)}") + + def fits(self, text: str) -> bool: + """Whether ``text`` fits on one line at the current indent.""" + return len(self._prefix()) + len(text) <= self.width + + def break_at(self, piece: Piece) -> tuple[str, Group, str] | None: + """Where a line that does not fit breaks: (text before, the list that breaks, text + after), or ``None`` to print the line as it is. Default: the LAST non-empty list.""" + return _last_group(piece) + + # ── internals ──────────────────────────────────────────────────────────────────── + + def _body(self) -> str: + if self._openers: + raise WriterError( + ERR_WRITER_UNCLOSED_BLOCK, f"unclosed block opened by: {self._openers[-1]}" + ) + return _NEWLINE.join(self._out) + + def _prefix(self) -> str: + return self.indent * len(self._openers) + + def _open_piece(self, piece: Piece) -> "CodeWriter": + self._put(piece) + self._openers.append(flat(piece).strip()) + self._at_block_start = True + return self + + def _close_piece(self, piece: Piece) -> "CodeWriter": + self._dedent(f"close({flat(piece)!r})") + self._want_blank = 0 + return self._put(piece) + + def _dedent(self, what: str) -> None: + if not self._openers: + raise WriterError(ERR_WRITER_UNBALANCED_CLOSE, f"{what} with no block open") + self._openers.pop() + + def _put(self, piece: Piece) -> "CodeWriter": + raw = flat(piece) + if _ANY_LINE_BREAK.search(raw): + raise WriterError( + ERR_WRITER_NEWLINE_IN_LINE, + "line text contains a line break; write each line separately or use " + f"text(): {raw!r}", + ) + text = raw.rstrip() + if text == "": + return self.blank() + if not self._at_block_start: + self._out.extend([""] * self._want_blank) + self._want_blank = 0 + self._at_block_start = False + pre = self._prefix() + split = None if self.fits(text) else self.break_at(piece) + if split is None: + self._out.append(pre + text) + return self + before, grp, after = split + self._open_piece(before + grp.open) + last = len(grp.items) - 1 + for n, item in enumerate(grp.items): + comma = "," if n < last or self.trailing_comma else "" + self._put((item, comma)) + return self._close_piece(grp.close + after) + + +def _describe(p: object) -> str: + if p is None: + return "None" + return f"an object ({type(p).__name__})" diff --git a/server/python/src/metaobjects/codegen/writer/py_writer.py b/server/python/src/metaobjects/codegen/writer/py_writer.py new file mode 100644 index 0000000000..0633cbd91f --- /dev/null +++ b/server/python/src/metaobjects/codegen/writer/py_writer.py @@ -0,0 +1,243 @@ +"""The Python dialect of the code writer (ADR-0063; contract: ``spec/code-writer.md``). + +Adds what is Python's own: imports collected while the body is written and printed first, +string quoting, suites (a block that closes by dedenting, with no closing token) and +docstrings. Four-space indent, 88 columns and a trailing comma in a broken list are its +defaults; none of that is a formatter's doing, the writer lays the text out itself. +""" +from __future__ import annotations + +import json +from collections.abc import Callable +from dataclasses import dataclass, field + +from .code_writer import ( + ERR_WRITER_IMPORT_CONFLICT, + CodeWriter, + Group, + Piece, + WriterError, + group, +) + +__all__ = ["PyWriter", "str_lit", "call", "seq", "mapping", "kwarg"] + +FUTURE_MODULE = "__future__" + + +def str_lit(value: str) -> str: + """A correctly quoted Python string literal (double-quoted, ``\\n`` escaped).""" + return json.dumps(value, ensure_ascii=False) + + +def call(fn: str, args: "list[object] | tuple[object, ...]") -> Group: + """A call: ``fn(a, b)``.""" + return group(f"{fn}(", list(args), ")") # type: ignore[arg-type] + + +def seq(items: "list[object] | tuple[object, ...]", open_: str = "[", close: str = "]") -> Group: + """A list literal ``[a, b]``. Do not use ``("(", ")")`` for a tuple: a flat one-item ``(x)`` is no tuple.""" + return group(open_, list(items), close) # type: ignore[arg-type] + + +def mapping(entries: "list[tuple[object, object]]") -> Group: + """A dict literal ``{k: v, ...}``; keys and values are written as given.""" + return group("{", [[k, ": ", v] for k, v in entries], "}") # type: ignore[arg-type] + + +def kwarg(name: str, value: object) -> Piece: + """``name=value``.""" + return [name, "=", value] # type: ignore[list-item] + + +@dataclass +class _ModuleImports: + #: local name -> exported name + named: dict[str, str] = field(default_factory=dict) + #: ``import module`` / ``import module as alias`` -> the alias (or the module itself) + plain: set[str] = field(default_factory=set) + + +class PyWriter(CodeWriter): + """The Python writer. Built to be extended: each section of the file + (``write_header``, ``write_imports``, ``write_import``, ``order_modules``) is its own + overridable method, and none of them is a stability contract.""" + + def __init__( + self, indent: str = " ", width: int = 88, trailing_comma: bool = True + ) -> None: + super().__init__(indent=indent, width=width, trailing_comma=trailing_comma) + self._modules: dict[str, _ModuleImports] = {} + #: local name -> the module it was imported from, so one name cannot come from two + self._locals: dict[str, str] = {} + self._head: list[str] = [] + + # ── imports ────────────────────────────────────────────────────────────────────── + + def use(self, name: str, from_: str, as_: str | None = None) -> str: + """Reference ``from import [as ]``; returns the name to write.""" + local = as_ or name + self._claim(local, from_) + mod = self._module(from_) + seen = mod.named.get(local) + if seen is not None and seen != name: + raise WriterError( + ERR_WRITER_IMPORT_CONFLICT, + f"{local} from {from_} names both {seen} and {name}", + ) + mod.named[local] = name + return local + + def use_module(self, module: str, as_: str | None = None) -> str: + """Reference ``import [as ]``; returns the name to write.""" + local = as_ or module.split(".")[0] + self._claim(local, module if as_ else local) + self._module(module).plain.add(as_ or "") + return local + + def use_future(self, name: str = "annotations") -> None: + """``from __future__ import ``: always printed first.""" + self.use(name, FUTURE_MODULE) + + def header(self, *lines: str) -> "PyWriter": + """Lines printed at the very top, before the imports: a banner comment.""" + self._head.extend(lines) + return self + + # ── members ────────────────────────────────────────────────────────────────────── + + def suite(self, head: object, body: Callable[[], None]) -> "PyWriter": + """``open(head)``, the body, then dedent: a Python block has no closing token. A + blank-line request made at the end of the body is kept, so a gap before the next + top-level definition survives the dedent.""" + self.open(head) + body() + return self.dedent() + + def dedent(self) -> "PyWriter": + """End the suite opened by ``open`` without writing a line.""" + self._dedent("dedent()") + return self + + def gap(self) -> "PyWriter": + """Two blank lines before whatever is written next: the gap between top-level + definitions.""" + self._want_blank = max(self._want_blank, 2) + return self + + def doc(self, *lines: str) -> "PyWriter": + """A docstring at the current indent: one line when it fits, otherwise a block with + the closing quotes on their own line. An empty entry is a blank line. A backslash is + written as ``\\\\`` and ``\"\"\"`` in the text is escaped, and so is a double quote that + would end a one-line docstring.""" + for ln in self._doc_lines(lines, len(self._prefix())): + self.line(ln) + return self + + def module_doc(self, *lines: str) -> "PyWriter": + """The module docstring. It is a header line group, so it prints before the imports + (a ``from __future__`` import must follow it).""" + self._head.extend(self._doc_lines(lines, 0)) + return self + + def _doc_lines(self, lines: "tuple[str, ...]", depth: int) -> list[str]: + if not lines: + return [] + safe = [ln.replace("\\", "\\\\").replace('"""', '\\"\\"\\"') for ln in lines] + if len(safe) == 1: + # On one line the closing quotes follow the text directly, so a double quote at + # the end of the text would join them (four quotes in a row end the string early + # and leave a stray one). Escape the trailing run. + text = lines[0] + tail = len(text) - len(text.rstrip('"')) + body = text[: len(text) - tail] if tail else text + body = body.replace("\\", "\\\\").replace('"""', '\\"\\"\\"') + one = f'"""{body}' + '\\"' * tail + '"""' + if depth + len(one) <= self.width: + return [one] + return [f'"""{safe[0]}', *safe[1:], '"""'] + + # ── output ─────────────────────────────────────────────────────────────────────── + + def to_string(self) -> str: + # A Python suite ends where the file does, so a suite still open here is closed + # for the generator (the core's ERR_WRITER_UNCLOSED_BLOCK is for closing tokens). + self._openers.clear() + head = self._section_writer() + self.write_header(head) + head.blank() + self.write_imports(head) + top = head.to_string() + body = super().to_string() + if top == "": + return body + if body == "": + return top + return f"{top}\n{body}" + + def _section_writer(self) -> CodeWriter: + return CodeWriter(indent=self.indent, width=self.width, trailing_comma=self.trailing_comma) + + def write_header(self, w: CodeWriter) -> None: + """The ``header(...)`` lines, as given.""" + for ln in self._head: + w.line(ln) + + def write_imports(self, w: CodeWriter) -> None: + """Every collected import, one blank line between the ``__future__`` import, the + absolute modules and the relative ones. In a section the plain ``import m`` lines + come first, then the ``from m import ...`` lines, each in ``order_modules`` order.""" + for n, mods in enumerate(self.order_modules(list(self._modules))): + if n > 0: + w.blank() + for m in mods: + self.write_plain_imports(w, m, self._modules[m]) + for m in mods: + self.write_from_import(w, m, self._modules[m]) + + def order_modules(self, modules: list[str]) -> list[list[str]]: + """Three sections: ``__future__``, then absolute modules, then relative ones, each + in code-point order.""" + future = [m for m in modules if m == FUTURE_MODULE] + relative = sorted(m for m in modules if m.startswith(".")) + absolute = sorted(m for m in modules if m != FUTURE_MODULE and not m.startswith(".")) + return [s for s in (future, absolute, relative) if s] + + def write_plain_imports(self, w: CodeWriter, from_: str, m: _ModuleImports) -> None: + for alias in sorted(m.plain): + w.line(f"import {from_} as {alias}" if alias else f"import {from_}") + + def write_from_import(self, w: CodeWriter, from_: str, m: _ModuleImports) -> None: + if not m.named: + return + items = [ + local if exported == local else f"{exported} as {local}" + for local, exported in sorted(m.named.items()) + ] + one = f"from {from_} import " + ", ".join(items) + if len(items) == 1 or w.fits(one): + # One name never breaks: it stays on one line however long the module is. + w.line(one) + else: + # A parenthesised list, one name per line with a trailing comma. + w.open(f"from {from_} import (") + for item in items: + w.line(item, ",") + w.close(")") + + # ── internals ──────────────────────────────────────────────────────────────────── + + def _claim(self, local: str, from_: str) -> None: + owner = self._locals.get(local) + if owner is not None and owner != from_: + raise WriterError( + ERR_WRITER_IMPORT_CONFLICT, f"{local} is imported from both {owner} and {from_}" + ) + self._locals[local] = from_ + + def _module(self, from_: str) -> _ModuleImports: + m = self._modules.get(from_) + if m is None: + m = _ModuleImports() + self._modules[from_] = m + return m diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 257c46c6e3..9205b36253 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -1246,6 +1246,67 @@ def ops_for_field(field: MetaData) -> frozenset[str]: EXPR_CASE_OPERAND = "operand" EXPR_NOW = FILTER_RELATIVE_NOW EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF +# { cast: , as: "", dbColumnType?: "" }. +EXPR_CAST = "cast" +EXPR_CAST_AS = "as" +EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType" +# The closed, typed function set beside coalesce. Mirrors the TS EXPR_FN_*. +EXPR_FN_GREATEST = "greatest" +EXPR_FN_LEAST = "least" +EXPR_FN_NULLIF = "nullif" +EXPR_FN_LOWER = "lower" +EXPR_FN_UPPER = "upper" +EXPR_FN_BTRIM = "btrim" +EXPR_FN_SPLIT_PART = "splitPart" +EXPR_FN_CONCAT = "concat" +EXPR_FN_CONCAT_WS = "concatWs" +EXPR_FN_SUBSTRING = "substring" +EXPR_FN_REPLACE = "replace" +EXPR_FN_LEFT = "left" +EXPR_FN_RIGHT = "right" +EXPR_FN_LENGTH = "length" + + +class ExprFnSignature(NamedTuple): + """One expression function's signature: its arity, each parameter's kind (the last one + repeats), and its result. A parameter kind is ``string``, ``int``, ``scalar`` (any scalar) or + ``same`` (the type every ``same`` parameter shares). ``max_args`` is None for a variadic.""" + + min_args: int + max_args: int | None + params: tuple[str, ...] + result: str # "string" | "int" | "same" + ordered: bool = False # the "same" type must be orderable (greatest / least) + + +# Every expression function, by name. A closed set, never free SQL; each lowers to the dialect's +# own function in the view emitter. Mirrors the TS EXPR_FUNCTIONS. +EXPR_FUNCTIONS: dict[str, ExprFnSignature] = { + EXPR_FN_COALESCE: ExprFnSignature(1, None, ("same",), "same"), + EXPR_FN_GREATEST: ExprFnSignature(1, None, ("same",), "same", True), + EXPR_FN_LEAST: ExprFnSignature(1, None, ("same",), "same", True), + EXPR_FN_NULLIF: ExprFnSignature(2, 2, ("same", "same"), "same"), + EXPR_FN_LOWER: ExprFnSignature(1, 1, ("string",), "string"), + EXPR_FN_UPPER: ExprFnSignature(1, 1, ("string",), "string"), + EXPR_FN_BTRIM: ExprFnSignature(1, 2, ("string", "string"), "string"), + EXPR_FN_SPLIT_PART: ExprFnSignature(3, 3, ("string", "string", "int"), "string"), + EXPR_FN_CONCAT: ExprFnSignature(1, None, ("scalar",), "string"), + EXPR_FN_CONCAT_WS: ExprFnSignature(2, None, ("string", "scalar"), "string"), + EXPR_FN_SUBSTRING: ExprFnSignature(2, 3, ("string", "int", "int"), "string"), + EXPR_FN_REPLACE: ExprFnSignature(3, 3, ("string", "string", "string"), "string"), + EXPR_FN_LEFT: ExprFnSignature(2, 2, ("string", "int"), "string"), + EXPR_FN_RIGHT: ExprFnSignature(2, 2, ("string", "int"), "string"), + EXPR_FN_LENGTH: ExprFnSignature(1, 1, ("string",), "int"), +} + +# The field subtypes a cast may name in ``as``. +EXPR_CAST_TARGETS: tuple[str, ...] = ( + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, + FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, + FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, +) +_EXPR_NON_SCALAR_SUBTYPES: frozenset[str] = frozenset({FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP}) +_EXPR_INTEGER_SUBTYPES: frozenset[str] = frozenset({FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG}) # Filter-op / compose names shared with the filter vocabulary (see query-constants.ts). _FILTER_OP_EQ = "eq" @@ -1279,6 +1340,75 @@ def ops_for_field(field: MetaData) -> frozenset[str]: }) +def cast_problem(from_type: str | None, to: str, int_stored_enum: bool) -> str | None: + """Why a value of ``from_type`` cannot be cast to ``to``, or None when it can. + ``int_stored_enum`` is whether the operand is an enum field stored as an integer + (``@intValueMap``). The same table in every port: a cast never makes a value of a kind the + source cannot hold. Mirrors the TS castProblem.""" + if from_type is None: + return None # a null literal casts to anything + if from_type in _EXPR_NON_SCALAR_SUBTYPES: + return f"a field.{from_type} value cannot be cast" + if from_type == to: + return None + if from_type == FIELD_SUBTYPE_ENUM: + if to == FIELD_SUBTYPE_STRING: + return ( + "an int-stored enum (@intValueMap) cast to string gives its integer, not its " + "member; cast it to int" + ) if int_stored_enum else None + if to in _EXPR_INTEGER_SUBTYPES: + return None if int_stored_enum else ( + "only an enum stored as an integer (@intValueMap) can be cast to a number" + ) + return f"an enum cannot be cast to {to}" + if to == FIELD_SUBTYPE_STRING or from_type == FIELD_SUBTYPE_STRING: + return None # anything prints; the database parses a string + # Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if to in _EXPR_NUMERIC_SUBTYPES: + if from_type == FIELD_SUBTYPE_BOOLEAN: + return None if to == FIELD_SUBTYPE_INT else f"a boolean casts only to int, not {to}" + return None if from_type in _EXPR_NUMERIC_SUBTYPES else f"a {from_type} cannot be cast to {to}" + if to == FIELD_SUBTYPE_BOOLEAN: + return None if from_type == FIELD_SUBTYPE_INT else ( + f"a {from_type} cannot be cast to boolean; only an int can" + ) + if to in (FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP): + return None if from_type in (FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP) else ( + f"a {from_type} cannot be cast to {to}" + ) + return f"a {from_type} cannot be cast to {to}" + + +def expr_view_only_node(node: object) -> str | None: + """What in an expression tree only a view can hold (a cast, a case, ``now``, a function other + than coalesce, a dotted path), or None: the CHECK-condition subset. Mirrors TS exprViewOnlyNode.""" + if not isinstance(node, dict): + return None + if EXPR_CAST in node: + return EXPR_CAST + if EXPR_CASE in node: + return EXPR_CASE + if EXPR_NOW in node: + return EXPR_NOW + if "fn" in node and node["fn"] != EXPR_FN_COALESCE: + return str(node["fn"]) + field = node.get("field") + if isinstance(field, str) and "." in field: + return f'the path "{field}"' + for key in ("left", "right", "arg"): + hit = expr_view_only_node(node.get(key)) + if hit is not None: + return hit + args = node.get("args") + if isinstance(args, list): + for a in args: + hit = expr_view_only_node(a) + if hit is not None: + return hit + return None + + def validate_expr_node(node: object) -> list[str]: """Structural well-formedness of an expression tree (known node kinds, ops, arity). Returns [] when valid. No entity/type context — see infer_expr_type @@ -1332,13 +1462,40 @@ def validate_expr_node(node: object) -> list[str]: if EXPR_CASE_OPERAND in node: errs.extend(validate_expr_node(node[EXPR_CASE_OPERAND])) return errs + if EXPR_CAST in node: + extra = [k for k in node if k not in (EXPR_CAST, EXPR_CAST_AS, EXPR_CAST_DB_COLUMN_TYPE)] + if extra: + return [ + f"expression '{EXPR_CAST}' takes only '{EXPR_CAST_AS}' and " + f"'{EXPR_CAST_DB_COLUMN_TYPE}' beside it, not {', '.join(extra)}" + ] + to = node.get(EXPR_CAST_AS) + if not isinstance(to, str) or to not in EXPR_CAST_TARGETS: + return [f"'{EXPR_CAST}' requires '{EXPR_CAST_AS}': one of {', '.join(EXPR_CAST_TARGETS)}"] + if EXPR_CAST_DB_COLUMN_TYPE in node: + spelling = node[EXPR_CAST_DB_COLUMN_TYPE] + parsed = parse_db_column_type(spelling) if isinstance(spelling, str) else None + if parsed is None or parsed[0] in ("uuid", "jsonb") or to != FIELD_SUBTYPE_STRING: + return [ + f"'{EXPR_CAST}' '{EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType " + "(text, varchar, character varying, varchar(n), character varying(n), " + f"character(n)) with '{EXPR_CAST_AS}: {FIELD_SUBTYPE_STRING}'" + ] + return validate_expr_node(node[EXPR_CAST]) if "fn" in node: - if node["fn"] != EXPR_FN_COALESCE: - return [f"unknown expression fn '{node['fn']}'"] + name = node["fn"] + sig = EXPR_FUNCTIONS.get(name) if isinstance(name, str) else None + if sig is None: + return [f"unknown expression fn '{name}'"] args = node.get("args") - if isinstance(args, list) and len(args) >= 1: - return [m for a in args for m in validate_expr_node(a)] - return [f"'{EXPR_FN_COALESCE}' requires a non-empty args array"] + if not isinstance(args, list) or len(args) < max(sig.min_args, 1): + return [ + f"'{name}' requires a non-empty args array" if sig.min_args <= 1 + else f"'{name}' requires at least {sig.min_args} args" + ] + if sig.max_args is not None and len(args) > sig.max_args: + return [f"'{name}' takes at most {sig.max_args} args, got {len(args)}"] + return [m for a in args for m in validate_expr_node(a)] if "op" in node: op = node["op"] if not isinstance(op, str): @@ -1357,7 +1514,7 @@ def validate_expr_node(node: object) -> list[str]: return [m for a in args for m in validate_expr_node(a)] return [f"op '{op}' requires a non-empty args array"] return [f"unknown expression op '{op}'"] - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"] + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"] def _literal_type(v: object) -> str | None: @@ -1411,13 +1568,16 @@ class InferResult(NamedTuple): def infer_expr_type( - node: object, resolve_field: Callable[[str], str | None] + node: object, + resolve_field: Callable[[str], str | None], + is_int_stored_enum: Callable[[str], bool] = lambda _name: False, ) -> InferResult: """Bottom-up type inference for a computed expression. ``resolve_field(name)`` returns the subType of a base-entity field ref (None = unresolvable). Comparisons / null-tests / logic → boolean; a field ref → its subType; coalesce → the unified arg subType. Also enforces per-operand op legality against the same bands filters use. - Mirrors the TS inferExprType.""" + ``is_int_stored_enum(name)`` is whether a ``{field}`` names an enum stored as an integer + (``@intValueMap``), which a cast needs. Mirrors the TS inferExprType.""" structural = validate_expr_node(node) if structural: return InferResult(None, structural) @@ -1438,13 +1598,13 @@ def infer_expr_type( return InferResult(FIELD_SUBTYPE_TIMESTAMP, []) if EXPR_CASE in n: errors: list[str] = [] - operand = infer_expr_type(n[EXPR_CASE_OPERAND], resolve_field) if EXPR_CASE_OPERAND in n else None + operand = infer_expr_type(n[EXPR_CASE_OPERAND], resolve_field, is_int_stored_enum) if EXPR_CASE_OPERAND in n else None if operand is not None: errors.extend(operand.errors) results: list[str | None] = [] result_nodes: list[object] = [] for arm in n[EXPR_CASE]: - w = infer_expr_type(arm[EXPR_CASE_WHEN], resolve_field) + w = infer_expr_type(arm[EXPR_CASE_WHEN], resolve_field, is_int_stored_enum) errors.extend(w.errors) if operand is None and w.type is not None and w.type != FIELD_SUBTYPE_BOOLEAN: errors.append(f"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.type}") @@ -1456,12 +1616,12 @@ def infer_expr_type( f"a simple '{EXPR_CASE}' compares its {operand.type} '{EXPR_CASE_OPERAND}' " f"with a {w.type} '{EXPR_CASE_WHEN}'" ) - t = infer_expr_type(arm[EXPR_CASE_THEN], resolve_field) + t = infer_expr_type(arm[EXPR_CASE_THEN], resolve_field, is_int_stored_enum) errors.extend(t.errors) results.append(t.type) result_nodes.append(arm[EXPR_CASE_THEN]) if EXPR_CASE_ELSE in n: - e = infer_expr_type(n[EXPR_CASE_ELSE], resolve_field) + e = infer_expr_type(n[EXPR_CASE_ELSE], resolve_field, is_int_stored_enum) errors.extend(e.errors) results.append(e.type) result_nodes.append(n[EXPR_CASE_ELSE]) @@ -1470,29 +1630,70 @@ def infer_expr_type( errors.append(f"'{EXPR_CASE}' results have differing types ({', '.join(differing)})") return InferResult(unified, errors) - if "fn" in n: # coalesce - arg_results = [infer_expr_type(a, resolve_field) for a in n["args"]] + if EXPR_CAST in n: + inner = n[EXPR_CAST] + operand = infer_expr_type(inner, resolve_field, is_int_stored_enum) + to = n[EXPR_CAST_AS] + field_ref = inner.get("field") if isinstance(inner, dict) else None + problem = cast_problem( + operand.type, to, isinstance(field_ref, str) and is_int_stored_enum(field_ref) + ) + return InferResult( + to, operand.errors if problem is None else [*operand.errors, f"'{EXPR_CAST}': {problem}"] + ) + if "fn" in n: + name = n["fn"] + sig = EXPR_FUNCTIONS[name] + args = n["args"] + arg_results = [infer_expr_type(a, resolve_field, is_int_stored_enum) for a in args] errors = [e for r in arg_results for e in r.errors] - unified, differing = _unify_types(n["args"], [r.type for r in arg_results]) + same: list[str | None] = [] + same_nodes: list[object] = [] + for i, a in enumerate(arg_results): + kind = sig.params[min(i, len(sig.params) - 1)] + if a.type is None: + continue # a null literal fits any parameter + if kind == "same": + same.append(a.type) + same_nodes.append(args[i]) + elif kind == "string" and a.type != FIELD_SUBTYPE_STRING: + errors.append(f"'{name}' argument {i + 1} must be a string, got {a.type}") + elif kind == "int" and a.type != FIELD_SUBTYPE_INT: + # Postgres resolves these functions over int4 only (no implicit bigint -> int for a call). + hint = f"; cast it ({{ cast: , as: int }})" if a.type == FIELD_SUBTYPE_LONG else "" + errors.append(f"'{name}' argument {i + 1} must be an int, got {a.type}{hint}") + elif kind == "scalar" and a.type in _EXPR_NON_SCALAR_SUBTYPES: + errors.append(f"'{name}' argument {i + 1} must be a scalar, got {a.type}") + # Adaptable literals (an int literal beside a decimal) fit the typed anchor. + unified, differing = _unify_types(same_nodes, same) if differing is not None: - errors.append(f"'{EXPR_FN_COALESCE}' arguments have differing types ({', '.join(differing)})") - return InferResult(unified, errors) + errors.append(f"'{name}' arguments have differing types ({', '.join(differing)})") + if sig.ordered and unified is not None and ( + unified == FIELD_SUBTYPE_BOOLEAN or unified in _EXPR_NON_SCALAR_SUBTYPES + ): + errors.append(f"'{name}' needs ordered arguments, got {unified}") + result = ( + unified if sig.result == "same" + else FIELD_SUBTYPE_INT if sig.result == "int" + else FIELD_SUBTYPE_STRING + ) + return InferResult(result, errors) op = n["op"] if op in _COMPARISON_OPS: - left = infer_expr_type(n["left"], resolve_field) - right = infer_expr_type(n["right"], resolve_field) + left = infer_expr_type(n["left"], resolve_field, is_int_stored_enum) + right = infer_expr_type(n["right"], resolve_field, is_int_stored_enum) errors = [*left.errors, *right.errors] if left.type is not None and op not in ops_for_subtype(left.type): errors.append(f"op '{op}' is not legal for a {left.type} operand") return InferResult(FIELD_SUBTYPE_BOOLEAN, errors) if op in _NULL_OPS: - return InferResult(FIELD_SUBTYPE_BOOLEAN, infer_expr_type(n["arg"], resolve_field).errors) + return InferResult(FIELD_SUBTYPE_BOOLEAN, infer_expr_type(n["arg"], resolve_field, is_int_stored_enum).errors) if op == EXPR_OP_NOT or op in _VARIADIC_LOGIC_OPS: kids = [n["arg"]] if op == EXPR_OP_NOT else n["args"] errors = [] for k in kids: - kt = infer_expr_type(k, resolve_field) + kt = infer_expr_type(k, resolve_field, is_int_stored_enum) errors.extend(kt.errors) if kt.type is not None and kt.type != FIELD_SUBTYPE_BOOLEAN: errors.append(f"op '{op}' requires boolean operands, got {kt.type}") @@ -3002,7 +3203,26 @@ def _resolve_field( ErrorCode.ERR_INVALID_ORIGIN, envelope=src)) continue - inferred = infer_expr_type(expr, _resolve_field) + def _is_int_stored_enum( + name: str, _base: MetaData = base, _obj: MetaData = obj, _self: str = node.name + ) -> bool: + # A cast needs it: an enum stored as an integer (@intValueMap), resolved as the + # inference resolved the ref (the projection's own field first, else a base field). + target = None + if _obj is not _base and name != _self: + target = next( + (o for o in _obj.children() if o.type == TYPE_FIELD and o.name == name), None + ) + if target is None: + target = next( + (f for f in _base.children() if f.type == TYPE_FIELD and f.name == name), None + ) + return ( + target is not None and target.sub_type == FIELD_SUBTYPE_ENUM + and target.attrs().get(FIELD_ATTR_INT_VALUE_MAP) is not None + ) + + inferred = infer_expr_type(expr, _resolve_field, _is_int_stored_enum) if inferred.errors: for m in inferred.errors: errors.append(MetaError( @@ -4409,7 +4629,7 @@ def _expr_nodes(node: object, out: list[dict[str, Any]] | None = None) -> list[d if not isinstance(node, dict): return out out.append(node) - for key in ("left", "right", "arg", EXPR_CASE_OPERAND, EXPR_CASE_ELSE): + for key in ("left", "right", "arg", EXPR_CAST, EXPR_CASE_OPERAND, EXPR_CASE_ELSE): _expr_nodes(node.get(key), out) args = node.get("args") if isinstance(args, list): @@ -4495,6 +4715,15 @@ def _condition_problem(condition: object, obj: MetaData) -> str | None: f"is not a valid expression: a condition takes no '{kind}' node, " f"since a CHECK can hold neither a CASE nor the current time." ) + # A CHECK holds the condition's SQL, rendered by every port's CHECK emitter, which takes fields, + # literals, comparisons, null tests, and / or / not and coalesce. The rest of the expression + # grammar (case, now, cast, the other functions, paths) is for views only. + view_only = expr_view_only_node(condition) + if view_only is not None: + return ( + f"uses {view_only}, which a CHECK condition cannot hold: it takes fields, literals, " + "comparisons, null tests, and / or / not, and coalesce." + ) fields = {f.name: f for f in obj.fields()} inferred = infer_expr_type( condition, lambda name: fields[name].sub_type if name in fields else None diff --git a/server/python/src/metaobjects/runtime/__init__.py b/server/python/src/metaobjects/runtime/__init__.py index 70df1e18b1..2e1745c6bb 100644 --- a/server/python/src/metaobjects/runtime/__init__.py +++ b/server/python/src/metaobjects/runtime/__init__.py @@ -1,14 +1,15 @@ -"""Minimal runtime persistence layer — ObjectManager + Postgres driver. +"""Runtime persistence layer — the abstract ``ObjectManager`` and ``ObjectManagerDb``. -Cross-port shape mirrors TS runtime-ts and Java ObjectManagerDB: method-based -query API (`find_by_id` / `find_many` / `count`) that translates a Filter dict -into parameterized SQL via a pluggable driver. The corpus query scenarios -exercise eq/ne/gt/gte/lt/lte/in/like/isNull operators + the top-level `and:` -combinator + asc/desc sort + limit/offset. +Cross-port shape mirrors Java ``ObjectManager`` / ``ObjectManagerDB``: ``ObjectManager`` is the +store-neutral contract (method-based API, listeners, transactions); ``ObjectManagerDb`` is the +DB-API implementation that translates a Filter dict into parameterized SQL via a driver +(Postgres, SQLite, MySQL). The corpus query scenarios exercise eq/ne/gt/gte/lt/lte/in/like/isNull +operators + the top-level `and:` combinator + asc/desc sort + limit/offset. """ from .dialect import MYSQL, POSTGRES, SQLITE, Dialect -from .drivers import MySqlDriver, SqliteDriver -from .object_manager import DbApiDriver, Filter, ObjectManager, PostgresDriver +from .drivers import DbApiDriver, MySqlDriver, PostgresDriver, SelectResult, SqliteDriver +from .object_manager import Filter, ObjectManager, PersistenceListener +from .object_manager_db import ObjectManagerDb from .validator_runner import ValidationFailure, ValidationResult, run_validators from .llm_recorder import ( STATUS_ERROR, @@ -34,6 +35,9 @@ "SQLITE", "SqliteDriver", "ObjectManager", + "ObjectManagerDb", + "PersistenceListener", + "SelectResult", "PostgresDriver", "ValidationFailure", "ValidationResult", diff --git a/server/python/src/metaobjects/runtime/drivers.py b/server/python/src/metaobjects/runtime/drivers.py index 91ad569a95..296b97555f 100644 --- a/server/python/src/metaobjects/runtime/drivers.py +++ b/server/python/src/metaobjects/runtime/drivers.py @@ -1,11 +1,29 @@ -"""Drivers for the engines beyond Postgres: SQLite (stdlib ``sqlite3``) and MySQL (PyMySQL). +"""The DB-API drivers: a connection plus the engine's :class:`~metaobjects.runtime.dialect.Dialect`. -Each is a :class:`~metaobjects.runtime.object_manager.DbApiDriver` that names its -:class:`~metaobjects.runtime.dialect.Dialect`; the ObjectManager reads the dialect off the -driver, so ``ObjectManager(root, SqliteDriver(conn))`` is the whole wiring. +:class:`DbApiDriver` is the base; :class:`PostgresDriver` (pg8000 / psycopg), +:class:`SqliteDriver` (stdlib ``sqlite3``) and :class:`MySqlDriver` (PyMySQL) name their +dialect. :class:`~metaobjects.runtime.object_manager_db.ObjectManagerDb` reads the dialect off +the driver, so ``ObjectManagerDb(root, SqliteDriver(conn))`` is the whole wiring. + +Per ADR-0019 (runtime return-type contract) the query path returns **native, in-process +Python types** — pg8000's own `int` / `Decimal` / `datetime` / `date` / `time` / +`uuid.UUID` / `dict` / `list`. Canonicalization to the cross-port wire form is a +serialization/boundary concern, applied by the persistence runner (see +``tests/integration/normalization.py``), never baked into this runtime query path. + +The one piece of SQL-type information the boundary cannot recover from a native Python value +is the int4-vs-int8 distinction (pg8000 returns plain ``int`` for both INTEGER and BIGINT, and +a BIGINT aggregate over an INTEGER column is genuinely indistinguishable by value). Other +ports get this from their driver's native typing. To keep the same discriminator available at +the Python boundary each query result carries the per-column OID beside the rows +(:class:`SelectResult`) — out-of-band type metadata, not a mutation of the native row values. + +**Transactions.** A write commits on its own unless it runs inside :meth:`DbApiDriver.transaction`, +which holds every statement in it open on the connection and commits once when the outermost +block ends, or rolls all of it back when the block raises. A block inside a block joins it. * **SQLite** has no per-column type codes (a column's declared type is not on the cursor), - so the ObjectManager derives the wire discriminator from each field's declared subtype. + so the manager derives the wire discriminator from each field's declared subtype. ``RETURNING`` needs SQLite >= 3.35; on an older library the write path inserts and then re-reads the row by key, as it does for MySQL. * **MySQL** has no ``RETURNING`` at all; the write path re-reads the row by key (the @@ -18,10 +36,284 @@ """ from __future__ import annotations -from typing import Any +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any, Protocol + +from ..codegen.runtime.duration_wire import parse_postgres_interval +from .dialect import MYSQL, POSTGRES, SQLITE, Dialect + + +class Cursor(Protocol): + def execute(self, sql: str, params: tuple[Any, ...] = ...) -> Any: ... + def fetchall(self) -> list[Any]: ... + @property + def description(self) -> Any: ... + @property + def rowcount(self) -> int: ... + def close(self) -> None: ... + + +class Connection(Protocol): + def cursor(self) -> Cursor: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def close(self) -> None: ... + + +class SelectResult: + """A native-typed result set plus the per-column OID type metadata. + + ``rows`` carry pg8000's native Python values verbatim (ADR-0019 — the runtime + returns native types, never wire-strings). ``column_oids`` maps each selected + column name to its Postgres type OID so the serialization boundary can apply + the int4-vs-int8 (and any other SQL-type-driven) wire rule without inspecting + the value — type metadata travels beside the data, not inside it. + """ + + __slots__ = ("rows", "column_oids") + + def __init__(self, rows: list[dict[str, Any]], column_oids: dict[str, int]) -> None: + self.rows = rows + self.column_oids = column_oids + + +class DbApiDriver: + """Wrap a DB-API 2 connection. Owns no state beyond the connection and its + :class:`~metaobjects.runtime.dialect.Dialect`. + + Subclasses pick the dialect and the per-column type metadata; everything else (the + cursor handling, commit-per-write, parameter encoding) is shared. Statements arrive + already spelled for the dialect (quoting, placeholders), and every bound parameter is + run through :meth:`Dialect.encode_param` here, so no caller binds an engine-specific + spelling by hand.""" + + dialect: Dialect = POSTGRES + + def __init__(self, conn: Connection) -> None: + self._conn = conn + self._depth = 0 # transaction() blocks currently open + + @property + def in_transaction(self) -> bool: + """Whether a :meth:`transaction` block is open: a write then does not commit.""" + return self._depth > 0 + + def _commit_write(self) -> None: + """Commit one write, unless it is held by an open :meth:`transaction`.""" + if self._depth == 0: + self._conn.commit() + + @contextmanager + def transaction(self) -> Iterator[None]: + """Hold every statement run inside the block in one transaction on the connection. + + The outermost block commits once when it ends and rolls everything back when it + raises (the exception then propagates). A block opened inside another joins it: + there is no savepoint, so an exception that leaves an inner block unwinds through + the outer one and rolls the whole transaction back, unless the caller catches it + between the two (the work done so far is then still held, and commits with the outer + block). A caller that needs a failure to undo only part of the work uses a + savepoint of its own on the connection.""" + self._depth += 1 + try: + yield + except BaseException: + self._depth -= 1 + if self._depth == 0: + self._conn.rollback() + raise + else: + self._depth -= 1 + if self._depth == 0: + self._conn.commit() + + def _cursor(self) -> Any: + """A cursor for one statement (a driver may set it up for its engine).""" + return self._conn.cursor() + + def _bind(self, params: tuple[Any, ...]) -> tuple[Any, ...]: + return tuple(self.dialect.encode_param(p) for p in params) + + @staticmethod + def _type_codes(description: Any) -> list[Any]: + """Per-column SQL type codes beside the names (Postgres: the type OID).""" + return [d[1] for d in description] + + def _result(self, description: Any, rows: list[Any]) -> SelectResult: + cols = [d[0] for d in description] + codes = self._type_codes(description) + column_oids = {c: codes[i] for i, c in enumerate(cols) if codes[i] is not None} + return SelectResult([{c: row[i] for i, c in enumerate(cols)} for row in rows], column_oids) + + def select(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: + cur = self._cursor() + try: + cur.execute(sql, self._bind(params)) + return self._result(cur.description, list(cur.fetchall())) + finally: + cur.close() + + def scalar(self, sql: str, params: tuple[Any, ...] = ()) -> Any: + result = self.select(sql, params) + if not result.rows: + return None + return next(iter(result.rows[0].values())) + + def insert_returning(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: + """Run an INSERT ... RETURNING and return a single-row :class:`SelectResult` + (row + per-column OID type metadata). + + The write path commits on success (each conformance scenario owns a + fresh container, so autocommit-per-write semantics are fine and keep the + round-trip read in the same connection visible without a separate + transaction handshake). The OIDs carry the int4-vs-int8 (BIGINT→string) + wire discriminator into the serialization boundary, exactly like the read + path — so an op:create asserting the RETURNING row sees BIGINT as a string. + """ + cur = self._cursor() + try: + cur.execute(sql, self._bind(params)) + description = cur.description + rows = list(cur.fetchall())[:1] + self._commit_write() + return self._result(description, rows) + finally: + cur.close() + + def update_returning( + self, sql: str, params: tuple[Any, ...] = () + ) -> SelectResult | None: + """Run an UPDATE ... RETURNING; return a single-row :class:`SelectResult` + (row + per-column OID type metadata), or ``None`` when no row matched. + Commits on success (same per-write autocommit semantics as + ``insert_returning``). The OIDs carry the int4-vs-int8 (BIGINT→string) + wire discriminator into the serialization boundary, exactly like the read + path — so a BIGINT/currency column updates back as a numeric string.""" + cur = self._cursor() + try: + cur.execute(sql, self._bind(params)) + description = cur.description + rows = list(cur.fetchall())[:1] + self._commit_write() + if not rows: + return None + return self._result(description, rows) + finally: + cur.close() + + def insert_last_id(self, sql: str, params: tuple[Any, ...] = ()) -> Any: + """Run an INSERT on an engine with no ``RETURNING`` and answer the key the + engine generated (``lastrowid``; ``0`` / ``None`` when the caller supplied the key). + Commits on success.""" + cur = self._cursor() + try: + cur.execute(sql, self._bind(params)) + last = getattr(cur, "lastrowid", None) + self._commit_write() + return last + finally: + cur.close() + + def execute_rowcount(self, sql: str, params: tuple[Any, ...] = ()) -> int: + """Run a DML statement (DELETE / UPDATE) and return the affected row + count. Commits on success.""" + cur = self._cursor() + try: + cur.execute(sql, self._bind(params)) + count = cur.rowcount + self._commit_write() + return int(count) if count is not None else 0 + finally: + cur.close() + + +class PostgresDriver(DbApiDriver): + """Wrap a pg8000 / psycopg connection (the Postgres dialect). + + An ``interval`` is read exactly, and one with a year or month part is never turned into a + ``timedelta`` (a month has no fixed length, so a ``field.duration`` refuses it): + + * **pg8000** gets an exact ``interval`` / ``interval[]`` reader registered on the connection + (pg8000 has no per-cursor adapters). pg8000 1.31 drops the sign of a negative time part's + minutes and seconds (``-00:01:30`` reads as ``+90 s``, ``-01:30:00`` as ``-30 min``). The + reader takes the default-``IntervalStyle`` text exactly (:func:`parse_postgres_interval`) + and hands anything else to pg8000's own reader, so an interval with a year or month part + is still the ``PGInterval`` pg8000 makes of it, and every other interval reads as before. + * **psycopg** (3, and psycopg2) turns a month into 30 days and a year into 365. The reader + is registered on each cursor this driver opens, never on the connection: it reads the + text exactly and hands an interval it cannot read as a fixed span back as its text, which + a ``field.duration`` refuses.""" + + dialect = POSTGRES + + def __init__(self, conn: Connection) -> None: + super().__init__(conn) + _register_pg8000_interval_reader(conn) + + def _cursor(self) -> Any: + cur = self._conn.cursor() + _register_psycopg_interval_reader(cur) + return cur + + +def _interval_or_text(text: str) -> Any: + """The default-style text of an interval as a ``timedelta``, or the text itself when it is + not one this reads exactly (a year or month part, another ``IntervalStyle``): a + ``field.duration`` read refuses that text rather than guessing.""" + try: + return parse_postgres_interval(text) + except ValueError: + return text + + +def _register_pg8000_interval_reader(conn: Any) -> None: + """Register the exact ``interval`` reader on a pg8000 connection; any other is untouched.""" + register = getattr(conn, "register_in_adapter", None) + if not callable(register) or not type(conn).__module__.startswith("pg8000"): + return + from pg8000 import converters as _pgc # type: ignore[import-untyped] # only with a pg8000 connection + + pg8000_interval_in = _pgc.interval_in + + def interval_in(text: str) -> Any: + value = _interval_or_text(text) + # Not read here: pg8000's own reading (a PGInterval for a year or month part). + return pg8000_interval_in(text) if isinstance(value, str) else value + + register(_pgc.INTERVAL, interval_in) + register(_pgc.INTERVAL_ARRAY, _pgc._array_in(interval_in)) + + +#: The psycopg 3 text loader for ``interval``, made on first use (psycopg is optional). +_PSYCOPG_INTERVAL_LOADER: Any = None + + +def _register_psycopg_interval_reader(cur: Any) -> None: + """Register the exact ``interval`` reader on a psycopg 3 or psycopg2 cursor.""" + module = type(cur).__module__ + if module.startswith("psycopg2"): + import psycopg2.extensions as _ext # type: ignore[import-untyped] # only with a psycopg2 cursor + + interval = _ext.new_type( + (1186,), "METAOBJECTS_INTERVAL", lambda v, _c: None if v is None else _interval_or_text(v) + ) + _ext.register_type(interval, cur) + _ext.register_type(_ext.new_array_type((1187,), "METAOBJECTS_INTERVAL_ARRAY", interval), cur) + return + adapters = getattr(cur, "adapters", None) + if adapters is None or not module.startswith("psycopg"): + return + global _PSYCOPG_INTERVAL_LOADER + if _PSYCOPG_INTERVAL_LOADER is None: + from psycopg.adapt import Loader # type: ignore[import-not-found, unused-ignore] # only with psycopg 3 + + class _IntervalLoader(Loader): # type: ignore[misc, unused-ignore] + def load(self, data: Any) -> Any: + return _interval_or_text(bytes(data).decode("ascii")) -from .dialect import MYSQL, SQLITE, Dialect -from .object_manager import DbApiDriver + _PSYCOPG_INTERVAL_LOADER = _IntervalLoader + adapters.register_loader("interval", _PSYCOPG_INTERVAL_LOADER) class SqliteDriver(DbApiDriver): diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index d6568c86cb..efb7d2e7f8 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1,73 +1,39 @@ -"""ObjectManager + the DB-API drivers — minimal query runtime. +"""ObjectManager — the store-neutral contract of the runtime persistence layer. -Compiles a Filter dict to parameterized SQL and runs it via a DB-API 2 driver. The SQL is -spelled by the driver's :class:`~metaobjects.runtime.dialect.Dialect`: Postgres (here: -``PostgresDriver``, pg8000 / psycopg) double-quotes identifiers and uses ``%s`` -placeholders (mixed-case columns like `programId` round-trip through PG); SQLite and MySQL -drivers live in :mod:`metaobjects.runtime.drivers`. +Cross-port shape mirrors the Java ``ObjectManager`` / ``ObjectManagerDB`` pair: this abstract +class is what generated and hand-written code is written against, and a concrete manager +supplies the store. :class:`~metaobjects.runtime.object_manager_db.ObjectManagerDb` is the +DB-API one (Postgres, SQLite, MySQL). -Per ADR-0019 (runtime return-type contract) the query path returns **native, -in-process Python types** — pg8000's own `int` / `Decimal` / `datetime` / -`date` / `time` / `uuid.UUID` / `dict` / `list`. Canonicalization to the -cross-port wire form is a *serialization/boundary* concern, applied by the -persistence runner (see ``tests/integration/normalization.py``), never baked -into this runtime query path. +What lives here is what does not depend on a store: -The one piece of SQL-type information the boundary cannot recover from a native -Python value is the int4-vs-int8 distinction (pg8000 returns plain ``int`` for -both INTEGER and BIGINT, and a BIGINT aggregate over an INTEGER column — e.g. -``count``/``sum`` → BIGINT vs ``min``/``max`` → INTEGER on the projection views — -is genuinely indistinguishable by value). Other ports get this for free from -their driver's native typing (Java JDBC ``Long`` vs ``Integer``; node-postgres -BIGINT-as-string vs INTEGER-as-number). To keep the same discriminator available -at the Python boundary we expose the per-column OID alongside each query — as -out-of-band type metadata, not by mutating the native row values — so the runner -can apply the BIGINT→string wire rule by SQL type, exactly like the other ports. +* the method-based API (``find_by_id`` / ``find_many`` / ``count`` / ``create`` / ``update`` / + ``delete`` / ``relate``) and the Filter shape; +* looking an object up by name and refusing what a report cannot do; +* ``@autoSet`` stamping (#203); +* :meth:`transaction`, which a store implements; +* persistence listeners (:class:`PersistenceListener`), notified around every write. + +Write methods are template methods: the base refuses reports, stamps, notifies the listeners +and calls the store's ``_insert_row`` / ``_update_row`` / ``_delete_row``. """ from __future__ import annotations import datetime as _dt -import decimal as _decimal -import json as _json -import math as _math -import re as _re -import uuid as _uuid +from abc import ABC, abstractmethod from collections.abc import Iterable, Mapping -from typing import Any, Protocol +from contextlib import AbstractContextManager +from typing import Any -from ..codegen.runtime.duration_wire import ( - duration_from_driver, - format_duration, - parse_duration_input, - parse_postgres_interval, -) -from ..meta.meta_root import MetaRoot +from ..meta.core.identity import identity_constants as ic from ..meta.core.object.meta_object import MetaObject -from ..naming_refs import ref_target -from ..meta.core.object.object_constants import OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_REPORT +from ..meta.core.object.object_constants import OBJECT_SUBTYPE_REPORT from ..meta.core.reporting.report_read_model import report_read_model -from ..meta.core.field.meta_field import MetaField -from ..meta.core.field import field_constants as fc -from ..naming import ( - DEFAULT_COLUMN_NAMING, - naming_rules_of, - removed_naming_source_message, - resolve_column_name, -) -from ..meta.core.identity import identity_constants as ic -from ..meta.persistence.db import db_constants as dbc +from ..meta.meta_root import MetaRoot from ..meta.persistence.source.meta_source import MetaSource -from ..source_resolution import primary_rdb_source, resolve_table_name -from .n2m_resolver import ( - N2mDescriptor, - collect_column_ids, - collect_symmetric_target_ids, - resolve_n2m_descriptor, -) -from .dialect import MYSQL, POSTGRES, Dialect, DurationParam -from .tph import TphSubtype, tph_subtype_of +from ..naming import naming_rules_of from .validator_runner import ValidationResult, run_validators - +from .values import auto_set_fields, auto_set_stamp, coerce_key_value # Filter shape: # {"field": "value"} → equality shortcut @@ -76,264 +42,48 @@ Filter = dict[str, Any] -class Cursor(Protocol): - def execute(self, sql: str, params: tuple[Any, ...] = ...) -> Any: ... - def fetchall(self) -> list[Any]: ... - @property - def description(self) -> Any: ... - @property - def rowcount(self) -> int: ... - def close(self) -> None: ... - - -class Connection(Protocol): - def cursor(self) -> Cursor: ... - def commit(self) -> None: ... - def close(self) -> None: ... - - -class SelectResult: - """A native-typed result set plus the per-column OID type metadata. - - ``rows`` carry pg8000's native Python values verbatim (ADR-0019 — the runtime - returns native types, never wire-strings). ``column_oids`` maps each selected - column name to its Postgres type OID so the serialization boundary can apply - the int4-vs-int8 (and any other SQL-type-driven) wire rule without inspecting - the value — type metadata travels beside the data, not inside it. - """ - - __slots__ = ("rows", "column_oids") - - def __init__(self, rows: list[dict[str, Any]], column_oids: dict[str, int]) -> None: - self.rows = rows - self.column_oids = column_oids - - -class DbApiDriver: - """Wrap a DB-API 2 connection. Owns no state beyond the connection and its - :class:`~metaobjects.runtime.dialect.Dialect`. +class PersistenceListener: + """Notified around every write a manager makes. Subclass and override what you need; every + method does nothing by default (the Java ``PersistenceEventListener``). - Subclasses pick the dialect and the per-column type metadata; everything else (the - cursor handling, commit-per-write, parameter encoding) is shared. Statements arrive - already spelled for the dialect (quoting, placeholders), and every bound parameter is - run through :meth:`Dialect.encode_param` here, so no caller binds an engine-specific - spelling by hand.""" + ``entity_name`` is the object's name as the manager API takes it. A ``before`` method runs + before anything is written and may raise to refuse the write, which then does not happen; + an ``after`` method runs once the store has the change. Inside + :meth:`ObjectManager.transaction` an ``after`` method runs BEFORE the transaction commits, + so an exception from it rolls the whole transaction back. A listener sees the data as the + caller passed it (``on_before_*``) and the row as persisted (``on_after_*``, with + ``@autoSet`` timestamps, generated keys and column defaults filled in).""" - dialect: Dialect = POSTGRES + def on_before_create(self, entity_name: str, data: dict[str, Any]) -> None: ... - def __init__(self, conn: Connection) -> None: - self._conn = conn + def on_after_create(self, entity_name: str, row: dict[str, Any]) -> None: ... - def _cursor(self) -> Any: - """A cursor for one statement (a driver may set it up for its engine).""" - return self._conn.cursor() + def on_before_update(self, entity_name: str, id_value: Any, data: dict[str, Any]) -> None: ... - def _bind(self, params: tuple[Any, ...]) -> tuple[Any, ...]: - return tuple(self.dialect.encode_param(p) for p in params) + def on_after_update(self, entity_name: str, id_value: Any, row: dict[str, Any]) -> None: + """Not called when no row matched the key.""" - @staticmethod - def _type_codes(description: Any) -> list[Any]: - """Per-column SQL type codes beside the names (Postgres: the type OID).""" - return [d[1] for d in description] - - def _result(self, description: Any, rows: list[Any]) -> SelectResult: - cols = [d[0] for d in description] - codes = self._type_codes(description) - column_oids = {c: codes[i] for i, c in enumerate(cols) if codes[i] is not None} - return SelectResult([{c: row[i] for i, c in enumerate(cols)} for row in rows], column_oids) - - def select(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: - cur = self._cursor() - try: - cur.execute(sql, self._bind(params)) - return self._result(cur.description, list(cur.fetchall())) - finally: - cur.close() - - def scalar(self, sql: str, params: tuple[Any, ...] = ()) -> Any: - result = self.select(sql, params) - if not result.rows: - return None - return next(iter(result.rows[0].values())) - - def insert_returning(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: - """Run an INSERT ... RETURNING and return a single-row :class:`SelectResult` - (row + per-column OID type metadata). - - The write path commits on success (each conformance scenario owns a - fresh container, so autocommit-per-write semantics are fine and keep the - round-trip read in the same connection visible without a separate - transaction handshake). The OIDs carry the int4-vs-int8 (BIGINT→string) - wire discriminator into the serialization boundary, exactly like the read - path — so an op:create asserting the RETURNING row sees BIGINT as a string. - """ - cur = self._cursor() - try: - cur.execute(sql, self._bind(params)) - description = cur.description - rows = list(cur.fetchall())[:1] - self._conn.commit() - return self._result(description, rows) - finally: - cur.close() - - def update_returning( - self, sql: str, params: tuple[Any, ...] = () - ) -> SelectResult | None: - """Run an UPDATE ... RETURNING; return a single-row :class:`SelectResult` - (row + per-column OID type metadata), or ``None`` when no row matched. - Commits on success (same per-write autocommit semantics as - ``insert_returning``). The OIDs carry the int4-vs-int8 (BIGINT→string) - wire discriminator into the serialization boundary, exactly like the read - path — so a BIGINT/currency column updates back as a numeric string.""" - cur = self._cursor() - try: - cur.execute(sql, self._bind(params)) - description = cur.description - rows = list(cur.fetchall())[:1] - self._conn.commit() - if not rows: - return None - return self._result(description, rows) - finally: - cur.close() - - def insert_last_id(self, sql: str, params: tuple[Any, ...] = ()) -> Any: - """Run an INSERT on an engine with no ``RETURNING`` and answer the key the - engine generated (``lastrowid``; ``0`` / ``None`` when the caller supplied the key). - Commits on success.""" - cur = self._cursor() - try: - cur.execute(sql, self._bind(params)) - last = getattr(cur, "lastrowid", None) - self._conn.commit() - return last - finally: - cur.close() - - def execute_rowcount(self, sql: str, params: tuple[Any, ...] = ()) -> int: - """Run a DML statement (DELETE / UPDATE) and return the affected row - count. Commits on success.""" - cur = self._cursor() - try: - cur.execute(sql, self._bind(params)) - count = cur.rowcount - self._conn.commit() - return int(count) if count is not None else 0 - finally: - cur.close() + def on_before_delete(self, entity_name: str, id_value: Any) -> None: ... + def on_after_delete(self, entity_name: str, id_value: Any) -> None: + """Not called when no row matched the key.""" -class PostgresDriver(DbApiDriver): - """Wrap a pg8000 / psycopg connection (the Postgres dialect). - An ``interval`` is read exactly, and one with a year or month part is never turned into a - ``timedelta`` (a month has no fixed length, so a ``field.duration`` refuses it): +class ObjectManager(ABC): + """The persistence contract. Abstract: construct a concrete manager, e.g. + ``ObjectManagerDb(root, driver)``.""" - * **pg8000** gets an exact ``interval`` / ``interval[]`` reader registered on the connection - (pg8000 has no per-cursor adapters). pg8000 1.31 drops the sign of a negative time part's - minutes and seconds (``-00:01:30`` reads as ``+90 s``, ``-01:30:00`` as ``-30 min``). The - reader takes the default-``IntervalStyle`` text exactly (:func:`parse_postgres_interval`) - and hands anything else to pg8000's own reader, so an interval with a year or month part - is still the ``PGInterval`` pg8000 makes of it, and every other interval reads as before. - * **psycopg** (3, and psycopg2) turns a month into 30 days and a year into 365. The reader - is registered on each cursor this driver opens, never on the connection: it reads the - text exactly and hands an interval it cannot read as a fixed span back as its text, which - a ``field.duration`` refuses.""" - - dialect = POSTGRES - - def __init__(self, conn: Connection) -> None: - super().__init__(conn) - _register_pg8000_interval_reader(conn) - - def _cursor(self) -> Any: - cur = self._conn.cursor() - _register_psycopg_interval_reader(cur) - return cur - - -def _interval_or_text(text: str) -> Any: - """The default-style text of an interval as a ``timedelta``, or the text itself when it is - not one this reads exactly (a year or month part, another ``IntervalStyle``): a - ``field.duration`` read refuses that text rather than guessing.""" - try: - return parse_postgres_interval(text) - except ValueError: - return text - - -def _register_pg8000_interval_reader(conn: Any) -> None: - """Register the exact ``interval`` reader on a pg8000 connection; any other is untouched.""" - register = getattr(conn, "register_in_adapter", None) - if not callable(register) or not type(conn).__module__.startswith("pg8000"): - return - from pg8000 import converters as _pgc # type: ignore[import-untyped] # only with a pg8000 connection - - pg8000_interval_in = _pgc.interval_in - - def interval_in(text: str) -> Any: - value = _interval_or_text(text) - # Not read here: pg8000's own reading (a PGInterval for a year or month part). - return pg8000_interval_in(text) if isinstance(value, str) else value - - register(_pgc.INTERVAL, interval_in) - register(_pgc.INTERVAL_ARRAY, _pgc._array_in(interval_in)) - - -#: The psycopg 3 text loader for ``interval``, made on first use (psycopg is optional). -_PSYCOPG_INTERVAL_LOADER: Any = None - - -def _register_psycopg_interval_reader(cur: Any) -> None: - """Register the exact ``interval`` reader on a psycopg 3 or psycopg2 cursor.""" - module = type(cur).__module__ - if module.startswith("psycopg2"): - import psycopg2.extensions as _ext # type: ignore[import-untyped] # only with a psycopg2 cursor - - interval = _ext.new_type( - (1186,), "METAOBJECTS_INTERVAL", lambda v, _c: None if v is None else _interval_or_text(v) - ) - _ext.register_type(interval, cur) - _ext.register_type(_ext.new_array_type((1187,), "METAOBJECTS_INTERVAL_ARRAY", interval), cur) - return - adapters = getattr(cur, "adapters", None) - if adapters is None or not module.startswith("psycopg"): - return - global _PSYCOPG_INTERVAL_LOADER - if _PSYCOPG_INTERVAL_LOADER is None: - from psycopg.adapt import Loader # type: ignore[import-not-found, unused-ignore] # only with psycopg 3 - - class _IntervalLoader(Loader): # type: ignore[misc, unused-ignore] - def load(self, data: Any) -> Any: - return _interval_or_text(bytes(data).decode("ascii")) - - _PSYCOPG_INTERVAL_LOADER = _IntervalLoader - adapters.register_loader("interval", _PSYCOPG_INTERVAL_LOADER) - - -class ObjectManager: - """Method-based read API. Translates Filter dicts → parameterized SQL.""" - - def __init__( - self, - root: MetaRoot, - driver: DbApiDriver, - column_naming: str | None = None, - ) -> None: - if column_naming is not None: - # ADR-0058 Decision 4 — `ObjectManager(column_naming=...)` was removed in - # 1.1.0: naming is one project setting now, read from the loaded root - # (never guessed — the old value may have been right for that adopter's - # database, and silently dropping it would rename every column). - raise ValueError( - removed_naming_source_message("ObjectManager(column_naming=...)", column_naming) + def __new__(cls, *args: Any, **kwargs: Any) -> "ObjectManager": + if cls is ObjectManager: + raise TypeError( + "ObjectManager is the abstract persistence contract and cannot be constructed. " + "Construct ObjectManagerDb(root, driver) for a DB-API connection " + "(metaobjects.runtime.ObjectManagerDb); write code against ObjectManager." ) + return super().__new__(cls) + + def __init__(self, root: MetaRoot) -> None: self._root = root - self._driver = driver - #: The SQL dialect of the driver's engine; a driver that declares none (a test - #: double) is Postgres, the corpus' own engine. - self._d: Dialect = getattr(driver, "dialect", POSTGRES) # How a field with no explicit `@column` becomes a physical column name — # ADR-0058: THE one project setting, read from the loaded root # (`naming_rules_of`), so codegen's `names` generator and this runtime cannot @@ -346,21 +96,43 @@ def __init__( for c in root.own_children(): if isinstance(c, MetaObject): self._entity_by_name.setdefault(c.name, c) - #: Per-field Postgres type OID from the most recent ``find_*`` query, - #: keyed by metadata field name. Out-of-band SQL-type metadata for the - #: serialization boundary (the int4-vs-int8 wire discriminator); the - #: returned row values themselves stay native (ADR-0019). - #: - #: Single-query-scoped: overwritten by each ``find_*`` call, so read it - #: immediately after the query whose result you are serializing. Not - #: safe to interleave concurrent queries on one ObjectManager instance - #: (the row values are unaffected — only this discriminator is racy). + self._listeners: list[PersistenceListener] = [] + #: Per-field SQL type code from the most recent ``find_*`` query, keyed by metadata + #: field name. Out-of-band SQL-type metadata for the serialization boundary (the + #: int4-vs-int8 wire discriminator); the returned row values themselves stay native + #: (ADR-0019). Single-query-scoped: overwritten by each query, so read it immediately + #: after the query whose result you are serializing. Not safe to interleave + #: concurrent queries on one manager instance (the row values are unaffected — only + #: this discriminator is racy). A store with no such codes leaves it empty. self.last_column_oids: dict[str, int] = {} + # --- Listeners ----------------------------------------------------------- + + def add_listener(self, listener: PersistenceListener) -> None: + """Register *listener*; it is notified, in registration order, around every write.""" + self._listeners.append(listener) + + def remove_listener(self, listener: PersistenceListener) -> None: + """Unregister *listener* (a listener that was never added is ignored).""" + if listener in self._listeners: + self._listeners.remove(listener) + + def _notify(self, event: str, *args: Any) -> None: + for listener in tuple(self._listeners): + getattr(listener, event)(*args) + + # --- Transactions -------------------------------------------------------- + + @abstractmethod + def transaction(self) -> AbstractContextManager[None]: + """``with om.transaction(): ...`` — every write made inside the block commits together + when the (outermost) block ends and rolls back together when it raises. A block opened + inside another joins it. Reads inside the block see the block's own writes.""" + # --- Public API ---------------------------------------------------------- def validate(self, entity_name: str, data: Mapping[str, Any]) -> ValidationResult: - """Validate ``data`` against ``entity_name``'s metadata — no database access, and + """Validate ``data`` against ``entity_name``'s metadata — no store access, and nothing is raised for invalid data: the failures come back on the result. Mirrors the TS ``om.validate()``. The write methods do not call it; validate first when the data is untrusted.""" @@ -372,10 +144,32 @@ def find_by_id(self, entity_name: str, id_value: Any) -> dict[str, Any] | None: pk_field = self._primary_pk_field(entity) pk = entity.find_field(pk_field) if pk is not None: - id_value = _coerce_key_value(pk, id_value) + id_value = coerce_key_value(pk, id_value) rows = self.find_many(entity_name, {pk_field: id_value}, sort=None, limit=1, offset=None) return rows[0] if rows else None + @abstractmethod + def find_many( + self, + entity_name: str, + filter: Filter | None = None, + *, + sort: Iterable[tuple[str, str]] | None = None, + limit: int | None = None, + offset: int | None = None, + ) -> list[dict[str, Any]]: + """The rows matching *filter*, as field-keyed dicts of native values.""" + + @abstractmethod + def count(self, entity_name: str, filter: Filter | None = None) -> int: + """How many rows match *filter*.""" + + @abstractmethod + def relate( + self, entity_name: str, record: dict[str, Any], relation_name: str + ) -> list[dict[str, Any]] | dict[str, Any] | None: + """Traverse a relationship from a source *record* to its related rows.""" + def create(self, entity_name: str, data: dict[str, Any]) -> dict[str, Any]: """INSERT a row through the runtime write path, returning the inserted row. @@ -383,12 +177,11 @@ def create(self, entity_name: str, data: dict[str, Any]) -> dict[str, Any]: (the persistence-conformance ``op: roundtrip`` contract): a decimal / uuid / temporal as a string, a ``field.object`` as a dict, currency as an integer (minor units). Each value is coerced to the native Python type - the driver binds to the column's physical type (``Decimal`` / ``uuid.UUID`` - / ``date`` / ``time`` / naive-or-aware ``datetime`` / ``dict``→jsonb), so - the WRITE codec is exercised end-to-end. Server-defaulted columns the - caller omits (e.g. a ``gen_random_uuid()`` PK) are left out of the INSERT - and filled by Postgres; the full row — including the generated PK — is - returned via ``RETURNING`` so a round-trip read can key off it. + the store binds to the column's physical type, so the WRITE codec is + exercised end-to-end. Server-defaulted columns the caller omits (e.g. a + ``gen_random_uuid()`` PK) are left out of the INSERT and filled by the + store; the full row — including the generated PK — is returned so a + round-trip read can key off it. #203 — ``@autoSet`` stamping: EVERY ``onCreate`` AND ``onUpdate`` temporal column is stamped with a single shared ``now()`` (keyed off the column's @@ -398,15 +191,19 @@ def create(self, entity_name: str, data: dict[str, Any]) -> dict[str, Any]: """ self._refuse_report("create", entity_name) entity = self._require_entity(entity_name) + self._notify("on_before_create", entity_name, data) + stamped = data # #203: stamp every onCreate AND onUpdate column with one shared now() (the # caller's value is ignored). No-op for entities that declare no @autoSet field. - on_create, on_update = _auto_set_fields(entity) + on_create, on_update = auto_set_fields(entity) if on_create or on_update: base = _dt.datetime.now(_dt.timezone.utc) - data = {**data} + stamped = {**data} for f in (*on_create, *on_update): - data[f.name] = _auto_set_stamp(f, base) - return self._insert_row(entity, entity_name, data) + stamped[f.name] = auto_set_stamp(f, base) + row = self._insert_row(entity, entity_name, stamped) + self._notify("on_after_create", entity_name, row) + return row def insert_preserving(self, entity_name: str, data: dict[str, Any]) -> dict[str, Any]: """#203 escape hatch — INSERT that writes the ``@autoSet`` columns VERBATIM @@ -415,99 +212,15 @@ def insert_preserving(self, entity_name: str, data: dict[str, Any]) -> dict[str, For import / restore / replication paths that must persist the ORIGINAL ``createdAt`` / ``updatedAt`` timestamps a row carried, not fresh ones. Every other column behaves exactly as :meth:`create` (same write codec, - same TPH discriminator injection, same ``RETURNING`` row). For an entity - that declares no ``@autoSet`` field this is identical to :meth:`create`. + same TPH discriminator injection, same returned row, same listener events). For an + entity that declares no ``@autoSet`` field this is identical to :meth:`create`. """ self._refuse_report("insert_preserving", entity_name) entity = self._require_entity(entity_name) - return self._insert_row(entity, entity_name, data) - - def _insert_row( - self, entity: MetaObject, entity_name: str, data: dict[str, Any] - ) -> dict[str, Any]: - """Shared INSERT core for :meth:`create` / :meth:`insert_preserving` — the - two differ only in whether *data* was ``@autoSet``-stamped before arriving - here. Builds the parameterized INSERT (coercing each value via the write - codec), runs it ``RETURNING`` the full physical column set, and maps the - row back to metadata field names.""" - table = self._table_name(entity) - - # FR-017 TPH: a subtype create injects its discriminator value (the entity - # names the subtype; the caller never sets it). - tph = tph_subtype_of(entity) - if tph is not None: - data = {**data, tph.field: tph.value} - - insert_cols: list[str] = [] - params: list[Any] = [] - for field_name, raw in data.items(): - f = entity.find_field(field_name) - if f is None: - raise ValueError( - f"create('{entity_name}'): no field '{field_name}' in metadata" - ) - # #214: a DERIVED (origin.*) field has no column on the write table — it is - # view-computed. A read-modify-write round-trip (a client POSTs back the read - # model, which carries derived fields) must not try to INSERT it; drop it here. - if f.is_derived(): - continue - insert_cols.append(_column_of(f, self._column_naming)) - params.append(_coerce_write_value(f, raw)) - - # RETURNING the physical column set so the inserted row — including any - # server-generated PK / default — comes back, then map columns → metadata field - # names for cross-port row-shape parity. #214: a DERIVED (origin.*) field has no - # column on the write table (it is computed by the replica view), so it is - # excluded from RETURNING; the write-through re-read below fetches it via the view. - returning_fields = [f for f in entity.fields() if not f.is_derived()] - all_cols = [_column_of(f, self._column_naming) for f in returning_fields] - col_to_field = {_column_of(f, self._column_naming): f.name for f in returning_fields} - - if insert_cols: - col_list = ", ".join(self._d.quote(c) for c in insert_cols) - placeholders = ", ".join(self._d.placeholder for _ in insert_cols) - sql = f"INSERT INTO {self._relation(entity)} ({col_list}) VALUES ({placeholders})" - else: - sql = f"INSERT INTO {self._relation(entity)} {self._d.default_values}" - if self._d.supports_returning: - sql += f" RETURNING {', '.join(self._d.quote(c) for c in all_cols)}" - result = self._driver.insert_returning(sql, tuple(params)) - else: - # No RETURNING (MySQL): insert, then re-read the row by its key -- the key the - # caller supplied, else the one the engine generated (AUTO_INCREMENT). - generated = self._driver.insert_last_id(sql, tuple(params)) - pk_field = self._primary_pk_field(entity) - supplied = data.get(pk_field) - pk_value = supplied if supplied is not None else generated - if pk_value is None or (supplied is None and pk_value == 0): - raise ValueError( - f"create('{entity_name}'): the {self._d.name} engine cannot return a " - f"generated key other than an AUTO_INCREMENT one, so supply a value for " - f"'{pk_field}'" - ) - written = self._select_by_key(entity, returning_fields, pk_field, pk_value, tph) - if written is None: - raise RuntimeError( - f"create('{entity_name}'): the inserted row {pk_field}={pk_value!r} " - f"could not be read back" - ) - result = written - # Surface the RETURNING column OIDs (mapped to metadata field names) so the - # serialization boundary applies the same SQL-type wire rules as a read — a - # BIGINT / currency column comes back as a numeric string. Mirrors update(). - self.last_column_oids = self._type_codes(result, col_to_field, returning_fields) - row = result.rows[0] - mapped = {col_to_field.get(k, k): v for k, v in row.items()} - # int-backed enums come back as integers; hand the caller the symbol. - mapped = _decode_read_row({f.name: f for f in returning_fields}, mapped, self._d) - # #214: a write-through entity's INSERT RETURNING covers only the table (non-derived) - # columns; re-read the persisted row through the replica VIEW by PK so the returned row - # carries the derived origin.* fields (read-your-writes). find_by_id routes to the view. - if entity.is_write_through(): - reread = self.find_by_id(entity_name, mapped[self._primary_pk_field(entity)]) - if reread is not None: - return reread - return mapped + self._notify("on_before_create", entity_name, data) + row = self._insert_row(entity, entity_name, data) + self._notify("on_after_create", entity_name, row) + return row def update( self, @@ -520,164 +233,40 @@ def update( """UPDATE a row by primary key through the runtime write path. ``data`` carries field-keyed values in the same *native authoring forms* - as :meth:`create` (a decimal/uuid/temporal as a string, ``field.object`` - as a dict, currency as integer minor units). Each value is run through the - SAME write codec the INSERT path uses (``_coerce_write_value``) so the - PATCH path cannot silently skip the type coercion INSERT applies — the - per-port hazard the ``update-delete-all-types`` corpus gates. + as :meth:`create`, run through the SAME write codec the INSERT path uses. #203 — ``@autoSet`` stamping: every ``onUpdate`` temporal column is bumped to ``now()`` (overriding any caller value), while ``onCreate`` columns are stripped and never rewritten — a full-row update carrying a stale ``createdAt`` cannot clobber the write-once creation timestamp. - Returns the updated row (mapped to metadata field names) via ``RETURNING``. - When no row matched the (TPH-scoped) PK, behavior follows *if_missing* - (mirrors the TS ``WriteOpts.ifMissing``): ``"ignore"`` (default) → ``None`` - so a REST route renders 404; ``"throw"`` → raise so the persistence DSL's - ``expect-error`` op is satisfied. The discriminator is immutable, so a TPH - subtype's patch strips it and the by-id write is scoped to the subtype (a - cross-subtype id matches no row → the same not-found path). + Returns the updated row (mapped to metadata field names). When no row matched the + (TPH-scoped) PK, behavior follows *if_missing* (mirrors the TS + ``WriteOpts.ifMissing``): ``"ignore"`` (default) → ``None`` so a REST route renders + 404; ``"throw"`` → raise so the persistence DSL's ``expect-error`` op is satisfied. + The discriminator is immutable, so a TPH subtype's patch strips it and the by-id write + is scoped to the subtype (a cross-subtype id matches no row → the same not-found path). """ self._refuse_report("update", entity_name) entity = self._require_entity(entity_name) - table = self._table_name(entity) - pk_field = self._primary_pk_field(entity) - pk_col = _column_of(entity.find_field(pk_field), self._column_naming) - + self._notify("on_before_update", entity_name, id_value, data) + stamped = data # #203 — @autoSet: bump every onUpdate column to now(), and NEVER rewrite an # onCreate column — strip it even if the caller supplied a (stale) value. # Omitting this onCreate-skip is the latent lost-update bug the issue calls # out. No-op for entities that declare no @autoSet field. - on_create, on_update = _auto_set_fields(entity) + on_create, on_update = auto_set_fields(entity) if on_create or on_update: base = _dt.datetime.now(_dt.timezone.utc) - data = {**data} + stamped = {**data} for f in on_create: - data.pop(f.name, None) # created_at is write-once — never overwritten on update + stamped.pop(f.name, None) # created_at is write-once — never overwritten on update for f in on_update: - data[f.name] = _auto_set_stamp(f, base) - - # FR-017 TPH: the discriminator is immutable — strip it from the patch; the - # by-id write is subtype-scoped (a row of a different subtype is invisible). - tph = tph_subtype_of(entity) - if tph is not None and tph.field in data: - data = {k: v for k, v in data.items() if k != tph.field} - - set_cols: list[str] = [] - params: list[Any] = [] - for field_name, raw in data.items(): - f = entity.find_field(field_name) - if f is None: - raise ValueError( - f"update('{entity_name}'): no field '{field_name}' in metadata" - ) - # #214: a DERIVED (origin.*) field has no column on the write table (view-computed). - # A read-modify-write round-trip PATCHing back the whole read model must not try to - # UPDATE it; drop it from the SET list. - if f.is_derived(): - continue - set_cols.append(_column_of(f, self._column_naming)) - params.append(_coerce_write_value(f, raw)) - if not set_cols: - # No columns to set → just read the (scoped) row back by PK (no-op update). - row = self.find_by_id(entity_name, id_value) - return self._on_missing_update(entity_name, pk_field, id_value, if_missing) if row is None else row - - # #214: exclude DERIVED (origin.*) fields from RETURNING — they have no column on - # the write table (computed by the replica view); the write-through re-read below - # fetches them via the view. - returning_fields = [f for f in entity.fields() if not f.is_derived()] - all_cols = [_column_of(f, self._column_naming) for f in returning_fields] - col_to_field = {_column_of(f, self._column_naming): f.name for f in returning_fields} - assignments = ", ".join(f"{self._d.quote(c)} = {self._d.placeholder}" for c in set_cols) - params.append(_coerce_key_value(entity.find_field(pk_field), id_value)) - where = f"{self._d.quote(pk_col)} = {self._d.placeholder}" - if tph is not None: - where += f" AND {self._d.quote(_column_of(entity.find_field(tph.field), self._column_naming))} = {self._d.placeholder}" - params.append(tph.value) - sql = f"UPDATE {self._relation(entity)} SET {assignments} WHERE {where}" - if self._d.supports_returning: - sql += f" RETURNING {', '.join(self._d.quote(c) for c in all_cols)}" - result = self._driver.update_returning(sql, tuple(params)) - else: - # No RETURNING (MySQL): update, then re-read the (TPH-scoped) row by its key. A - # row that matched but changed nothing still reads back, which a rowcount would - # report as no match. - self._driver.execute_rowcount(sql, tuple(params)) - result = self._select_by_key(entity, returning_fields, pk_field, id_value, tph) - if result is None: - self.last_column_oids = {} - return self._on_missing_update(entity_name, pk_field, id_value, if_missing) - # Surface the RETURNING column OIDs (mapped to metadata field names) so the - # serialization boundary applies the same SQL-type wire rules as a read — - # a BIGINT / currency column comes back as a numeric string. Mirrors the - # find_many bookkeeping. - self.last_column_oids = self._type_codes(result, col_to_field, returning_fields) - row = result.rows[0] - mapped = {col_to_field.get(k, k): v for k, v in row.items()} - # int-backed enums come back as integers; hand the caller the symbol. - mapped = _decode_read_row({f.name: f for f in returning_fields}, mapped, self._d) - # #214: re-read the updated row through the replica VIEW by PK so the returned row - # carries the derived origin.* fields (write targeted the table, which lacks them). - if entity.is_write_through(): - reread = self.find_by_id(entity_name, id_value) - if reread is not None: - return reread - return mapped - - def _type_codes( - self, result: SelectResult, col_to_field: dict[str, str], fields: Iterable[MetaField] - ) -> dict[str, int]: - """The per-field SQL type metadata for the serialization boundary. A driver with - column OIDs (Postgres) supplies them; an engine with none (SQLite, MySQL) reports - the equivalent for each field's declared subtype.""" - if self._d.synthesizes_type_codes: - codes = ((f.name, self._d.type_code(f)) for f in fields) - return {name: code for name, code in codes if code is not None} - return {col_to_field.get(c, c): oid for c, oid in result.column_oids.items()} - - def _select_by_key( - self, - entity: MetaObject, - fields: list[MetaField], - pk_field: str, - key: Any, - tph: TphSubtype | None, - ) -> SelectResult | None: - """Read one row of the WRITE table by its key (TPH-scoped), or ``None``: how an - engine with no ``RETURNING`` hands back what it just wrote.""" - ph = self._d.placeholder - cols = [_column_of(f, self._column_naming) for f in fields] - pk = entity.find_field(pk_field) - if pk is None: - raise ValueError(f"Entity '{entity.name}' has no primary key field '{pk_field}'") - pk_col = _column_of(pk, self._column_naming) - params: list[Any] = [_coerce_key_value(pk, key)] - where = f"{self._d.quote(pk_col)} = {ph}" - if tph is not None: - where += f" AND {self._d.quote(_column_of(entity.find_field(tph.field), self._column_naming))} = {ph}" - params.append(tph.value) - sql = ( - f"SELECT {', '.join(self._d.quote(c) for c in cols)} " - f"FROM {self._relation(entity)} WHERE {where}" - ) - result = self._driver.select(sql, tuple(params)) - if not result.rows: - return None - return SelectResult(result.rows[:1], result.column_oids) - - @staticmethod - def _on_missing_update( - entity_name: str, pk_field: str, id_value: Any, if_missing: str - ) -> None: - """No (TPH-scoped) row matched an update: ``"throw"`` raises (the persistence - ``expect-error`` contract), ``"ignore"`` returns ``None`` (REST route → 404).""" - if if_missing == "throw": - raise KeyError( - f"update('{entity_name}'): no row with {pk_field}={id_value!r} in scope" - ) - return None + stamped[f.name] = auto_set_stamp(f, base) + row = self._update_row(entity, entity_name, id_value, stamped, if_missing) + if row is not None: + self._notify("on_after_update", entity_name, id_value, row) + return row def delete(self, entity_name: str, id_value: Any) -> bool: """DELETE a row by primary key through the runtime write path. @@ -687,161 +276,35 @@ def delete(self, entity_name: str, id_value: Any) -> bool: """ self._refuse_report("delete", entity_name) entity = self._require_entity(entity_name) - table = self._table_name(entity) - pk_field = self._primary_pk_field(entity) - pk_col = _column_of(entity.find_field(pk_field), self._column_naming) - params: list[Any] = [_coerce_key_value(entity.find_field(pk_field), id_value)] - where = f"{self._d.quote(pk_col)} = {self._d.placeholder}" - # FR-017 TPH: a subtype delete is scoped to its discriminator (cross-subtype - # delete matches no row → False, mirroring the per-subtype route's 404). - tph = tph_subtype_of(entity) - if tph is not None: - where += f" AND {self._d.quote(_column_of(entity.find_field(tph.field), self._column_naming))} = {self._d.placeholder}" - params.append(tph.value) - sql = f"DELETE FROM {self._relation(entity)} WHERE {where}" - return self._driver.execute_rowcount(sql, tuple(params)) > 0 - - def find_many( - self, - entity_name: str, - filter: Filter | None = None, - *, - sort: Iterable[tuple[str, str]] | None = None, - limit: int | None = None, - offset: int | None = None, - ) -> list[dict[str, Any]]: - entity = self._require_entity(entity_name) - # #214: reads route to the replica VIEW for a write-through entity (carrying the - # derived origin.* columns), else the entity's own primary source. All effective - # fields (incl. derived) are selected — the view exposes them. An entity with no read - # view reads its table, which stores no derived field, so those are left out. - table = self._read_source_name(entity) - read_fields = _read_fields(entity) - cols = [_column_of(f, self._column_naming) for f in read_fields] - sql = f'SELECT {", ".join(self._d.quote(c) for c in cols)} FROM {self._read_relation(entity)}' - params: list[Any] = [] - # FR-017 TPH: a subtype read is scoped to its discriminator value (a row of - # a different subtype is invisible); the base entity (no @discriminatorValue) - # reads polymorphically across the single table. - filter = self._scope_filter(filter, tph_subtype_of(entity)) - where = _compile_filter(filter, entity, self._column_naming, self._d) if filter else None - if where is not None: - sql += " WHERE " + where[0] - params.extend(where[1]) - if sort: - order_parts = [] - for field_name, direction in sort: - f = entity.find_field(field_name) - col = _column_of(f, self._column_naming) if f is not None else field_name - order_parts.append(self._d.order_term(self._d.quote(col), direction.lower() == "desc")) - if order_parts: - sql += " ORDER BY " + ", ".join(order_parts) - if limit is not None: - sql += f" LIMIT {int(limit)}" - elif offset is not None and self._d.unbounded_limit: - sql += f" LIMIT {self._d.unbounded_limit}" # OFFSET needs a LIMIT on this engine - if offset is not None: - sql += f" OFFSET {int(offset)}" - result = self._driver.select(sql, tuple(params)) - # Map raw column → metadata field name for cross-port row-shape parity. - # Values stay native (ADR-0019); the boundary canonicalizes them. - col_to_field = {_column_of(f, self._column_naming): f.name for f in read_fields} - self.last_column_oids = self._type_codes(result, col_to_field, read_fields) - # int-backed enums come back as integers; hand the caller the symbol. - fields_by_name = {f.name: f for f in read_fields} - return [ - _decode_read_row(fields_by_name, {col_to_field.get(k, k): v for k, v in row.items()}, self._d) - for row in result.rows - ] - - def count(self, entity_name: str, filter: Filter | None = None) -> int: - entity = self._require_entity(entity_name) - # #214: count reads through the same source as find_many (the replica view for a - # write-through entity — a 1:1 replica, so the count is unchanged). - table = self._read_source_name(entity) - sql = f"SELECT COUNT(*) FROM {self._read_relation(entity)}" - params: list[Any] = [] - filter = self._scope_filter(filter, tph_subtype_of(entity)) # FR-017 TPH subtype scope - where = _compile_filter(filter, entity, self._column_naming, self._d) if filter else None - if where is not None: - sql += " WHERE " + where[0] - params.extend(where[1]) - n = self._driver.scalar(sql, tuple(params)) - return int(n) if n is not None else 0 - - def relate( - self, entity_name: str, record: dict[str, Any], relation_name: str - ) -> list[dict[str, Any]] | dict[str, Any] | None: - """Traverse a relationship from a source *record* to its related rows. - - M:N (FR-017) is resolved generically from metadata: derive the junction - FK fields from the junction's two ``identity.reference`` children, query - the junction, then load the target rows. Three modes — hetero, directed - self-join (``@sourceRefField``), symmetric self-join (``@symmetric``) — - mirror the TS reference resolver. ``record`` is a source-key dict (e.g. - ``{"id": 1}``); only the source PK is read from it. - """ - self._refuse_report("relate", entity_name) - entity = self._require_entity(entity_name) - desc = resolve_n2m_descriptor(entity, relation_name, self._entity_by_name) - if desc is None: - raise ValueError( - f"Relationship '{relation_name}' on '{entity_name}' is not a " - f"resolvable M:N relationship (only M:N traversal is supported " - f"by relate() today)" - ) - return self._relate_n2m(entity, desc, record) + self._notify("on_before_delete", entity_name, id_value) + deleted = self._delete_row(entity, entity_name, id_value) + if deleted: + self._notify("on_after_delete", entity_name, id_value) + return deleted - def _relate_n2m( - self, entity: MetaObject, desc: N2mDescriptor, record: dict[str, Any] - ) -> list[dict[str, Any]]: - junction = self._require_entity(desc.junction_entity_name) - target = self._require_entity(desc.target_entity_name) - - # Source PK value from the in-process record (the relate `by` key). - source_pk_field = self._primary_pk_field(entity) - source_id = record.get(source_pk_field) - if source_id is None: - return [] + # --- What a store supplies ---------------------------------------------- - # Physical junction columns for the derived FK fields. - source_col = self._junction_column(junction, desc.source_field) - target_col = self._junction_column(junction, desc.target_field) - - # Query the junction. Symmetric unions both FK columns; directed/hetero - # filter only the source side. - join_table = self._table_name(junction) - select_cols = f"{self._d.quote(source_col)}, {self._d.quote(target_col)}" - if desc.symmetric: - sql = ( - f"SELECT {select_cols} FROM {self._relation(junction)} " - f"WHERE {self._d.quote(source_col)} = {self._d.placeholder} OR {self._d.quote(target_col)} = {self._d.placeholder}" - ) - params: tuple[Any, ...] = (source_id, source_id) - else: - sql = ( - f"SELECT {select_cols} FROM {self._relation(junction)} " - f"WHERE {self._d.quote(source_col)} = {self._d.placeholder}" - ) - params = (source_id,) - join_rows = self._driver.select(sql, params).rows + @abstractmethod + def _insert_row( + self, entity: MetaObject, entity_name: str, data: dict[str, Any] + ) -> dict[str, Any]: + """INSERT *data* (already stamped where it should be) and return the stored row.""" - # Collect the related (target) ids. - if desc.symmetric: - target_ids = collect_symmetric_target_ids( - join_rows, source_col, target_col, {source_id} - ) - else: - target_ids = collect_column_ids(join_rows, target_col) - if not target_ids: - return [] + @abstractmethod + def _update_row( + self, + entity: MetaObject, + entity_name: str, + id_value: Any, + data: dict[str, Any], + if_missing: str, + ) -> dict[str, Any] | None: + """UPDATE the row keyed *id_value* and return it, or answer a missing row as + *if_missing* says (``"ignore"`` → ``None``, ``"throw"`` → raise).""" - # Load the target rows by PK. Reuse find_many so the row shape (metadata - # field names) + last_column_oids match every other read path. - target_pk_field = self._primary_pk_field(target) - return self.find_many( - desc.target_entity_name, {target_pk_field: {"in": target_ids}} - ) + @abstractmethod + def _delete_row(self, entity: MetaObject, entity_name: str, id_value: Any) -> bool: + """DELETE the row keyed *id_value*; ``True`` when one was deleted.""" # --- Helpers ------------------------------------------------------------- @@ -889,94 +352,6 @@ def _refuse_report(self, op: str, name: str) -> None: f"(it is a view over aggregates; only find_many and count read it)" ) - def _table_name(self, entity: MetaObject) -> str: - """The physical relation *entity* lives in. - - Delegates to :func:`~metaobjects.source_resolution.resolve_table_name` — - THE resolver, shared with codegen and the api-docs builder. It applies the - FR-016 / ADR-0018 four-step rule to the ``@role: primary`` source, and it - is RESOLVING (ADR-0039): a FR-017 TPH subtype, which declares no source of - its own and inherits the discriminator base's single table, resolves to - that base table, while an entity declaring its own source shadows the - inherited one and is unchanged. - - Raises :class:`ValueError` when *entity* declares no primary source at all. - This used to fall back to ``entity.name`` — #248 says participation in - persistence derives from a DECLARED source, never from the object subtype, - so that fallback sent every read, write and delete to a relation nothing - created. Codegen's resolver already returned ``None`` for the shape and the - M:N descriptor already raised on it; the runtime was the one caller that - kept its own copy of the predicate and guessed. - """ - table = resolve_table_name(entity) - if table is None: - raise ValueError( - f'{entity.name}: no primary source (source.rdb) is declared or ' - f"inherited, so this object has no physical relation to read from " - f"or write to. Declare a source.rdb, or do not persist it through " - f"the ObjectManager." - ) - return table - - def _qualified(self, name: str, schema: str | None) -> str: - """*name* quoted, qualified by its source's ``@schema`` where the engine has schemas. - ``meta migrate`` creates a relation declared with ``@schema: sales`` as - ``"sales".""``; a bare name would resolve through ``search_path`` to another - relation, or none. SQLite has no schemas, so its names stay bare.""" - quoted = self._d.quote(name) - return f"{self._d.quote(schema)}.{quoted}" if schema and self._d.qualifies_schemas else quoted - - def _relation(self, entity: MetaObject) -> str: - """The relation WRITES (and by-id reads) target, quoted and schema-qualified.""" - src = primary_rdb_source(entity) - return self._qualified(self._table_name(entity), src.schema() if src is not None else None) - - def _read_relation(self, entity: MetaObject) -> str: - """The relation list and count READS run against (:meth:`_read_source_name`), quoted - and qualified by the schema of the source it names.""" - if entity.is_write_through(): - for c in entity.own_children(): - if isinstance(c, MetaSource) and c.is_read_only() and c.physical_name(): - return self._qualified(c.physical_name(), c.schema()) - return self._relation(entity) - - def _read_source_name(self, entity: MetaObject) -> str: - """The physical relation READS run against. FR-024 §7 (#214): a write-through - entity read-view reads through its read-only REPLICA VIEW (which carries the - derived ``origin.*`` columns), while writes still target the table - (:meth:`_table_name`). Every other object reads its own primary source (= - ``_table_name``), so vanilla/projection behavior is unchanged. - - OWN + role-agnostic: the replica view carries ``@role: replica``, so it is found - by read-only kind among the entity's own sources, not a primary-role accessor.""" - if entity.is_write_through(): - for c in entity.own_children(): - if isinstance(c, MetaSource) and c.is_read_only(): - pn = c.physical_name() - if pn: - return pn - return self._table_name(entity) - - @staticmethod - def _scope_filter(filter: Filter | None, tph: TphSubtype | None) -> Filter | None: - """AND the TPH discriminator predicate into a filter (subtype-scoped reads). - Non-TPH (``tph is None``) returns the filter unchanged.""" - if tph is None: - return filter - disc: Filter = {tph.field: tph.value} # equality shortcut - if not filter: - return disc - return {"and": [filter, disc]} - - def _junction_column(self, junction: MetaObject, field_name: str) -> str: - """Physical column for a junction FK field (metadata field name → column).""" - f = junction.find_field(field_name) - if f is None: - raise ValueError( - f"Junction '{junction.name}' has no field '{field_name}'" - ) - return _column_of(f, self._column_naming) - def primary_key_field(self, entity_name: str) -> str: """The single-field primary-key NAME for an entity, from its ``identity.primary`` ``@fields``. ``op: roundtrip`` reads the inserted @@ -994,599 +369,3 @@ def _primary_pk_field(self, entity: MetaObject) -> str: if isinstance(raw, (list, tuple)) and raw: return str(raw[0]) raise ValueError(f"Entity '{entity.name}' primary identity has no fields") - - -# ---------------------------------------------------------------------------- -# Filter compiler — Filter dict → (WHERE clause SQL, params tuple) -# ---------------------------------------------------------------------------- - - -def _compile_filter( - f: Filter | None, - entity: MetaObject, - column_naming: str = DEFAULT_COLUMN_NAMING, - dialect: Dialect = POSTGRES, -) -> tuple[str, list[Any]] | None: - if not f: - return None - # Top-level `and: [filter, filter, ...]` combinator. - if "and" in f and isinstance(f["and"], list): - parts: list[str] = [] - params: list[Any] = [] - for child in f["and"]: - compiled = _compile_filter(child, entity, column_naming, dialect) - if compiled is None: - continue - parts.append("(" + compiled[0] + ")") - params.extend(compiled[1]) - if not parts: - return None - return " AND ".join(parts), params - - parts = [] - params = [] - for field_name, ops in f.items(): - mf = entity.find_field(field_name) - col = _column_of(mf, column_naming) if mf is not None else field_name - if not isinstance(ops, dict): - # Shortcut: {field: value} → equality. Encoded like any other bound - # value (see _op_clause) so an int-backed enum reaches SQL as its int. - parts.append(f"{dialect.quote(col)} = {dialect.placeholder}") - params.append(_coerce_filter_value(mf, ops) if mf is not None else ops) - continue - for op, value in ops.items(): - sql, p = _op_clause(col, op, value, mf, dialect) - parts.append(sql) - params.extend(p) - if not parts: - return None - return " AND ".join(parts), params - - -def _op_clause( - col: str, op: str, value: Any, field: MetaField | None = None, dialect: Dialect = POSTGRES -) -> tuple[str, list[Any]]: - """Translate one operator → SQL + params. Mirrors TS/C#/Java semantics. - - Bound values go through the WRITE codec, exactly as an INSERT's do: the four - sibling ports all encode on this path (TS through the Drizzle customType, Java - through GenericSQLDriver.setStatementValue → EnumCodec.write, Kotlin through - Exposed's toDb, C# through the EF converter). Without it an int-backed enum's - filter binds the member SYMBOL against an INTEGER column — the filter band - keeps eq/ne/in for int-backed enums precisely BECAUSE the symbol is supposed - to encode to its integer before reaching SQL. - """ - qc = dialect.quote(col) - ph = dialect.placeholder - if dialect is MYSQL and field is not None and field.sub_type == "decimal" and op not in ("isNull", "like"): - # ADR-0019 W2: MySQL compares DECIMAL = 'text' as doubles; a cast operand compares as a - # decimal, so a 19-digit operand is exact. - ph = f"CAST({ph} AS DECIMAL(65,30))" - if field is not None and op != "isNull": - value = ([_coerce_filter_value(field, v) for v in value] - if op == "in" and value else _coerce_filter_value(field, value)) - if op == "eq": return f"{qc} = {ph}", [value] - if op == "ne": return f"{qc} <> {ph}", [value] - if op == "gt": return f"{qc} > {ph}", [value] - if op == "gte": return f"{qc} >= {ph}", [value] - if op == "lt": return f"{qc} < {ph}", [value] - if op == "lte": return f"{qc} <= {ph}", [value] - # `like` is case-SENSITIVE SQL LIKE — verbatim pattern, %/_ wildcards - # (ADR-0049; the de-blinded filter-like-and-ne fixture gates this). The dialect - # spells it where the engine's own LIKE is not case-sensitive. - if op == "like": return dialect.like_clause(qc, value) - if op == "isNull": - wants_null = bool(value) if not isinstance(value, str) else value.lower() == "true" - return (f"{qc} IS NULL" if wants_null else f"{qc} IS NOT NULL"), [] - if op == "in": - if not value: - # Empty IN list — match nothing. - return dialect.false_predicate(), [] - placeholders = ", ".join(ph for _ in value) - return f"{qc} IN ({placeholders})", list(value) - raise ValueError(f"Unsupported filter op '{op}' on column '{col}'") - - -# ---------------------------------------------------------------------------- -# Write codec — authoring form → native Python type the driver binds (ADR-0019 -# write side). pg8000 maps Decimal→numeric, uuid.UUID→uuid, naive datetime→ -# timestamp, aware datetime→timestamptz, date→date, time→time, dict→jsonb. We -# only need to turn the corpus' authoring *strings* into those native types; the -# driver does the rest. Mirrors the TS runtime write coercer (type-coercer.ts): -# jsonb objects + native binding per subtype, everything else passes through. -# ---------------------------------------------------------------------------- - - -def _field_is_array(field: MetaField) -> bool: - """Effective array-ness (ADR-0039 resolving): the native ``is_array`` flag OR - the ``@isArray`` attr, resolved through the ``extends`` super chain so a concrete - field inheriting array-ness from an abstract parent is honored at write time.""" - return field.resolved_is_array() - - -_FILTER_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG, fc.FIELD_SUBTYPE_CURRENCY) -_FILTER_FLOAT_SUBTYPES = (fc.FIELD_SUBTYPE_FLOAT, fc.FIELD_SUBTYPE_DOUBLE) - - -def _coerce_filter_value(field: MetaField, value: Any) -> Any: - """A filter operand as the native type the column compares against. - - A filter value usually arrives as TEXT (the REST grammar ``filter[f][op]=v`` hands the - repository the raw URL text). Postgres lets the driver pick the column type for a - bound string; SQLite and MySQL compare a bound string against a number as TEXT, so - ``count > '0'`` is wrong there. Numeric and boolean operands are parsed from text by - the field's declared subtype, then the write codec applies as for any bound value.""" - if isinstance(value, str): - sub = field.sub_type - if sub in _FILTER_INT_SUBTYPES: - value = int(value) if _INT_TEXT.match(value) else value - elif sub in _FILTER_FLOAT_SUBTYPES: - try: - value = float(value) - except ValueError: - pass - elif sub == fc.FIELD_SUBTYPE_BOOLEAN: - lowered = value.strip().lower() - if lowered in ("true", "1"): - value = True - elif lowered in ("false", "0"): - value = False - return _coerce_write_value(field, value, for_filter=True) - - -_INT_TEXT = _re.compile(r"^\s*-?\d+\s*$") - - -_ASCII_DIGITS = "0123456789" -_KEY_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG) -_KEY_DECIMAL_SUBTYPES = (fc.FIELD_SUBTYPE_DECIMAL, fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT) - - -def _is_canonical_decimal_text(text: str, *, fractional: bool) -> bool: - """Canonical decimal key text: optional ``-``, ASCII digits with no leading zero (a lone - ``0`` is fine), no ``-0``, and, when *fractional*, an optional ``.`` plus at least one - digit. Checked character by character: ``int()``/``float()``/``Decimal()`` accept - whitespace, ``+``, ``_``, exponents, Unicode digits, ``nan`` and ``inf``, and - ``str.isdigit`` accepts Unicode digits, so none of them may decide.""" - body = text[1:] if text.startswith("-") else text - whole, dot, frac = body.partition(".") - if dot and not fractional: - return False - if not whole or any(c not in _ASCII_DIGITS for c in whole): - return False - if len(whole) > 1 and whole[0] == "0": - return False - if dot and (not frac or any(c not in _ASCII_DIGITS for c in frac)): - return False - if text.startswith("-") and whole == "0" and all(c == "0" for c in frac): - return False - return True - - -def _coerce_key_value(field: MetaField, value: Any) -> Any: - """A primary-key / id argument as the native value the key column binds. - - A key arrives as TEXT from a route or a ref. For a numeric key field the text must be - canonical decimal (see :func:`_is_canonical_decimal_text`), else the same ``ValueError`` - the OM raises for any unusable argument; text that names no key never names row 1 or 0. - A non-text value, or a non-numeric key (string, uuid), goes to the ordinary write codec.""" - if isinstance(value, str): - sub = field.sub_type - integer = sub in _KEY_INT_SUBTYPES - if integer or sub in _KEY_DECIMAL_SUBTYPES: - if not _is_canonical_decimal_text(value, fractional=not integer) or ( - sub in (fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT) and _math.isinf(float(value)) - ): - owner = field.parent.name if field.parent is not None else "?" - raise ValueError( - f"Entity '{owner}' key field '{field.name}' (field.{sub}) is not canonical decimal text" - ) - if integer: - return int(value) - return _decimal.Decimal(value) if sub == fc.FIELD_SUBTYPE_DECIMAL else float(value) - return _coerce_write_value(field, value) - - -def _coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False) -> Any: - if value is None: - return None - sub = field.sub_type - # ADR-0039 own-only: @dbColumnType is a physical column-type override, never - # inherited via extends (the one deliberately own-only attribute). - col_type = field.attr(dbc.FIELD_ATTR_DB_COLUMN_TYPE) - - # decimal / currency: a decimal authored as a string → Decimal (exact; never - # via float). currency is integer minor units — already an int, pass through. - if sub == fc.FIELD_SUBTYPE_DECIMAL: - if _field_is_array(field) and isinstance(value, list): - return [None if v is None else v if isinstance(v, _decimal.Decimal) else _decimal.Decimal(str(v)) for v in value] - return value if isinstance(value, _decimal.Decimal) else _decimal.Decimal(str(value)) - - # uuid (logical field.uuid, or a string field pinned to a uuid column): - # string → uuid.UUID so the driver binds the native uuid type. PG stores it - # lowercase-canonically regardless of input case. - # - # For isArray=true (native uuid[] column, Phase 1): coerce each element in the - # list. pg8000 binds a Python list[uuid.UUID] to a uuid[] column natively. - # field.string isArray=true (text[] column) passes through — pg8000 binds - # list[str] to text[] natively without element conversion. - if sub == fc.FIELD_SUBTYPE_UUID or col_type == dbc.DB_COLUMN_TYPE_UUID: - if _field_is_array(field) and isinstance(value, list): - return [v if isinstance(v, _uuid.UUID) else _uuid.UUID(str(v)) for v in value] - return value if isinstance(value, _uuid.UUID) else _uuid.UUID(str(value)) - - # field.duration: an accepted ISO-8601 duration (or a timedelta already in process) → - # datetime.timedelta, which pg8000 binds as an interval; the SQLite and MySQL dialects - # bind its microsecond count (Dialect.encode_param), so a filter operand compares and - # orders as a number there. Anything else — a calendar span, a - # clock string, a number — is refused here, not by the database. - if sub == fc.FIELD_SUBTYPE_DURATION: - if _field_is_array(field) and isinstance(value, list): - return [None if v is None else _duration_write_value(field, v) for v in value] - return _duration_write_value(field, value) - - # temporal: parse the authoring string to the native type, with tz-awareness - # driven by the field so the driver binds the correct physical type. ADR-0036 - # Wave 2: field.timestamp is instant / tz-aware BY DEFAULT (→ timestamptz); the - # rare naive wall-clock case opts out with @localTime:true (→ plain timestamp). - if sub == fc.FIELD_SUBTYPE_DATE: - return value if isinstance(value, _dt.date) else _dt.date.fromisoformat(str(value)) - if sub == fc.FIELD_SUBTYPE_TIME: - return value if isinstance(value, _dt.time) else _dt.time.fromisoformat(str(value)) - if sub == fc.FIELD_SUBTYPE_TIMESTAMP: - if isinstance(value, _dt.datetime): - return value - is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving: @localTime may be inherited - return _parse_datetime(str(value), tz_aware=is_tz) - - # field.object / field.map stored as a single jsonb column: serialize to a - # JSON text string so pg8000 sends it as jsonb text (PG assignment-casts text - # → jsonb). pg8000 binds a native *dict* to jsonb natively, but a native - # *list* (array-of-VO, isArray:true) it adapts as a Postgres ARRAY literal - # `{...,...}` which the JSONB column rejects with 22P02 'invalid input syntax - # for type json' — so we cannot rely on driver magic for the list form. - # Serializing both shapes to a JSON string is the explicit codec every other - # port has (Java/Gson, C#/System.Text.Json, TS/JSON.stringify, Kotlin/Jackson) - # and handles dict (single VO), list (array-of-VO), and [] uniformly. - # - # Scope: only jsonb-storage field.object/field.map. A *flattened* field.object - # is expanded to separate scalar columns (never reaches here as the object - # node) and must not be touched; a field.string pinned to a jsonb column via - # @dbColumnType already carries a string value and is left alone above. - if sub in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): - storage = field.get_meta_attr(fc.FIELD_ATTR_STORAGE) # ADR-0039 resolving - if storage != "flattened": # None / "jsonb" / "subdocument" → single jsonb column - # A field.duration inside the value object is stored in its canonical form, so the - # column holds what every port writes (and refuses what is not a duration). - return _json.dumps(_vo_durations(field, value, _write_duration_member)) - # field.enum carrying @intValueMap: the column is an INTEGER while the native - # and wire contract stays the member SYMBOL (int-backing is a persistence-layer - # concern, invisible above this codec), so encode symbol -> declared int here. - # - # An unmapped symbol is passed through untouched: membership is the column's - # CHECK constraint to enforce, and inventing a value here would hide the drift. - # - # isArray=true (an ``integer[]`` column): encode ELEMENT-WISE, so the driver - # binds a list of ints, never the symbol list. A null element stays a null - # element (as in a string-backed enum array), and an unmapped element passes - # through like the scalar does; an array column carries no CHECK, so the - # database's integer[] type is what rejects it. - if sub == fc.FIELD_SUBTYPE_ENUM: - int_map = _int_value_map(field) - if int_map is not None: - if _field_is_array(field) and isinstance(value, list): - return [_encode_enum_member(int_map, v) for v in value] - return _encode_enum_member(int_map, value) - # rc.21: a @stringValueMap enum stores the member's string (scalar only; the - # loader refuses it on an array). - stored_map = _string_value_map(field) - if stored_map is not None and isinstance(value, str): - if value in stored_map: - return stored_map[value] - # An unmapped member raises, written or filtered (rc.21 rulings, every port). Written: - # no CHECK need hold behind it (@dbCheck: false), and storing the symbol would write a - # spelling the column does not hold. Filtered: passed through, the symbol could equal - # ANOTHER member's stored string and match that member's rows. - verb = "filter on" if for_filter else "write" - raise ValueError( - f"field.enum '{field.name}' cannot {verb} {value!r}: it has no stored string in " - f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} — the value is not one of the members the model declares." - ) - - # Everything else (string / int / long / double / float / boolean / enum) - # is already the native type pg8000 binds directly. - return value - - -def _write_duration_member(field: MetaField, value: Any) -> str: - """A ``field.duration`` member of a value object, as the canonical string its JSON holds.""" - try: - return format_duration(parse_duration_input(value)) - except ValueError as e: - raise ValueError(f"field.duration '{field.name}' cannot be written: {e}") from None - - -def _read_duration_member(field: MetaField, value: Any) -> str: - """A ``field.duration`` member of a stored value object, in its canonical form (a value - another writer stored in an accepted but non-canonical spelling is normalised).""" - try: - return format_duration(duration_from_driver(value)) - except ValueError as e: - raise ValueError(f"field.duration '{field.name}' read a stored value that is not one: {e}") from None - - -def _vo_has_duration(vo: MetaObject, seen: frozenset[int] = frozenset()) -> bool: - """True when value object *vo*, or one it embeds, has a ``field.duration`` member.""" - if id(vo) in seen: - return False - seen = seen | {id(vo)} - for f in vo.fields(): - if f.sub_type == fc.FIELD_SUBTYPE_DURATION: - return True - if f.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): - target = ref_target(f, fc.FIELD_ATTR_OBJECT_REF) - if isinstance(target, MetaObject) and _vo_has_duration(target, seen): - return True - return False - - -def _vo_durations(field: MetaField, value: Any, convert: Any, seen: frozenset[int] = frozenset()) -> Any: - """The value of a jsonb ``field.object`` / ``field.map`` with *convert* applied to every - ``field.duration`` member of its value object, at any depth: a single object, an array of - them, the values of a map, and the value objects those embed. Anything that is not the - shape the metadata declares is left as it is (validation reports it, not this).""" - if value is None: - return None - target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) # ADR-0039 resolving @objectRef - if not isinstance(target, MetaObject) or id(target) in seen or not _vo_has_duration(target): - return value - seen = seen | {id(target)} - - def one(member: Any) -> Any: - if not isinstance(member, Mapping): - return member - out = dict(member) - for f in target.fields(): - v = out.get(f.name) - if v is None: - continue - if f.sub_type == fc.FIELD_SUBTYPE_DURATION: - out[f.name] = [None if x is None else convert(f, x) for x in v] if isinstance(v, list) else convert(f, v) - elif f.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): - out[f.name] = _vo_durations(f, v, convert, seen) - return out - - if field.sub_type == fc.FIELD_SUBTYPE_MAP: - return {k: one(v) for k, v in value.items()} if isinstance(value, Mapping) else value - if isinstance(value, list): - return [one(v) for v in value] - return one(value) - - -def _duration_write_value(field: MetaField, value: Any) -> DurationParam: - """The bound value of a ``field.duration``: a :class:`DurationParam`, so the dialect that - binds a duration as text does so by the field, never by a value's type.""" - try: - return DurationParam.of(parse_duration_input(value)) - except ValueError as e: - raise ValueError(f"field.duration '{field.name}' cannot be written: {e}") from None - - -def _encode_enum_member(int_map: dict[Any, Any], member: Any) -> Any: - """One member symbol as its declared int; ``None`` and an unmapped (or - unhashable) value pass through untouched.""" - if isinstance(member, str) and member in int_map: - return int_map[member] - return member - - -def _int_value_map(field: MetaField) -> dict[Any, Any] | None: - """The declared ``@intValueMap`` (symbol → int), or ``None`` when the enum is - string-backed. - - ADR-0039 resolving: the map is ``@values``' numeric half — a logical property - of the enum vocabulary that inherits through ``extends`` — so it is read with - ``get_meta_attr``, NOT the own-only accessor (contrast ``@dbColumnType`` in - :func:`_coerce_write_value`, the one field attribute that is deliberately - own-only). Shared by the write and read halves of the enum codec, mirroring - the dedicated int-map helper each sibling port's codec keeps (Java - ``EnumCodec.intValueMap``, Kotlin ``readIntValueMap``, C# ``IntValueMapOf``). - """ - m = field.get_meta_attr(fc.FIELD_ATTR_INT_VALUE_MAP) - return m if isinstance(m, dict) else None - - -def _string_value_map(field: MetaField) -> dict[str, str] | None: - """rc.21 — the declared ``@stringValueMap`` (member → stored string), or ``None``. - ADR-0039 resolving, as :func:`_int_value_map`.""" - m = field.get_meta_attr(fc.FIELD_ATTR_STRING_VALUE_MAP) - return m if isinstance(m, dict) else None - - -def _decode_read_value(field: MetaField, value: Any) -> Any: - """Decode a stored value back to its authoring form on read. - - A ``field.duration`` reads back as a ``datetime.timedelta`` whatever the engine handed - back (see the branch below). Beyond that, two cases. The inverse of - :func:`_coerce_write_value`'s int-backed-enum branch: - the column holds the member's integer, callers expect the member SYMBOL. And - ``field.currency``, whose native type is ``int`` minor units: a table column is - BIGINT and already reads back as an ``int``, but a VIEW column need not be — - ``SUM`` over BIGINT is Postgres ``numeric``, read back as a ``Decimal``, which a - FastAPI route then serializes as a JSON STRING. An integral ``Decimal`` is - decoded to ``int``; a fractional one (an ``avg`` over minor units) has no honest - ``int`` and is returned as read. Every other field subtype is returned verbatim, - keeping ADR-0019's "runtime returns native in-process types" contract intact. - - An int with no member RAISES. The database then holds a value the model says - is impossible — a hand-written INSERT, or a member removed without a - migration — and neither alternative is honest: returning the raw int hands - the caller a "member" that is not one (C#, Kotlin and TypeScript type this - property as a CLOSED enum, where ``7`` is not even representable), and - returning ``None`` hides the corruption behind a nullable column. Every port - throws here. - """ - if value is None: - return None - if field.sub_type == fc.FIELD_SUBTYPE_DURATION: - # A duration reads back as a datetime.timedelta on every engine: pg8000 hands one back - # for an interval, a SQLite / MySQL integer column holds the microsecond count. An interval with a month - # part (a PGInterval from pg8000, its text from psycopg: see PostgresDriver) is not a fixed length: refused. - if isinstance(value, list): - return [None if v is None else duration_from_driver(v) for v in value] - return duration_from_driver(value) - if field.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): - # A jsonb value object's duration members read back in their canonical form. - if field.get_meta_attr(fc.FIELD_ATTR_STORAGE) != "flattened": # ADR-0039 resolving - return _vo_durations(field, value, _read_duration_member) - return value - if field.sub_type == fc.FIELD_SUBTYPE_CURRENCY: - if isinstance(value, _decimal.Decimal) and value == value.to_integral_value(): - return int(value) - return value - if field.sub_type != fc.FIELD_SUBTYPE_ENUM: - return value - int_map = _int_value_map(field) - if int_map is None: - stored_map = _string_value_map(field) - if stored_map is not None and isinstance(value, str): - # rc.21: the stored string back to its member; an unmapped one RAISES, as an - # unmapped int does. - for member, stored in stored_map.items(): - if stored == value: - return member - raise ValueError( - f"field.enum '{field.name}' read stored value {value!r} with no member in " - f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} (declared: {stored_map}) — the database holds " - f"a value the model does not describe." - ) - return value - if isinstance(value, list): - # isArray=true (``integer[]``): decode element-wise; a null element stays null. - return [None if v is None else _decode_enum_int(field, int_map, v) for v in value] - return _decode_enum_int(field, int_map, value) - - -def _decode_enum_int(field: MetaField, int_map: dict[Any, Any], value: Any) -> Any: - """One stored int as its member symbol. A non-int is returned as read; an int - with no member RAISES (see :func:`_decode_read_value`).""" - if not isinstance(value, int) or isinstance(value, bool): - return value - for symbol, stored in int_map.items(): - if stored == value: - return symbol - raise ValueError( - f"field.enum '{field.name}' read stored value {value} with no member in " - f"@{fc.FIELD_ATTR_INT_VALUE_MAP} (declared: {int_map}) — the database holds " - f"a value the model does not describe." - ) - - -def _decode_read_row( - fields_by_name: dict[str, MetaField], row: dict[str, Any], dialect: Dialect = POSTGRES -) -> dict[str, Any]: - """Apply the engine's storage decode, then :func:`_decode_read_value`, to every - field-keyed value in a mapped row.""" - return { - k: ( - _decode_read_value(fields_by_name[k], dialect.decode_value(fields_by_name[k], v)) - if k in fields_by_name - else v - ) - for k, v in row.items() - } - - -# ---------------------------------------------------------------------------- -# #203 — @autoSet CRUD stamping. A ``field.timestamp`` (or any temporal field) -# marked ``@autoSet: onCreate|onUpdate`` declares "the runtime owns this -# timestamp, the caller does not." create() stamps every onCreate AND onUpdate -# column; update() bumps onUpdate and NEVER rewrites onCreate (the lost-update -# guard); insert_preserving() writes them verbatim. The stamp is keyed off the -# COLUMN's temporal type (generalizes past ``datetime`` to date/time), matching -# the TS Zod-transform contract (server owns the value; a fresh row's updated -# timestamp equals its created one). -# ---------------------------------------------------------------------------- - -_AUTO_SET_TEMPORAL_SUBTYPES = ( - fc.FIELD_SUBTYPE_TIMESTAMP, - fc.FIELD_SUBTYPE_DATE, - fc.FIELD_SUBTYPE_TIME, -) - - -def _read_fields(entity: MetaObject) -> list[MetaField]: - """The fields a read selects. An entity that is not write-through reads its own table, - which has no column for a derived (``origin.*``) field: an entity's primary source is - always writable (the loader refuses a read-only primary). Every other object reads a view - that carries them.""" - if entity.sub_type == OBJECT_SUBTYPE_ENTITY and not entity.is_write_through(): - return [f for f in entity.fields() if not f.is_derived()] - return list(entity.fields()) - - -def _auto_set_fields(entity: MetaObject) -> tuple[list[MetaField], list[MetaField]]: - """The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``. - - Reads the RESOLVING ``@autoSet`` (ADR-0039) so a field inherited from an - abstract base — the common ``BaseEntity.createdAt/updatedAt`` pattern — is - honored. A non-temporal field is skipped (``@autoSet`` is a temporal-only - marker). Both lists are empty for an entity that declares no ``@autoSet`` - field, so the write path stays byte-identical for those entities.""" - on_create: list[MetaField] = [] - on_update: list[MetaField] = [] - for f in entity.fields(): - if f.sub_type not in _AUTO_SET_TEMPORAL_SUBTYPES: - continue - mode = f.get_meta_attr(fc.FIELD_ATTR_AUTO_SET) # ADR-0039 resolving: may be inherited via extends - if mode == fc.AUTO_SET_ON_CREATE: - on_create.append(f) - elif mode == fc.AUTO_SET_ON_UPDATE: - on_update.append(f) - return on_create, on_update - - -def _auto_set_stamp(field: MetaField, base: _dt.datetime) -> Any: - """The native ``now()`` value for an ``@autoSet`` *field*, derived from the - single shared *base* instant so every column stamped in one operation is - equal (a fresh row's created == updated). Keyed off the COLUMN's temporal - type: ``field.date`` → ``date``; ``field.time`` → ``time``; ``field.timestamp`` - → a tz-aware ``datetime`` (the instant default) unless ``@localTime`` opts into - a naive wall-clock value (matching :func:`_coerce_write_value`).""" - sub = field.sub_type - if sub == fc.FIELD_SUBTYPE_DATE: - return base.date() - if sub == fc.FIELD_SUBTYPE_TIME: - return base.time() - # field.timestamp: instant / tz-aware by default; @localTime → naive wall clock. - is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving - return base if is_tz else base.replace(tzinfo=None) - - -def _parse_datetime(text: str, *, tz_aware: bool) -> _dt.datetime: - """Parse an ISO-8601 timestamp authoring string to a native datetime. - - A trailing ``Z`` (Zulu/UTC) is normalized to ``+00:00`` for ``fromisoformat``. - For a TIMESTAMPTZ column we keep the resulting datetime tz-aware (defaulting - an offset-less string to UTC); for a plain TIMESTAMP column we strip any - offset to a naive wall-clock value so the driver binds ``timestamp`` (not - ``timestamptz``). - """ - iso = text[:-1] + "+00:00" if text.endswith("Z") else text - dt = _dt.datetime.fromisoformat(iso) - if tz_aware: - if dt.tzinfo is None: - dt = dt.replace(tzinfo=_dt.timezone.utc) - return dt - # Naive wall clock: drop any offset without shifting (the wire form already - # carried the intended wall-clock components). - return dt.replace(tzinfo=None) - - -def _column_of(field: MetaField | None, strategy: str = DEFAULT_COLUMN_NAMING) -> str: - """Physical column for a field. Module-level shim over the shared - :func:`metaobjects.naming.resolve_column_name` so the runtime and codegen cannot - drift on what a column is called.""" - if field is None: - return "" - return resolve_column_name(field, strategy) diff --git a/server/python/src/metaobjects/runtime/object_manager_db.py b/server/python/src/metaobjects/runtime/object_manager_db.py new file mode 100644 index 0000000000..4a3e5b2ca1 --- /dev/null +++ b/server/python/src/metaobjects/runtime/object_manager_db.py @@ -0,0 +1,650 @@ +"""ObjectManagerDb — the DB-API implementation of :class:`~metaobjects.runtime.object_manager.ObjectManager`. + +Compiles a Filter dict to parameterized SQL and runs it through a DB-API 2 driver +(:mod:`metaobjects.runtime.drivers`). The SQL is spelled by the driver's +:class:`~metaobjects.runtime.dialect.Dialect`: Postgres (``PostgresDriver``, pg8000 / +psycopg) double-quotes identifiers and uses ``%s`` placeholders (mixed-case columns like +`programId` round-trip through PG); SQLite and MySQL have their own drivers. Value +conversion (the write and read codecs) lives in :mod:`metaobjects.runtime.values`. + +Per ADR-0019 the query path returns native, in-process Python types; see +:mod:`metaobjects.runtime.drivers` for the out-of-band column type metadata +(``last_column_oids``) the serialization boundary reads. +""" +from __future__ import annotations + +from collections.abc import Iterable +from contextlib import AbstractContextManager +from typing import Any + +from ..meta.meta_root import MetaRoot +from ..meta.core.object.meta_object import MetaObject +from ..meta.core.field.meta_field import MetaField +from ..naming import DEFAULT_COLUMN_NAMING, removed_naming_source_message +from ..meta.persistence.source.meta_source import MetaSource +from ..source_resolution import primary_rdb_source, resolve_table_name +from .n2m_resolver import ( + N2mDescriptor, + collect_column_ids, + collect_symmetric_target_ids, + resolve_n2m_descriptor, +) +from .dialect import MYSQL, POSTGRES, Dialect +from .drivers import DbApiDriver, SelectResult +from .object_manager import Filter, ObjectManager +from .tph import TphSubtype, tph_subtype_of +from .values import ( + coerce_filter_value, + coerce_key_value, + coerce_write_value, + column_of, + decode_read_row, + read_fields, +) + + +class ObjectManagerDb(ObjectManager): + """The runtime persistence layer over a DB-API 2 driver. Translates Filter dicts → + parameterized SQL; see :class:`~metaobjects.runtime.object_manager.ObjectManager` for the + contract.""" + + def __init__( + self, + root: MetaRoot, + driver: DbApiDriver, + column_naming: str | None = None, + ) -> None: + if column_naming is not None: + # ADR-0058 Decision 4 — `ObjectManagerDb(column_naming=...)` was removed in + # 1.1.0 (as `ObjectManager(column_naming=...)`): naming is one project setting + # now, read from the loaded root (never guessed — the old value may have been + # right for that adopter's database, and silently dropping it would rename every + # column). + raise ValueError( + removed_naming_source_message("ObjectManagerDb(column_naming=...)", column_naming) + ) + super().__init__(root) + self._driver = driver + #: The SQL dialect of the driver's engine; a driver that declares none (a test + #: double) is Postgres, the corpus' own engine. + self._d: Dialect = getattr(driver, "dialect", POSTGRES) + + def transaction(self) -> AbstractContextManager[None]: + """Hold the writes made inside the ``with`` block in one transaction on the driver's + connection (see :meth:`~metaobjects.runtime.drivers.DbApiDriver.transaction`): they + commit together when the outermost block ends and roll back together when it raises. + Reads inside the block see the block's own writes.""" + return self._driver.transaction() + + # --- Writes (the base class stamps, notifies and refuses reports; these run the SQL) --- + + def _insert_row( + self, entity: MetaObject, entity_name: str, data: dict[str, Any] + ) -> dict[str, Any]: + """INSERT core behind :meth:`create` / :meth:`insert_preserving` — the + two differ only in whether *data* was ``@autoSet``-stamped before arriving + here. Builds the parameterized INSERT (coercing each value via the write + codec), runs it ``RETURNING`` the full physical column set, and maps the + row back to metadata field names.""" + + # FR-017 TPH: a subtype create injects its discriminator value (the entity + # names the subtype; the caller never sets it). + tph = tph_subtype_of(entity) + if tph is not None: + data = {**data, tph.field: tph.value} + + insert_cols: list[str] = [] + params: list[Any] = [] + for field_name, raw in data.items(): + f = entity.find_field(field_name) + if f is None: + raise ValueError( + f"create('{entity_name}'): no field '{field_name}' in metadata" + ) + # #214: a DERIVED (origin.*) field has no column on the write table — it is + # view-computed. A read-modify-write round-trip (a client POSTs back the read + # model, which carries derived fields) must not try to INSERT it; drop it here. + if f.is_derived(): + continue + insert_cols.append(column_of(f, self._column_naming)) + params.append(coerce_write_value(f, raw)) + + # RETURNING the physical column set so the inserted row — including any + # server-generated PK / default — comes back, then map columns → metadata field + # names for cross-port row-shape parity. #214: a DERIVED (origin.*) field has no + # column on the write table (it is computed by the replica view), so it is + # excluded from RETURNING; the write-through re-read below fetches it via the view. + returning_fields = [f for f in entity.fields() if not f.is_derived()] + all_cols = [column_of(f, self._column_naming) for f in returning_fields] + col_to_field = {column_of(f, self._column_naming): f.name for f in returning_fields} + + if insert_cols: + col_list = ", ".join(self._d.quote(c) for c in insert_cols) + placeholders = ", ".join(self._d.placeholder for _ in insert_cols) + sql = f"INSERT INTO {self._relation(entity)} ({col_list}) VALUES ({placeholders})" + else: + sql = f"INSERT INTO {self._relation(entity)} {self._d.default_values}" + if self._d.supports_returning: + sql += f" RETURNING {', '.join(self._d.quote(c) for c in all_cols)}" + result = self._driver.insert_returning(sql, tuple(params)) + else: + # No RETURNING (MySQL): insert, then re-read the row by its key -- the key the + # caller supplied, else the one the engine generated (AUTO_INCREMENT). + generated = self._driver.insert_last_id(sql, tuple(params)) + pk_field = self._primary_pk_field(entity) + supplied = data.get(pk_field) + pk_value = supplied if supplied is not None else generated + if pk_value is None or (supplied is None and pk_value == 0): + raise ValueError( + f"create('{entity_name}'): the {self._d.name} engine cannot return a " + f"generated key other than an AUTO_INCREMENT one, so supply a value for " + f"'{pk_field}'" + ) + written = self._select_by_key(entity, returning_fields, pk_field, pk_value, tph) + if written is None: + raise RuntimeError( + f"create('{entity_name}'): the inserted row {pk_field}={pk_value!r} " + f"could not be read back" + ) + result = written + # Surface the RETURNING column OIDs (mapped to metadata field names) so the + # serialization boundary applies the same SQL-type wire rules as a read — a + # BIGINT / currency column comes back as a numeric string. Mirrors update(). + self.last_column_oids = self._type_codes(result, col_to_field, returning_fields) + row = result.rows[0] + mapped = {col_to_field.get(k, k): v for k, v in row.items()} + # int-backed enums come back as integers; hand the caller the symbol. + mapped = decode_read_row({f.name: f for f in returning_fields}, mapped, self._d) + # #214: a write-through entity's INSERT RETURNING covers only the table (non-derived) + # columns; re-read the persisted row through the replica VIEW by PK so the returned row + # carries the derived origin.* fields (read-your-writes). find_by_id routes to the view. + if entity.is_write_through(): + reread = self.find_by_id(entity_name, mapped[self._primary_pk_field(entity)]) + if reread is not None: + return reread + return mapped + + def _update_row( + self, + entity: MetaObject, + entity_name: str, + id_value: Any, + data: dict[str, Any], + if_missing: str, + ) -> dict[str, Any] | None: + """UPDATE core behind :meth:`update`: the base class has already refused a report + and stamped the ``@autoSet`` columns. ``data`` is run through the SAME write codec + the INSERT path uses (``coerce_write_value``) so the PATCH path cannot silently skip + the type coercion INSERT applies — the per-port hazard the ``update-delete-all-types`` + corpus gates. Returns the updated row via ``RETURNING``; with no match the answer is + decided by *if_missing*.""" + pk_field = self._primary_pk_field(entity) + pk_col = column_of(entity.find_field(pk_field), self._column_naming) + + # FR-017 TPH: the discriminator is immutable — strip it from the patch; the + # by-id write is subtype-scoped (a row of a different subtype is invisible). + tph = tph_subtype_of(entity) + if tph is not None and tph.field in data: + data = {k: v for k, v in data.items() if k != tph.field} + + set_cols: list[str] = [] + params: list[Any] = [] + for field_name, raw in data.items(): + f = entity.find_field(field_name) + if f is None: + raise ValueError( + f"update('{entity_name}'): no field '{field_name}' in metadata" + ) + # #214: a DERIVED (origin.*) field has no column on the write table (view-computed). + # A read-modify-write round-trip PATCHing back the whole read model must not try to + # UPDATE it; drop it from the SET list. + if f.is_derived(): + continue + set_cols.append(column_of(f, self._column_naming)) + params.append(coerce_write_value(f, raw)) + if not set_cols: + # No columns to set → just read the (scoped) row back by PK (no-op update). + row = self.find_by_id(entity_name, id_value) + return self._on_missing_update(entity_name, pk_field, id_value, if_missing) if row is None else row + + # #214: exclude DERIVED (origin.*) fields from RETURNING — they have no column on + # the write table (computed by the replica view); the write-through re-read below + # fetches them via the view. + returning_fields = [f for f in entity.fields() if not f.is_derived()] + all_cols = [column_of(f, self._column_naming) for f in returning_fields] + col_to_field = {column_of(f, self._column_naming): f.name for f in returning_fields} + assignments = ", ".join(f"{self._d.quote(c)} = {self._d.placeholder}" for c in set_cols) + params.append(coerce_key_value(entity.find_field(pk_field), id_value)) + where = f"{self._d.quote(pk_col)} = {self._d.placeholder}" + if tph is not None: + where += f" AND {self._d.quote(column_of(entity.find_field(tph.field), self._column_naming))} = {self._d.placeholder}" + params.append(tph.value) + sql = f"UPDATE {self._relation(entity)} SET {assignments} WHERE {where}" + if self._d.supports_returning: + sql += f" RETURNING {', '.join(self._d.quote(c) for c in all_cols)}" + result = self._driver.update_returning(sql, tuple(params)) + else: + # No RETURNING (MySQL): update, then re-read the (TPH-scoped) row by its key. A + # row that matched but changed nothing still reads back, which a rowcount would + # report as no match. + self._driver.execute_rowcount(sql, tuple(params)) + result = self._select_by_key(entity, returning_fields, pk_field, id_value, tph) + if result is None: + self.last_column_oids = {} + return self._on_missing_update(entity_name, pk_field, id_value, if_missing) + # Surface the RETURNING column OIDs (mapped to metadata field names) so the + # serialization boundary applies the same SQL-type wire rules as a read — + # a BIGINT / currency column comes back as a numeric string. Mirrors the + # find_many bookkeeping. + self.last_column_oids = self._type_codes(result, col_to_field, returning_fields) + row = result.rows[0] + mapped = {col_to_field.get(k, k): v for k, v in row.items()} + # int-backed enums come back as integers; hand the caller the symbol. + mapped = decode_read_row({f.name: f for f in returning_fields}, mapped, self._d) + # #214: re-read the updated row through the replica VIEW by PK so the returned row + # carries the derived origin.* fields (write targeted the table, which lacks them). + if entity.is_write_through(): + reread = self.find_by_id(entity_name, id_value) + if reread is not None: + return reread + return mapped + + def _type_codes( + self, result: SelectResult, col_to_field: dict[str, str], fields: Iterable[MetaField] + ) -> dict[str, int]: + """The per-field SQL type metadata for the serialization boundary. A driver with + column OIDs (Postgres) supplies them; an engine with none (SQLite, MySQL) reports + the equivalent for each field's declared subtype.""" + if self._d.synthesizes_type_codes: + codes = ((f.name, self._d.type_code(f)) for f in fields) + return {name: code for name, code in codes if code is not None} + return {col_to_field.get(c, c): oid for c, oid in result.column_oids.items()} + + def _select_by_key( + self, + entity: MetaObject, + fields: list[MetaField], + pk_field: str, + key: Any, + tph: TphSubtype | None, + ) -> SelectResult | None: + """Read one row of the WRITE table by its key (TPH-scoped), or ``None``: how an + engine with no ``RETURNING`` hands back what it just wrote.""" + ph = self._d.placeholder + cols = [column_of(f, self._column_naming) for f in fields] + pk = entity.find_field(pk_field) + if pk is None: + raise ValueError(f"Entity '{entity.name}' has no primary key field '{pk_field}'") + pk_col = column_of(pk, self._column_naming) + params: list[Any] = [coerce_key_value(pk, key)] + where = f"{self._d.quote(pk_col)} = {ph}" + if tph is not None: + where += f" AND {self._d.quote(column_of(entity.find_field(tph.field), self._column_naming))} = {ph}" + params.append(tph.value) + sql = ( + f"SELECT {', '.join(self._d.quote(c) for c in cols)} " + f"FROM {self._relation(entity)} WHERE {where}" + ) + result = self._driver.select(sql, tuple(params)) + if not result.rows: + return None + return SelectResult(result.rows[:1], result.column_oids) + + @staticmethod + def _on_missing_update( + entity_name: str, pk_field: str, id_value: Any, if_missing: str + ) -> None: + """No (TPH-scoped) row matched an update: ``"throw"`` raises (the persistence + ``expect-error`` contract), ``"ignore"`` returns ``None`` (REST route → 404).""" + if if_missing == "throw": + raise KeyError( + f"update('{entity_name}'): no row with {pk_field}={id_value!r} in scope" + ) + return None + + def _delete_row(self, entity: MetaObject, entity_name: str, id_value: Any) -> bool: + """DELETE core behind :meth:`delete`: ``True`` when a row was deleted, ``False`` when + the (TPH-scoped) key matched nothing.""" + pk_field = self._primary_pk_field(entity) + pk_col = column_of(entity.find_field(pk_field), self._column_naming) + params: list[Any] = [coerce_key_value(entity.find_field(pk_field), id_value)] + where = f"{self._d.quote(pk_col)} = {self._d.placeholder}" + # FR-017 TPH: a subtype delete is scoped to its discriminator (cross-subtype + # delete matches no row → False, mirroring the per-subtype route's 404). + tph = tph_subtype_of(entity) + if tph is not None: + where += f" AND {self._d.quote(column_of(entity.find_field(tph.field), self._column_naming))} = {self._d.placeholder}" + params.append(tph.value) + sql = f"DELETE FROM {self._relation(entity)} WHERE {where}" + return self._driver.execute_rowcount(sql, tuple(params)) > 0 + + def find_many( + self, + entity_name: str, + filter: Filter | None = None, + *, + sort: Iterable[tuple[str, str]] | None = None, + limit: int | None = None, + offset: int | None = None, + ) -> list[dict[str, Any]]: + entity = self._require_entity(entity_name) + # #214: reads route to the replica VIEW for a write-through entity (carrying the + # derived origin.* columns), else the entity's own primary source. All effective + # fields (incl. derived) are selected — the view exposes them. An entity with no read + # view reads its table, which stores no derived field, so those are left out. + fields = read_fields(entity) + cols = [column_of(f, self._column_naming) for f in fields] + sql = f'SELECT {", ".join(self._d.quote(c) for c in cols)} FROM {self._read_relation(entity)}' + params: list[Any] = [] + # FR-017 TPH: a subtype read is scoped to its discriminator value (a row of + # a different subtype is invisible); the base entity (no @discriminatorValue) + # reads polymorphically across the single table. + filter = self._scope_filter(filter, tph_subtype_of(entity)) + where = _compile_filter(filter, entity, self._column_naming, self._d) if filter else None + if where is not None: + sql += " WHERE " + where[0] + params.extend(where[1]) + if sort: + order_parts = [] + for field_name, direction in sort: + f = entity.find_field(field_name) + col = column_of(f, self._column_naming) if f is not None else field_name + order_parts.append(self._d.order_term(self._d.quote(col), direction.lower() == "desc")) + if order_parts: + sql += " ORDER BY " + ", ".join(order_parts) + if limit is not None: + sql += f" LIMIT {int(limit)}" + elif offset is not None and self._d.unbounded_limit: + sql += f" LIMIT {self._d.unbounded_limit}" # OFFSET needs a LIMIT on this engine + if offset is not None: + sql += f" OFFSET {int(offset)}" + result = self._driver.select(sql, tuple(params)) + # Map raw column → metadata field name for cross-port row-shape parity. + # Values stay native (ADR-0019); the boundary canonicalizes them. + col_to_field = {column_of(f, self._column_naming): f.name for f in fields} + self.last_column_oids = self._type_codes(result, col_to_field, fields) + # int-backed enums come back as integers; hand the caller the symbol. + fields_by_name = {f.name: f for f in fields} + return [ + decode_read_row(fields_by_name, {col_to_field.get(k, k): v for k, v in row.items()}, self._d) + for row in result.rows + ] + + def count(self, entity_name: str, filter: Filter | None = None) -> int: + entity = self._require_entity(entity_name) + # #214: count reads through the same source as find_many (the replica view for a + # write-through entity — a 1:1 replica, so the count is unchanged). + sql = f"SELECT COUNT(*) FROM {self._read_relation(entity)}" + params: list[Any] = [] + filter = self._scope_filter(filter, tph_subtype_of(entity)) # FR-017 TPH subtype scope + where = _compile_filter(filter, entity, self._column_naming, self._d) if filter else None + if where is not None: + sql += " WHERE " + where[0] + params.extend(where[1]) + n = self._driver.scalar(sql, tuple(params)) + return int(n) if n is not None else 0 + + def relate( + self, entity_name: str, record: dict[str, Any], relation_name: str + ) -> list[dict[str, Any]] | dict[str, Any] | None: + """Traverse a relationship from a source *record* to its related rows. + + M:N (FR-017) is resolved generically from metadata: derive the junction + FK fields from the junction's two ``identity.reference`` children, query + the junction, then load the target rows. Three modes — hetero, directed + self-join (``@sourceRefField``), symmetric self-join (``@symmetric``) — + mirror the TS reference resolver. ``record`` is a source-key dict (e.g. + ``{"id": 1}``); only the source PK is read from it. + """ + self._refuse_report("relate", entity_name) + entity = self._require_entity(entity_name) + desc = resolve_n2m_descriptor(entity, relation_name, self._entity_by_name) + if desc is None: + raise ValueError( + f"Relationship '{relation_name}' on '{entity_name}' is not a " + f"resolvable M:N relationship (only M:N traversal is supported " + f"by relate() today)" + ) + return self._relate_n2m(entity, desc, record) + + def _relate_n2m( + self, entity: MetaObject, desc: N2mDescriptor, record: dict[str, Any] + ) -> list[dict[str, Any]]: + junction = self._require_entity(desc.junction_entity_name) + target = self._require_entity(desc.target_entity_name) + + # Source PK value from the in-process record (the relate `by` key). + source_pk_field = self._primary_pk_field(entity) + source_id = record.get(source_pk_field) + if source_id is None: + return [] + + # Physical junction columns for the derived FK fields. + source_col = self._junction_column(junction, desc.source_field) + target_col = self._junction_column(junction, desc.target_field) + + # Query the junction. Symmetric unions both FK columns; directed/hetero + # filter only the source side. + select_cols = f"{self._d.quote(source_col)}, {self._d.quote(target_col)}" + if desc.symmetric: + sql = ( + f"SELECT {select_cols} FROM {self._relation(junction)} " + f"WHERE {self._d.quote(source_col)} = {self._d.placeholder} OR {self._d.quote(target_col)} = {self._d.placeholder}" + ) + params: tuple[Any, ...] = (source_id, source_id) + else: + sql = ( + f"SELECT {select_cols} FROM {self._relation(junction)} " + f"WHERE {self._d.quote(source_col)} = {self._d.placeholder}" + ) + params = (source_id,) + join_rows = self._driver.select(sql, params).rows + + # Collect the related (target) ids. + if desc.symmetric: + target_ids = collect_symmetric_target_ids( + join_rows, source_col, target_col, {source_id} + ) + else: + target_ids = collect_column_ids(join_rows, target_col) + if not target_ids: + return [] + + # Load the target rows by PK. Reuse find_many so the row shape (metadata + # field names) + last_column_oids match every other read path. + target_pk_field = self._primary_pk_field(target) + return self.find_many( + desc.target_entity_name, {target_pk_field: {"in": target_ids}} + ) + + # --- Helpers --------------------------------------------------------------- + + def _table_name(self, entity: MetaObject) -> str: + """The physical relation *entity* lives in. + + Delegates to :func:`~metaobjects.source_resolution.resolve_table_name` — + THE resolver, shared with codegen and the api-docs builder. It applies the + FR-016 / ADR-0018 four-step rule to the ``@role: primary`` source, and it + is RESOLVING (ADR-0039): a FR-017 TPH subtype, which declares no source of + its own and inherits the discriminator base's single table, resolves to + that base table, while an entity declaring its own source shadows the + inherited one and is unchanged. + + Raises :class:`ValueError` when *entity* declares no primary source at all. + This used to fall back to ``entity.name`` — #248 says participation in + persistence derives from a DECLARED source, never from the object subtype, + so that fallback sent every read, write and delete to a relation nothing + created. Codegen's resolver already returned ``None`` for the shape and the + M:N descriptor already raised on it; the runtime was the one caller that + kept its own copy of the predicate and guessed. + """ + table = resolve_table_name(entity) + if table is None: + raise ValueError( + f'{entity.name}: no primary source (source.rdb) is declared or ' + f"inherited, so this object has no physical relation to read from " + f"or write to. Declare a source.rdb, or do not persist it through " + f"the ObjectManager." + ) + return table + + def _qualified(self, name: str, schema: str | None) -> str: + """*name* quoted, qualified by its source's ``@schema`` where the engine has schemas. + ``meta migrate`` creates a relation declared with ``@schema: sales`` as + ``"sales".""``; a bare name would resolve through ``search_path`` to another + relation, or none. SQLite has no schemas, so its names stay bare.""" + quoted = self._d.quote(name) + return f"{self._d.quote(schema)}.{quoted}" if schema and self._d.qualifies_schemas else quoted + + def _relation(self, entity: MetaObject) -> str: + """The relation WRITES (and by-id reads) target, quoted and schema-qualified.""" + src = primary_rdb_source(entity) + return self._qualified(self._table_name(entity), src.schema() if src is not None else None) + + def _read_relation(self, entity: MetaObject) -> str: + """The relation list and count READS run against (:meth:`_read_source_name`), quoted + and qualified by the schema of the source it names.""" + if entity.is_write_through(): + for c in entity.own_children(): + if isinstance(c, MetaSource) and c.is_read_only() and c.physical_name(): + return self._qualified(c.physical_name(), c.schema()) + return self._relation(entity) + + def _read_source_name(self, entity: MetaObject) -> str: + """The physical relation READS run against. FR-024 §7 (#214): a write-through + entity read-view reads through its read-only REPLICA VIEW (which carries the + derived ``origin.*`` columns), while writes still target the table + (:meth:`_table_name`). Every other object reads its own primary source (= + ``_table_name``), so vanilla/projection behavior is unchanged. + + OWN + role-agnostic: the replica view carries ``@role: replica``, so it is found + by read-only kind among the entity's own sources, not a primary-role accessor.""" + if entity.is_write_through(): + for c in entity.own_children(): + if isinstance(c, MetaSource) and c.is_read_only(): + pn = c.physical_name() + if pn: + return pn + return self._table_name(entity) + + @staticmethod + def _scope_filter(filter: Filter | None, tph: TphSubtype | None) -> Filter | None: + """AND the TPH discriminator predicate into a filter (subtype-scoped reads). + Non-TPH (``tph is None``) returns the filter unchanged.""" + if tph is None: + return filter + disc: Filter = {tph.field: tph.value} # equality shortcut + if not filter: + return disc + return {"and": [filter, disc]} + + def _junction_column(self, junction: MetaObject, field_name: str) -> str: + """Physical column for a junction FK field (metadata field name → column).""" + f = junction.find_field(field_name) + if f is None: + raise ValueError( + f"Junction '{junction.name}' has no field '{field_name}'" + ) + return column_of(f, self._column_naming) + + +# ---------------------------------------------------------------------------- +# Filter compiler — Filter dict → (WHERE clause SQL, params tuple) +# ---------------------------------------------------------------------------- + + + +def _compile_filter( + f: Filter | None, + entity: MetaObject, + column_naming: str = DEFAULT_COLUMN_NAMING, + dialect: Dialect = POSTGRES, +) -> tuple[str, list[Any]] | None: + if not f: + return None + # Top-level `and: [filter, filter, ...]` combinator. + if "and" in f and isinstance(f["and"], list): + parts: list[str] = [] + params: list[Any] = [] + for child in f["and"]: + compiled = _compile_filter(child, entity, column_naming, dialect) + if compiled is None: + continue + parts.append("(" + compiled[0] + ")") + params.extend(compiled[1]) + if not parts: + return None + return " AND ".join(parts), params + + parts = [] + params = [] + for field_name, ops in f.items(): + mf = entity.find_field(field_name) + col = column_of(mf, column_naming) if mf is not None else field_name + if not isinstance(ops, dict): + # Shortcut: {field: value} → equality. Encoded like any other bound + # value (see _op_clause) so an int-backed enum reaches SQL as its int. + parts.append(f"{dialect.quote(col)} = {dialect.placeholder}") + params.append(coerce_filter_value(mf, ops) if mf is not None else ops) + continue + for op, value in ops.items(): + sql, p = _op_clause(col, op, value, mf, dialect) + parts.append(sql) + params.extend(p) + if not parts: + return None + return " AND ".join(parts), params + + +def _op_clause( + col: str, op: str, value: Any, field: MetaField | None = None, dialect: Dialect = POSTGRES +) -> tuple[str, list[Any]]: + """Translate one operator → SQL + params. Mirrors TS/C#/Java semantics. + + Bound values go through the WRITE codec, exactly as an INSERT's do: the four + sibling ports all encode on this path (TS through the Drizzle customType, Java + through GenericSQLDriver.setStatementValue → EnumCodec.write, Kotlin through + Exposed's toDb, C# through the EF converter). Without it an int-backed enum's + filter binds the member SYMBOL against an INTEGER column — the filter band + keeps eq/ne/in for int-backed enums precisely BECAUSE the symbol is supposed + to encode to its integer before reaching SQL. + """ + qc = dialect.quote(col) + ph = dialect.placeholder + if dialect is MYSQL and field is not None and field.sub_type == "decimal" and op not in ("isNull", "like"): + # ADR-0019 W2: MySQL compares DECIMAL = 'text' as doubles; a cast operand compares as a + # decimal, so a 19-digit operand is exact. + ph = f"CAST({ph} AS DECIMAL(65,30))" + if field is not None and op != "isNull": + value = ([coerce_filter_value(field, v) for v in value] + if op == "in" and value else coerce_filter_value(field, value)) + if op == "eq": return f"{qc} = {ph}", [value] + if op == "ne": return f"{qc} <> {ph}", [value] + if op == "gt": return f"{qc} > {ph}", [value] + if op == "gte": return f"{qc} >= {ph}", [value] + if op == "lt": return f"{qc} < {ph}", [value] + if op == "lte": return f"{qc} <= {ph}", [value] + # `like` is case-SENSITIVE SQL LIKE — verbatim pattern, %/_ wildcards + # (ADR-0049; the de-blinded filter-like-and-ne fixture gates this). The dialect + # spells it where the engine's own LIKE is not case-sensitive. + if op == "like": return dialect.like_clause(qc, value) + if op == "isNull": + wants_null = bool(value) if not isinstance(value, str) else value.lower() == "true" + return (f"{qc} IS NULL" if wants_null else f"{qc} IS NOT NULL"), [] + if op == "in": + if not value: + # Empty IN list — match nothing. + return dialect.false_predicate(), [] + placeholders = ", ".join(ph for _ in value) + return f"{qc} IN ({placeholders})", list(value) + raise ValueError(f"Unsupported filter op '{op}' on column '{col}'") + + +# ---------------------------------------------------------------------------- +# Write codec — authoring form → native Python type the driver binds (ADR-0019 +# write side). pg8000 maps Decimal→numeric, uuid.UUID→uuid, naive datetime→ +# timestamp, aware datetime→timestamptz, date→date, time→time, dict→jsonb. We +# only need to turn the corpus' authoring *strings* into those native types; the +# driver does the rest. Mirrors the TS runtime write coercer (type-coercer.ts): +# jsonb objects + native binding per subtype, everything else passes through. +# ---------------------------------------------------------------------------- diff --git a/server/python/src/metaobjects/runtime/values.py b/server/python/src/metaobjects/runtime/values.py new file mode 100644 index 0000000000..49d18bb9e5 --- /dev/null +++ b/server/python/src/metaobjects/runtime/values.py @@ -0,0 +1,543 @@ +"""Value conversion for the runtime persistence layer: authoring form to the native value a +driver binds, and the column value read back to the value a caller sees. + +Store-neutral, in the sense that no SQL is spelled here: the write codec (``coerce_write_value``, +``coerce_key_value``, ``coerce_filter_value``), the read codec (``decode_read_value``, +``decode_read_row``, int-backed enums, durations, arrays of value objects), ``@autoSet`` +stamping and the column-name rule all work from a field's declared metadata alone. A manager +for any store reuses them, and :class:`~metaobjects.runtime.object_manager_db.ObjectManagerDb` +is the one that binds the results to a DB-API driver. + +Per ADR-0019 (runtime return-type contract) the read side returns **native, in-process Python +types**; canonicalization to the cross-port wire form is a serialization-boundary concern +(see ``tests/integration/normalization.py``), never done here. +""" +from __future__ import annotations + +import datetime as _dt +import decimal as _decimal +import json as _json +import math as _math +import re as _re +import uuid as _uuid +from collections.abc import Mapping +from typing import Any + +from ..codegen.runtime.duration_wire import ( + duration_from_driver, + format_duration, + parse_duration_input, +) +from ..meta.core.field import field_constants as fc +from ..meta.core.field.meta_field import MetaField +from ..meta.core.object.meta_object import MetaObject +from ..meta.core.object.object_constants import OBJECT_SUBTYPE_ENTITY +from ..naming_refs import ref_target +from ..naming import DEFAULT_COLUMN_NAMING, resolve_column_name +from ..meta.persistence.db import db_constants as dbc +from .dialect import POSTGRES, Dialect, DurationParam + + +# ---------------------------------------------------------------------------- +# Write codec — authoring form → native Python type the driver binds (ADR-0019 +# write side). pg8000 maps Decimal→numeric, uuid.UUID→uuid, naive datetime→ +# timestamp, aware datetime→timestamptz, date→date, time→time, dict→jsonb. We +# only need to turn the corpus' authoring *strings* into those native types; the +# driver does the rest. Mirrors the TS runtime write coercer (type-coercer.ts): +# jsonb objects + native binding per subtype, everything else passes through. +# ---------------------------------------------------------------------------- + + +def field_is_array(field: MetaField) -> bool: + """Effective array-ness (ADR-0039 resolving): the native ``is_array`` flag OR + the ``@isArray`` attr, resolved through the ``extends`` super chain so a concrete + field inheriting array-ness from an abstract parent is honored at write time.""" + return field.resolved_is_array() + + +_FILTER_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG, fc.FIELD_SUBTYPE_CURRENCY) +_FILTER_FLOAT_SUBTYPES = (fc.FIELD_SUBTYPE_FLOAT, fc.FIELD_SUBTYPE_DOUBLE) + + +def coerce_filter_value(field: MetaField, value: Any) -> Any: + """A filter operand as the native type the column compares against. + + A filter value usually arrives as TEXT (the REST grammar ``filter[f][op]=v`` hands the + repository the raw URL text). Postgres lets the driver pick the column type for a + bound string; SQLite and MySQL compare a bound string against a number as TEXT, so + ``count > '0'`` is wrong there. Numeric and boolean operands are parsed from text by + the field's declared subtype, then the write codec applies as for any bound value.""" + if isinstance(value, str): + sub = field.sub_type + if sub in _FILTER_INT_SUBTYPES: + value = int(value) if _INT_TEXT.match(value) else value + elif sub in _FILTER_FLOAT_SUBTYPES: + try: + value = float(value) + except ValueError: + pass + elif sub == fc.FIELD_SUBTYPE_BOOLEAN: + lowered = value.strip().lower() + if lowered in ("true", "1"): + value = True + elif lowered in ("false", "0"): + value = False + return coerce_write_value(field, value, for_filter=True) + + +_INT_TEXT = _re.compile(r"^\s*-?\d+\s*$") + + +_ASCII_DIGITS = "0123456789" +_KEY_INT_SUBTYPES = (fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG) +_KEY_DECIMAL_SUBTYPES = (fc.FIELD_SUBTYPE_DECIMAL, fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT) + + +def _is_canonical_decimal_text(text: str, *, fractional: bool) -> bool: + """Canonical decimal key text: optional ``-``, ASCII digits with no leading zero (a lone + ``0`` is fine), no ``-0``, and, when *fractional*, an optional ``.`` plus at least one + digit. Checked character by character: ``int()``/``float()``/``Decimal()`` accept + whitespace, ``+``, ``_``, exponents, Unicode digits, ``nan`` and ``inf``, and + ``str.isdigit`` accepts Unicode digits, so none of them may decide.""" + body = text[1:] if text.startswith("-") else text + whole, dot, frac = body.partition(".") + if dot and not fractional: + return False + if not whole or any(c not in _ASCII_DIGITS for c in whole): + return False + if len(whole) > 1 and whole[0] == "0": + return False + if dot and (not frac or any(c not in _ASCII_DIGITS for c in frac)): + return False + if text.startswith("-") and whole == "0" and all(c == "0" for c in frac): + return False + return True + + +def coerce_key_value(field: MetaField, value: Any) -> Any: + """A primary-key / id argument as the native value the key column binds. + + A key arrives as TEXT from a route or a ref. For a numeric key field the text must be + canonical decimal (see :func:`_is_canonical_decimal_text`), else the same ``ValueError`` + the OM raises for any unusable argument; text that names no key never names row 1 or 0. + A non-text value, or a non-numeric key (string, uuid), goes to the ordinary write codec.""" + if isinstance(value, str): + sub = field.sub_type + integer = sub in _KEY_INT_SUBTYPES + if integer or sub in _KEY_DECIMAL_SUBTYPES: + if not _is_canonical_decimal_text(value, fractional=not integer) or ( + sub in (fc.FIELD_SUBTYPE_DOUBLE, fc.FIELD_SUBTYPE_FLOAT) and _math.isinf(float(value)) + ): + owner = field.parent.name if field.parent is not None else "?" + raise ValueError( + f"Entity '{owner}' key field '{field.name}' (field.{sub}) is not canonical decimal text" + ) + if integer: + return int(value) + return _decimal.Decimal(value) if sub == fc.FIELD_SUBTYPE_DECIMAL else float(value) + return coerce_write_value(field, value) + + +def coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False) -> Any: + if value is None: + return None + sub = field.sub_type + # ADR-0039 own-only: @dbColumnType is a physical column-type override, never + # inherited via extends (the one deliberately own-only attribute). + col_type = field.attr(dbc.FIELD_ATTR_DB_COLUMN_TYPE) + + # decimal / currency: a decimal authored as a string → Decimal (exact; never + # via float). currency is integer minor units — already an int, pass through. + if sub == fc.FIELD_SUBTYPE_DECIMAL: + if field_is_array(field) and isinstance(value, list): + return [None if v is None else v if isinstance(v, _decimal.Decimal) else _decimal.Decimal(str(v)) for v in value] + return value if isinstance(value, _decimal.Decimal) else _decimal.Decimal(str(value)) + + # uuid (logical field.uuid, or a string field pinned to a uuid column): + # string → uuid.UUID so the driver binds the native uuid type. PG stores it + # lowercase-canonically regardless of input case. + # + # For isArray=true (native uuid[] column, Phase 1): coerce each element in the + # list. pg8000 binds a Python list[uuid.UUID] to a uuid[] column natively. + # field.string isArray=true (text[] column) passes through — pg8000 binds + # list[str] to text[] natively without element conversion. + if sub == fc.FIELD_SUBTYPE_UUID or col_type == dbc.DB_COLUMN_TYPE_UUID: + if field_is_array(field) and isinstance(value, list): + return [v if isinstance(v, _uuid.UUID) else _uuid.UUID(str(v)) for v in value] + return value if isinstance(value, _uuid.UUID) else _uuid.UUID(str(value)) + + # field.duration: an accepted ISO-8601 duration (or a timedelta already in process) → + # datetime.timedelta, which pg8000 binds as an interval; the SQLite and MySQL dialects + # bind its microsecond count (Dialect.encode_param), so a filter operand compares and + # orders as a number there. Anything else — a calendar span, a + # clock string, a number — is refused here, not by the database. + if sub == fc.FIELD_SUBTYPE_DURATION: + if field_is_array(field) and isinstance(value, list): + return [None if v is None else _duration_write_value(field, v) for v in value] + return _duration_write_value(field, value) + + # temporal: parse the authoring string to the native type, with tz-awareness + # driven by the field so the driver binds the correct physical type. ADR-0036 + # Wave 2: field.timestamp is instant / tz-aware BY DEFAULT (→ timestamptz); the + # rare naive wall-clock case opts out with @localTime:true (→ plain timestamp). + if sub == fc.FIELD_SUBTYPE_DATE: + return value if isinstance(value, _dt.date) else _dt.date.fromisoformat(str(value)) + if sub == fc.FIELD_SUBTYPE_TIME: + return value if isinstance(value, _dt.time) else _dt.time.fromisoformat(str(value)) + if sub == fc.FIELD_SUBTYPE_TIMESTAMP: + if isinstance(value, _dt.datetime): + return value + is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving: @localTime may be inherited + return _parse_datetime(str(value), tz_aware=is_tz) + + # field.object / field.map stored as a single jsonb column: serialize to a + # JSON text string so pg8000 sends it as jsonb text (PG assignment-casts text + # → jsonb). pg8000 binds a native *dict* to jsonb natively, but a native + # *list* (array-of-VO, isArray:true) it adapts as a Postgres ARRAY literal + # `{...,...}` which the JSONB column rejects with 22P02 'invalid input syntax + # for type json' — so we cannot rely on driver magic for the list form. + # Serializing both shapes to a JSON string is the explicit codec every other + # port has (Java/Gson, C#/System.Text.Json, TS/JSON.stringify, Kotlin/Jackson) + # and handles dict (single VO), list (array-of-VO), and [] uniformly. + # + # Scope: only jsonb-storage field.object/field.map. A *flattened* field.object + # is expanded to separate scalar columns (never reaches here as the object + # node) and must not be touched; a field.string pinned to a jsonb column via + # @dbColumnType already carries a string value and is left alone above. + if sub in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): + storage = field.get_meta_attr(fc.FIELD_ATTR_STORAGE) # ADR-0039 resolving + if storage != "flattened": # None / "jsonb" / "subdocument" → single jsonb column + # A field.duration inside the value object is stored in its canonical form, so the + # column holds what every port writes (and refuses what is not a duration). + return _json.dumps(_vo_durations(field, value, _write_duration_member)) + # field.enum carrying @intValueMap: the column is an INTEGER while the native + # and wire contract stays the member SYMBOL (int-backing is a persistence-layer + # concern, invisible above this codec), so encode symbol -> declared int here. + # + # An unmapped symbol is passed through untouched: membership is the column's + # CHECK constraint to enforce, and inventing a value here would hide the drift. + # + # isArray=true (an ``integer[]`` column): encode ELEMENT-WISE, so the driver + # binds a list of ints, never the symbol list. A null element stays a null + # element (as in a string-backed enum array), and an unmapped element passes + # through like the scalar does; an array column carries no CHECK, so the + # database's integer[] type is what rejects it. + if sub == fc.FIELD_SUBTYPE_ENUM: + int_map = _int_value_map(field) + if int_map is not None: + if field_is_array(field) and isinstance(value, list): + return [_encode_enum_member(int_map, v) for v in value] + return _encode_enum_member(int_map, value) + # rc.21: a @stringValueMap enum stores the member's string (scalar only; the + # loader refuses it on an array). + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + if value in stored_map: + return stored_map[value] + # An unmapped member raises, written or filtered (rc.21 rulings, every port). Written: + # no CHECK need hold behind it (@dbCheck: false), and storing the symbol would write a + # spelling the column does not hold. Filtered: passed through, the symbol could equal + # ANOTHER member's stored string and match that member's rows. + verb = "filter on" if for_filter else "write" + raise ValueError( + f"field.enum '{field.name}' cannot {verb} {value!r}: it has no stored string in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} — the value is not one of the members the model declares." + ) + + # Everything else (string / int / long / double / float / boolean / enum) + # is already the native type pg8000 binds directly. + return value + + +def _write_duration_member(field: MetaField, value: Any) -> str: + """A ``field.duration`` member of a value object, as the canonical string its JSON holds.""" + try: + return format_duration(parse_duration_input(value)) + except ValueError as e: + raise ValueError(f"field.duration '{field.name}' cannot be written: {e}") from None + + +def _read_duration_member(field: MetaField, value: Any) -> str: + """A ``field.duration`` member of a stored value object, in its canonical form (a value + another writer stored in an accepted but non-canonical spelling is normalised).""" + try: + return format_duration(duration_from_driver(value)) + except ValueError as e: + raise ValueError(f"field.duration '{field.name}' read a stored value that is not one: {e}") from None + + +def _vo_has_duration(vo: MetaObject, seen: frozenset[int] = frozenset()) -> bool: + """True when value object *vo*, or one it embeds, has a ``field.duration`` member.""" + if id(vo) in seen: + return False + seen = seen | {id(vo)} + for f in vo.fields(): + if f.sub_type == fc.FIELD_SUBTYPE_DURATION: + return True + if f.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): + target = ref_target(f, fc.FIELD_ATTR_OBJECT_REF) + if isinstance(target, MetaObject) and _vo_has_duration(target, seen): + return True + return False + + +def _vo_durations(field: MetaField, value: Any, convert: Any, seen: frozenset[int] = frozenset()) -> Any: + """The value of a jsonb ``field.object`` / ``field.map`` with *convert* applied to every + ``field.duration`` member of its value object, at any depth: a single object, an array of + them, the values of a map, and the value objects those embed. Anything that is not the + shape the metadata declares is left as it is (validation reports it, not this).""" + if value is None: + return None + target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) # ADR-0039 resolving @objectRef + if not isinstance(target, MetaObject) or id(target) in seen or not _vo_has_duration(target): + return value + seen = seen | {id(target)} + + def one(member: Any) -> Any: + if not isinstance(member, Mapping): + return member + out = dict(member) + for f in target.fields(): + v = out.get(f.name) + if v is None: + continue + if f.sub_type == fc.FIELD_SUBTYPE_DURATION: + out[f.name] = [None if x is None else convert(f, x) for x in v] if isinstance(v, list) else convert(f, v) + elif f.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): + out[f.name] = _vo_durations(f, v, convert, seen) + return out + + if field.sub_type == fc.FIELD_SUBTYPE_MAP: + return {k: one(v) for k, v in value.items()} if isinstance(value, Mapping) else value + if isinstance(value, list): + return [one(v) for v in value] + return one(value) + + +def _duration_write_value(field: MetaField, value: Any) -> DurationParam: + """The bound value of a ``field.duration``: a :class:`DurationParam`, so the dialect that + binds a duration as text does so by the field, never by a value's type.""" + try: + return DurationParam.of(parse_duration_input(value)) + except ValueError as e: + raise ValueError(f"field.duration '{field.name}' cannot be written: {e}") from None + + +def _encode_enum_member(int_map: dict[Any, Any], member: Any) -> Any: + """One member symbol as its declared int; ``None`` and an unmapped (or + unhashable) value pass through untouched.""" + if isinstance(member, str) and member in int_map: + return int_map[member] + return member + + +def _int_value_map(field: MetaField) -> dict[Any, Any] | None: + """The declared ``@intValueMap`` (symbol → int), or ``None`` when the enum is + string-backed. + + ADR-0039 resolving: the map is ``@values``' numeric half — a logical property + of the enum vocabulary that inherits through ``extends`` — so it is read with + ``get_meta_attr``, NOT the own-only accessor (contrast ``@dbColumnType`` in + :func:`coerce_write_value`, the one field attribute that is deliberately + own-only). Shared by the write and read halves of the enum codec, mirroring + the dedicated int-map helper each sibling port's codec keeps (Java + ``EnumCodec.intValueMap``, Kotlin ``readIntValueMap``, C# ``IntValueMapOf``). + """ + m = field.get_meta_attr(fc.FIELD_ATTR_INT_VALUE_MAP) + return m if isinstance(m, dict) else None + + +def _string_value_map(field: MetaField) -> dict[str, str] | None: + """rc.21 — the declared ``@stringValueMap`` (member → stored string), or ``None``. + ADR-0039 resolving, as :func:`_int_value_map`.""" + m = field.get_meta_attr(fc.FIELD_ATTR_STRING_VALUE_MAP) + return m if isinstance(m, dict) else None + + +def decode_read_value(field: MetaField, value: Any) -> Any: + """Decode a stored value back to its authoring form on read. + + A ``field.duration`` reads back as a ``datetime.timedelta`` whatever the engine handed + back (see the branch below). Beyond that, two cases. The inverse of + :func:`coerce_write_value`'s int-backed-enum branch: + the column holds the member's integer, callers expect the member SYMBOL. And + ``field.currency``, whose native type is ``int`` minor units: a table column is + BIGINT and already reads back as an ``int``, but a VIEW column need not be — + ``SUM`` over BIGINT is Postgres ``numeric``, read back as a ``Decimal``, which a + FastAPI route then serializes as a JSON STRING. An integral ``Decimal`` is + decoded to ``int``; a fractional one (an ``avg`` over minor units) has no honest + ``int`` and is returned as read. Every other field subtype is returned verbatim, + keeping ADR-0019's "runtime returns native in-process types" contract intact. + + An int with no member RAISES. The database then holds a value the model says + is impossible — a hand-written INSERT, or a member removed without a + migration — and neither alternative is honest: returning the raw int hands + the caller a "member" that is not one (C#, Kotlin and TypeScript type this + property as a CLOSED enum, where ``7`` is not even representable), and + returning ``None`` hides the corruption behind a nullable column. Every port + throws here. + """ + if value is None: + return None + if field.sub_type == fc.FIELD_SUBTYPE_DURATION: + # A duration reads back as a datetime.timedelta on every engine: pg8000 hands one back + # for an interval, a SQLite / MySQL integer column holds the microsecond count. An interval with a month + # part (a PGInterval from pg8000, its text from psycopg: see PostgresDriver) is not a fixed length: refused. + if isinstance(value, list): + return [None if v is None else duration_from_driver(v) for v in value] + return duration_from_driver(value) + if field.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): + # A jsonb value object's duration members read back in their canonical form. + if field.get_meta_attr(fc.FIELD_ATTR_STORAGE) != "flattened": # ADR-0039 resolving + return _vo_durations(field, value, _read_duration_member) + return value + if field.sub_type == fc.FIELD_SUBTYPE_CURRENCY: + if isinstance(value, _decimal.Decimal) and value == value.to_integral_value(): + return int(value) + return value + if field.sub_type != fc.FIELD_SUBTYPE_ENUM: + return value + int_map = _int_value_map(field) + if int_map is None: + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + # rc.21: the stored string back to its member; an unmapped one RAISES, as an + # unmapped int does. + for member, stored in stored_map.items(): + if stored == value: + return member + raise ValueError( + f"field.enum '{field.name}' read stored value {value!r} with no member in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} (declared: {stored_map}) — the database holds " + f"a value the model does not describe." + ) + return value + if isinstance(value, list): + # isArray=true (``integer[]``): decode element-wise; a null element stays null. + return [None if v is None else _decode_enum_int(field, int_map, v) for v in value] + return _decode_enum_int(field, int_map, value) + + +def _decode_enum_int(field: MetaField, int_map: dict[Any, Any], value: Any) -> Any: + """One stored int as its member symbol. A non-int is returned as read; an int + with no member RAISES (see :func:`decode_read_value`).""" + if not isinstance(value, int) or isinstance(value, bool): + return value + for symbol, stored in int_map.items(): + if stored == value: + return symbol + raise ValueError( + f"field.enum '{field.name}' read stored value {value} with no member in " + f"@{fc.FIELD_ATTR_INT_VALUE_MAP} (declared: {int_map}) — the database holds " + f"a value the model does not describe." + ) + + +def decode_read_row( + fields_by_name: dict[str, MetaField], row: dict[str, Any], dialect: Dialect = POSTGRES +) -> dict[str, Any]: + """Apply the engine's storage decode, then :func:`decode_read_value`, to every + field-keyed value in a mapped row.""" + return { + k: ( + decode_read_value(fields_by_name[k], dialect.decode_value(fields_by_name[k], v)) + if k in fields_by_name + else v + ) + for k, v in row.items() + } + + +# ---------------------------------------------------------------------------- +# #203 — @autoSet CRUD stamping. A ``field.timestamp`` (or any temporal field) +# marked ``@autoSet: onCreate|onUpdate`` declares "the runtime owns this +# timestamp, the caller does not." create() stamps every onCreate AND onUpdate +# column; update() bumps onUpdate and NEVER rewrites onCreate (the lost-update +# guard); insert_preserving() writes them verbatim. The stamp is keyed off the +# COLUMN's temporal type (generalizes past ``datetime`` to date/time), matching +# the TS Zod-transform contract (server owns the value; a fresh row's updated +# timestamp equals its created one). +# ---------------------------------------------------------------------------- + +_AUTO_SET_TEMPORAL_SUBTYPES = ( + fc.FIELD_SUBTYPE_TIMESTAMP, + fc.FIELD_SUBTYPE_DATE, + fc.FIELD_SUBTYPE_TIME, +) + + +def read_fields(entity: MetaObject) -> list[MetaField]: + """The fields a read selects. An entity that is not write-through reads its own table, + which has no column for a derived (``origin.*``) field: an entity's primary source is + always writable (the loader refuses a read-only primary). Every other object reads a view + that carries them.""" + if entity.sub_type == OBJECT_SUBTYPE_ENTITY and not entity.is_write_through(): + return [f for f in entity.fields() if not f.is_derived()] + return list(entity.fields()) + + +def auto_set_fields(entity: MetaObject) -> tuple[list[MetaField], list[MetaField]]: + """The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``. + + Reads the RESOLVING ``@autoSet`` (ADR-0039) so a field inherited from an + abstract base — the common ``BaseEntity.createdAt/updatedAt`` pattern — is + honored. A non-temporal field is skipped (``@autoSet`` is a temporal-only + marker). Both lists are empty for an entity that declares no ``@autoSet`` + field, so the write path stays byte-identical for those entities.""" + on_create: list[MetaField] = [] + on_update: list[MetaField] = [] + for f in entity.fields(): + if f.sub_type not in _AUTO_SET_TEMPORAL_SUBTYPES: + continue + mode = f.get_meta_attr(fc.FIELD_ATTR_AUTO_SET) # ADR-0039 resolving: may be inherited via extends + if mode == fc.AUTO_SET_ON_CREATE: + on_create.append(f) + elif mode == fc.AUTO_SET_ON_UPDATE: + on_update.append(f) + return on_create, on_update + + +def auto_set_stamp(field: MetaField, base: _dt.datetime) -> Any: + """The native ``now()`` value for an ``@autoSet`` *field*, derived from the + single shared *base* instant so every column stamped in one operation is + equal (a fresh row's created == updated). Keyed off the COLUMN's temporal + type: ``field.date`` → ``date``; ``field.time`` → ``time``; ``field.timestamp`` + → a tz-aware ``datetime`` (the instant default) unless ``@localTime`` opts into + a naive wall-clock value (matching :func:`coerce_write_value`).""" + sub = field.sub_type + if sub == fc.FIELD_SUBTYPE_DATE: + return base.date() + if sub == fc.FIELD_SUBTYPE_TIME: + return base.time() + # field.timestamp: instant / tz-aware by default; @localTime → naive wall clock. + is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving + return base if is_tz else base.replace(tzinfo=None) + + +def _parse_datetime(text: str, *, tz_aware: bool) -> _dt.datetime: + """Parse an ISO-8601 timestamp authoring string to a native datetime. + + A trailing ``Z`` (Zulu/UTC) is normalized to ``+00:00`` for ``fromisoformat``. + For a TIMESTAMPTZ column we keep the resulting datetime tz-aware (defaulting + an offset-less string to UTC); for a plain TIMESTAMP column we strip any + offset to a naive wall-clock value so the driver binds ``timestamp`` (not + ``timestamptz``). + """ + iso = text[:-1] + "+00:00" if text.endswith("Z") else text + dt = _dt.datetime.fromisoformat(iso) + if tz_aware: + if dt.tzinfo is None: + dt = dt.replace(tzinfo=_dt.timezone.utc) + return dt + # Naive wall clock: drop any offset without shifting (the wire form already + # carried the intended wall-clock components). + return dt.replace(tzinfo=None) + + +def column_of(field: MetaField | None, strategy: str = DEFAULT_COLUMN_NAMING) -> str: + """Physical column for a field. Module-level shim over the shared + :func:`metaobjects.naming.resolve_column_name` so the runtime and codegen cannot + drift on what a column is called.""" + if field is None: + return "" + return resolve_column_name(field, strategy) diff --git a/server/python/src/metaobjects/shared_model.py b/server/python/src/metaobjects/shared_model.py new file mode 100644 index 0000000000..e3e7c0c178 --- /dev/null +++ b/server/python/src/metaobjects/shared_model.py @@ -0,0 +1,310 @@ +"""FR-023 §4.3 — the shared-model CONTRACT, publisher side: the flattened shared-model artifact +and the manifest that pins it, the pair a consumer's ``deps sync`` copies into its own repo and +verifies. + +Mirrors ``build-shared-model.ts`` in ``codegen-ts`` (and ``SharedModel`` in the JVM and C# +ports), and is held to it by the shared ``fixtures/shared-model-conformance/`` corpus: the +artifact and manifest bytes are the contract, so a project that changes which port publishes +sees no spurious ``drifted``. + +Two stages, both pure of the run, and both in the package on purpose. A generator that an +application owns decides which source files may contribute and which version is published, and +calls these for everything a consumer checks: what is selected, that the selection is closed, +the document's bytes, the hash over them, and the manifest's shape and file names. An owned copy +that changed any of those would publish an artifact a consumer's sync refuses, or worse, +accepts and cannot load, so they are not in the copy. + +:func:`build_shared_model` (design §4.3 steps 1 to 5), in order: + +1. Standalone, strict load of ``files`` with the run's composed providers (the SAME vocabulary + the project's own metadata loaded with). +2. Select the top-level nodes matching the compiled include/exclude scope. Never ``template.*`` + (a publisher's prompts are not a consumer's shapes), and never ``requirement.*`` unless the + publisher opts in with ``requirements`` (default off): a published ledger is design a + consumer can choose to inherit, so publishing one is the publisher's decision. +3. Closure check: every ``extends`` target and every ref-bearing attribute value of a selected + node (and of its own descendants) must resolve to a SELECTED node, else the selection is not + self-contained and the build fails naming the ``(referrer, target)`` pairs. A selected + requirement's ``@implementedBy`` claims are followed too: they are deliberately not loader + references (a planned claim may name a node that does not exist yet), but an exported + requirement claiming a node the export leaves out would dangle in every consumer that + inherits it. +4. Serialize the selection with :func:`~metaobjects.serializer_json.serialize_shared_document`. +5. Re-load the emitted document standalone with CORE providers only, strict: a consumer loads + it with ITS providers, and an export must not need the publisher's non-core vocabulary. + +:func:`render_shared_model_files` (step 6): ``.metaobjects.json`` and +``metaobjects.pkg.json``, the manifest carrying the sha256 of the artifact's bytes. +""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Sequence + +from .core_types import core_providers +from .loader.meta_data_loader import MetaDataLoader +from .loader.sources import InMemoryStringSource, UriSource +from .meta.core.requirement.requirement_constants import REQUIREMENT_ATTR_IMPLEMENTED_BY +from .meta.core.requirement.resolve_claim import resolve_claim_target +from .meta.meta_data import MetaData +from .naming import package_of_resolution_key +from .naming_refs import ( + CHILD_REF_SEP, + REF_BEARING_ATTR_NAMES, + is_ref_bearing_attr, + resolve_object_ref, +) +from .registry_manifest import METAMODEL_VERSION +from .requirement_check import effective_package as effective_requirement_package +from .scope import compile_scope, matches_scope +from .serializer_json import serialize_shared_document +from .shared.base_types import TYPE_REQUIREMENT, TYPE_TEMPLATE +from .shared.separators import PACKAGE_SEP + +#: The FR-023 manifest/artifact file conventions (design §3.2, §4.3, "Hash format"), the same +#: values as ``dependencies.py`` and every other port. +MANIFEST_FILE = "metaobjects.pkg.json" +ARTIFACT_SUFFIX = ".metaobjects.json" +INTEGRITY_PREFIX = "sha256-" +#: design §3.2 — the manifest schema's own version, distinct from ``metamodelVersion``. +MANIFEST_SCHEMA_VERSION = 1 + +#: Why a publish was refused: the contract the conformance corpus pins (the message is not). +REASON_EMPTY_SELECTION = "empty-selection" +REASON_NOT_CLOSED = "not-closed" +REASON_NON_CORE_VOCABULARY = "non-core-vocabulary" + + +class SharedModelError(ValueError): + """A publish the contract refuses. ``reason`` is one of the ``REASON_*`` constants; + ``pairs`` is, for ``not-closed``, the exhaustive ``(referrer, target)`` resolution keys the + selection leaves dangling, sorted by referrer then target.""" + + def __init__(self, reason: str, message: str, pairs: Sequence[tuple[str, str]] = ()) -> None: + super().__init__(message) + self.reason = reason + self.pairs = tuple(pairs) + + +@dataclass(frozen=True) +class SharedModel: + """A selection that passed every check, serialized. Produced by :func:`build_shared_model` + and consumed by :func:`render_shared_model_files`; nothing else should construct or change + one, because ``document`` is exactly the bytes that were re-loaded with core vocabulary and + the manifest's hash is taken over them.""" + + name: str + #: The canonical-JSON ``metadata.root`` document: the artifact's bytes. + document: str + #: The metadata packages the selection spans, sorted. + packages: tuple[str, ...] + #: The resolution key of every selected top-level node, sorted. + nodes: tuple[str, ...] + + +@dataclass(frozen=True) +class SharedModelFiles: + """The two files a shared model is published as: ``(path, content)`` each.""" + + artifact: tuple[str, str] + manifest: tuple[str, str] + + +def artifact_file_name(name: str) -> str: + """``.metaobjects.json``: the artifact's file name, as ``deps sync`` reads it.""" + return f"{name}{ARTIFACT_SUFFIX}" + + +def _ref_owner(ref: str) -> str: + """The object part of a possibly dotted ref: everything before the first child separator + that follows the LAST package separator (package segments never fold onto a non-root + child, so a ``.`` before the final ``::`` segment cannot occur).""" + last = ref.rfind(PACKAGE_SEP) + start = 0 if last == -1 else last + len(PACKAGE_SEP) + dot = ref.find(CHILD_REF_SEP, start) + return ref if dot == -1 else ref[:dot] + + +def _walk_own(node: MetaData) -> list[MetaData]: + """A node and its OWN descendants, node itself first. ADR-0039 sanctioned own-only case: + ``serialize_shared_document`` emits each selected node's OWN layer only (``extends`` + preserved, not flattened), so the closure check walks exactly what will be emitted, never + what ``extends`` would additionally contribute (that is the base's own layer, checked + separately if the base is itself selected).""" + out = [node] + for child in node.own_children(): # ADR-0039 sanctioned own: see the docstring + out.extend(_walk_own(child)) + return out + + +def _check_closure( + root: MetaData, selected: Sequence[MetaData], selected_keys: set[str] +) -> list[tuple[str, str]]: + """design §4.3 step 3. ``root`` already loaded (step 1), so every ref found here resolves + to some node in it: the loader's own validation rejects a dangling ``extends`` or object + ref before this runs. What is not guaranteed is that the resolved node is selected.""" + pairs: list[tuple[str, str]] = [] + seen: set[tuple[str, str]] = set() + for top in selected: + referrer_key = top.resolution_key() + for node in _walk_own(top): + referrer_pkg = node.effective_package() or "" + candidates: list[str] = [] + if node.super_ref is not None: + candidates.append(node.super_ref) + # ADR-0039 sanctioned own-only case (same rationale as _walk_own): an INHERITED + # ref-bearing attr belongs to the base node's own layer and is checked when the + # base itself is walked; reading it through the resolving accessor here would + # attribute the base's reference to this node. + own = node.own_attrs() + for attr_name in sorted(REF_BEARING_ATTR_NAMES): + if not is_ref_bearing_attr(node, attr_name): + continue + value = own.get(attr_name) + if isinstance(value, str): + candidates.append(value) + targets: list[MetaData] = [] + for raw in candidates: + resolved = resolve_object_ref(root, _ref_owner(raw), referrer_pkg) + if resolved is not None: # else already refused at load: defensive only + targets.append(resolved) + if node.type == TYPE_REQUIREMENT: + # `@implementedBy` resolves with the requirement's own resolver, in the + # requirement's effective package (ADR-0042), owner segment only: a member + # claim (`Customer.email`) is closed when its owner is selected. A claim that + # resolves nothing names nothing the export could carry (a planned requirement + # may name a node that does not exist yet), so it is not a pair. + claims = own.get(REQUIREMENT_ATTR_IMPLEMENTED_BY) + claim_pkg = effective_requirement_package(node) # type: ignore[arg-type] + for ref in claims if isinstance(claims, list) else []: + if not isinstance(ref, str): + continue + owner = resolve_claim_target(root, ref.split(CHILD_REF_SEP)[0], claim_pkg) + if owner is not None: + targets.append(owner) + for resolved in targets: + target_key = resolved.resolution_key() + if target_key in selected_keys: + continue + pair = (referrer_key, target_key) + if pair in seen: + continue + seen.add(pair) + pairs.append(pair) + return sorted(pairs) + + +def build_shared_model( + name: str, + files: Sequence[str | Path], + include: Sequence[str], + exclude: Sequence[str] = (), + *, + requirements: bool = False, + providers: Sequence[object] = (), +) -> SharedModel: + """Load ``files`` standalone, select by ``include`` / ``exclude``, and return the selection + as a checked, serialized shared model (design §4.3 steps 1 to 5). + + ``providers`` are the run's own consumer-supplied providers, honoured exactly as they were + for the project's main load (core vocabulary is always included). Raises + :class:`SharedModelError` when the selection is empty, is not closed, or needs vocabulary a + consumer's toolchain does not ship; any load error of ``files`` is raised as a + :class:`ValueError` carrying its code and message.""" + # Step 1 — standalone, strict load with the run's composed providers. + loader = MetaDataLoader(providers=[*core_providers, *providers], strict=True) + loaded = loader.load([UriSource(Path(f).resolve().as_uri()) for f in files]) + if loaded.errors: + first = loaded.errors[0] + raise ValueError(f"sharedModel({name!r}): {first.code}: {first.message}") + root = loaded.root + + # Step 2 — select top-level nodes. ADR-0039 sanctioned own: the root never extends, so its + # own children ARE its effective children. + compiled = compile_scope(include, exclude) + selected = [ + n + for n in root.own_children() + if n.type != TYPE_TEMPLATE + and (requirements or n.type != TYPE_REQUIREMENT) + and matches_scope(n.resolution_key(), compiled) + ] + if not selected: + dropped = "template.*" if requirements else "requirement.* and template.*" + raise SharedModelError( + REASON_EMPTY_SELECTION, + f"sharedModel({name!r}): selected no nodes (include/exclude, always excluding " + f"{dropped}); nothing to publish. Check `include`.", + ) + + # Step 3 — closure. + selected_keys = {n.resolution_key() for n in selected} + failures = _check_closure(root, selected, selected_keys) + if failures: + template_keys = { + n.resolution_key() for n in root.own_children() if n.type == TYPE_TEMPLATE + } + lines = "\n".join( + f" {referrer} -> {target}: " + + ( + "templates are never exported; exclude the referrer" + if target in template_keys + else "include it or exclude the referrer" + ) + for referrer, target in failures + ) + raise SharedModelError( + REASON_NOT_CLOSED, + f"sharedModel({name!r}): the selection is not closed; these references point " + f"outside it:\n{lines}", + failures, + ) + + # Step 4 — serialize (sorted by resolution key; the callee also refuses an unpackaged node). + document = serialize_shared_document(selected) + + # Step 5 — re-load with CORE providers only, strict. A consumer loads this artifact with + # ITS providers, never the publisher's, so an export needing publisher-only vocabulary must + # fail here, not at the consumer. + core = MetaDataLoader(providers=list(core_providers), strict=True).load( + [InMemoryStringSource(document, id=artifact_file_name(name))] + ) + if core.errors: + first = core.errors[0] + raise SharedModelError( + REASON_NON_CORE_VOCABULARY, + f"sharedModel({name!r}): the export needs a provider this toolchain does not " + f"ship; exports must load with core vocabulary: {first.message}", + ) + + return SharedModel( + name=name, + document=document, + packages=tuple(sorted({package_of_resolution_key(k) for k in selected_keys})), + nodes=tuple(sorted(selected_keys)), + ) + + +def render_shared_model_files(model: SharedModel, version: str) -> SharedModelFiles: + """The artifact and the manifest that pins it (design §4.3 step 6, §3.2), as the two files + a consumer's ``deps sync`` reads: the manifest names the artifact and carries the sha256 of + its bytes, so the pair is rendered together and never one without the other.""" + artifact_path = artifact_file_name(model.name) + integrity = INTEGRITY_PREFIX + hashlib.sha256(model.document.encode("utf-8")).hexdigest() + manifest = { + "schema_version": MANIFEST_SCHEMA_VERSION, + "name": model.name, + "version": version, + "metamodelVersion": METAMODEL_VERSION, + "artifact": artifact_path, + "integrity": integrity, + "packages": list(model.packages), + "nodes": list(model.nodes), + } + return SharedModelFiles( + artifact=(artifact_path, model.document), + manifest=(MANIFEST_FILE, json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"), + ) diff --git a/server/python/tests/codegen/golden_generators/expected/__init__.py b/server/python/tests/codegen/golden_generators/expected/__init__.py new file mode 100644 index 0000000000..6a2d6b24cd --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/__init__.py @@ -0,0 +1,2 @@ +# @generated by metaobjects — DO NOT EDIT. +# Package marker so the generated output directory is importable. diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_filter_allowlist.py new file mode 100644 index 0000000000..b4eaefbf2e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_filter_allowlist.py @@ -0,0 +1,40 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypesBreakdown (fitness::AllTypesBreakdown) +# Extend in your own module (e.g. AllTypesBreakdown_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for AllTypesBreakdown. + +ALLTYPESBREAKDOWN_FILTER_FIELDS lists the filterable field names; ALLTYPESBREAKDOWN_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ALLTYPESBREAKDOWN_FILTER_FIELDS: frozenset[str] = frozenset( + { + "flag", + "level", + "legacyStatus", + "dateKey", + "uuidKey", + "allRows", + "totalInts", + "avgDec", + "maxMoney", + "minLong", + "highRows", + }, +) + +ALLTYPESBREAKDOWN_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "flag": frozenset({"eq", "isNull"}), + "level": frozenset({"eq", "ne", "in", "like", "isNull"}), + "legacyStatus": frozenset({"eq", "ne", "in", "isNull"}), + "dateKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "uuidKey": frozenset({"eq", "ne", "in", "isNull"}), + "allRows": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalInts": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgDec": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "maxMoney": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "minLong": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "highRows": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_names.py b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_names.py new file mode 100644 index 0000000000..906de6fa1f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_names.py @@ -0,0 +1,54 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypesBreakdown (fitness::AllTypesBreakdown) +# Extend in your own module (e.g. AllTypesBreakdown_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for AllTypesBreakdown (#248).""" + +from __future__ import annotations + +from typing import Final + +ALLTYPESBREAKDOWN_TYPE: Final[str] = "object" +ALLTYPESBREAKDOWN_SUB_TYPE: Final[str] = "report" +ALLTYPESBREAKDOWN_NAME: Final[str] = "AllTypesBreakdown" + +ALLTYPESBREAKDOWN_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ALLTYPESBREAKDOWN_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ALLTYPESBREAKDOWN_SOURCE_PRIMARY_KIND: Final[str] = "view" +ALLTYPESBREAKDOWN_SOURCE_PRIMARY_VIEW: Final[str] = "v_all_types_breakdown" + +ALLTYPESBREAKDOWN_ALL_ROWS_FIELD: Final[str] = "allRows" +ALLTYPESBREAKDOWN_ALL_ROWS_COLUMN: Final[str] = "all_rows" +ALLTYPESBREAKDOWN_AVG_DEC_FIELD: Final[str] = "avgDec" +ALLTYPESBREAKDOWN_AVG_DEC_COLUMN: Final[str] = "avg_dec" +ALLTYPESBREAKDOWN_DATE_KEY_FIELD: Final[str] = "dateKey" +ALLTYPESBREAKDOWN_DATE_KEY_COLUMN: Final[str] = "date_key" +ALLTYPESBREAKDOWN_FLAG_FIELD: Final[str] = "flag" +ALLTYPESBREAKDOWN_FLAG_COLUMN: Final[str] = "flag" +ALLTYPESBREAKDOWN_HIGH_ROWS_FIELD: Final[str] = "highRows" +ALLTYPESBREAKDOWN_HIGH_ROWS_COLUMN: Final[str] = "high_rows" +ALLTYPESBREAKDOWN_LEGACY_STATUS_FIELD: Final[str] = "legacyStatus" +ALLTYPESBREAKDOWN_LEGACY_STATUS_COLUMN: Final[str] = "legacy_status" +ALLTYPESBREAKDOWN_LEVEL_FIELD: Final[str] = "level" +ALLTYPESBREAKDOWN_LEVEL_COLUMN: Final[str] = "level" +ALLTYPESBREAKDOWN_MAX_MONEY_FIELD: Final[str] = "maxMoney" +ALLTYPESBREAKDOWN_MAX_MONEY_COLUMN: Final[str] = "max_money" +ALLTYPESBREAKDOWN_MIN_LONG_FIELD: Final[str] = "minLong" +ALLTYPESBREAKDOWN_MIN_LONG_COLUMN: Final[str] = "min_long" +ALLTYPESBREAKDOWN_TOTAL_INTS_FIELD: Final[str] = "totalInts" +ALLTYPESBREAKDOWN_TOTAL_INTS_COLUMN: Final[str] = "total_ints" +ALLTYPESBREAKDOWN_UUID_KEY_FIELD: Final[str] = "uuidKey" +ALLTYPESBREAKDOWN_UUID_KEY_COLUMN: Final[str] = "uuid_key" + +ALLTYPESBREAKDOWN_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "allRows": ALLTYPESBREAKDOWN_ALL_ROWS_COLUMN, + "avgDec": ALLTYPESBREAKDOWN_AVG_DEC_COLUMN, + "dateKey": ALLTYPESBREAKDOWN_DATE_KEY_COLUMN, + "flag": ALLTYPESBREAKDOWN_FLAG_COLUMN, + "highRows": ALLTYPESBREAKDOWN_HIGH_ROWS_COLUMN, + "legacyStatus": ALLTYPESBREAKDOWN_LEGACY_STATUS_COLUMN, + "level": ALLTYPESBREAKDOWN_LEVEL_COLUMN, + "maxMoney": ALLTYPESBREAKDOWN_MAX_MONEY_COLUMN, + "minLong": ALLTYPESBREAKDOWN_MIN_LONG_COLUMN, + "totalInts": ALLTYPESBREAKDOWN_TOTAL_INTS_COLUMN, + "uuidKey": ALLTYPESBREAKDOWN_UUID_KEY_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_router.py b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_router.py new file mode 100644 index 0000000000..08e17f8bfb --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_breakdown_router.py @@ -0,0 +1,200 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypesBreakdown (fitness::AllTypesBreakdown) +# Extend in your own module (e.g. AllTypesBreakdown_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the AllTypesBreakdown report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .all_types_breakdown_filter_allowlist import ( + ALLTYPESBREAKDOWN_FILTER_FIELDS, + ALLTYPESBREAKDOWN_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/all_types_breakdowns", tags=["all_types_breakdowns"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "flag", + "level", + "legacyStatus", + "dateKey", + "uuidKey", + "allRows", + "totalInts", + "avgDec", + "maxMoney", + "minLong", + "highRows", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "avgDec", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AllTypesBreakdownRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> AllTypesBreakdownRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_all_types_breakdowns( + request: Request, + repo: Annotated[AllTypesBreakdownRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + ALLTYPESBREAKDOWN_FILTER_FIELDS, + ALLTYPESBREAKDOWN_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_all_types_breakdown() -> Any: + """GENERATED — all_types_breakdowns is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/all_types_filter_allowlist.py new file mode 100644 index 0000000000..b4013ca89a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypes (fitness::AllTypes) +# Extend in your own module (e.g. AllTypes_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for AllTypes. + +ALLTYPES_FILTER_FIELDS lists the filterable field names; ALLTYPES_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ALLTYPES_FILTER_FIELDS: frozenset[str] = frozenset() + +ALLTYPES_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_names.py b/server/python/tests/codegen/golden_generators/expected/all_types_names.py new file mode 100644 index 0000000000..0228260a44 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_names.py @@ -0,0 +1,91 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypes (fitness::AllTypes) +# Extend in your own module (e.g. AllTypes_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for AllTypes (#248).""" + +from __future__ import annotations + +from typing import Final + +ALLTYPES_TYPE: Final[str] = "object" +ALLTYPES_SUB_TYPE: Final[str] = "entity" +ALLTYPES_NAME: Final[str] = "AllTypes" + +ALLTYPES_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ALLTYPES_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ALLTYPES_SOURCE_PRIMARY_KIND: Final[str] = "table" +ALLTYPES_SOURCE_PRIMARY_TABLE: Final[str] = "all_types" + +ALLTYPES_B_VAL_FIELD: Final[str] = "bVal" +ALLTYPES_B_VAL_COLUMN: Final[str] = "b_val" +ALLTYPES_D_VAL_FIELD: Final[str] = "dVal" +ALLTYPES_D_VAL_COLUMN: Final[str] = "d_val" +ALLTYPES_DATE_VAL_FIELD: Final[str] = "dateVal" +ALLTYPES_DATE_VAL_COLUMN: Final[str] = "date_val" +ALLTYPES_DEC_VAL_FIELD: Final[str] = "decVal" +ALLTYPES_DEC_VAL_COLUMN: Final[str] = "dec_val" +ALLTYPES_DURATION_VAL_FIELD: Final[str] = "durationVal" +ALLTYPES_DURATION_VAL_COLUMN: Final[str] = "duration_val" +ALLTYPES_ENUM_VAL_FIELD: Final[str] = "enumVal" +ALLTYPES_ENUM_VAL_COLUMN: Final[str] = "enum_val" +ALLTYPES_F_VAL_FIELD: Final[str] = "fVal" +ALLTYPES_F_VAL_COLUMN: Final[str] = "f_val" +ALLTYPES_I_VAL_FIELD: Final[str] = "iVal" +ALLTYPES_I_VAL_COLUMN: Final[str] = "i_val" +ALLTYPES_ID_FIELD: Final[str] = "id" +ALLTYPES_ID_COLUMN: Final[str] = "id" +ALLTYPES_INET6_VAL_FIELD: Final[str] = "inet6Val" +ALLTYPES_INET6_VAL_COLUMN: Final[str] = "inet6_val" +ALLTYPES_INET_VAL_FIELD: Final[str] = "inetVal" +ALLTYPES_INET_VAL_COLUMN: Final[str] = "inet_val" +ALLTYPES_INT_ENUM_VAL_FIELD: Final[str] = "intEnumVal" +ALLTYPES_INT_ENUM_VAL_COLUMN: Final[str] = "int_enum_val" +ALLTYPES_L_VAL_FIELD: Final[str] = "lVal" +ALLTYPES_L_VAL_COLUMN: Final[str] = "l_val" +ALLTYPES_LABELS_FIELD: Final[str] = "labels" +ALLTYPES_LABELS_COLUMN: Final[str] = "labels" +ALLTYPES_MONEY_VAL_FIELD: Final[str] = "moneyVal" +ALLTYPES_MONEY_VAL_COLUMN: Final[str] = "money_val" +ALLTYPES_S_VAL_FIELD: Final[str] = "sVal" +ALLTYPES_S_VAL_COLUMN: Final[str] = "s_val" +ALLTYPES_SETTINGS_FIELD: Final[str] = "settings" +ALLTYPES_SETTINGS_COLUMN: Final[str] = "settings" +ALLTYPES_TIME_VAL_FIELD: Final[str] = "timeVal" +ALLTYPES_TIME_VAL_COLUMN: Final[str] = "time_val" +ALLTYPES_TS_TZ_VAL_FIELD: Final[str] = "tsTzVal" +ALLTYPES_TS_TZ_VAL_COLUMN: Final[str] = "ts_tz_val" +ALLTYPES_TS_VAL_FIELD: Final[str] = "tsVal" +ALLTYPES_TS_VAL_COLUMN: Final[str] = "ts_val" +ALLTYPES_URI_VAL_FIELD: Final[str] = "uriVal" +ALLTYPES_URI_VAL_COLUMN: Final[str] = "uri_val" +ALLTYPES_UUID_VAL_FIELD: Final[str] = "uuidVal" +ALLTYPES_UUID_VAL_COLUMN: Final[str] = "uuid_val" + +ALLTYPES_IDENTITY_ID_TYPE: Final[str] = "identity" +ALLTYPES_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +ALLTYPES_IDENTITY_ID_NAME: Final[str] = "id" + +ALLTYPES_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "bVal": ALLTYPES_B_VAL_COLUMN, + "dVal": ALLTYPES_D_VAL_COLUMN, + "dateVal": ALLTYPES_DATE_VAL_COLUMN, + "decVal": ALLTYPES_DEC_VAL_COLUMN, + "durationVal": ALLTYPES_DURATION_VAL_COLUMN, + "enumVal": ALLTYPES_ENUM_VAL_COLUMN, + "fVal": ALLTYPES_F_VAL_COLUMN, + "iVal": ALLTYPES_I_VAL_COLUMN, + "id": ALLTYPES_ID_COLUMN, + "inet6Val": ALLTYPES_INET6_VAL_COLUMN, + "inetVal": ALLTYPES_INET_VAL_COLUMN, + "intEnumVal": ALLTYPES_INT_ENUM_VAL_COLUMN, + "lVal": ALLTYPES_L_VAL_COLUMN, + "labels": ALLTYPES_LABELS_COLUMN, + "moneyVal": ALLTYPES_MONEY_VAL_COLUMN, + "sVal": ALLTYPES_S_VAL_COLUMN, + "settings": ALLTYPES_SETTINGS_COLUMN, + "timeVal": ALLTYPES_TIME_VAL_COLUMN, + "tsTzVal": ALLTYPES_TS_TZ_VAL_COLUMN, + "tsVal": ALLTYPES_TS_VAL_COLUMN, + "uriVal": ALLTYPES_URI_VAL_COLUMN, + "uuidVal": ALLTYPES_UUID_VAL_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/all_types_router.py b/server/python/tests/codegen/golden_generators/expected/all_types_router.py new file mode 100644 index 0000000000..37aa31582e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/all_types_router.py @@ -0,0 +1,395 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AllTypes (fitness::AllTypes) +# Extend in your own module (e.g. AllTypes_extra.py) — nothing imports it for you. +"""GENERATED — REST router for AllTypes entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +import uuid +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from ._duration_wire import format_duration, parse_duration +from .all_types_filter_allowlist import ( + ALLTYPES_FILTER_FIELDS, + ALLTYPES_FILTER_OPS_BY_FIELD, +) +from .AllTypes import AllTypesCreate, AllTypesPatch + +router = APIRouter(prefix="/api/all_types", tags=["all_types"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "sVal", + "iVal", + "lVal", + "dVal", + "fVal", + "decVal", + "bVal", + "dateVal", + "timeVal", + "tsVal", + "tsTzVal", + "moneyVal", + "enumVal", + "intEnumVal", + "uuidVal", + "uriVal", + "inetVal", + "inet6Val", + "durationVal", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "sVal", + "iVal", + "lVal", + "dVal", + "fVal", + "decVal", + "bVal", + "dateVal", + "timeVal", + "tsVal", + "tsTzVal", + "moneyVal", + "enumVal", + "uuidVal", + "uriVal", + "inetVal", + "inet6Val", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "decVal", + } +) +_DURATION_FIELDS: dict[str, object] = {"durationVal": parse_duration} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {"decVal": (18, 6)} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput( + decimals="string", + null_members="omit", + shapes={ + "settings": {"f": ["theme", "notify", "retries"], "o": {}}, + "labels": {"f": ["key", "weight"], "o": {}}, + }, + duration=format_duration, +) + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "sVal", + "iVal", + "lVal", + "dVal", + "fVal", + "decVal", + "bVal", + "dateVal", + "timeVal", + "tsVal", + "tsTzVal", + "moneyVal", + "enumVal", + "intEnumVal", + "uuidVal", + "uriVal", + "inetVal", + "inet6Val", + "durationVal", + "settings", + "labels", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AllTypesRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: uuid.UUID) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: uuid.UUID, dto: Any) -> Any | None: ... + def delete(self, id: uuid.UUID) -> bool: ... + + +def get_repository() -> AllTypesRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_all_types( + request: Request, + repo: Annotated[AllTypesRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, ALLTYPES_FILTER_FIELDS, ALLTYPES_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{all_types_id}") +def get_all_types( + all_types_id: uuid.UUID, + repo: Annotated[AllTypesRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(all_types_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_all_types( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AllTypesRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = AllTypesCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{all_types_id}") +@router.put("/{all_types_id}") +def update_all_types( + all_types_id: uuid.UUID, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AllTypesRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = AllTypesPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(all_types_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{all_types_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_all_types( + all_types_id: uuid.UUID, + repo: Annotated[AllTypesRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(all_types_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_filter_allowlist.py new file mode 100644 index 0000000000..007abb8c12 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ArchivedLedgerEntry (fitness::ArchivedLedgerEntry) +# Extend in your own module (e.g. ArchivedLedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ArchivedLedgerEntry. + +ARCHIVEDLEDGERENTRY_FILTER_FIELDS lists the filterable field names; ARCHIVEDLEDGERENTRY_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ARCHIVEDLEDGERENTRY_FILTER_FIELDS: frozenset[str] = frozenset() + +ARCHIVEDLEDGERENTRY_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_names.py b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_names.py new file mode 100644 index 0000000000..00ff5dca02 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_names.py @@ -0,0 +1,32 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ArchivedLedgerEntry (fitness::ArchivedLedgerEntry) +# Extend in your own module (e.g. ArchivedLedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ArchivedLedgerEntry (#248).""" + +from __future__ import annotations + +from typing import Final + +ARCHIVEDLEDGERENTRY_TYPE: Final[str] = "object" +ARCHIVEDLEDGERENTRY_SUB_TYPE: Final[str] = "entity" +ARCHIVEDLEDGERENTRY_NAME: Final[str] = "ArchivedLedgerEntry" + +ARCHIVEDLEDGERENTRY_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ARCHIVEDLEDGERENTRY_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ARCHIVEDLEDGERENTRY_SOURCE_PRIMARY_KIND: Final[str] = "table" +ARCHIVEDLEDGERENTRY_SOURCE_PRIMARY_SCHEMA: Final[str] = "archive" +ARCHIVEDLEDGERENTRY_SOURCE_PRIMARY_TABLE: Final[str] = "ledger_entries" + +ARCHIVEDLEDGERENTRY_ID_FIELD: Final[str] = "id" +ARCHIVEDLEDGERENTRY_ID_COLUMN: Final[str] = "id" +ARCHIVEDLEDGERENTRY_MEMO_FIELD: Final[str] = "memo" +ARCHIVEDLEDGERENTRY_MEMO_COLUMN: Final[str] = "memo" + +ARCHIVEDLEDGERENTRY_IDENTITY_ID_TYPE: Final[str] = "identity" +ARCHIVEDLEDGERENTRY_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +ARCHIVEDLEDGERENTRY_IDENTITY_ID_NAME: Final[str] = "id" + +ARCHIVEDLEDGERENTRY_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": ARCHIVEDLEDGERENTRY_ID_COLUMN, + "memo": ARCHIVEDLEDGERENTRY_MEMO_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_router.py b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_router.py new file mode 100644 index 0000000000..26df3e2b42 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/archived_ledger_entry_router.py @@ -0,0 +1,327 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ArchivedLedgerEntry (fitness::ArchivedLedgerEntry) +# Extend in your own module (e.g. ArchivedLedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — REST router for ArchivedLedgerEntry entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .archived_ledger_entry_filter_allowlist import ( + ARCHIVEDLEDGERENTRY_FILTER_FIELDS, + ARCHIVEDLEDGERENTRY_FILTER_OPS_BY_FIELD, +) +from .ArchivedLedgerEntry import ArchivedLedgerEntryCreate, ArchivedLedgerEntryPatch + +router = APIRouter( + prefix="/api/archived_ledger_entries", tags=["archived_ledger_entries"] +) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "memo", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset() + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "memo", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ArchivedLedgerEntryRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> ArchivedLedgerEntryRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_archived_ledger_entries( + request: Request, + repo: Annotated[ArchivedLedgerEntryRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + ARCHIVEDLEDGERENTRY_FILTER_FIELDS, + ARCHIVEDLEDGERENTRY_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{archived_ledger_entry_id}") +def get_archived_ledger_entry( + archived_ledger_entry_id: int, + repo: Annotated[ArchivedLedgerEntryRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(archived_ledger_entry_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_archived_ledger_entry( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[ArchivedLedgerEntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = ArchivedLedgerEntryCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{archived_ledger_entry_id}") +@router.put("/{archived_ledger_entry_id}") +def update_archived_ledger_entry( + archived_ledger_entry_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[ArchivedLedgerEntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = ArchivedLedgerEntryPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(archived_ledger_entry_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{archived_ledger_entry_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_archived_ledger_entry( + archived_ledger_entry_id: int, + repo: Annotated[ArchivedLedgerEntryRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(archived_ledger_entry_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/asset_activity_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/asset_activity_filter_allowlist.py new file mode 100644 index 0000000000..33c286beff --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_activity_filter_allowlist.py @@ -0,0 +1,20 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetActivity (fitness::AssetActivity) +# Extend in your own module (e.g. AssetActivity_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for AssetActivity. + +ASSETACTIVITY_FILTER_FIELDS lists the filterable field names; ASSETACTIVITY_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ASSETACTIVITY_FILTER_FIELDS: frozenset[str] = frozenset( + {"recordedAtHour", "asOfDateWeek", "assets"}, +) + +ASSETACTIVITY_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "recordedAtHour": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "asOfDateWeek": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "assets": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_activity_names.py b/server/python/tests/codegen/golden_generators/expected/asset_activity_names.py new file mode 100644 index 0000000000..6b1b991fe3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_activity_names.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetActivity (fitness::AssetActivity) +# Extend in your own module (e.g. AssetActivity_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for AssetActivity (#248).""" + +from __future__ import annotations + +from typing import Final + +ASSETACTIVITY_TYPE: Final[str] = "object" +ASSETACTIVITY_SUB_TYPE: Final[str] = "report" +ASSETACTIVITY_NAME: Final[str] = "AssetActivity" + +ASSETACTIVITY_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ASSETACTIVITY_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ASSETACTIVITY_SOURCE_PRIMARY_KIND: Final[str] = "view" +ASSETACTIVITY_SOURCE_PRIMARY_VIEW: Final[str] = "v_asset_activity" + +ASSETACTIVITY_AS_OF_DATE_WEEK_FIELD: Final[str] = "asOfDateWeek" +ASSETACTIVITY_AS_OF_DATE_WEEK_COLUMN: Final[str] = "as_of_date_week" +ASSETACTIVITY_ASSETS_FIELD: Final[str] = "assets" +ASSETACTIVITY_ASSETS_COLUMN: Final[str] = "assets" +ASSETACTIVITY_RECORDED_AT_HOUR_FIELD: Final[str] = "recordedAtHour" +ASSETACTIVITY_RECORDED_AT_HOUR_COLUMN: Final[str] = "recorded_at_hour" + +ASSETACTIVITY_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "asOfDateWeek": ASSETACTIVITY_AS_OF_DATE_WEEK_COLUMN, + "assets": ASSETACTIVITY_ASSETS_COLUMN, + "recordedAtHour": ASSETACTIVITY_RECORDED_AT_HOUR_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_activity_router.py b/server/python/tests/codegen/golden_generators/expected/asset_activity_router.py new file mode 100644 index 0000000000..1fe33e8e3d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_activity_router.py @@ -0,0 +1,188 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetActivity (fitness::AssetActivity) +# Extend in your own module (e.g. AssetActivity_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the AssetActivity report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .asset_activity_filter_allowlist import ( + ASSETACTIVITY_FILTER_FIELDS, + ASSETACTIVITY_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/asset_activities", tags=["asset_activities"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "recordedAtHour", + "asOfDateWeek", + "assets", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AssetActivityRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> AssetActivityRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_asset_activities( + request: Request, + repo: Annotated[AssetActivityRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + ASSETACTIVITY_FILTER_FIELDS, + ASSETACTIVITY_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_asset_activity() -> Any: + """GENERATED — asset_activities is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/asset_days_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/asset_days_filter_allowlist.py new file mode 100644 index 0000000000..05bf6e47b3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_days_filter_allowlist.py @@ -0,0 +1,32 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetDays (fitness::AssetDays) +# Extend in your own module (e.g. AssetDays_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for AssetDays. + +ASSETDAYS_FILTER_FIELDS lists the filterable field names; ASSETDAYS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ASSETDAYS_FILTER_FIELDS: frozenset[str] = frozenset( + { + "recordedAtDay", + "asOfDateMonth", + "assets", + "owners", + "firstRecorded", + "lastObserved", + "lastAsOf", + }, +) + +ASSETDAYS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "recordedAtDay": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "asOfDateMonth": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "assets": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "owners": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "firstRecorded": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "lastObserved": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "lastAsOf": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_days_names.py b/server/python/tests/codegen/golden_generators/expected/asset_days_names.py new file mode 100644 index 0000000000..63cbaf5502 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_days_names.py @@ -0,0 +1,42 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetDays (fitness::AssetDays) +# Extend in your own module (e.g. AssetDays_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for AssetDays (#248).""" + +from __future__ import annotations + +from typing import Final + +ASSETDAYS_TYPE: Final[str] = "object" +ASSETDAYS_SUB_TYPE: Final[str] = "report" +ASSETDAYS_NAME: Final[str] = "AssetDays" + +ASSETDAYS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ASSETDAYS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ASSETDAYS_SOURCE_PRIMARY_KIND: Final[str] = "view" +ASSETDAYS_SOURCE_PRIMARY_VIEW: Final[str] = "v_asset_days" + +ASSETDAYS_AS_OF_DATE_MONTH_FIELD: Final[str] = "asOfDateMonth" +ASSETDAYS_AS_OF_DATE_MONTH_COLUMN: Final[str] = "as_of_date_month" +ASSETDAYS_ASSETS_FIELD: Final[str] = "assets" +ASSETDAYS_ASSETS_COLUMN: Final[str] = "assets" +ASSETDAYS_FIRST_RECORDED_FIELD: Final[str] = "firstRecorded" +ASSETDAYS_FIRST_RECORDED_COLUMN: Final[str] = "first_recorded" +ASSETDAYS_LAST_AS_OF_FIELD: Final[str] = "lastAsOf" +ASSETDAYS_LAST_AS_OF_COLUMN: Final[str] = "last_as_of" +ASSETDAYS_LAST_OBSERVED_FIELD: Final[str] = "lastObserved" +ASSETDAYS_LAST_OBSERVED_COLUMN: Final[str] = "last_observed" +ASSETDAYS_OWNERS_FIELD: Final[str] = "owners" +ASSETDAYS_OWNERS_COLUMN: Final[str] = "owners" +ASSETDAYS_RECORDED_AT_DAY_FIELD: Final[str] = "recordedAtDay" +ASSETDAYS_RECORDED_AT_DAY_COLUMN: Final[str] = "recorded_at_day" + +ASSETDAYS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "asOfDateMonth": ASSETDAYS_AS_OF_DATE_MONTH_COLUMN, + "assets": ASSETDAYS_ASSETS_COLUMN, + "firstRecorded": ASSETDAYS_FIRST_RECORDED_COLUMN, + "lastAsOf": ASSETDAYS_LAST_AS_OF_COLUMN, + "lastObserved": ASSETDAYS_LAST_OBSERVED_COLUMN, + "owners": ASSETDAYS_OWNERS_COLUMN, + "recordedAtDay": ASSETDAYS_RECORDED_AT_DAY_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_days_router.py b/server/python/tests/codegen/golden_generators/expected/asset_days_router.py new file mode 100644 index 0000000000..a5410211da --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_days_router.py @@ -0,0 +1,190 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AssetDays (fitness::AssetDays) +# Extend in your own module (e.g. AssetDays_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the AssetDays report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .asset_days_filter_allowlist import ( + ASSETDAYS_FILTER_FIELDS, + ASSETDAYS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/asset_days", tags=["asset_days"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "recordedAtDay", + "asOfDateMonth", + "assets", + "owners", + "firstRecorded", + "lastObserved", + "lastAsOf", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AssetDaysRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> AssetDaysRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_asset_days( + request: Request, + repo: Annotated[AssetDaysRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, ASSETDAYS_FILTER_FIELDS, ASSETDAYS_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_asset_days() -> Any: + """GENERATED — asset_days is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/asset_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/asset_filter_allowlist.py new file mode 100644 index 0000000000..3911c247df --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Asset (fitness::Asset) +# Extend in your own module (e.g. Asset_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Asset. + +ASSET_FILTER_FIELDS lists the filterable field names; ASSET_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ASSET_FILTER_FIELDS: frozenset[str] = frozenset() + +ASSET_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_names.py b/server/python/tests/codegen/golden_generators/expected/asset_names.py new file mode 100644 index 0000000000..6bf22dabda --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_names.py @@ -0,0 +1,49 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Asset (fitness::Asset) +# Extend in your own module (e.g. Asset_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Asset (#248).""" + +from __future__ import annotations + +from typing import Final + +ASSET_TYPE: Final[str] = "object" +ASSET_SUB_TYPE: Final[str] = "entity" +ASSET_NAME: Final[str] = "Asset" + +ASSET_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ASSET_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ASSET_SOURCE_PRIMARY_KIND: Final[str] = "table" +ASSET_SOURCE_PRIMARY_TABLE: Final[str] = "assets" + +ASSET_AS_OF_DATE_FIELD: Final[str] = "asOfDate" +ASSET_AS_OF_DATE_COLUMN: Final[str] = "as_of_date" +ASSET_AT_TIME_FIELD: Final[str] = "atTime" +ASSET_AT_TIME_COLUMN: Final[str] = "at_time" +ASSET_EXTERNAL_ID_FIELD: Final[str] = "externalId" +ASSET_EXTERNAL_ID_COLUMN: Final[str] = "external_id" +ASSET_ID_FIELD: Final[str] = "id" +ASSET_ID_COLUMN: Final[str] = "id" +ASSET_OBSERVED_AT_FIELD: Final[str] = "observedAt" +ASSET_OBSERVED_AT_COLUMN: Final[str] = "observed_at" +ASSET_OWNER_ID_FIELD: Final[str] = "ownerId" +ASSET_OWNER_ID_COLUMN: Final[str] = "owner_id" +ASSET_PAYLOAD_FIELD: Final[str] = "payload" +ASSET_PAYLOAD_COLUMN: Final[str] = "payload" +ASSET_RECORDED_AT_FIELD: Final[str] = "recordedAt" +ASSET_RECORDED_AT_COLUMN: Final[str] = "recorded_at" + +ASSET_IDENTITY_ID_TYPE: Final[str] = "identity" +ASSET_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +ASSET_IDENTITY_ID_NAME: Final[str] = "id" + +ASSET_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "asOfDate": ASSET_AS_OF_DATE_COLUMN, + "atTime": ASSET_AT_TIME_COLUMN, + "externalId": ASSET_EXTERNAL_ID_COLUMN, + "id": ASSET_ID_COLUMN, + "observedAt": ASSET_OBSERVED_AT_COLUMN, + "ownerId": ASSET_OWNER_ID_COLUMN, + "payload": ASSET_PAYLOAD_COLUMN, + "recordedAt": ASSET_RECORDED_AT_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/asset_router.py b/server/python/tests/codegen/golden_generators/expected/asset_router.py new file mode 100644 index 0000000000..f5f1e0105c --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/asset_router.py @@ -0,0 +1,341 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Asset (fitness::Asset) +# Extend in your own module (e.g. Asset_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Asset entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +import uuid +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Asset import AssetCreate, AssetPatch +from .asset_filter_allowlist import ASSET_FILTER_FIELDS, ASSET_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/assets", tags=["assets"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "ownerId", + "externalId", + "payload", + "recordedAt", + "observedAt", + "asOfDate", + "atTime", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "ownerId", + "recordedAt", + "observedAt", + "asOfDate", + "atTime", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "ownerId", + "externalId", + "payload", + "recordedAt", + "observedAt", + "asOfDate", + "atTime", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AssetRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: uuid.UUID) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: uuid.UUID, dto: Any) -> Any | None: ... + def delete(self, id: uuid.UUID) -> bool: ... + + +def get_repository() -> AssetRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_assets( + request: Request, + repo: Annotated[AssetRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, ASSET_FILTER_FIELDS, ASSET_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{asset_id}") +def get_asset( + asset_id: uuid.UUID, + repo: Annotated[AssetRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(asset_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_asset( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AssetRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = AssetCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{asset_id}") +@router.put("/{asset_id}") +def update_asset( + asset_id: uuid.UUID, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AssetRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = AssetPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(asset_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{asset_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_asset( + asset_id: uuid.UUID, + repo: Annotated[AssetRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(asset_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/auth_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/auth_filter_allowlist.py new file mode 100644 index 0000000000..2de5802352 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auth_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Auth (fitness::Auth) +# Extend in your own module (e.g. Auth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Auth. + +AUTH_FILTER_FIELDS lists the filterable field names; AUTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +AUTH_FILTER_FIELDS: frozenset[str] = frozenset() + +AUTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/auth_names.py b/server/python/tests/codegen/golden_generators/expected/auth_names.py new file mode 100644 index 0000000000..99a271f022 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auth_names.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Auth (fitness::Auth) +# Extend in your own module (e.g. Auth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Auth (#248).""" + +from __future__ import annotations + +from typing import Final + +AUTH_TYPE: Final[str] = "object" +AUTH_SUB_TYPE: Final[str] = "entity" +AUTH_NAME: Final[str] = "Auth" + +AUTH_SOURCE_PRIMARY_TYPE: Final[str] = "source" +AUTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +AUTH_SOURCE_PRIMARY_KIND: Final[str] = "table" +AUTH_SOURCE_PRIMARY_TABLE: Final[str] = "auths" + +AUTH_ID_FIELD: Final[str] = "id" +AUTH_ID_COLUMN: Final[str] = "id" +AUTH_REFERENCE_FIELD: Final[str] = "reference" +AUTH_REFERENCE_COLUMN: Final[str] = "reference" +AUTH_TYPE_FIELD: Final[str] = "type" +AUTH_TYPE_COLUMN: Final[str] = "type" + +AUTH_IDENTITY_ID_TYPE: Final[str] = "identity" +AUTH_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +AUTH_IDENTITY_ID_NAME: Final[str] = "id" + +AUTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": AUTH_ID_COLUMN, + "reference": AUTH_REFERENCE_COLUMN, + "type": AUTH_TYPE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/auth_router.py b/server/python/tests/codegen/golden_generators/expected/auth_router.py new file mode 100644 index 0000000000..8446c4dcb5 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auth_router.py @@ -0,0 +1,895 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Auth (fitness::Auth) +# Extend in your own module (e.g. Auth_extra.py) — nothing imports it for you. +"""GENERATED — TPH polymorphic REST router for the Auth hierarchy (single-table inheritance: polymorphic base + per-subtype CRUD). + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .auth_filter_allowlist import AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD +from .BridgeAuth import BridgeAuthCreate, BridgeAuthPatch +from .CouponAuth import CouponAuthCreate, CouponAuthPatch +from .PermitAuth import PermitAuthCreate, PermitAuthPatch +from .ReferralAuth import ReferralAuthCreate, ReferralAuthPatch + +router = APIRouter(prefix="/api/auths", tags=["auths"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "type", + "reference", + "quantity", + "couponAmount", + "approver", + "urgency", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "reference", + "quantity", + "urgency", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "couponAmount", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {"couponAmount": (10, 2)} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +_WIRE_POST = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "type", + "reference", + "quantity", + "couponAmount", + "approver", + "urgency", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AuthRepository(Protocol): + """GENERATED — TPH seam. `subtype` is the @discriminatorValue, or None for + the polymorphic base; the consumer scopes the single table accordingly. + + For `subtype=None` the base collection is the discriminated union: each row + carries its OWN subtype's fields, and `find_by_id(None, id)` likewise. The + route returns what this returns. ObjectManager's base read projects only the + base's columns, so read a base row through its own subtype entity.""" + + def list( + self, + subtype: str | None, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, subtype: str | None, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, subtype: str | None, id: int) -> Any | None: ... + def create(self, subtype: str, dto: Any) -> Any: ... + def update(self, subtype: str, id: int, dto: Any) -> Any | None: ... + def delete(self, subtype: str, id: int) -> bool: ... + def find_related_posts(self, subtype: str | None, id: int) -> _list[Any]: ... + + +def get_repository() -> AuthRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("/bridge") +def list_auths_bridge( + request: Request, + repo: Annotated[AuthRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list("Bridge", actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count("Bridge", predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("/bridge", status_code=status.HTTP_201_CREATED) +def create_auths_bridge( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-036: run the subtype's field constraints before persisting. + try: + _valid = BridgeAuthCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create("Bridge", dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.get("/bridge/{auth_id}") +def get_auths_bridge( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id("Bridge", auth_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.patch("/bridge/{auth_id}") +@router.put("/bridge/{auth_id}") +def update_auths_bridge( + auth_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-035 PATCH-2: an explicit null on a @required field is a 400. + # FR-036: validate PRESENT, non-null values with the subtype's create rules. + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = BridgeAuthPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update("Bridge", auth_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/bridge/{auth_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_auths_bridge( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete("Bridge", auth_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/coupon") +def list_auths_coupon( + request: Request, + repo: Annotated[AuthRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list("Coupon", actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count("Coupon", predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("/coupon", status_code=status.HTTP_201_CREATED) +def create_auths_coupon( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-036: run the subtype's field constraints before persisting. + try: + _valid = CouponAuthCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create("Coupon", dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.get("/coupon/{auth_id}") +def get_auths_coupon( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id("Coupon", auth_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.patch("/coupon/{auth_id}") +@router.put("/coupon/{auth_id}") +def update_auths_coupon( + auth_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-035 PATCH-2: an explicit null on a @required field is a 400. + # FR-036: validate PRESENT, non-null values with the subtype's create rules. + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = CouponAuthPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update("Coupon", auth_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/coupon/{auth_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_auths_coupon( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete("Coupon", auth_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/permit") +def list_auths_permit( + request: Request, + repo: Annotated[AuthRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list("Permit", actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count("Permit", predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("/permit", status_code=status.HTTP_201_CREATED) +def create_auths_permit( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-036: run the subtype's field constraints before persisting. + try: + _valid = PermitAuthCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create("Permit", dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.get("/permit/{auth_id}") +def get_auths_permit( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id("Permit", auth_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.patch("/permit/{auth_id}") +@router.put("/permit/{auth_id}") +def update_auths_permit( + auth_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-035 PATCH-2: an explicit null on a @required field is a 400. + # FR-036: validate PRESENT, non-null values with the subtype's create rules. + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = PermitAuthPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update("Permit", auth_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/permit/{auth_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_auths_permit( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete("Permit", auth_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/referral") +def list_auths_referral( + request: Request, + repo: Annotated[AuthRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list("Referral", actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count("Referral", predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("/referral", status_code=status.HTTP_201_CREATED) +def create_auths_referral( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-036: run the subtype's field constraints before persisting. + try: + _valid = ReferralAuthCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create("Referral", dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.get("/referral/{auth_id}") +def get_auths_referral( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id("Referral", auth_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.patch("/referral/{auth_id}") +@router.put("/referral/{auth_id}") +def update_auths_referral( + auth_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + dto.pop("type", None) + # FR-035 PATCH-2: an explicit null on a @required field is a 400. + # FR-036: validate PRESENT, non-null values with the subtype's create rules. + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = ReferralAuthPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update("Referral", auth_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/referral/{auth_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_auths_referral( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete("Referral", auth_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/referral/{auth_id}/posts") +def list_auths_referral_posts( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> list[Any]: + if repo.find_by_id("Referral", auth_id) is None: + return [] + rows: list[Any] = render_wire( + repo.find_related_posts("Referral", auth_id), _WIRE_POST + ) + return rows + + +@router.get("") +def list_auths( + request: Request, + repo: Annotated[AuthRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTH_FILTER_FIELDS, AUTH_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(None, actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(None, predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{auth_id}") +def get_auth( + auth_id: int, + repo: Annotated[AuthRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(None, auth_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) diff --git a/server/python/tests/codegen/golden_generators/expected/auths_by_kind_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_filter_allowlist.py new file mode 100644 index 0000000000..43f480c7ad --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_filter_allowlist.py @@ -0,0 +1,18 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AuthsByKind (fitness::AuthsByKind) +# Extend in your own module (e.g. AuthsByKind_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for AuthsByKind. + +AUTHSBYKIND_FILTER_FIELDS lists the filterable field names; AUTHSBYKIND_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +AUTHSBYKIND_FILTER_FIELDS: frozenset[str] = frozenset({"kind", "auths", "distinctRefs"}) + +AUTHSBYKIND_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "kind": frozenset({"eq", "ne", "in", "like", "isNull"}), + "auths": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "distinctRefs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/auths_by_kind_names.py b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_names.py new file mode 100644 index 0000000000..c4782c0d48 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_names.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AuthsByKind (fitness::AuthsByKind) +# Extend in your own module (e.g. AuthsByKind_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for AuthsByKind (#248).""" + +from __future__ import annotations + +from typing import Final + +AUTHSBYKIND_TYPE: Final[str] = "object" +AUTHSBYKIND_SUB_TYPE: Final[str] = "report" +AUTHSBYKIND_NAME: Final[str] = "AuthsByKind" + +AUTHSBYKIND_SOURCE_PRIMARY_TYPE: Final[str] = "source" +AUTHSBYKIND_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +AUTHSBYKIND_SOURCE_PRIMARY_KIND: Final[str] = "view" +AUTHSBYKIND_SOURCE_PRIMARY_VIEW: Final[str] = "v_auths_by_kind" + +AUTHSBYKIND_AUTHS_FIELD: Final[str] = "auths" +AUTHSBYKIND_AUTHS_COLUMN: Final[str] = "auths" +AUTHSBYKIND_DISTINCT_REFS_FIELD: Final[str] = "distinctRefs" +AUTHSBYKIND_DISTINCT_REFS_COLUMN: Final[str] = "distinct_refs" +AUTHSBYKIND_KIND_FIELD: Final[str] = "kind" +AUTHSBYKIND_KIND_COLUMN: Final[str] = "kind" + +AUTHSBYKIND_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "auths": AUTHSBYKIND_AUTHS_COLUMN, + "distinctRefs": AUTHSBYKIND_DISTINCT_REFS_COLUMN, + "kind": AUTHSBYKIND_KIND_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/auths_by_kind_router.py b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_router.py new file mode 100644 index 0000000000..38c3e7d66b --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/auths_by_kind_router.py @@ -0,0 +1,186 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: AuthsByKind (fitness::AuthsByKind) +# Extend in your own module (e.g. AuthsByKind_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the AuthsByKind report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .auths_by_kind_filter_allowlist import ( + AUTHSBYKIND_FILTER_FIELDS, + AUTHSBYKIND_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/auths_by_kinds", tags=["auths_by_kinds"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "kind", + "auths", + "distinctRefs", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class AuthsByKindRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> AuthsByKindRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_auths_by_kinds( + request: Request, + repo: Annotated[AuthsByKindRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, AUTHSBYKIND_FILTER_FIELDS, AUTHSBYKIND_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_auths_by_kind() -> Any: + """GENERATED — auths_by_kinds is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/bridge_auth_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/bridge_auth_filter_allowlist.py new file mode 100644 index 0000000000..b77e61b85f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/bridge_auth_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: BridgeAuth (fitness::BridgeAuth) +# Extend in your own module (e.g. BridgeAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for BridgeAuth. + +BRIDGEAUTH_FILTER_FIELDS lists the filterable field names; BRIDGEAUTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +BRIDGEAUTH_FILTER_FIELDS: frozenset[str] = frozenset() + +BRIDGEAUTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/bridge_auth_names.py b/server/python/tests/codegen/golden_generators/expected/bridge_auth_names.py new file mode 100644 index 0000000000..8d4c2c7f2d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/bridge_auth_names.py @@ -0,0 +1,53 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: BridgeAuth (fitness::BridgeAuth) +# Extend in your own module (e.g. BridgeAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for BridgeAuth (#248).""" + +from __future__ import annotations + +from typing import Final + +from .auth_names import ( + AUTH_ID_COLUMN, + AUTH_ID_FIELD, + AUTH_IDENTITY_ID_NAME, + AUTH_IDENTITY_ID_SUB_TYPE, + AUTH_IDENTITY_ID_TYPE, + AUTH_REFERENCE_COLUMN, + AUTH_REFERENCE_FIELD, + AUTH_SOURCE_PRIMARY_KIND, + AUTH_SOURCE_PRIMARY_SUB_TYPE, + AUTH_SOURCE_PRIMARY_TABLE, + AUTH_SOURCE_PRIMARY_TYPE, + AUTH_TYPE_COLUMN, + AUTH_TYPE_FIELD, +) + +BRIDGEAUTH_TYPE: Final[str] = "object" +BRIDGEAUTH_SUB_TYPE: Final[str] = "entity" +BRIDGEAUTH_NAME: Final[str] = "BridgeAuth" + +BRIDGEAUTH_SOURCE_PRIMARY_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_TYPE +BRIDGEAUTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_SUB_TYPE +BRIDGEAUTH_SOURCE_PRIMARY_KIND: Final[str] = AUTH_SOURCE_PRIMARY_KIND +BRIDGEAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE + +BRIDGEAUTH_ID_FIELD: Final[str] = AUTH_ID_FIELD +BRIDGEAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +BRIDGEAUTH_QUANTITY_FIELD: Final[str] = "quantity" +BRIDGEAUTH_QUANTITY_COLUMN: Final[str] = "quantity" +BRIDGEAUTH_REFERENCE_FIELD: Final[str] = AUTH_REFERENCE_FIELD +BRIDGEAUTH_REFERENCE_COLUMN: Final[str] = AUTH_REFERENCE_COLUMN +BRIDGEAUTH_TYPE_FIELD: Final[str] = AUTH_TYPE_FIELD +BRIDGEAUTH_TYPE_COLUMN: Final[str] = AUTH_TYPE_COLUMN + +BRIDGEAUTH_IDENTITY_ID_TYPE: Final[str] = AUTH_IDENTITY_ID_TYPE +BRIDGEAUTH_IDENTITY_ID_SUB_TYPE: Final[str] = AUTH_IDENTITY_ID_SUB_TYPE +BRIDGEAUTH_IDENTITY_ID_NAME: Final[str] = AUTH_IDENTITY_ID_NAME + +BRIDGEAUTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": BRIDGEAUTH_ID_COLUMN, + "quantity": BRIDGEAUTH_QUANTITY_COLUMN, + "reference": BRIDGEAUTH_REFERENCE_COLUMN, + "type": BRIDGEAUTH_TYPE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/coupon_auth_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/coupon_auth_filter_allowlist.py new file mode 100644 index 0000000000..65d3fcee84 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/coupon_auth_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: CouponAuth (fitness::CouponAuth) +# Extend in your own module (e.g. CouponAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for CouponAuth. + +COUPONAUTH_FILTER_FIELDS lists the filterable field names; COUPONAUTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +COUPONAUTH_FILTER_FIELDS: frozenset[str] = frozenset() + +COUPONAUTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/coupon_auth_names.py b/server/python/tests/codegen/golden_generators/expected/coupon_auth_names.py new file mode 100644 index 0000000000..83efe90b3e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/coupon_auth_names.py @@ -0,0 +1,53 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: CouponAuth (fitness::CouponAuth) +# Extend in your own module (e.g. CouponAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for CouponAuth (#248).""" + +from __future__ import annotations + +from typing import Final + +from .auth_names import ( + AUTH_ID_COLUMN, + AUTH_ID_FIELD, + AUTH_IDENTITY_ID_NAME, + AUTH_IDENTITY_ID_SUB_TYPE, + AUTH_IDENTITY_ID_TYPE, + AUTH_REFERENCE_COLUMN, + AUTH_REFERENCE_FIELD, + AUTH_SOURCE_PRIMARY_KIND, + AUTH_SOURCE_PRIMARY_SUB_TYPE, + AUTH_SOURCE_PRIMARY_TABLE, + AUTH_SOURCE_PRIMARY_TYPE, + AUTH_TYPE_COLUMN, + AUTH_TYPE_FIELD, +) + +COUPONAUTH_TYPE: Final[str] = "object" +COUPONAUTH_SUB_TYPE: Final[str] = "entity" +COUPONAUTH_NAME: Final[str] = "CouponAuth" + +COUPONAUTH_SOURCE_PRIMARY_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_TYPE +COUPONAUTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_SUB_TYPE +COUPONAUTH_SOURCE_PRIMARY_KIND: Final[str] = AUTH_SOURCE_PRIMARY_KIND +COUPONAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE + +COUPONAUTH_COUPON_AMOUNT_FIELD: Final[str] = "couponAmount" +COUPONAUTH_COUPON_AMOUNT_COLUMN: Final[str] = "coupon_amount" +COUPONAUTH_ID_FIELD: Final[str] = AUTH_ID_FIELD +COUPONAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +COUPONAUTH_REFERENCE_FIELD: Final[str] = AUTH_REFERENCE_FIELD +COUPONAUTH_REFERENCE_COLUMN: Final[str] = AUTH_REFERENCE_COLUMN +COUPONAUTH_TYPE_FIELD: Final[str] = AUTH_TYPE_FIELD +COUPONAUTH_TYPE_COLUMN: Final[str] = AUTH_TYPE_COLUMN + +COUPONAUTH_IDENTITY_ID_TYPE: Final[str] = AUTH_IDENTITY_ID_TYPE +COUPONAUTH_IDENTITY_ID_SUB_TYPE: Final[str] = AUTH_IDENTITY_ID_SUB_TYPE +COUPONAUTH_IDENTITY_ID_NAME: Final[str] = AUTH_IDENTITY_ID_NAME + +COUPONAUTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "couponAmount": COUPONAUTH_COUPON_AMOUNT_COLUMN, + "id": COUPONAUTH_ID_COLUMN, + "reference": COUPONAUTH_REFERENCE_COLUMN, + "type": COUPONAUTH_TYPE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/entry_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/entry_filter_allowlist.py new file mode 100644 index 0000000000..c80d39ffa3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_filter_allowlist.py @@ -0,0 +1,16 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Entry (fitness::Entry) +# Extend in your own module (e.g. Entry_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Entry. + +ENTRY_FILTER_FIELDS lists the filterable field names; ENTRY_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ENTRY_FILTER_FIELDS: frozenset[str] = frozenset({"amount"}) + +ENTRY_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "amount": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/entry_names.py b/server/python/tests/codegen/golden_generators/expected/entry_names.py new file mode 100644 index 0000000000..02467f09de --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Entry (fitness::Entry) +# Extend in your own module (e.g. Entry_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Entry (#248).""" + +from __future__ import annotations + +from typing import Final + +ENTRY_TYPE: Final[str] = "object" +ENTRY_SUB_TYPE: Final[str] = "entity" +ENTRY_NAME: Final[str] = "Entry" + +ENTRY_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ENTRY_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ENTRY_SOURCE_PRIMARY_KIND: Final[str] = "table" +ENTRY_SOURCE_PRIMARY_TABLE: Final[str] = "entries" + +ENTRY_AMOUNT_FIELD: Final[str] = "amount" +ENTRY_AMOUNT_COLUMN: Final[str] = "amount" +ENTRY_BUCKET_FIELD: Final[str] = "bucket" +ENTRY_BUCKET_COLUMN: Final[str] = "bucket" +ENTRY_FLAGGED_FIELD: Final[str] = "flagged" +ENTRY_FLAGGED_COLUMN: Final[str] = "flagged" +ENTRY_ID_FIELD: Final[str] = "id" +ENTRY_ID_COLUMN: Final[str] = "id" + +ENTRY_IDENTITY_PK_TYPE: Final[str] = "identity" +ENTRY_IDENTITY_PK_SUB_TYPE: Final[str] = "primary" +ENTRY_IDENTITY_PK_NAME: Final[str] = "pk" + +ENTRY_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "amount": ENTRY_AMOUNT_COLUMN, + "bucket": ENTRY_BUCKET_COLUMN, + "flagged": ENTRY_FLAGGED_COLUMN, + "id": ENTRY_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/entry_router.py b/server/python/tests/codegen/golden_generators/expected/entry_router.py new file mode 100644 index 0000000000..2f883588a0 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_router.py @@ -0,0 +1,333 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Entry (fitness::Entry) +# Extend in your own module (e.g. Entry_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Entry entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Entry import EntryCreate, EntryPatch +from .entry_filter_allowlist import ENTRY_FILTER_FIELDS, ENTRY_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/entries", tags=["entries"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "bucket", + "amount", + "flagged", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "bucket", + "flagged", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "amount", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {"amount": (28, 10)} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "bucket", + "amount", + "flagged", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class EntryRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> EntryRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_entries( + request: Request, + repo: Annotated[EntryRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, ENTRY_FILTER_FIELDS, ENTRY_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{entry_id}") +def get_entry( + entry_id: int, + repo: Annotated[EntryRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(entry_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_entry( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[EntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = EntryCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{entry_id}") +@router.put("/{entry_id}") +def update_entry( + entry_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[EntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = EntryPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(entry_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{entry_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_entry( + entry_id: int, + repo: Annotated[EntryRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(entry_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/entry_totals_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/entry_totals_filter_allowlist.py new file mode 100644 index 0000000000..cb4bdc35d3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_totals_filter_allowlist.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: EntryTotals (fitness::EntryTotals) +# Extend in your own module (e.g. EntryTotals_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for EntryTotals. + +ENTRYTOTALS_FILTER_FIELDS lists the filterable field names; ENTRYTOTALS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +ENTRYTOTALS_FILTER_FIELDS: frozenset[str] = frozenset( + { + "bucket", + "entries", + "total", + "totalOrZero", + "mean", + "top", + "flaggedShare", + "perFlagged", + }, +) + +ENTRYTOTALS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "bucket": frozenset({"eq", "ne", "in", "like", "isNull"}), + "entries": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "total": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalOrZero": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "mean": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "top": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "flaggedShare": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "perFlagged": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/entry_totals_names.py b/server/python/tests/codegen/golden_generators/expected/entry_totals_names.py new file mode 100644 index 0000000000..336bc1e5f3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_totals_names.py @@ -0,0 +1,45 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: EntryTotals (fitness::EntryTotals) +# Extend in your own module (e.g. EntryTotals_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for EntryTotals (#248).""" + +from __future__ import annotations + +from typing import Final + +ENTRYTOTALS_TYPE: Final[str] = "object" +ENTRYTOTALS_SUB_TYPE: Final[str] = "report" +ENTRYTOTALS_NAME: Final[str] = "EntryTotals" + +ENTRYTOTALS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +ENTRYTOTALS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +ENTRYTOTALS_SOURCE_PRIMARY_KIND: Final[str] = "view" +ENTRYTOTALS_SOURCE_PRIMARY_VIEW: Final[str] = "v_entry_totals" + +ENTRYTOTALS_BUCKET_FIELD: Final[str] = "bucket" +ENTRYTOTALS_BUCKET_COLUMN: Final[str] = "bucket" +ENTRYTOTALS_ENTRIES_FIELD: Final[str] = "entries" +ENTRYTOTALS_ENTRIES_COLUMN: Final[str] = "entries" +ENTRYTOTALS_FLAGGED_SHARE_FIELD: Final[str] = "flaggedShare" +ENTRYTOTALS_FLAGGED_SHARE_COLUMN: Final[str] = "flagged_share" +ENTRYTOTALS_MEAN_FIELD: Final[str] = "mean" +ENTRYTOTALS_MEAN_COLUMN: Final[str] = "mean" +ENTRYTOTALS_PER_FLAGGED_FIELD: Final[str] = "perFlagged" +ENTRYTOTALS_PER_FLAGGED_COLUMN: Final[str] = "per_flagged" +ENTRYTOTALS_TOP_FIELD: Final[str] = "top" +ENTRYTOTALS_TOP_COLUMN: Final[str] = "top" +ENTRYTOTALS_TOTAL_FIELD: Final[str] = "total" +ENTRYTOTALS_TOTAL_COLUMN: Final[str] = "total" +ENTRYTOTALS_TOTAL_OR_ZERO_FIELD: Final[str] = "totalOrZero" +ENTRYTOTALS_TOTAL_OR_ZERO_COLUMN: Final[str] = "total_or_zero" + +ENTRYTOTALS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "bucket": ENTRYTOTALS_BUCKET_COLUMN, + "entries": ENTRYTOTALS_ENTRIES_COLUMN, + "flaggedShare": ENTRYTOTALS_FLAGGED_SHARE_COLUMN, + "mean": ENTRYTOTALS_MEAN_COLUMN, + "perFlagged": ENTRYTOTALS_PER_FLAGGED_COLUMN, + "top": ENTRYTOTALS_TOP_COLUMN, + "total": ENTRYTOTALS_TOTAL_COLUMN, + "totalOrZero": ENTRYTOTALS_TOTAL_OR_ZERO_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/entry_totals_router.py b/server/python/tests/codegen/golden_generators/expected/entry_totals_router.py new file mode 100644 index 0000000000..3f9b2b4f0a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/entry_totals_router.py @@ -0,0 +1,200 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: EntryTotals (fitness::EntryTotals) +# Extend in your own module (e.g. EntryTotals_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the EntryTotals report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .entry_totals_filter_allowlist import ( + ENTRYTOTALS_FILTER_FIELDS, + ENTRYTOTALS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/entry_totals", tags=["entry_totals"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "bucket", + "entries", + "total", + "totalOrZero", + "mean", + "top", + "flaggedShare", + "perFlagged", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "total", + "totalOrZero", + "mean", + "top", + "flaggedShare", + "perFlagged", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class EntryTotalsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> EntryTotalsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_entry_totals( + request: Request, + repo: Annotated[EntryTotalsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, ENTRYTOTALS_FILTER_FIELDS, ENTRYTOTALS_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_entry_totals() -> Any: + """GENERATED — entry_totals is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_filter_allowlist.py new file mode 100644 index 0000000000..f7deb1b3c7 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_filter_allowlist.py @@ -0,0 +1,24 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotalsFilled (fitness::FitnessTotalsFilled) +# Extend in your own module (e.g. FitnessTotalsFilled_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for FitnessTotalsFilled. + +FITNESSTOTALSFILLED_FILTER_FIELDS lists the filterable field names; FITNESSTOTALSFILLED_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +FITNESSTOTALSFILLED_FILTER_FIELDS: frozenset[str] = frozenset( + {"weeks", "totalMinutesOrZero", "longShareOrZero"}, +) + +FITNESSTOTALSFILLED_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutesOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), + "longShareOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_names.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_names.py new file mode 100644 index 0000000000..fd1910c8a0 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_names.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotalsFilled (fitness::FitnessTotalsFilled) +# Extend in your own module (e.g. FitnessTotalsFilled_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for FitnessTotalsFilled (#248).""" + +from __future__ import annotations + +from typing import Final + +FITNESSTOTALSFILLED_TYPE: Final[str] = "object" +FITNESSTOTALSFILLED_SUB_TYPE: Final[str] = "report" +FITNESSTOTALSFILLED_NAME: Final[str] = "FitnessTotalsFilled" + +FITNESSTOTALSFILLED_SOURCE_PRIMARY_TYPE: Final[str] = "source" +FITNESSTOTALSFILLED_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +FITNESSTOTALSFILLED_SOURCE_PRIMARY_KIND: Final[str] = "view" +FITNESSTOTALSFILLED_SOURCE_PRIMARY_VIEW: Final[str] = "v_fitness_totals_filled" + +FITNESSTOTALSFILLED_LONG_SHARE_OR_ZERO_FIELD: Final[str] = "longShareOrZero" +FITNESSTOTALSFILLED_LONG_SHARE_OR_ZERO_COLUMN: Final[str] = "long_share_or_zero" +FITNESSTOTALSFILLED_TOTAL_MINUTES_OR_ZERO_FIELD: Final[str] = "totalMinutesOrZero" +FITNESSTOTALSFILLED_TOTAL_MINUTES_OR_ZERO_COLUMN: Final[str] = "total_minutes_or_zero" +FITNESSTOTALSFILLED_WEEKS_FIELD: Final[str] = "weeks" +FITNESSTOTALSFILLED_WEEKS_COLUMN: Final[str] = "weeks" + +FITNESSTOTALSFILLED_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "longShareOrZero": FITNESSTOTALSFILLED_LONG_SHARE_OR_ZERO_COLUMN, + "totalMinutesOrZero": FITNESSTOTALSFILLED_TOTAL_MINUTES_OR_ZERO_COLUMN, + "weeks": FITNESSTOTALSFILLED_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_router.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_router.py new file mode 100644 index 0000000000..57a13beb89 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filled_router.py @@ -0,0 +1,194 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotalsFilled (fitness::FitnessTotalsFilled) +# Extend in your own module (e.g. FitnessTotalsFilled_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the FitnessTotalsFilled report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .fitness_totals_filled_filter_allowlist import ( + FITNESSTOTALSFILLED_FILTER_FIELDS, + FITNESSTOTALSFILLED_FILTER_OPS_BY_FIELD, +) + +router = APIRouter( + prefix="/api/fitness_totals_filleds", tags=["fitness_totals_filleds"] +) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "weeks", + "totalMinutesOrZero", + "longShareOrZero", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "longShareOrZero", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class FitnessTotalsFilledRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> FitnessTotalsFilledRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_fitness_totals_filleds( + request: Request, + repo: Annotated[FitnessTotalsFilledRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + FITNESSTOTALSFILLED_FILTER_FIELDS, + FITNESSTOTALSFILLED_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_fitness_totals_filled() -> Any: + """GENERATED — fitness_totals_filleds is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filter_allowlist.py new file mode 100644 index 0000000000..fa22690bfa --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_filter_allowlist.py @@ -0,0 +1,20 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotals (fitness::FitnessTotals) +# Extend in your own module (e.g. FitnessTotals_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for FitnessTotals. + +FITNESSTOTALS_FILTER_FIELDS lists the filterable field names; FITNESSTOTALS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +FITNESSTOTALS_FILTER_FIELDS: frozenset[str] = frozenset( + {"weeks", "totalMinutes", "longShare"}, +) + +FITNESSTOTALS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "longShare": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_names.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_names.py new file mode 100644 index 0000000000..819d48c67e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_names.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotals (fitness::FitnessTotals) +# Extend in your own module (e.g. FitnessTotals_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for FitnessTotals (#248).""" + +from __future__ import annotations + +from typing import Final + +FITNESSTOTALS_TYPE: Final[str] = "object" +FITNESSTOTALS_SUB_TYPE: Final[str] = "report" +FITNESSTOTALS_NAME: Final[str] = "FitnessTotals" + +FITNESSTOTALS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +FITNESSTOTALS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +FITNESSTOTALS_SOURCE_PRIMARY_KIND: Final[str] = "view" +FITNESSTOTALS_SOURCE_PRIMARY_VIEW: Final[str] = "v_fitness_totals" + +FITNESSTOTALS_LONG_SHARE_FIELD: Final[str] = "longShare" +FITNESSTOTALS_LONG_SHARE_COLUMN: Final[str] = "long_share" +FITNESSTOTALS_TOTAL_MINUTES_FIELD: Final[str] = "totalMinutes" +FITNESSTOTALS_TOTAL_MINUTES_COLUMN: Final[str] = "total_minutes" +FITNESSTOTALS_WEEKS_FIELD: Final[str] = "weeks" +FITNESSTOTALS_WEEKS_COLUMN: Final[str] = "weeks" + +FITNESSTOTALS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "longShare": FITNESSTOTALS_LONG_SHARE_COLUMN, + "totalMinutes": FITNESSTOTALS_TOTAL_MINUTES_COLUMN, + "weeks": FITNESSTOTALS_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/fitness_totals_router.py b/server/python/tests/codegen/golden_generators/expected/fitness_totals_router.py new file mode 100644 index 0000000000..666719e607 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/fitness_totals_router.py @@ -0,0 +1,192 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: FitnessTotals (fitness::FitnessTotals) +# Extend in your own module (e.g. FitnessTotals_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the FitnessTotals report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .fitness_totals_filter_allowlist import ( + FITNESSTOTALS_FILTER_FIELDS, + FITNESSTOTALS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/fitness_totals", tags=["fitness_totals"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "weeks", + "totalMinutes", + "longShare", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "longShare", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class FitnessTotalsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> FitnessTotalsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_fitness_totals( + request: Request, + repo: Annotated[FitnessTotalsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + FITNESSTOTALS_FILTER_FIELDS, + FITNESSTOTALS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_fitness_totals() -> Any: + """GENERATED — fitness_totals is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/follow_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/follow_filter_allowlist.py new file mode 100644 index 0000000000..1793ce8556 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/follow_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Follow (fitness::Follow) +# Extend in your own module (e.g. Follow_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Follow. + +FOLLOW_FILTER_FIELDS lists the filterable field names; FOLLOW_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +FOLLOW_FILTER_FIELDS: frozenset[str] = frozenset() + +FOLLOW_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/follow_names.py b/server/python/tests/codegen/golden_generators/expected/follow_names.py new file mode 100644 index 0000000000..d4ec216882 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/follow_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Follow (fitness::Follow) +# Extend in your own module (e.g. Follow_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Follow (#248).""" + +from __future__ import annotations + +from typing import Final + +FOLLOW_TYPE: Final[str] = "object" +FOLLOW_SUB_TYPE: Final[str] = "entity" +FOLLOW_NAME: Final[str] = "Follow" + +FOLLOW_SOURCE_PRIMARY_TYPE: Final[str] = "source" +FOLLOW_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +FOLLOW_SOURCE_PRIMARY_KIND: Final[str] = "table" +FOLLOW_SOURCE_PRIMARY_TABLE: Final[str] = "follows" + +FOLLOW_FOLLOWEE_ID_FIELD: Final[str] = "followeeId" +FOLLOW_FOLLOWEE_ID_COLUMN: Final[str] = "followee_id" +FOLLOW_FOLLOWER_ID_FIELD: Final[str] = "followerId" +FOLLOW_FOLLOWER_ID_COLUMN: Final[str] = "follower_id" + +FOLLOW_IDENTITY_FK_FOLLOWEE_TYPE: Final[str] = "identity" +FOLLOW_IDENTITY_FK_FOLLOWEE_SUB_TYPE: Final[str] = "reference" +FOLLOW_IDENTITY_FK_FOLLOWEE_NAME: Final[str] = "fkFollowee" +FOLLOW_IDENTITY_FK_FOLLOWER_TYPE: Final[str] = "identity" +FOLLOW_IDENTITY_FK_FOLLOWER_SUB_TYPE: Final[str] = "reference" +FOLLOW_IDENTITY_FK_FOLLOWER_NAME: Final[str] = "fkFollower" +FOLLOW_IDENTITY_ID_TYPE: Final[str] = "identity" +FOLLOW_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +FOLLOW_IDENTITY_ID_NAME: Final[str] = "id" + +FOLLOW_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "followeeId": FOLLOW_FOLLOWEE_ID_COLUMN, + "followerId": FOLLOW_FOLLOWER_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/follow_router.py b/server/python/tests/codegen/golden_generators/expected/follow_router.py new file mode 100644 index 0000000000..7255b62d0d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/follow_router.py @@ -0,0 +1,333 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Follow (fitness::Follow) +# Extend in your own module (e.g. Follow_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Follow entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Follow import FollowCreate, FollowPatch +from .follow_filter_allowlist import FOLLOW_FILTER_FIELDS, FOLLOW_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/follows", tags=["follows"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "followerId", + "followeeId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "followerId", + "followeeId", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "followerId", + "followeeId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class FollowRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_follows_by_follower(self, follower_id: Any) -> _list[Any]: ... + def find_follows_by_follower_in( + self, follower_id_values: _list[Any] + ) -> _list[Any]: ... + def find_follows_by_followee(self, followee_id: Any) -> _list[Any]: ... + def find_follows_by_followee_in( + self, followee_id_values: _list[Any] + ) -> _list[Any]: ... + + +def get_repository() -> FollowRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_follows( + request: Request, + repo: Annotated[FollowRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, FOLLOW_FILTER_FIELDS, FOLLOW_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{follow_id}") +def get_follow( + follow_id: int, + repo: Annotated[FollowRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(follow_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_follow( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[FollowRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = FollowCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{follow_id}") +@router.put("/{follow_id}") +def update_follow( + follow_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[FollowRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = FollowPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(follow_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{follow_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_follow( + follow_id: int, + repo: Annotated[FollowRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(follow_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/friendship_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/friendship_filter_allowlist.py new file mode 100644 index 0000000000..ddbf950913 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/friendship_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Friendship (fitness::Friendship) +# Extend in your own module (e.g. Friendship_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Friendship. + +FRIENDSHIP_FILTER_FIELDS lists the filterable field names; FRIENDSHIP_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +FRIENDSHIP_FILTER_FIELDS: frozenset[str] = frozenset() + +FRIENDSHIP_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/friendship_names.py b/server/python/tests/codegen/golden_generators/expected/friendship_names.py new file mode 100644 index 0000000000..1740c0405d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/friendship_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Friendship (fitness::Friendship) +# Extend in your own module (e.g. Friendship_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Friendship (#248).""" + +from __future__ import annotations + +from typing import Final + +FRIENDSHIP_TYPE: Final[str] = "object" +FRIENDSHIP_SUB_TYPE: Final[str] = "entity" +FRIENDSHIP_NAME: Final[str] = "Friendship" + +FRIENDSHIP_SOURCE_PRIMARY_TYPE: Final[str] = "source" +FRIENDSHIP_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +FRIENDSHIP_SOURCE_PRIMARY_KIND: Final[str] = "table" +FRIENDSHIP_SOURCE_PRIMARY_TABLE: Final[str] = "friendships" + +FRIENDSHIP_PERSON_A_ID_FIELD: Final[str] = "personAId" +FRIENDSHIP_PERSON_A_ID_COLUMN: Final[str] = "person_a_id" +FRIENDSHIP_PERSON_B_ID_FIELD: Final[str] = "personBId" +FRIENDSHIP_PERSON_B_ID_COLUMN: Final[str] = "person_b_id" + +FRIENDSHIP_IDENTITY_FK_PERSON_A_TYPE: Final[str] = "identity" +FRIENDSHIP_IDENTITY_FK_PERSON_A_SUB_TYPE: Final[str] = "reference" +FRIENDSHIP_IDENTITY_FK_PERSON_A_NAME: Final[str] = "fkPersonA" +FRIENDSHIP_IDENTITY_FK_PERSON_B_TYPE: Final[str] = "identity" +FRIENDSHIP_IDENTITY_FK_PERSON_B_SUB_TYPE: Final[str] = "reference" +FRIENDSHIP_IDENTITY_FK_PERSON_B_NAME: Final[str] = "fkPersonB" +FRIENDSHIP_IDENTITY_ID_TYPE: Final[str] = "identity" +FRIENDSHIP_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +FRIENDSHIP_IDENTITY_ID_NAME: Final[str] = "id" + +FRIENDSHIP_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "personAId": FRIENDSHIP_PERSON_A_ID_COLUMN, + "personBId": FRIENDSHIP_PERSON_B_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/friendship_router.py b/server/python/tests/codegen/golden_generators/expected/friendship_router.py new file mode 100644 index 0000000000..277f896e85 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/friendship_router.py @@ -0,0 +1,336 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Friendship (fitness::Friendship) +# Extend in your own module (e.g. Friendship_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Friendship entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Friendship import FriendshipCreate, FriendshipPatch +from .friendship_filter_allowlist import ( + FRIENDSHIP_FILTER_FIELDS, + FRIENDSHIP_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/friendships", tags=["friendships"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "personAId", + "personBId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "personAId", + "personBId", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "personAId", + "personBId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class FriendshipRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_friendships_by_person_a(self, person_a_id: Any) -> _list[Any]: ... + def find_friendships_by_person_a_in( + self, person_a_id_values: _list[Any] + ) -> _list[Any]: ... + def find_friendships_by_person_b(self, person_b_id: Any) -> _list[Any]: ... + def find_friendships_by_person_b_in( + self, person_b_id_values: _list[Any] + ) -> _list[Any]: ... + + +def get_repository() -> FriendshipRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_friendships( + request: Request, + repo: Annotated[FriendshipRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, FRIENDSHIP_FILTER_FIELDS, FRIENDSHIP_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{friendship_id}") +def get_friendship( + friendship_id: int, + repo: Annotated[FriendshipRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(friendship_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_friendship( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[FriendshipRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = FriendshipCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{friendship_id}") +@router.put("/{friendship_id}") +def update_friendship( + friendship_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[FriendshipRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = FriendshipPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(friendship_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{friendship_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_friendship( + friendship_id: int, + repo: Annotated[FriendshipRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(friendship_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_event_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/gadget_event_filter_allowlist.py new file mode 100644 index 0000000000..4bc6ebd766 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_event_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEvent (fitness::GadgetEvent) +# Extend in your own module (e.g. GadgetEvent_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for GadgetEvent. + +GADGETEVENT_FILTER_FIELDS lists the filterable field names; GADGETEVENT_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +GADGETEVENT_FILTER_FIELDS: frozenset[str] = frozenset() + +GADGETEVENT_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_event_names.py b/server/python/tests/codegen/golden_generators/expected/gadget_event_names.py new file mode 100644 index 0000000000..e73f62aa9f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_event_names.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEvent (fitness::GadgetEvent) +# Extend in your own module (e.g. GadgetEvent_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for GadgetEvent (#248).""" + +from __future__ import annotations + +from typing import Final + +GADGETEVENT_TYPE: Final[str] = "object" +GADGETEVENT_SUB_TYPE: Final[str] = "entity" +GADGETEVENT_NAME: Final[str] = "GadgetEvent" + +GADGETEVENT_SOURCE_PRIMARY_TYPE: Final[str] = "source" +GADGETEVENT_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +GADGETEVENT_SOURCE_PRIMARY_KIND: Final[str] = "table" +GADGETEVENT_SOURCE_PRIMARY_TABLE: Final[str] = "gadget_events" + +GADGETEVENT_GADGET_ID_FIELD: Final[str] = "gadgetId" +GADGETEVENT_GADGET_ID_COLUMN: Final[str] = "gadget_id" +GADGETEVENT_ID_FIELD: Final[str] = "id" +GADGETEVENT_ID_COLUMN: Final[str] = "id" + +GADGETEVENT_IDENTITY_FK_GADGET_TYPE: Final[str] = "identity" +GADGETEVENT_IDENTITY_FK_GADGET_SUB_TYPE: Final[str] = "reference" +GADGETEVENT_IDENTITY_FK_GADGET_NAME: Final[str] = "fkGadget" +GADGETEVENT_IDENTITY_ID_TYPE: Final[str] = "identity" +GADGETEVENT_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +GADGETEVENT_IDENTITY_ID_NAME: Final[str] = "id" + +GADGETEVENT_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "gadgetId": GADGETEVENT_GADGET_ID_COLUMN, + "id": GADGETEVENT_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_event_router.py b/server/python/tests/codegen/golden_generators/expected/gadget_event_router.py new file mode 100644 index 0000000000..7445805d07 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_event_router.py @@ -0,0 +1,331 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEvent (fitness::GadgetEvent) +# Extend in your own module (e.g. GadgetEvent_extra.py) — nothing imports it for you. +"""GENERATED — REST router for GadgetEvent entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .gadget_event_filter_allowlist import ( + GADGETEVENT_FILTER_FIELDS, + GADGETEVENT_FILTER_OPS_BY_FIELD, +) +from .GadgetEvent import GadgetEventCreate, GadgetEventPatch + +router = APIRouter(prefix="/api/gadget_events", tags=["gadget_events"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "gadgetId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "gadgetId", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "gadgetId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class GadgetEventRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_gadget_events_by_gadget(self, gadget_id: Any) -> _list[Any]: ... + def find_gadget_events_by_gadget_in( + self, gadget_id_values: _list[Any] + ) -> _list[Any]: ... + + +def get_repository() -> GadgetEventRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_gadget_events( + request: Request, + repo: Annotated[GadgetEventRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, GADGETEVENT_FILTER_FIELDS, GADGETEVENT_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{gadget_event_id}") +def get_gadget_event( + gadget_event_id: int, + repo: Annotated[GadgetEventRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(gadget_event_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_gadget_event( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[GadgetEventRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = GadgetEventCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{gadget_event_id}") +@router.put("/{gadget_event_id}") +def update_gadget_event( + gadget_event_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[GadgetEventRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = GadgetEventPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(gadget_event_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{gadget_event_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_gadget_event( + gadget_event_id: int, + repo: Annotated[GadgetEventRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(gadget_event_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_filter_allowlist.py new file mode 100644 index 0000000000..5a695ff412 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_filter_allowlist.py @@ -0,0 +1,19 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEventsByLabel (fitness::GadgetEventsByLabel) +# Extend in your own module (e.g. GadgetEventsByLabel_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for GadgetEventsByLabel. + +GADGETEVENTSBYLABEL_FILTER_FIELDS lists the filterable field names; GADGETEVENTSBYLABEL_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +GADGETEVENTSBYLABEL_FILTER_FIELDS: frozenset[str] = frozenset( + {"gadgetLabel", "gadgetEvents"}, +) + +GADGETEVENTSBYLABEL_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "gadgetLabel": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "gadgetEvents": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_names.py b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_names.py new file mode 100644 index 0000000000..36517ff9ec --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_names.py @@ -0,0 +1,27 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEventsByLabel (fitness::GadgetEventsByLabel) +# Extend in your own module (e.g. GadgetEventsByLabel_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for GadgetEventsByLabel (#248).""" + +from __future__ import annotations + +from typing import Final + +GADGETEVENTSBYLABEL_TYPE: Final[str] = "object" +GADGETEVENTSBYLABEL_SUB_TYPE: Final[str] = "report" +GADGETEVENTSBYLABEL_NAME: Final[str] = "GadgetEventsByLabel" + +GADGETEVENTSBYLABEL_SOURCE_PRIMARY_TYPE: Final[str] = "source" +GADGETEVENTSBYLABEL_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +GADGETEVENTSBYLABEL_SOURCE_PRIMARY_KIND: Final[str] = "view" +GADGETEVENTSBYLABEL_SOURCE_PRIMARY_VIEW: Final[str] = "v_gadget_events_by_label" + +GADGETEVENTSBYLABEL_GADGET_EVENTS_FIELD: Final[str] = "gadgetEvents" +GADGETEVENTSBYLABEL_GADGET_EVENTS_COLUMN: Final[str] = "gadget_events" +GADGETEVENTSBYLABEL_GADGET_LABEL_FIELD: Final[str] = "gadgetLabel" +GADGETEVENTSBYLABEL_GADGET_LABEL_COLUMN: Final[str] = "gadget_label" + +GADGETEVENTSBYLABEL_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "gadgetEvents": GADGETEVENTSBYLABEL_GADGET_EVENTS_COLUMN, + "gadgetLabel": GADGETEVENTSBYLABEL_GADGET_LABEL_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_router.py b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_router.py new file mode 100644 index 0000000000..0ae3931065 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_events_by_label_router.py @@ -0,0 +1,189 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: GadgetEventsByLabel (fitness::GadgetEventsByLabel) +# Extend in your own module (e.g. GadgetEventsByLabel_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the GadgetEventsByLabel report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .gadget_events_by_label_filter_allowlist import ( + GADGETEVENTSBYLABEL_FILTER_FIELDS, + GADGETEVENTSBYLABEL_FILTER_OPS_BY_FIELD, +) + +router = APIRouter( + prefix="/api/gadget_events_by_labels", tags=["gadget_events_by_labels"] +) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "gadgetLabel", + "gadgetEvents", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class GadgetEventsByLabelRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> GadgetEventsByLabelRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_gadget_events_by_labels( + request: Request, + repo: Annotated[GadgetEventsByLabelRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + GADGETEVENTSBYLABEL_FILTER_FIELDS, + GADGETEVENTSBYLABEL_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_gadget_events_by_label() -> Any: + """GENERATED — gadget_events_by_labels is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/gadget_filter_allowlist.py new file mode 100644 index 0000000000..960b3d1e1b --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Gadget (fitness::Gadget) +# Extend in your own module (e.g. Gadget_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Gadget. + +GADGET_FILTER_FIELDS lists the filterable field names; GADGET_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +GADGET_FILTER_FIELDS: frozenset[str] = frozenset() + +GADGET_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_names.py b/server/python/tests/codegen/golden_generators/expected/gadget_names.py new file mode 100644 index 0000000000..9ea61fe4bd --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_names.py @@ -0,0 +1,39 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Gadget (fitness::Gadget) +# Extend in your own module (e.g. Gadget_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Gadget (#248).""" + +from __future__ import annotations + +from typing import Final + +from .labeled_names import ( + LABELED_ID_COLUMN, + LABELED_ID_FIELD, + LABELED_IDENTITY_ID_NAME, + LABELED_IDENTITY_ID_SUB_TYPE, + LABELED_IDENTITY_ID_TYPE, +) + +GADGET_TYPE: Final[str] = "object" +GADGET_SUB_TYPE: Final[str] = "entity" +GADGET_NAME: Final[str] = "Gadget" + +GADGET_SOURCE_PRIMARY_TYPE: Final[str] = "source" +GADGET_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +GADGET_SOURCE_PRIMARY_KIND: Final[str] = "table" +GADGET_SOURCE_PRIMARY_TABLE: Final[str] = "gadgets" + +GADGET_ID_FIELD: Final[str] = LABELED_ID_FIELD +GADGET_ID_COLUMN: Final[str] = LABELED_ID_COLUMN +GADGET_LABEL_FIELD: Final[str] = "label" +GADGET_LABEL_COLUMN: Final[str] = "gadget_code" + +GADGET_IDENTITY_ID_TYPE: Final[str] = LABELED_IDENTITY_ID_TYPE +GADGET_IDENTITY_ID_SUB_TYPE: Final[str] = LABELED_IDENTITY_ID_SUB_TYPE +GADGET_IDENTITY_ID_NAME: Final[str] = LABELED_IDENTITY_ID_NAME + +GADGET_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": GADGET_ID_COLUMN, + "label": GADGET_LABEL_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/gadget_router.py b/server/python/tests/codegen/golden_generators/expected/gadget_router.py new file mode 100644 index 0000000000..94c3a65a85 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/gadget_router.py @@ -0,0 +1,324 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Gadget (fitness::Gadget) +# Extend in your own module (e.g. Gadget_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Gadget entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Gadget import GadgetCreate, GadgetPatch +from .gadget_filter_allowlist import GADGET_FILTER_FIELDS, GADGET_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/gadgets", tags=["gadgets"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "label", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "label", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "label", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class GadgetRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> GadgetRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_gadgets( + request: Request, + repo: Annotated[GadgetRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, GADGET_FILTER_FIELDS, GADGET_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{gadget_id}") +def get_gadget( + gadget_id: int, + repo: Annotated[GadgetRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(gadget_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_gadget( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[GadgetRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = GadgetCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{gadget_id}") +@router.put("/{gadget_id}") +def update_gadget( + gadget_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[GadgetRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = GadgetPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(gadget_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{gadget_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_gadget( + gadget_id: int, + repo: Annotated[GadgetRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(gadget_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/int_enum_array_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/int_enum_array_filter_allowlist.py new file mode 100644 index 0000000000..4f42ed69ed --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/int_enum_array_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: IntEnumArray (fitness::IntEnumArray) +# Extend in your own module (e.g. IntEnumArray_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for IntEnumArray. + +INTENUMARRAY_FILTER_FIELDS lists the filterable field names; INTENUMARRAY_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +INTENUMARRAY_FILTER_FIELDS: frozenset[str] = frozenset() + +INTENUMARRAY_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/int_enum_array_names.py b/server/python/tests/codegen/golden_generators/expected/int_enum_array_names.py new file mode 100644 index 0000000000..4daad96baa --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/int_enum_array_names.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: IntEnumArray (fitness::IntEnumArray) +# Extend in your own module (e.g. IntEnumArray_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for IntEnumArray (#248).""" + +from __future__ import annotations + +from typing import Final + +INTENUMARRAY_TYPE: Final[str] = "object" +INTENUMARRAY_SUB_TYPE: Final[str] = "entity" +INTENUMARRAY_NAME: Final[str] = "IntEnumArray" + +INTENUMARRAY_SOURCE_PRIMARY_TYPE: Final[str] = "source" +INTENUMARRAY_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +INTENUMARRAY_SOURCE_PRIMARY_KIND: Final[str] = "table" +INTENUMARRAY_SOURCE_PRIMARY_TABLE: Final[str] = "int_enum_arrays" + +INTENUMARRAY_HISTORY_FIELD: Final[str] = "history" +INTENUMARRAY_HISTORY_COLUMN: Final[str] = "history" +INTENUMARRAY_ID_FIELD: Final[str] = "id" +INTENUMARRAY_ID_COLUMN: Final[str] = "id" +INTENUMARRAY_STATE_FIELD: Final[str] = "state" +INTENUMARRAY_STATE_COLUMN: Final[str] = "state" + +INTENUMARRAY_IDENTITY_ID_TYPE: Final[str] = "identity" +INTENUMARRAY_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +INTENUMARRAY_IDENTITY_ID_NAME: Final[str] = "id" + +INTENUMARRAY_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "history": INTENUMARRAY_HISTORY_COLUMN, + "id": INTENUMARRAY_ID_COLUMN, + "state": INTENUMARRAY_STATE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/int_enum_array_router.py b/server/python/tests/codegen/golden_generators/expected/int_enum_array_router.py new file mode 100644 index 0000000000..67d40be88c --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/int_enum_array_router.py @@ -0,0 +1,327 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: IntEnumArray (fitness::IntEnumArray) +# Extend in your own module (e.g. IntEnumArray_extra.py) — nothing imports it for you. +"""GENERATED — REST router for IntEnumArray entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .int_enum_array_filter_allowlist import ( + INTENUMARRAY_FILTER_FIELDS, + INTENUMARRAY_FILTER_OPS_BY_FIELD, +) +from .IntEnumArray import IntEnumArrayCreate, IntEnumArrayPatch + +router = APIRouter(prefix="/api/int_enum_arrays", tags=["int_enum_arrays"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "state", + "history", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset() + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "state", + "history", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class IntEnumArrayRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> IntEnumArrayRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_int_enum_arrays( + request: Request, + repo: Annotated[IntEnumArrayRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + INTENUMARRAY_FILTER_FIELDS, + INTENUMARRAY_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{int_enum_array_id}") +def get_int_enum_array( + int_enum_array_id: int, + repo: Annotated[IntEnumArrayRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(int_enum_array_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_int_enum_array( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[IntEnumArrayRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = IntEnumArrayCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{int_enum_array_id}") +@router.put("/{int_enum_array_id}") +def update_int_enum_array( + int_enum_array_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[IntEnumArrayRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = IntEnumArrayPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(int_enum_array_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{int_enum_array_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_int_enum_array( + int_enum_array_id: int, + repo: Annotated[IntEnumArrayRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(int_enum_array_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/labeled_names.py b/server/python/tests/codegen/golden_generators/expected/labeled_names.py new file mode 100644 index 0000000000..3e1eb87bfd --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/labeled_names.py @@ -0,0 +1,26 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Labeled (fitness::Labeled) +# Extend in your own module (e.g. Labeled_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Labeled (#248).""" + +from __future__ import annotations + +from typing import Final + +LABELED_TYPE: Final[str] = "object" +LABELED_SUB_TYPE: Final[str] = "entity" +LABELED_NAME: Final[str] = "Labeled" + +LABELED_ID_FIELD: Final[str] = "id" +LABELED_ID_COLUMN: Final[str] = "id" +LABELED_LABEL_FIELD: Final[str] = "label" +LABELED_LABEL_COLUMN: Final[str] = "label_text" + +LABELED_IDENTITY_ID_TYPE: Final[str] = "identity" +LABELED_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +LABELED_IDENTITY_ID_NAME: Final[str] = "id" + +LABELED_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": LABELED_ID_COLUMN, + "label": LABELED_LABEL_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/ledger_entry_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/ledger_entry_filter_allowlist.py new file mode 100644 index 0000000000..9aec5c8f9d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/ledger_entry_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LedgerEntry (fitness::LedgerEntry) +# Extend in your own module (e.g. LedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for LedgerEntry. + +LEDGERENTRY_FILTER_FIELDS lists the filterable field names; LEDGERENTRY_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +LEDGERENTRY_FILTER_FIELDS: frozenset[str] = frozenset() + +LEDGERENTRY_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/ledger_entry_names.py b/server/python/tests/codegen/golden_generators/expected/ledger_entry_names.py new file mode 100644 index 0000000000..6268c4828d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/ledger_entry_names.py @@ -0,0 +1,31 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LedgerEntry (fitness::LedgerEntry) +# Extend in your own module (e.g. LedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for LedgerEntry (#248).""" + +from __future__ import annotations + +from typing import Final + +LEDGERENTRY_TYPE: Final[str] = "object" +LEDGERENTRY_SUB_TYPE: Final[str] = "entity" +LEDGERENTRY_NAME: Final[str] = "LedgerEntry" + +LEDGERENTRY_SOURCE_PRIMARY_TYPE: Final[str] = "source" +LEDGERENTRY_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +LEDGERENTRY_SOURCE_PRIMARY_KIND: Final[str] = "table" +LEDGERENTRY_SOURCE_PRIMARY_TABLE: Final[str] = "ledger_entries" + +LEDGERENTRY_ID_FIELD: Final[str] = "id" +LEDGERENTRY_ID_COLUMN: Final[str] = "id" +LEDGERENTRY_MEMO_FIELD: Final[str] = "memo" +LEDGERENTRY_MEMO_COLUMN: Final[str] = "memo" + +LEDGERENTRY_IDENTITY_ID_TYPE: Final[str] = "identity" +LEDGERENTRY_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +LEDGERENTRY_IDENTITY_ID_NAME: Final[str] = "id" + +LEDGERENTRY_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": LEDGERENTRY_ID_COLUMN, + "memo": LEDGERENTRY_MEMO_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/ledger_entry_router.py b/server/python/tests/codegen/golden_generators/expected/ledger_entry_router.py new file mode 100644 index 0000000000..846b3b577f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/ledger_entry_router.py @@ -0,0 +1,323 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LedgerEntry (fitness::LedgerEntry) +# Extend in your own module (e.g. LedgerEntry_extra.py) — nothing imports it for you. +"""GENERATED — REST router for LedgerEntry entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .ledger_entry_filter_allowlist import ( + LEDGERENTRY_FILTER_FIELDS, + LEDGERENTRY_FILTER_OPS_BY_FIELD, +) +from .LedgerEntry import LedgerEntryCreate, LedgerEntryPatch + +router = APIRouter(prefix="/api/ledger_entries", tags=["ledger_entries"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "memo", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset() + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "memo", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class LedgerEntryRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> LedgerEntryRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_ledger_entries( + request: Request, + repo: Annotated[LedgerEntryRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, LEDGERENTRY_FILTER_FIELDS, LEDGERENTRY_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{ledger_entry_id}") +def get_ledger_entry( + ledger_entry_id: int, + repo: Annotated[LedgerEntryRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(ledger_entry_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_ledger_entry( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[LedgerEntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = LedgerEntryCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{ledger_entry_id}") +@router.put("/{ledger_entry_id}") +def update_ledger_entry( + ledger_entry_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[LedgerEntryRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = LedgerEntryPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(ledger_entry_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{ledger_entry_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_ledger_entry( + ledger_entry_id: int, + repo: Annotated[LedgerEntryRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(ledger_entry_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/live_intro_programs_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_filter_allowlist.py new file mode 100644 index 0000000000..dd8c35f588 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_filter_allowlist.py @@ -0,0 +1,21 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LiveIntroPrograms (fitness::LiveIntroPrograms) +# Extend in your own module (e.g. LiveIntroPrograms_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for LiveIntroPrograms. + +LIVEINTROPROGRAMS_FILTER_FIELDS lists the filterable field names; LIVEINTROPROGRAMS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +LIVEINTROPROGRAMS_FILTER_FIELDS: frozenset[str] = frozenset( + {"status", "programs", "notDrafts", "listValue"}, +) + +LIVEINTROPROGRAMS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "status": frozenset({"eq", "ne", "in", "like", "isNull"}), + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "notDrafts": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "listValue": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/live_intro_programs_names.py b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_names.py new file mode 100644 index 0000000000..3b24d10e2a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_names.py @@ -0,0 +1,33 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LiveIntroPrograms (fitness::LiveIntroPrograms) +# Extend in your own module (e.g. LiveIntroPrograms_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for LiveIntroPrograms (#248).""" + +from __future__ import annotations + +from typing import Final + +LIVEINTROPROGRAMS_TYPE: Final[str] = "object" +LIVEINTROPROGRAMS_SUB_TYPE: Final[str] = "report" +LIVEINTROPROGRAMS_NAME: Final[str] = "LiveIntroPrograms" + +LIVEINTROPROGRAMS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +LIVEINTROPROGRAMS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +LIVEINTROPROGRAMS_SOURCE_PRIMARY_KIND: Final[str] = "view" +LIVEINTROPROGRAMS_SOURCE_PRIMARY_VIEW: Final[str] = "v_live_intro_programs" + +LIVEINTROPROGRAMS_LIST_VALUE_FIELD: Final[str] = "listValue" +LIVEINTROPROGRAMS_LIST_VALUE_COLUMN: Final[str] = "list_value" +LIVEINTROPROGRAMS_NOT_DRAFTS_FIELD: Final[str] = "notDrafts" +LIVEINTROPROGRAMS_NOT_DRAFTS_COLUMN: Final[str] = "not_drafts" +LIVEINTROPROGRAMS_PROGRAMS_FIELD: Final[str] = "programs" +LIVEINTROPROGRAMS_PROGRAMS_COLUMN: Final[str] = "programs" +LIVEINTROPROGRAMS_STATUS_FIELD: Final[str] = "status" +LIVEINTROPROGRAMS_STATUS_COLUMN: Final[str] = "status" + +LIVEINTROPROGRAMS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "listValue": LIVEINTROPROGRAMS_LIST_VALUE_COLUMN, + "notDrafts": LIVEINTROPROGRAMS_NOT_DRAFTS_COLUMN, + "programs": LIVEINTROPROGRAMS_PROGRAMS_COLUMN, + "status": LIVEINTROPROGRAMS_STATUS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/live_intro_programs_router.py b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_router.py new file mode 100644 index 0000000000..16a6e16c34 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/live_intro_programs_router.py @@ -0,0 +1,189 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: LiveIntroPrograms (fitness::LiveIntroPrograms) +# Extend in your own module (e.g. LiveIntroPrograms_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the LiveIntroPrograms report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .live_intro_programs_filter_allowlist import ( + LIVEINTROPROGRAMS_FILTER_FIELDS, + LIVEINTROPROGRAMS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/live_intro_programs", tags=["live_intro_programs"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "status", + "programs", + "notDrafts", + "listValue", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class LiveIntroProgramsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> LiveIntroProgramsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_live_intro_programs( + request: Request, + repo: Annotated[LiveIntroProgramsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + LIVEINTROPROGRAMS_FILTER_FIELDS, + LIVEINTROPROGRAMS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_live_intro_programs() -> Any: + """GENERATED — live_intro_programs is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/measurement_filter_allowlist.py new file mode 100644 index 0000000000..d512f21474 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Measurement (fitness::Measurement) +# Extend in your own module (e.g. Measurement_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Measurement. + +MEASUREMENT_FILTER_FIELDS lists the filterable field names; MEASUREMENT_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +MEASUREMENT_FILTER_FIELDS: frozenset[str] = frozenset() + +MEASUREMENT_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_names.py b/server/python/tests/codegen/golden_generators/expected/measurement_names.py new file mode 100644 index 0000000000..2784899c8a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Measurement (fitness::Measurement) +# Extend in your own module (e.g. Measurement_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Measurement (#248).""" + +from __future__ import annotations + +from typing import Final + +MEASUREMENT_TYPE: Final[str] = "object" +MEASUREMENT_SUB_TYPE: Final[str] = "entity" +MEASUREMENT_NAME: Final[str] = "Measurement" + +MEASUREMENT_SOURCE_PRIMARY_TYPE: Final[str] = "source" +MEASUREMENT_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +MEASUREMENT_SOURCE_PRIMARY_KIND: Final[str] = "table" +MEASUREMENT_SOURCE_PRIMARY_TABLE: Final[str] = "measurements" + +MEASUREMENT_ID_FIELD: Final[str] = "id" +MEASUREMENT_ID_COLUMN: Final[str] = "id" +MEASUREMENT_MASS_KG_FIELD: Final[str] = "massKg" +MEASUREMENT_MASS_KG_COLUMN: Final[str] = "mass_kg" +MEASUREMENT_PRECISE_KG_FIELD: Final[str] = "preciseKg" +MEASUREMENT_PRECISE_KG_COLUMN: Final[str] = "precise_kg" +MEASUREMENT_TEMP_C_FIELD: Final[str] = "tempC" +MEASUREMENT_TEMP_C_COLUMN: Final[str] = "temp_c" + +MEASUREMENT_IDENTITY_ID_TYPE: Final[str] = "identity" +MEASUREMENT_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +MEASUREMENT_IDENTITY_ID_NAME: Final[str] = "id" + +MEASUREMENT_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": MEASUREMENT_ID_COLUMN, + "massKg": MEASUREMENT_MASS_KG_COLUMN, + "preciseKg": MEASUREMENT_PRECISE_KG_COLUMN, + "tempC": MEASUREMENT_TEMP_C_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_router.py b/server/python/tests/codegen/golden_generators/expected/measurement_router.py new file mode 100644 index 0000000000..740f15cb84 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_router.py @@ -0,0 +1,337 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Measurement (fitness::Measurement) +# Extend in your own module (e.g. Measurement_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Measurement entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Measurement import MeasurementCreate, MeasurementPatch +from .measurement_filter_allowlist import ( + MEASUREMENT_FILTER_FIELDS, + MEASUREMENT_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/measurements", tags=["measurements"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "tempC", + "massKg", + "preciseKg", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "tempC", + "massKg", + "preciseKg", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "preciseKg", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {"preciseKg": (9, 4)} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "tempC", + "massKg", + "preciseKg", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class MeasurementRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> MeasurementRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_measurements( + request: Request, + repo: Annotated[MeasurementRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, MEASUREMENT_FILTER_FIELDS, MEASUREMENT_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{measurement_id}") +def get_measurement( + measurement_id: int, + repo: Annotated[MeasurementRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(measurement_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_measurement( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[MeasurementRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = MeasurementCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{measurement_id}") +@router.put("/{measurement_id}") +def update_measurement( + measurement_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[MeasurementRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = MeasurementPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(measurement_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{measurement_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_measurement( + measurement_id: int, + repo: Annotated[MeasurementRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(measurement_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_filter_allowlist.py new file mode 100644 index 0000000000..df579f286c --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_filter_allowlist.py @@ -0,0 +1,24 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStatsFilled (fitness::MeasurementStatsFilled) +# Extend in your own module (e.g. MeasurementStatsFilled_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for MeasurementStatsFilled. + +MEASUREMENTSTATSFILLED_FILTER_FIELDS lists the filterable field names; MEASUREMENTSTATSFILLED_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +MEASUREMENTSTATSFILLED_FILTER_FIELDS: frozenset[str] = frozenset( + {"readings", "avgPreciseKgOrMinusOne", "maxPreciseKgOrZero"}, +) + +MEASUREMENTSTATSFILLED_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "readings": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgPreciseKgOrMinusOne": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), + "maxPreciseKgOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_names.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_names.py new file mode 100644 index 0000000000..cc4e24d088 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_names.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStatsFilled (fitness::MeasurementStatsFilled) +# Extend in your own module (e.g. MeasurementStatsFilled_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for MeasurementStatsFilled (#248).""" + +from __future__ import annotations + +from typing import Final + +MEASUREMENTSTATSFILLED_TYPE: Final[str] = "object" +MEASUREMENTSTATSFILLED_SUB_TYPE: Final[str] = "report" +MEASUREMENTSTATSFILLED_NAME: Final[str] = "MeasurementStatsFilled" + +MEASUREMENTSTATSFILLED_SOURCE_PRIMARY_TYPE: Final[str] = "source" +MEASUREMENTSTATSFILLED_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +MEASUREMENTSTATSFILLED_SOURCE_PRIMARY_KIND: Final[str] = "view" +MEASUREMENTSTATSFILLED_SOURCE_PRIMARY_VIEW: Final[str] = "v_measurement_stats_filled" + +MEASUREMENTSTATSFILLED_AVG_PRECISE_KG_OR_MINUS_ONE_FIELD: Final[str] = ( + "avgPreciseKgOrMinusOne" +) +MEASUREMENTSTATSFILLED_AVG_PRECISE_KG_OR_MINUS_ONE_COLUMN: Final[str] = ( + "avg_precise_kg_or_minus_one" +) +MEASUREMENTSTATSFILLED_MAX_PRECISE_KG_OR_ZERO_FIELD: Final[str] = "maxPreciseKgOrZero" +MEASUREMENTSTATSFILLED_MAX_PRECISE_KG_OR_ZERO_COLUMN: Final[str] = ( + "max_precise_kg_or_zero" +) +MEASUREMENTSTATSFILLED_READINGS_FIELD: Final[str] = "readings" +MEASUREMENTSTATSFILLED_READINGS_COLUMN: Final[str] = "readings" + +MEASUREMENTSTATSFILLED_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgPreciseKgOrMinusOne": MEASUREMENTSTATSFILLED_AVG_PRECISE_KG_OR_MINUS_ONE_COLUMN, + "maxPreciseKgOrZero": MEASUREMENTSTATSFILLED_MAX_PRECISE_KG_OR_ZERO_COLUMN, + "readings": MEASUREMENTSTATSFILLED_READINGS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_router.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_router.py new file mode 100644 index 0000000000..dcb7f8ab7f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filled_router.py @@ -0,0 +1,195 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStatsFilled (fitness::MeasurementStatsFilled) +# Extend in your own module (e.g. MeasurementStatsFilled_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the MeasurementStatsFilled report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .measurement_stats_filled_filter_allowlist import ( + MEASUREMENTSTATSFILLED_FILTER_FIELDS, + MEASUREMENTSTATSFILLED_FILTER_OPS_BY_FIELD, +) + +router = APIRouter( + prefix="/api/measurement_stats_filleds", tags=["measurement_stats_filleds"] +) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "readings", + "avgPreciseKgOrMinusOne", + "maxPreciseKgOrZero", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "avgPreciseKgOrMinusOne", + "maxPreciseKgOrZero", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class MeasurementStatsFilledRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> MeasurementStatsFilledRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_measurement_stats_filleds( + request: Request, + repo: Annotated[MeasurementStatsFilledRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + MEASUREMENTSTATSFILLED_FILTER_FIELDS, + MEASUREMENTSTATSFILLED_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_measurement_stats_filled() -> Any: + """GENERATED — measurement_stats_filleds is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filter_allowlist.py new file mode 100644 index 0000000000..f2347ee91f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_filter_allowlist.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStats (fitness::MeasurementStats) +# Extend in your own module (e.g. MeasurementStats_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for MeasurementStats. + +MEASUREMENTSTATS_FILTER_FIELDS lists the filterable field names; MEASUREMENTSTATS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +MEASUREMENTSTATS_FILTER_FIELDS: frozenset[str] = frozenset( + { + "readings", + "totalMassKg", + "avgMassKg", + "maxTempC", + "minTempC", + "totalPreciseKg", + "avgPreciseKg", + "maxPreciseKg", + "heavyReadings", + }, +) + +MEASUREMENTSTATS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "readings": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMassKg": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgMassKg": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "maxTempC": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "minTempC": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalPreciseKg": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgPreciseKg": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "maxPreciseKg": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "heavyReadings": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_names.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_names.py new file mode 100644 index 0000000000..212a23f90d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_names.py @@ -0,0 +1,48 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStats (fitness::MeasurementStats) +# Extend in your own module (e.g. MeasurementStats_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for MeasurementStats (#248).""" + +from __future__ import annotations + +from typing import Final + +MEASUREMENTSTATS_TYPE: Final[str] = "object" +MEASUREMENTSTATS_SUB_TYPE: Final[str] = "report" +MEASUREMENTSTATS_NAME: Final[str] = "MeasurementStats" + +MEASUREMENTSTATS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +MEASUREMENTSTATS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +MEASUREMENTSTATS_SOURCE_PRIMARY_KIND: Final[str] = "view" +MEASUREMENTSTATS_SOURCE_PRIMARY_VIEW: Final[str] = "v_measurement_stats" + +MEASUREMENTSTATS_AVG_MASS_KG_FIELD: Final[str] = "avgMassKg" +MEASUREMENTSTATS_AVG_MASS_KG_COLUMN: Final[str] = "avg_mass_kg" +MEASUREMENTSTATS_AVG_PRECISE_KG_FIELD: Final[str] = "avgPreciseKg" +MEASUREMENTSTATS_AVG_PRECISE_KG_COLUMN: Final[str] = "avg_precise_kg" +MEASUREMENTSTATS_HEAVY_READINGS_FIELD: Final[str] = "heavyReadings" +MEASUREMENTSTATS_HEAVY_READINGS_COLUMN: Final[str] = "heavy_readings" +MEASUREMENTSTATS_MAX_PRECISE_KG_FIELD: Final[str] = "maxPreciseKg" +MEASUREMENTSTATS_MAX_PRECISE_KG_COLUMN: Final[str] = "max_precise_kg" +MEASUREMENTSTATS_MAX_TEMP_C_FIELD: Final[str] = "maxTempC" +MEASUREMENTSTATS_MAX_TEMP_C_COLUMN: Final[str] = "max_temp_c" +MEASUREMENTSTATS_MIN_TEMP_C_FIELD: Final[str] = "minTempC" +MEASUREMENTSTATS_MIN_TEMP_C_COLUMN: Final[str] = "min_temp_c" +MEASUREMENTSTATS_READINGS_FIELD: Final[str] = "readings" +MEASUREMENTSTATS_READINGS_COLUMN: Final[str] = "readings" +MEASUREMENTSTATS_TOTAL_MASS_KG_FIELD: Final[str] = "totalMassKg" +MEASUREMENTSTATS_TOTAL_MASS_KG_COLUMN: Final[str] = "total_mass_kg" +MEASUREMENTSTATS_TOTAL_PRECISE_KG_FIELD: Final[str] = "totalPreciseKg" +MEASUREMENTSTATS_TOTAL_PRECISE_KG_COLUMN: Final[str] = "total_precise_kg" + +MEASUREMENTSTATS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgMassKg": MEASUREMENTSTATS_AVG_MASS_KG_COLUMN, + "avgPreciseKg": MEASUREMENTSTATS_AVG_PRECISE_KG_COLUMN, + "heavyReadings": MEASUREMENTSTATS_HEAVY_READINGS_COLUMN, + "maxPreciseKg": MEASUREMENTSTATS_MAX_PRECISE_KG_COLUMN, + "maxTempC": MEASUREMENTSTATS_MAX_TEMP_C_COLUMN, + "minTempC": MEASUREMENTSTATS_MIN_TEMP_C_COLUMN, + "readings": MEASUREMENTSTATS_READINGS_COLUMN, + "totalMassKg": MEASUREMENTSTATS_TOTAL_MASS_KG_COLUMN, + "totalPreciseKg": MEASUREMENTSTATS_TOTAL_PRECISE_KG_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/measurement_stats_router.py b/server/python/tests/codegen/golden_generators/expected/measurement_stats_router.py new file mode 100644 index 0000000000..28006a3194 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/measurement_stats_router.py @@ -0,0 +1,200 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: MeasurementStats (fitness::MeasurementStats) +# Extend in your own module (e.g. MeasurementStats_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the MeasurementStats report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .measurement_stats_filter_allowlist import ( + MEASUREMENTSTATS_FILTER_FIELDS, + MEASUREMENTSTATS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/measurement_stats", tags=["measurement_stats"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "readings", + "totalMassKg", + "avgMassKg", + "maxTempC", + "minTempC", + "totalPreciseKg", + "avgPreciseKg", + "maxPreciseKg", + "heavyReadings", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "totalPreciseKg", + "avgPreciseKg", + "maxPreciseKg", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class MeasurementStatsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> MeasurementStatsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_measurement_stats( + request: Request, + repo: Annotated[MeasurementStatsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + MEASUREMENTSTATS_FILTER_FIELDS, + MEASUREMENTSTATS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_measurement_stats() -> Any: + """GENERATED — measurement_stats is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/node_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/node_filter_allowlist.py new file mode 100644 index 0000000000..7787a84fec --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/node_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Node (fitness::Node) +# Extend in your own module (e.g. Node_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Node. + +NODE_FILTER_FIELDS lists the filterable field names; NODE_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +NODE_FILTER_FIELDS: frozenset[str] = frozenset() + +NODE_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/node_names.py b/server/python/tests/codegen/golden_generators/expected/node_names.py new file mode 100644 index 0000000000..bdc124ceb9 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/node_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Node (fitness::Node) +# Extend in your own module (e.g. Node_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Node (#248).""" + +from __future__ import annotations + +from typing import Final + +NODE_TYPE: Final[str] = "object" +NODE_SUB_TYPE: Final[str] = "entity" +NODE_NAME: Final[str] = "Node" + +NODE_SOURCE_PRIMARY_TYPE: Final[str] = "source" +NODE_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +NODE_SOURCE_PRIMARY_KIND: Final[str] = "table" +NODE_SOURCE_PRIMARY_TABLE: Final[str] = "nodes" + +NODE_ID_FIELD: Final[str] = "id" +NODE_ID_COLUMN: Final[str] = "id" +NODE_LABEL_FIELD: Final[str] = "label" +NODE_LABEL_COLUMN: Final[str] = "label" +NODE_PARENT_ID_FIELD: Final[str] = "parentId" +NODE_PARENT_ID_COLUMN: Final[str] = "parent_id" + +NODE_IDENTITY_FK_PARENT_TYPE: Final[str] = "identity" +NODE_IDENTITY_FK_PARENT_SUB_TYPE: Final[str] = "reference" +NODE_IDENTITY_FK_PARENT_NAME: Final[str] = "fkParent" +NODE_IDENTITY_ID_TYPE: Final[str] = "identity" +NODE_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +NODE_IDENTITY_ID_NAME: Final[str] = "id" + +NODE_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": NODE_ID_COLUMN, + "label": NODE_LABEL_COLUMN, + "parentId": NODE_PARENT_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/node_router.py b/server/python/tests/codegen/golden_generators/expected/node_router.py new file mode 100644 index 0000000000..85f79bb098 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/node_router.py @@ -0,0 +1,328 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Node (fitness::Node) +# Extend in your own module (e.g. Node_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Node entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Node import NodeCreate, NodePatch +from .node_filter_allowlist import NODE_FILTER_FIELDS, NODE_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/nodes", tags=["nodes"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "label", + "parentId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "label", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "label", + "parentId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class NodeRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_nodes_by_parent(self, parent_id: Any) -> _list[Any]: ... + def find_nodes_by_parent_in(self, parent_id_values: _list[Any]) -> _list[Any]: ... + + +def get_repository() -> NodeRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_nodes( + request: Request, + repo: Annotated[NodeRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, NODE_FILTER_FIELDS, NODE_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{node_id}") +def get_node( + node_id: int, + repo: Annotated[NodeRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(node_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_node( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[NodeRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = NodeCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{node_id}") +@router.put("/{node_id}") +def update_node( + node_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[NodeRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = NodePatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(node_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{node_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_node( + node_id: int, + repo: Annotated[NodeRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(node_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_filter_allowlist.py new file mode 100644 index 0000000000..86142daeaf --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_filter_allowlist.py @@ -0,0 +1,17 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: NodesByParent (fitness::NodesByParent) +# Extend in your own module (e.g. NodesByParent_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for NodesByParent. + +NODESBYPARENT_FILTER_FIELDS lists the filterable field names; NODESBYPARENT_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +NODESBYPARENT_FILTER_FIELDS: frozenset[str] = frozenset({"parentLabel", "nodes"}) + +NODESBYPARENT_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "parentLabel": frozenset({"eq", "ne", "in", "like", "isNull"}), + "nodes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_names.py b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_names.py new file mode 100644 index 0000000000..a1e062d402 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_names.py @@ -0,0 +1,27 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: NodesByParent (fitness::NodesByParent) +# Extend in your own module (e.g. NodesByParent_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for NodesByParent (#248).""" + +from __future__ import annotations + +from typing import Final + +NODESBYPARENT_TYPE: Final[str] = "object" +NODESBYPARENT_SUB_TYPE: Final[str] = "report" +NODESBYPARENT_NAME: Final[str] = "NodesByParent" + +NODESBYPARENT_SOURCE_PRIMARY_TYPE: Final[str] = "source" +NODESBYPARENT_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +NODESBYPARENT_SOURCE_PRIMARY_KIND: Final[str] = "view" +NODESBYPARENT_SOURCE_PRIMARY_VIEW: Final[str] = "v_nodes_by_parent" + +NODESBYPARENT_NODES_FIELD: Final[str] = "nodes" +NODESBYPARENT_NODES_COLUMN: Final[str] = "nodes" +NODESBYPARENT_PARENT_LABEL_FIELD: Final[str] = "parentLabel" +NODESBYPARENT_PARENT_LABEL_COLUMN: Final[str] = "parent_label" + +NODESBYPARENT_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "nodes": NODESBYPARENT_NODES_COLUMN, + "parentLabel": NODESBYPARENT_PARENT_LABEL_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_router.py b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_router.py new file mode 100644 index 0000000000..03fedbfbb8 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/nodes_by_parent_router.py @@ -0,0 +1,187 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: NodesByParent (fitness::NodesByParent) +# Extend in your own module (e.g. NodesByParent_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the NodesByParent report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .nodes_by_parent_filter_allowlist import ( + NODESBYPARENT_FILTER_FIELDS, + NODESBYPARENT_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/nodes_by_parents", tags=["nodes_by_parents"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "parentLabel", + "nodes", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class NodesByParentRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> NodesByParentRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_nodes_by_parents( + request: Request, + repo: Annotated[NodesByParentRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + NODESBYPARENT_FILTER_FIELDS, + NODESBYPARENT_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_nodes_by_parent() -> Any: + """GENERATED — nodes_by_parents is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/permit_auth_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/permit_auth_filter_allowlist.py new file mode 100644 index 0000000000..f4fb4abce9 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/permit_auth_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PermitAuth (fitness::PermitAuth) +# Extend in your own module (e.g. PermitAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for PermitAuth. + +PERMITAUTH_FILTER_FIELDS lists the filterable field names; PERMITAUTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PERMITAUTH_FILTER_FIELDS: frozenset[str] = frozenset() + +PERMITAUTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/permit_auth_names.py b/server/python/tests/codegen/golden_generators/expected/permit_auth_names.py new file mode 100644 index 0000000000..49e6875d6e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/permit_auth_names.py @@ -0,0 +1,53 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PermitAuth (fitness::PermitAuth) +# Extend in your own module (e.g. PermitAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for PermitAuth (#248).""" + +from __future__ import annotations + +from typing import Final + +from .auth_names import ( + AUTH_ID_COLUMN, + AUTH_ID_FIELD, + AUTH_IDENTITY_ID_NAME, + AUTH_IDENTITY_ID_SUB_TYPE, + AUTH_IDENTITY_ID_TYPE, + AUTH_REFERENCE_COLUMN, + AUTH_REFERENCE_FIELD, + AUTH_SOURCE_PRIMARY_KIND, + AUTH_SOURCE_PRIMARY_SUB_TYPE, + AUTH_SOURCE_PRIMARY_TABLE, + AUTH_SOURCE_PRIMARY_TYPE, + AUTH_TYPE_COLUMN, + AUTH_TYPE_FIELD, +) + +PERMITAUTH_TYPE: Final[str] = "object" +PERMITAUTH_SUB_TYPE: Final[str] = "entity" +PERMITAUTH_NAME: Final[str] = "PermitAuth" + +PERMITAUTH_SOURCE_PRIMARY_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_TYPE +PERMITAUTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_SUB_TYPE +PERMITAUTH_SOURCE_PRIMARY_KIND: Final[str] = AUTH_SOURCE_PRIMARY_KIND +PERMITAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE + +PERMITAUTH_APPROVER_FIELD: Final[str] = "approver" +PERMITAUTH_APPROVER_COLUMN: Final[str] = "approver" +PERMITAUTH_ID_FIELD: Final[str] = AUTH_ID_FIELD +PERMITAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +PERMITAUTH_REFERENCE_FIELD: Final[str] = AUTH_REFERENCE_FIELD +PERMITAUTH_REFERENCE_COLUMN: Final[str] = AUTH_REFERENCE_COLUMN +PERMITAUTH_TYPE_FIELD: Final[str] = AUTH_TYPE_FIELD +PERMITAUTH_TYPE_COLUMN: Final[str] = AUTH_TYPE_COLUMN + +PERMITAUTH_IDENTITY_ID_TYPE: Final[str] = AUTH_IDENTITY_ID_TYPE +PERMITAUTH_IDENTITY_ID_SUB_TYPE: Final[str] = AUTH_IDENTITY_ID_SUB_TYPE +PERMITAUTH_IDENTITY_ID_NAME: Final[str] = AUTH_IDENTITY_ID_NAME + +PERMITAUTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "approver": PERMITAUTH_APPROVER_COLUMN, + "id": PERMITAUTH_ID_COLUMN, + "reference": PERMITAUTH_REFERENCE_COLUMN, + "type": PERMITAUTH_TYPE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/person_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/person_filter_allowlist.py new file mode 100644 index 0000000000..1411bfc5db --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/person_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Person (fitness::Person) +# Extend in your own module (e.g. Person_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Person. + +PERSON_FILTER_FIELDS lists the filterable field names; PERSON_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PERSON_FILTER_FIELDS: frozenset[str] = frozenset() + +PERSON_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/person_names.py b/server/python/tests/codegen/golden_generators/expected/person_names.py new file mode 100644 index 0000000000..4d9cc38404 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/person_names.py @@ -0,0 +1,31 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Person (fitness::Person) +# Extend in your own module (e.g. Person_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Person (#248).""" + +from __future__ import annotations + +from typing import Final + +PERSON_TYPE: Final[str] = "object" +PERSON_SUB_TYPE: Final[str] = "entity" +PERSON_NAME: Final[str] = "Person" + +PERSON_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PERSON_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PERSON_SOURCE_PRIMARY_KIND: Final[str] = "table" +PERSON_SOURCE_PRIMARY_TABLE: Final[str] = "people" + +PERSON_ID_FIELD: Final[str] = "id" +PERSON_ID_COLUMN: Final[str] = "id" +PERSON_NAME_FIELD: Final[str] = "name" +PERSON_NAME_COLUMN: Final[str] = "name" + +PERSON_IDENTITY_ID_TYPE: Final[str] = "identity" +PERSON_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +PERSON_IDENTITY_ID_NAME: Final[str] = "id" + +PERSON_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": PERSON_ID_COLUMN, + "name": PERSON_NAME_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/person_router.py b/server/python/tests/codegen/golden_generators/expected/person_router.py new file mode 100644 index 0000000000..f8da703eda --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/person_router.py @@ -0,0 +1,347 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Person (fitness::Person) +# Extend in your own module (e.g. Person_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Person entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Person import PersonCreate, PersonPatch +from .person_filter_allowlist import PERSON_FILTER_FIELDS, PERSON_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/persons", tags=["persons"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "name", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "name", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +_WIRE_PERSON = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "name", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class PersonRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_related_following(self, id: int) -> _list[Any]: ... + def find_related_friends(self, id: int) -> _list[Any]: ... + + +def get_repository() -> PersonRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_persons( + request: Request, + repo: Annotated[PersonRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, PERSON_FILTER_FIELDS, PERSON_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{person_id}") +def get_person( + person_id: int, + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(person_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_person( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = PersonCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{person_id}") +@router.put("/{person_id}") +def update_person( + person_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = PersonPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(person_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{person_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_person( + person_id: int, + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(person_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/{person_id}/following") +def list_person_following( + person_id: int, + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> list[Any]: + rows: list[Any] = render_wire(repo.find_related_following(person_id), _WIRE_PERSON) + return rows + + +@router.get("/{person_id}/friends") +def list_person_friends( + person_id: int, + repo: Annotated[PersonRepository, Depends(get_repository)], +) -> list[Any]: + rows: list[Any] = render_wire(repo.find_related_friends(person_id), _WIRE_PERSON) + return rows diff --git a/server/python/tests/codegen/golden_generators/expected/post_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/post_filter_allowlist.py new file mode 100644 index 0000000000..d3ca8174a3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Post (fitness::Post) +# Extend in your own module (e.g. Post_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Post. + +POST_FILTER_FIELDS lists the filterable field names; POST_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +POST_FILTER_FIELDS: frozenset[str] = frozenset() + +POST_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/post_names.py b/server/python/tests/codegen/golden_generators/expected/post_names.py new file mode 100644 index 0000000000..d2a22f7fcd --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_names.py @@ -0,0 +1,31 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Post (fitness::Post) +# Extend in your own module (e.g. Post_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Post (#248).""" + +from __future__ import annotations + +from typing import Final + +POST_TYPE: Final[str] = "object" +POST_SUB_TYPE: Final[str] = "entity" +POST_NAME: Final[str] = "Post" + +POST_SOURCE_PRIMARY_TYPE: Final[str] = "source" +POST_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +POST_SOURCE_PRIMARY_KIND: Final[str] = "table" +POST_SOURCE_PRIMARY_TABLE: Final[str] = "posts" + +POST_ID_FIELD: Final[str] = "id" +POST_ID_COLUMN: Final[str] = "id" +POST_TITLE_FIELD: Final[str] = "title" +POST_TITLE_COLUMN: Final[str] = "title" + +POST_IDENTITY_ID_TYPE: Final[str] = "identity" +POST_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +POST_IDENTITY_ID_NAME: Final[str] = "id" + +POST_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": POST_ID_COLUMN, + "title": POST_TITLE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/post_referral_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/post_referral_filter_allowlist.py new file mode 100644 index 0000000000..4a35034c10 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_referral_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostReferral (fitness::PostReferral) +# Extend in your own module (e.g. PostReferral_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for PostReferral. + +POSTREFERRAL_FILTER_FIELDS lists the filterable field names; POSTREFERRAL_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +POSTREFERRAL_FILTER_FIELDS: frozenset[str] = frozenset() + +POSTREFERRAL_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/post_referral_names.py b/server/python/tests/codegen/golden_generators/expected/post_referral_names.py new file mode 100644 index 0000000000..c1473d3709 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_referral_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostReferral (fitness::PostReferral) +# Extend in your own module (e.g. PostReferral_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for PostReferral (#248).""" + +from __future__ import annotations + +from typing import Final + +POSTREFERRAL_TYPE: Final[str] = "object" +POSTREFERRAL_SUB_TYPE: Final[str] = "entity" +POSTREFERRAL_NAME: Final[str] = "PostReferral" + +POSTREFERRAL_SOURCE_PRIMARY_TYPE: Final[str] = "source" +POSTREFERRAL_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +POSTREFERRAL_SOURCE_PRIMARY_KIND: Final[str] = "table" +POSTREFERRAL_SOURCE_PRIMARY_TABLE: Final[str] = "post_referrals" + +POSTREFERRAL_POST_ID_FIELD: Final[str] = "postId" +POSTREFERRAL_POST_ID_COLUMN: Final[str] = "post_id" +POSTREFERRAL_REFERRAL_ID_FIELD: Final[str] = "referralId" +POSTREFERRAL_REFERRAL_ID_COLUMN: Final[str] = "referral_id" + +POSTREFERRAL_IDENTITY_FK_POST_TYPE: Final[str] = "identity" +POSTREFERRAL_IDENTITY_FK_POST_SUB_TYPE: Final[str] = "reference" +POSTREFERRAL_IDENTITY_FK_POST_NAME: Final[str] = "fkPost" +POSTREFERRAL_IDENTITY_FK_REFERRAL_TYPE: Final[str] = "identity" +POSTREFERRAL_IDENTITY_FK_REFERRAL_SUB_TYPE: Final[str] = "reference" +POSTREFERRAL_IDENTITY_FK_REFERRAL_NAME: Final[str] = "fkReferral" +POSTREFERRAL_IDENTITY_ID_TYPE: Final[str] = "identity" +POSTREFERRAL_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +POSTREFERRAL_IDENTITY_ID_NAME: Final[str] = "id" + +POSTREFERRAL_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "postId": POSTREFERRAL_POST_ID_COLUMN, + "referralId": POSTREFERRAL_REFERRAL_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/post_referral_router.py b/server/python/tests/codegen/golden_generators/expected/post_referral_router.py new file mode 100644 index 0000000000..490a8d39da --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_referral_router.py @@ -0,0 +1,338 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostReferral (fitness::PostReferral) +# Extend in your own module (e.g. PostReferral_extra.py) — nothing imports it for you. +"""GENERATED — REST router for PostReferral entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .post_referral_filter_allowlist import ( + POSTREFERRAL_FILTER_FIELDS, + POSTREFERRAL_FILTER_OPS_BY_FIELD, +) +from .PostReferral import PostReferralCreate, PostReferralPatch + +router = APIRouter(prefix="/api/post_referrals", tags=["post_referrals"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "postId", + "referralId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "postId", + "referralId", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "postId", + "referralId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class PostReferralRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_post_referrals_by_post(self, post_id: Any) -> _list[Any]: ... + def find_post_referrals_by_post_in( + self, post_id_values: _list[Any] + ) -> _list[Any]: ... + def find_post_referrals_by_referral(self, referral_id: Any) -> _list[Any]: ... + def find_post_referrals_by_referral_in( + self, referral_id_values: _list[Any] + ) -> _list[Any]: ... + + +def get_repository() -> PostReferralRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_post_referrals( + request: Request, + repo: Annotated[PostReferralRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + POSTREFERRAL_FILTER_FIELDS, + POSTREFERRAL_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{post_referral_id}") +def get_post_referral( + post_referral_id: int, + repo: Annotated[PostReferralRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(post_referral_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_post_referral( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostReferralRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = PostReferralCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{post_referral_id}") +@router.put("/{post_referral_id}") +def update_post_referral( + post_referral_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostReferralRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = PostReferralPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(post_referral_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{post_referral_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_post_referral( + post_referral_id: int, + repo: Annotated[PostReferralRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(post_referral_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/post_router.py b/server/python/tests/codegen/golden_generators/expected/post_router.py new file mode 100644 index 0000000000..c787af9b11 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_router.py @@ -0,0 +1,352 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Post (fitness::Post) +# Extend in your own module (e.g. Post_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Post entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Post import PostCreate, PostPatch +from .post_filter_allowlist import POST_FILTER_FIELDS, POST_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/posts", tags=["posts"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "title", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "title", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +_WIRE_TAG = WireOutput(decimals="string", null_members="omit") + + +_WIRE_REFERRAL_AUTH = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "title", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class PostRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_related_tags(self, id: int) -> _list[Any]: ... + def find_related_referrals(self, id: int, target_subtype: str) -> _list[Any]: ... + + +def get_repository() -> PostRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_posts( + request: Request, + repo: Annotated[PostRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, POST_FILTER_FIELDS, POST_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{post_id}") +def get_post( + post_id: int, + repo: Annotated[PostRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(post_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_post( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = PostCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{post_id}") +@router.put("/{post_id}") +def update_post( + post_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = PostPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(post_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{post_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_post( + post_id: int, + repo: Annotated[PostRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(post_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/{post_id}/tags") +def list_post_tags( + post_id: int, + repo: Annotated[PostRepository, Depends(get_repository)], +) -> list[Any]: + rows: list[Any] = render_wire(repo.find_related_tags(post_id), _WIRE_TAG) + return rows + + +@router.get("/{post_id}/referrals") +def list_post_referrals( + post_id: int, + repo: Annotated[PostRepository, Depends(get_repository)], +) -> list[Any]: + rows: list[Any] = render_wire( + repo.find_related_referrals(post_id, "Referral"), _WIRE_REFERRAL_AUTH + ) + return rows diff --git a/server/python/tests/codegen/golden_generators/expected/post_tag_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/post_tag_filter_allowlist.py new file mode 100644 index 0000000000..fc709b8168 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_tag_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostTag (fitness::PostTag) +# Extend in your own module (e.g. PostTag_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for PostTag. + +POSTTAG_FILTER_FIELDS lists the filterable field names; POSTTAG_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +POSTTAG_FILTER_FIELDS: frozenset[str] = frozenset() + +POSTTAG_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/post_tag_names.py b/server/python/tests/codegen/golden_generators/expected/post_tag_names.py new file mode 100644 index 0000000000..61e6dafaf5 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_tag_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostTag (fitness::PostTag) +# Extend in your own module (e.g. PostTag_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for PostTag (#248).""" + +from __future__ import annotations + +from typing import Final + +POSTTAG_TYPE: Final[str] = "object" +POSTTAG_SUB_TYPE: Final[str] = "entity" +POSTTAG_NAME: Final[str] = "PostTag" + +POSTTAG_SOURCE_PRIMARY_TYPE: Final[str] = "source" +POSTTAG_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +POSTTAG_SOURCE_PRIMARY_KIND: Final[str] = "table" +POSTTAG_SOURCE_PRIMARY_TABLE: Final[str] = "post_tags" + +POSTTAG_POST_ID_FIELD: Final[str] = "postId" +POSTTAG_POST_ID_COLUMN: Final[str] = "post_id" +POSTTAG_TAG_ID_FIELD: Final[str] = "tagId" +POSTTAG_TAG_ID_COLUMN: Final[str] = "tag_id" + +POSTTAG_IDENTITY_FK_POST_TYPE: Final[str] = "identity" +POSTTAG_IDENTITY_FK_POST_SUB_TYPE: Final[str] = "reference" +POSTTAG_IDENTITY_FK_POST_NAME: Final[str] = "fkPost" +POSTTAG_IDENTITY_FK_TAG_TYPE: Final[str] = "identity" +POSTTAG_IDENTITY_FK_TAG_SUB_TYPE: Final[str] = "reference" +POSTTAG_IDENTITY_FK_TAG_NAME: Final[str] = "fkTag" +POSTTAG_IDENTITY_ID_TYPE: Final[str] = "identity" +POSTTAG_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +POSTTAG_IDENTITY_ID_NAME: Final[str] = "id" + +POSTTAG_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "postId": POSTTAG_POST_ID_COLUMN, + "tagId": POSTTAG_TAG_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/post_tag_router.py b/server/python/tests/codegen/golden_generators/expected/post_tag_router.py new file mode 100644 index 0000000000..d07a6292f0 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/post_tag_router.py @@ -0,0 +1,332 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: PostTag (fitness::PostTag) +# Extend in your own module (e.g. PostTag_extra.py) — nothing imports it for you. +"""GENERATED — REST router for PostTag entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .post_tag_filter_allowlist import ( + POSTTAG_FILTER_FIELDS, + POSTTAG_FILTER_OPS_BY_FIELD, +) +from .PostTag import PostTagCreate, PostTagPatch + +router = APIRouter(prefix="/api/post_tags", tags=["post_tags"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "postId", + "tagId", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "postId", + "tagId", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "postId", + "tagId", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class PostTagRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_post_tags_by_post(self, post_id: Any) -> _list[Any]: ... + def find_post_tags_by_post_in(self, post_id_values: _list[Any]) -> _list[Any]: ... + def find_post_tags_by_tag(self, tag_id: Any) -> _list[Any]: ... + def find_post_tags_by_tag_in(self, tag_id_values: _list[Any]) -> _list[Any]: ... + + +def get_repository() -> PostTagRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_post_tags( + request: Request, + repo: Annotated[PostTagRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, POSTTAG_FILTER_FIELDS, POSTTAG_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{post_tag_id}") +def get_post_tag( + post_tag_id: int, + repo: Annotated[PostTagRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(post_tag_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_post_tag( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostTagRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = PostTagCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{post_tag_id}") +@router.put("/{post_tag_id}") +def update_post_tag( + post_tag_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[PostTagRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = PostTagPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(post_tag_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{post_tag_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_post_tag( + post_tag_id: int, + repo: Annotated[PostTagRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(post_tag_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/program_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_filter_allowlist.py new file mode 100644 index 0000000000..de9dd719fb --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Program (fitness::Program) +# Extend in your own module (e.g. Program_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Program. + +PROGRAM_FILTER_FIELDS lists the filterable field names; PROGRAM_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAM_FILTER_FIELDS: frozenset[str] = frozenset() + +PROGRAM_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/program_flag_roster_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_filter_allowlist.py new file mode 100644 index 0000000000..96e0b4cee5 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_filter_allowlist.py @@ -0,0 +1,22 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlagRoster (fitness::ProgramFlagRoster) +# Extend in your own module (e.g. ProgramFlagRoster_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramFlagRoster. + +PROGRAMFLAGROSTER_FILTER_FIELDS lists the filterable field names; PROGRAMFLAGROSTER_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMFLAGROSTER_FILTER_FIELDS: frozenset[str] = frozenset( + {"programKey", "weeks", "anyDeload", "anyDeloadOrFalse", "allDeloadOrTrue"}, +) + +PROGRAMFLAGROSTER_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "anyDeload": frozenset({"eq", "isNull"}), + "anyDeloadOrFalse": frozenset({"eq", "isNull"}), + "allDeloadOrTrue": frozenset({"eq", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_flag_roster_names.py b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_names.py new file mode 100644 index 0000000000..fbbf369bf0 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_names.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlagRoster (fitness::ProgramFlagRoster) +# Extend in your own module (e.g. ProgramFlagRoster_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramFlagRoster (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMFLAGROSTER_TYPE: Final[str] = "object" +PROGRAMFLAGROSTER_SUB_TYPE: Final[str] = "report" +PROGRAMFLAGROSTER_NAME: Final[str] = "ProgramFlagRoster" + +PROGRAMFLAGROSTER_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMFLAGROSTER_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMFLAGROSTER_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMFLAGROSTER_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_flag_roster" + +PROGRAMFLAGROSTER_ALL_DELOAD_OR_TRUE_FIELD: Final[str] = "allDeloadOrTrue" +PROGRAMFLAGROSTER_ALL_DELOAD_OR_TRUE_COLUMN: Final[str] = "all_deload_or_true" +PROGRAMFLAGROSTER_ANY_DELOAD_FIELD: Final[str] = "anyDeload" +PROGRAMFLAGROSTER_ANY_DELOAD_COLUMN: Final[str] = "any_deload" +PROGRAMFLAGROSTER_ANY_DELOAD_OR_FALSE_FIELD: Final[str] = "anyDeloadOrFalse" +PROGRAMFLAGROSTER_ANY_DELOAD_OR_FALSE_COLUMN: Final[str] = "any_deload_or_false" +PROGRAMFLAGROSTER_PROGRAM_KEY_FIELD: Final[str] = "programKey" +PROGRAMFLAGROSTER_PROGRAM_KEY_COLUMN: Final[str] = "program_key" +PROGRAMFLAGROSTER_WEEKS_FIELD: Final[str] = "weeks" +PROGRAMFLAGROSTER_WEEKS_COLUMN: Final[str] = "weeks" + +PROGRAMFLAGROSTER_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "allDeloadOrTrue": PROGRAMFLAGROSTER_ALL_DELOAD_OR_TRUE_COLUMN, + "anyDeload": PROGRAMFLAGROSTER_ANY_DELOAD_COLUMN, + "anyDeloadOrFalse": PROGRAMFLAGROSTER_ANY_DELOAD_OR_FALSE_COLUMN, + "programKey": PROGRAMFLAGROSTER_PROGRAM_KEY_COLUMN, + "weeks": PROGRAMFLAGROSTER_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_flag_roster_router.py b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_router.py new file mode 100644 index 0000000000..ada0e265c4 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flag_roster_router.py @@ -0,0 +1,190 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlagRoster (fitness::ProgramFlagRoster) +# Extend in your own module (e.g. ProgramFlagRoster_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramFlagRoster report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_flag_roster_filter_allowlist import ( + PROGRAMFLAGROSTER_FILTER_FIELDS, + PROGRAMFLAGROSTER_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_flag_rosters", tags=["program_flag_rosters"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programKey", + "weeks", + "anyDeload", + "anyDeloadOrFalse", + "allDeloadOrTrue", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramFlagRosterRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramFlagRosterRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_flag_rosters( + request: Request, + repo: Annotated[ProgramFlagRosterRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMFLAGROSTER_FILTER_FIELDS, + PROGRAMFLAGROSTER_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_flag_roster() -> Any: + """GENERATED — program_flag_rosters is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_flags_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_flags_filter_allowlist.py new file mode 100644 index 0000000000..43bc418a62 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flags_filter_allowlist.py @@ -0,0 +1,22 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlags (fitness::ProgramFlags) +# Extend in your own module (e.g. ProgramFlags_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramFlags. + +PROGRAMFLAGS_FILTER_FIELDS lists the filterable field names; PROGRAMFLAGS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMFLAGS_FILTER_FIELDS: frozenset[str] = frozenset( + {"program", "weeks", "anyDeload", "allDeload", "anyLongDeload"}, +) + +PROGRAMFLAGS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "program": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "anyDeload": frozenset({"eq", "isNull"}), + "allDeload": frozenset({"eq", "isNull"}), + "anyLongDeload": frozenset({"eq", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_flags_names.py b/server/python/tests/codegen/golden_generators/expected/program_flags_names.py new file mode 100644 index 0000000000..ba9948478d --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flags_names.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlags (fitness::ProgramFlags) +# Extend in your own module (e.g. ProgramFlags_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramFlags (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMFLAGS_TYPE: Final[str] = "object" +PROGRAMFLAGS_SUB_TYPE: Final[str] = "report" +PROGRAMFLAGS_NAME: Final[str] = "ProgramFlags" + +PROGRAMFLAGS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMFLAGS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMFLAGS_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMFLAGS_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_flags" + +PROGRAMFLAGS_ALL_DELOAD_FIELD: Final[str] = "allDeload" +PROGRAMFLAGS_ALL_DELOAD_COLUMN: Final[str] = "all_deload" +PROGRAMFLAGS_ANY_DELOAD_FIELD: Final[str] = "anyDeload" +PROGRAMFLAGS_ANY_DELOAD_COLUMN: Final[str] = "any_deload" +PROGRAMFLAGS_ANY_LONG_DELOAD_FIELD: Final[str] = "anyLongDeload" +PROGRAMFLAGS_ANY_LONG_DELOAD_COLUMN: Final[str] = "any_long_deload" +PROGRAMFLAGS_PROGRAM_FIELD: Final[str] = "program" +PROGRAMFLAGS_PROGRAM_COLUMN: Final[str] = "program" +PROGRAMFLAGS_WEEKS_FIELD: Final[str] = "weeks" +PROGRAMFLAGS_WEEKS_COLUMN: Final[str] = "weeks" + +PROGRAMFLAGS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "allDeload": PROGRAMFLAGS_ALL_DELOAD_COLUMN, + "anyDeload": PROGRAMFLAGS_ANY_DELOAD_COLUMN, + "anyLongDeload": PROGRAMFLAGS_ANY_LONG_DELOAD_COLUMN, + "program": PROGRAMFLAGS_PROGRAM_COLUMN, + "weeks": PROGRAMFLAGS_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_flags_router.py b/server/python/tests/codegen/golden_generators/expected/program_flags_router.py new file mode 100644 index 0000000000..dd5ee1c7ea --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_flags_router.py @@ -0,0 +1,190 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramFlags (fitness::ProgramFlags) +# Extend in your own module (e.g. ProgramFlags_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramFlags report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_flags_filter_allowlist import ( + PROGRAMFLAGS_FILTER_FIELDS, + PROGRAMFLAGS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_flags", tags=["program_flags"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "program", + "weeks", + "anyDeload", + "allDeload", + "anyLongDeload", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramFlagsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramFlagsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_flags( + request: Request, + repo: Annotated[ProgramFlagsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMFLAGS_FILTER_FIELDS, + PROGRAMFLAGS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_flags() -> Any: + """GENERATED — program_flags is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_long_weeks_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_filter_allowlist.py new file mode 100644 index 0000000000..d45bb20897 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_filter_allowlist.py @@ -0,0 +1,22 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramLongWeeks (fitness::ProgramLongWeeks) +# Extend in your own module (e.g. ProgramLongWeeks_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramLongWeeks. + +PROGRAMLONGWEEKS_FILTER_FIELDS lists the filterable field names; PROGRAMLONGWEEKS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMLONGWEEKS_FILTER_FIELDS: frozenset[str] = frozenset( + {"programKey", "weeks", "totalMinutesOrZero"}, +) + +PROGRAMLONGWEEKS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutesOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_long_weeks_names.py b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_names.py new file mode 100644 index 0000000000..69128bf366 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_names.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramLongWeeks (fitness::ProgramLongWeeks) +# Extend in your own module (e.g. ProgramLongWeeks_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramLongWeeks (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMLONGWEEKS_TYPE: Final[str] = "object" +PROGRAMLONGWEEKS_SUB_TYPE: Final[str] = "report" +PROGRAMLONGWEEKS_NAME: Final[str] = "ProgramLongWeeks" + +PROGRAMLONGWEEKS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMLONGWEEKS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMLONGWEEKS_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMLONGWEEKS_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_long_weeks" + +PROGRAMLONGWEEKS_PROGRAM_KEY_FIELD: Final[str] = "programKey" +PROGRAMLONGWEEKS_PROGRAM_KEY_COLUMN: Final[str] = "program_key" +PROGRAMLONGWEEKS_TOTAL_MINUTES_OR_ZERO_FIELD: Final[str] = "totalMinutesOrZero" +PROGRAMLONGWEEKS_TOTAL_MINUTES_OR_ZERO_COLUMN: Final[str] = "total_minutes_or_zero" +PROGRAMLONGWEEKS_WEEKS_FIELD: Final[str] = "weeks" +PROGRAMLONGWEEKS_WEEKS_COLUMN: Final[str] = "weeks" + +PROGRAMLONGWEEKS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "programKey": PROGRAMLONGWEEKS_PROGRAM_KEY_COLUMN, + "totalMinutesOrZero": PROGRAMLONGWEEKS_TOTAL_MINUTES_OR_ZERO_COLUMN, + "weeks": PROGRAMLONGWEEKS_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_long_weeks_router.py b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_router.py new file mode 100644 index 0000000000..bad2662203 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_long_weeks_router.py @@ -0,0 +1,188 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramLongWeeks (fitness::ProgramLongWeeks) +# Extend in your own module (e.g. ProgramLongWeeks_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramLongWeeks report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_long_weeks_filter_allowlist import ( + PROGRAMLONGWEEKS_FILTER_FIELDS, + PROGRAMLONGWEEKS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_long_weeks", tags=["program_long_weeks"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programKey", + "weeks", + "totalMinutesOrZero", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramLongWeeksRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramLongWeeksRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_long_weeks( + request: Request, + repo: Annotated[ProgramLongWeeksRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMLONGWEEKS_FILTER_FIELDS, + PROGRAMLONGWEEKS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_long_weeks() -> Any: + """GENERATED — program_long_weeks is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_minutes_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_minutes_filter_allowlist.py new file mode 100644 index 0000000000..689a00013f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_minutes_filter_allowlist.py @@ -0,0 +1,40 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramMinutes (fitness::ProgramMinutes) +# Extend in your own module (e.g. ProgramMinutes_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramMinutes. + +PROGRAMMINUTES_FILTER_FIELDS lists the filterable field names; PROGRAMMINUTES_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMMINUTES_FILTER_FIELDS: frozenset[str] = frozenset( + { + "program", + "programTitle", + "weeks", + "longWeeks", + "labels", + "slots", + "totalMinutes", + "avgMinutes", + "minMinutes", + "maxMinutes", + "longShare", + }, +) + +PROGRAMMINUTES_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "program": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "programTitle": frozenset({"eq", "ne", "in", "like", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "longWeeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "labels": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "slots": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "minMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "maxMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "longShare": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_minutes_names.py b/server/python/tests/codegen/golden_generators/expected/program_minutes_names.py new file mode 100644 index 0000000000..e2e2329662 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_minutes_names.py @@ -0,0 +1,54 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramMinutes (fitness::ProgramMinutes) +# Extend in your own module (e.g. ProgramMinutes_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramMinutes (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMMINUTES_TYPE: Final[str] = "object" +PROGRAMMINUTES_SUB_TYPE: Final[str] = "report" +PROGRAMMINUTES_NAME: Final[str] = "ProgramMinutes" + +PROGRAMMINUTES_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMMINUTES_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMMINUTES_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMMINUTES_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_minutes" + +PROGRAMMINUTES_AVG_MINUTES_FIELD: Final[str] = "avgMinutes" +PROGRAMMINUTES_AVG_MINUTES_COLUMN: Final[str] = "avg_minutes" +PROGRAMMINUTES_LABELS_FIELD: Final[str] = "labels" +PROGRAMMINUTES_LABELS_COLUMN: Final[str] = "labels" +PROGRAMMINUTES_LONG_SHARE_FIELD: Final[str] = "longShare" +PROGRAMMINUTES_LONG_SHARE_COLUMN: Final[str] = "long_share" +PROGRAMMINUTES_LONG_WEEKS_FIELD: Final[str] = "longWeeks" +PROGRAMMINUTES_LONG_WEEKS_COLUMN: Final[str] = "long_weeks" +PROGRAMMINUTES_MAX_MINUTES_FIELD: Final[str] = "maxMinutes" +PROGRAMMINUTES_MAX_MINUTES_COLUMN: Final[str] = "max_minutes" +PROGRAMMINUTES_MIN_MINUTES_FIELD: Final[str] = "minMinutes" +PROGRAMMINUTES_MIN_MINUTES_COLUMN: Final[str] = "min_minutes" +PROGRAMMINUTES_PROGRAM_FIELD: Final[str] = "program" +PROGRAMMINUTES_PROGRAM_COLUMN: Final[str] = "program" +PROGRAMMINUTES_PROGRAM_TITLE_FIELD: Final[str] = "programTitle" +PROGRAMMINUTES_PROGRAM_TITLE_COLUMN: Final[str] = "program_title" +PROGRAMMINUTES_SLOTS_FIELD: Final[str] = "slots" +PROGRAMMINUTES_SLOTS_COLUMN: Final[str] = "slots" +PROGRAMMINUTES_TOTAL_MINUTES_FIELD: Final[str] = "totalMinutes" +PROGRAMMINUTES_TOTAL_MINUTES_COLUMN: Final[str] = "total_minutes" +PROGRAMMINUTES_WEEKS_FIELD: Final[str] = "weeks" +PROGRAMMINUTES_WEEKS_COLUMN: Final[str] = "weeks" + +PROGRAMMINUTES_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgMinutes": PROGRAMMINUTES_AVG_MINUTES_COLUMN, + "labels": PROGRAMMINUTES_LABELS_COLUMN, + "longShare": PROGRAMMINUTES_LONG_SHARE_COLUMN, + "longWeeks": PROGRAMMINUTES_LONG_WEEKS_COLUMN, + "maxMinutes": PROGRAMMINUTES_MAX_MINUTES_COLUMN, + "minMinutes": PROGRAMMINUTES_MIN_MINUTES_COLUMN, + "program": PROGRAMMINUTES_PROGRAM_COLUMN, + "programTitle": PROGRAMMINUTES_PROGRAM_TITLE_COLUMN, + "slots": PROGRAMMINUTES_SLOTS_COLUMN, + "totalMinutes": PROGRAMMINUTES_TOTAL_MINUTES_COLUMN, + "weeks": PROGRAMMINUTES_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_minutes_router.py b/server/python/tests/codegen/golden_generators/expected/program_minutes_router.py new file mode 100644 index 0000000000..3cc7ba3c4b --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_minutes_router.py @@ -0,0 +1,201 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramMinutes (fitness::ProgramMinutes) +# Extend in your own module (e.g. ProgramMinutes_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramMinutes report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_minutes_filter_allowlist import ( + PROGRAMMINUTES_FILTER_FIELDS, + PROGRAMMINUTES_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_minutes", tags=["program_minutes"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "program", + "programTitle", + "weeks", + "longWeeks", + "labels", + "slots", + "totalMinutes", + "avgMinutes", + "minMinutes", + "maxMinutes", + "longShare", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "avgMinutes", + "longShare", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramMinutesRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramMinutesRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_minutes( + request: Request, + repo: Annotated[ProgramMinutesRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMMINUTES_FILTER_FIELDS, + PROGRAMMINUTES_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_minutes() -> Any: + """GENERATED — program_minutes is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_names.py b/server/python/tests/codegen/golden_generators/expected/program_names.py new file mode 100644 index 0000000000..46d16f4775 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_names.py @@ -0,0 +1,49 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Program (fitness::Program) +# Extend in your own module (e.g. Program_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Program (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAM_TYPE: Final[str] = "object" +PROGRAM_SUB_TYPE: Final[str] = "entity" +PROGRAM_NAME: Final[str] = "Program" + +PROGRAM_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAM_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAM_SOURCE_PRIMARY_KIND: Final[str] = "table" +PROGRAM_SOURCE_PRIMARY_TABLE: Final[str] = "programs" + +PROGRAM_CREATED_AT_FIELD: Final[str] = "createdAt" +PROGRAM_CREATED_AT_COLUMN: Final[str] = "created_ts" +PROGRAM_ID_FIELD: Final[str] = "id" +PROGRAM_ID_COLUMN: Final[str] = "id" +PROGRAM_PRICE_CENTS_FIELD: Final[str] = "priceCents" +PROGRAM_PRICE_CENTS_COLUMN: Final[str] = "price_cents" +PROGRAM_STATUS_FIELD: Final[str] = "status" +PROGRAM_STATUS_COLUMN: Final[str] = "status" +PROGRAM_TITLE_FIELD: Final[str] = "title" +PROGRAM_TITLE_COLUMN: Final[str] = "title" + +PROGRAM_IDENTITY_BY_TITLE_TYPE: Final[str] = "identity" +PROGRAM_IDENTITY_BY_TITLE_SUB_TYPE: Final[str] = "secondary" +PROGRAM_IDENTITY_BY_TITLE_NAME: Final[str] = "byTitle" +PROGRAM_IDENTITY_BY_TITLE_INDEX: Final[str] = "byTitle" +PROGRAM_IDENTITY_ID_TYPE: Final[str] = "identity" +PROGRAM_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +PROGRAM_IDENTITY_ID_NAME: Final[str] = "id" + +PROGRAM_INDEX_IDX_PROGRAMS_TITLE_STATUS_TYPE: Final[str] = "index" +PROGRAM_INDEX_IDX_PROGRAMS_TITLE_STATUS_SUB_TYPE: Final[str] = "lookup" +PROGRAM_INDEX_IDX_PROGRAMS_TITLE_STATUS_NAME: Final[str] = "idx_programs_title_status" +PROGRAM_INDEX_IDX_PROGRAMS_TITLE_STATUS_INDEX: Final[str] = "idx_programs_title_status" + +PROGRAM_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "createdAt": PROGRAM_CREATED_AT_COLUMN, + "id": PROGRAM_ID_COLUMN, + "priceCents": PROGRAM_PRICE_CENTS_COLUMN, + "status": PROGRAM_STATUS_COLUMN, + "title": PROGRAM_TITLE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_roster_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_roster_filter_allowlist.py new file mode 100644 index 0000000000..66dda91a6a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_roster_filter_allowlist.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramRoster (fitness::ProgramRoster) +# Extend in your own module (e.g. ProgramRoster_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramRoster. + +PROGRAMROSTER_FILTER_FIELDS lists the filterable field names; PROGRAMROSTER_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMROSTER_FILTER_FIELDS: frozenset[str] = frozenset( + { + "programKey", + "programTitle", + "weeks", + "totalMinutes", + "totalMinutesOrZero", + "longShare", + "longShareOrZero", + }, +) + +PROGRAMROSTER_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "programTitle": frozenset({"eq", "ne", "in", "like", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "totalMinutesOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), + "longShare": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "longShareOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_roster_names.py b/server/python/tests/codegen/golden_generators/expected/program_roster_names.py new file mode 100644 index 0000000000..670eea1d6b --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_roster_names.py @@ -0,0 +1,42 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramRoster (fitness::ProgramRoster) +# Extend in your own module (e.g. ProgramRoster_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramRoster (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMROSTER_TYPE: Final[str] = "object" +PROGRAMROSTER_SUB_TYPE: Final[str] = "report" +PROGRAMROSTER_NAME: Final[str] = "ProgramRoster" + +PROGRAMROSTER_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMROSTER_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMROSTER_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMROSTER_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_roster" + +PROGRAMROSTER_LONG_SHARE_FIELD: Final[str] = "longShare" +PROGRAMROSTER_LONG_SHARE_COLUMN: Final[str] = "long_share" +PROGRAMROSTER_LONG_SHARE_OR_ZERO_FIELD: Final[str] = "longShareOrZero" +PROGRAMROSTER_LONG_SHARE_OR_ZERO_COLUMN: Final[str] = "long_share_or_zero" +PROGRAMROSTER_PROGRAM_KEY_FIELD: Final[str] = "programKey" +PROGRAMROSTER_PROGRAM_KEY_COLUMN: Final[str] = "program_key" +PROGRAMROSTER_PROGRAM_TITLE_FIELD: Final[str] = "programTitle" +PROGRAMROSTER_PROGRAM_TITLE_COLUMN: Final[str] = "program_title" +PROGRAMROSTER_TOTAL_MINUTES_FIELD: Final[str] = "totalMinutes" +PROGRAMROSTER_TOTAL_MINUTES_COLUMN: Final[str] = "total_minutes" +PROGRAMROSTER_TOTAL_MINUTES_OR_ZERO_FIELD: Final[str] = "totalMinutesOrZero" +PROGRAMROSTER_TOTAL_MINUTES_OR_ZERO_COLUMN: Final[str] = "total_minutes_or_zero" +PROGRAMROSTER_WEEKS_FIELD: Final[str] = "weeks" +PROGRAMROSTER_WEEKS_COLUMN: Final[str] = "weeks" + +PROGRAMROSTER_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "longShare": PROGRAMROSTER_LONG_SHARE_COLUMN, + "longShareOrZero": PROGRAMROSTER_LONG_SHARE_OR_ZERO_COLUMN, + "programKey": PROGRAMROSTER_PROGRAM_KEY_COLUMN, + "programTitle": PROGRAMROSTER_PROGRAM_TITLE_COLUMN, + "totalMinutes": PROGRAMROSTER_TOTAL_MINUTES_COLUMN, + "totalMinutesOrZero": PROGRAMROSTER_TOTAL_MINUTES_OR_ZERO_COLUMN, + "weeks": PROGRAMROSTER_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_roster_router.py b/server/python/tests/codegen/golden_generators/expected/program_roster_router.py new file mode 100644 index 0000000000..1ef5e782b4 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_roster_router.py @@ -0,0 +1,197 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramRoster (fitness::ProgramRoster) +# Extend in your own module (e.g. ProgramRoster_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramRoster report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_roster_filter_allowlist import ( + PROGRAMROSTER_FILTER_FIELDS, + PROGRAMROSTER_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_rosters", tags=["program_rosters"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programKey", + "programTitle", + "weeks", + "totalMinutes", + "totalMinutesOrZero", + "longShare", + "longShareOrZero", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "longShare", + "longShareOrZero", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramRosterRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramRosterRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_rosters( + request: Request, + repo: Annotated[ProgramRosterRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMROSTER_FILTER_FIELDS, + PROGRAMROSTER_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_roster() -> Any: + """GENERATED — program_rosters is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_router.py b/server/python/tests/codegen/golden_generators/expected/program_router.py new file mode 100644 index 0000000000..363ec4ca84 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_router.py @@ -0,0 +1,332 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Program (fitness::Program) +# Extend in your own module (e.g. Program_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Program entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Program import ProgramCreate, ProgramPatch +from .program_filter_allowlist import PROGRAM_FILTER_FIELDS, PROGRAM_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/programs", tags=["programs"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "title", + "priceCents", + "status", + "createdAt", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "priceCents", + "status", + "createdAt", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "title", + "priceCents", + "status", + "createdAt", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> ProgramRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_programs( + request: Request, + repo: Annotated[ProgramRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, PROGRAM_FILTER_FIELDS, PROGRAM_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{program_id}") +def get_program( + program_id: int, + repo: Annotated[ProgramRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(program_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_program( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[ProgramRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = ProgramCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{program_id}") +@router.put("/{program_id}") +def update_program( + program_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[ProgramRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = ProgramPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(program_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{program_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_program( + program_id: int, + repo: Annotated[ProgramRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(program_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/program_sessions_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_sessions_filter_allowlist.py new file mode 100644 index 0000000000..b983a2a871 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_sessions_filter_allowlist.py @@ -0,0 +1,30 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramSessions (fitness::ProgramSessions) +# Extend in your own module (e.g. ProgramSessions_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramSessions. + +PROGRAMSESSIONS_FILTER_FIELDS lists the filterable field names; PROGRAMSESSIONS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSESSIONS_FILTER_FIELDS: frozenset[str] = frozenset( + { + "programKey", + "programTitle", + "sessions", + "sessionMinutes", + "sessionMinutesOrZero", + }, +) + +PROGRAMSESSIONS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "programTitle": frozenset({"eq", "ne", "in", "like", "isNull"}), + "sessions": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "sessionMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "sessionMinutesOrZero": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_sessions_names.py b/server/python/tests/codegen/golden_generators/expected/program_sessions_names.py new file mode 100644 index 0000000000..780025407f --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_sessions_names.py @@ -0,0 +1,36 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramSessions (fitness::ProgramSessions) +# Extend in your own module (e.g. ProgramSessions_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramSessions (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSESSIONS_TYPE: Final[str] = "object" +PROGRAMSESSIONS_SUB_TYPE: Final[str] = "report" +PROGRAMSESSIONS_NAME: Final[str] = "ProgramSessions" + +PROGRAMSESSIONS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSESSIONS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSESSIONS_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSESSIONS_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_sessions" + +PROGRAMSESSIONS_PROGRAM_KEY_FIELD: Final[str] = "programKey" +PROGRAMSESSIONS_PROGRAM_KEY_COLUMN: Final[str] = "program_key" +PROGRAMSESSIONS_PROGRAM_TITLE_FIELD: Final[str] = "programTitle" +PROGRAMSESSIONS_PROGRAM_TITLE_COLUMN: Final[str] = "program_title" +PROGRAMSESSIONS_SESSION_MINUTES_FIELD: Final[str] = "sessionMinutes" +PROGRAMSESSIONS_SESSION_MINUTES_COLUMN: Final[str] = "session_minutes" +PROGRAMSESSIONS_SESSION_MINUTES_OR_ZERO_FIELD: Final[str] = "sessionMinutesOrZero" +PROGRAMSESSIONS_SESSION_MINUTES_OR_ZERO_COLUMN: Final[str] = "session_minutes_or_zero" +PROGRAMSESSIONS_SESSIONS_FIELD: Final[str] = "sessions" +PROGRAMSESSIONS_SESSIONS_COLUMN: Final[str] = "sessions" + +PROGRAMSESSIONS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "programKey": PROGRAMSESSIONS_PROGRAM_KEY_COLUMN, + "programTitle": PROGRAMSESSIONS_PROGRAM_TITLE_COLUMN, + "sessionMinutes": PROGRAMSESSIONS_SESSION_MINUTES_COLUMN, + "sessionMinutesOrZero": PROGRAMSESSIONS_SESSION_MINUTES_OR_ZERO_COLUMN, + "sessions": PROGRAMSESSIONS_SESSIONS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_sessions_router.py b/server/python/tests/codegen/golden_generators/expected/program_sessions_router.py new file mode 100644 index 0000000000..b652d69bd3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_sessions_router.py @@ -0,0 +1,190 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramSessions (fitness::ProgramSessions) +# Extend in your own module (e.g. ProgramSessions_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramSessions report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_sessions_filter_allowlist import ( + PROGRAMSESSIONS_FILTER_FIELDS, + PROGRAMSESSIONS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_sessions", tags=["program_sessions"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programKey", + "programTitle", + "sessions", + "sessionMinutes", + "sessionMinutesOrZero", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramSessionsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramSessionsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_sessions( + request: Request, + repo: Annotated[ProgramSessionsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMSESSIONS_FILTER_FIELDS, + PROGRAMSESSIONS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_program_sessions() -> Any: + """GENERATED — program_sessions is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_stat_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_stat_filter_allowlist.py new file mode 100644 index 0000000000..8542a613c5 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_stat_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramStat (fitness::ProgramStat) +# Extend in your own module (e.g. ProgramStat_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramStat. + +PROGRAMSTAT_FILTER_FIELDS lists the filterable field names; PROGRAMSTAT_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSTAT_FILTER_FIELDS: frozenset[str] = frozenset() + +PROGRAMSTAT_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/program_stat_names.py b/server/python/tests/codegen/golden_generators/expected/program_stat_names.py new file mode 100644 index 0000000000..6763aa4bfc --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_stat_names.py @@ -0,0 +1,43 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramStat (fitness::ProgramStat) +# Extend in your own module (e.g. ProgramStat_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramStat (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSTAT_TYPE: Final[str] = "object" +PROGRAMSTAT_SUB_TYPE: Final[str] = "projection" +PROGRAMSTAT_NAME: Final[str] = "ProgramStat" + +PROGRAMSTAT_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSTAT_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSTAT_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSTAT_SOURCE_PRIMARY_VIEW: Final[str] = "v_program_stat" + +PROGRAMSTAT_AVG_MINUTES_FIELD: Final[str] = "avgMinutes" +PROGRAMSTAT_AVG_MINUTES_COLUMN: Final[str] = "avg_minutes" +PROGRAMSTAT_MAX_MINUTES_FIELD: Final[str] = "maxMinutes" +PROGRAMSTAT_MAX_MINUTES_COLUMN: Final[str] = "max_minutes" +PROGRAMSTAT_MIN_MINUTES_FIELD: Final[str] = "minMinutes" +PROGRAMSTAT_MIN_MINUTES_COLUMN: Final[str] = "min_minutes" +PROGRAMSTAT_PROGRAM_ID_FIELD: Final[str] = "programId" +PROGRAMSTAT_PROGRAM_ID_COLUMN: Final[str] = "program_id" +PROGRAMSTAT_TOTAL_MINUTES_FIELD: Final[str] = "totalMinutes" +PROGRAMSTAT_TOTAL_MINUTES_COLUMN: Final[str] = "total_minutes" +PROGRAMSTAT_WEEK_COUNT_FIELD: Final[str] = "weekCount" +PROGRAMSTAT_WEEK_COUNT_COLUMN: Final[str] = "week_count" + +PROGRAMSTAT_IDENTITY_ID_TYPE: Final[str] = "identity" +PROGRAMSTAT_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +PROGRAMSTAT_IDENTITY_ID_NAME: Final[str] = "id" + +PROGRAMSTAT_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgMinutes": PROGRAMSTAT_AVG_MINUTES_COLUMN, + "maxMinutes": PROGRAMSTAT_MAX_MINUTES_COLUMN, + "minMinutes": PROGRAMSTAT_MIN_MINUTES_COLUMN, + "programId": PROGRAMSTAT_PROGRAM_ID_COLUMN, + "totalMinutes": PROGRAMSTAT_TOTAL_MINUTES_COLUMN, + "weekCount": PROGRAMSTAT_WEEK_COUNT_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_stat_router.py b/server/python/tests/codegen/golden_generators/expected/program_stat_router.py new file mode 100644 index 0000000000..2a78128f49 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_stat_router.py @@ -0,0 +1,202 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramStat (fitness::ProgramStat) +# Extend in your own module (e.g. ProgramStat_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramStat projection. + +Implements the cross-port API contract: GET list + GET by id; every write +verb answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_stat_filter_allowlist import ( + PROGRAMSTAT_FILTER_FIELDS, + PROGRAMSTAT_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_stats", tags=["program_stats"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programId", + "weekCount", + "totalMinutes", + "avgMinutes", + "minMinutes", + "maxMinutes", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramStatRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a projection is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + + +def get_repository() -> ProgramStatRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_stats( + request: Request, + repo: Annotated[ProgramStatRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, PROGRAMSTAT_FILTER_FIELDS, PROGRAMSTAT_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{program_stat_id}") +def get_program_stat( + program_stat_id: int, + repo: Annotated[ProgramStatRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(program_stat_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("") +def create_program_stat() -> Any: + """GENERATED — program_stats is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a projection (read-only).", + }, + ) + + +@router.patch("/{program_stat_id}") +def update_program_stat() -> Any: + """GENERATED — program_stats is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "PATCH is not supported on a projection (read-only).", + }, + ) + + +@router.put("/{program_stat_id}") +def replace_program_stat() -> Any: + """GENERATED — program_stats is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "PUT is not supported on a projection (read-only).", + }, + ) + + +@router.delete("/{program_stat_id}") +def delete_program_stat() -> Any: + """GENERATED — program_stats is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "DELETE is not supported on a projection (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/program_view_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/program_view_filter_allowlist.py new file mode 100644 index 0000000000..404d5cb9be --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_view_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramView (fitness::ProgramView) +# Extend in your own module (e.g. ProgramView_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramView. + +PROGRAMVIEW_FILTER_FIELDS lists the filterable field names; PROGRAMVIEW_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMVIEW_FILTER_FIELDS: frozenset[str] = frozenset() + +PROGRAMVIEW_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/program_view_names.py b/server/python/tests/codegen/golden_generators/expected/program_view_names.py new file mode 100644 index 0000000000..2092e09b50 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_view_names.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramView (fitness::ProgramView) +# Extend in your own module (e.g. ProgramView_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramView (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMVIEW_TYPE: Final[str] = "object" +PROGRAMVIEW_SUB_TYPE: Final[str] = "projection" +PROGRAMVIEW_NAME: Final[str] = "ProgramView" + +PROGRAMVIEW_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMVIEW_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMVIEW_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMVIEW_SOURCE_PRIMARY_VIEW: Final[str] = "v_program" + +PROGRAMVIEW_ID_FIELD: Final[str] = "id" +PROGRAMVIEW_ID_COLUMN: Final[str] = "id" +PROGRAMVIEW_STATUS_FIELD: Final[str] = "status" +PROGRAMVIEW_STATUS_COLUMN: Final[str] = "status" +PROGRAMVIEW_TITLE_FIELD: Final[str] = "title" +PROGRAMVIEW_TITLE_COLUMN: Final[str] = "title" + +PROGRAMVIEW_IDENTITY_ID_TYPE: Final[str] = "identity" +PROGRAMVIEW_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +PROGRAMVIEW_IDENTITY_ID_NAME: Final[str] = "id" + +PROGRAMVIEW_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": PROGRAMVIEW_ID_COLUMN, + "status": PROGRAMVIEW_STATUS_COLUMN, + "title": PROGRAMVIEW_TITLE_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/program_view_router.py b/server/python/tests/codegen/golden_generators/expected/program_view_router.py new file mode 100644 index 0000000000..eeb81ad6a4 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/program_view_router.py @@ -0,0 +1,199 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramView (fitness::ProgramView) +# Extend in your own module (e.g. ProgramView_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramView projection. + +Implements the cross-port API contract: GET list + GET by id; every write +verb answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .program_view_filter_allowlist import ( + PROGRAMVIEW_FILTER_FIELDS, + PROGRAMVIEW_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/program_views", tags=["program_views"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "title", + "status", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramViewRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a projection is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + + +def get_repository() -> ProgramViewRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_program_views( + request: Request, + repo: Annotated[ProgramViewRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, PROGRAMVIEW_FILTER_FIELDS, PROGRAMVIEW_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{program_view_id}") +def get_program_view( + program_view_id: int, + repo: Annotated[ProgramViewRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(program_view_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("") +def create_program_view() -> Any: + """GENERATED — program_views is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a projection (read-only).", + }, + ) + + +@router.patch("/{program_view_id}") +def update_program_view() -> Any: + """GENERATED — program_views is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "PATCH is not supported on a projection (read-only).", + }, + ) + + +@router.put("/{program_view_id}") +def replace_program_view() -> Any: + """GENERATED — program_views is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "PUT is not supported on a projection (read-only).", + }, + ) + + +@router.delete("/{program_view_id}") +def delete_program_view() -> Any: + """GENERATED — program_views is a read-only projection; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "DELETE is not supported on a projection (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_month_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/programs_by_month_filter_allowlist.py new file mode 100644 index 0000000000..4fbe9d51e4 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_month_filter_allowlist.py @@ -0,0 +1,21 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByMonth (fitness::ProgramsByMonth) +# Extend in your own module (e.g. ProgramsByMonth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramsByMonth. + +PROGRAMSBYMONTH_FILTER_FIELDS lists the filterable field names; PROGRAMSBYMONTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSBYMONTH_FILTER_FIELDS: frozenset[str] = frozenset( + {"createdAtMonth", "status", "programs", "listValue"}, +) + +PROGRAMSBYMONTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "createdAtMonth": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "status": frozenset({"eq", "ne", "in", "like", "isNull"}), + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "listValue": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_month_names.py b/server/python/tests/codegen/golden_generators/expected/programs_by_month_names.py new file mode 100644 index 0000000000..895e1be11b --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_month_names.py @@ -0,0 +1,33 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByMonth (fitness::ProgramsByMonth) +# Extend in your own module (e.g. ProgramsByMonth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramsByMonth (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSBYMONTH_TYPE: Final[str] = "object" +PROGRAMSBYMONTH_SUB_TYPE: Final[str] = "report" +PROGRAMSBYMONTH_NAME: Final[str] = "ProgramsByMonth" + +PROGRAMSBYMONTH_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSBYMONTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSBYMONTH_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSBYMONTH_SOURCE_PRIMARY_VIEW: Final[str] = "v_programs_by_month" + +PROGRAMSBYMONTH_CREATED_AT_MONTH_FIELD: Final[str] = "createdAtMonth" +PROGRAMSBYMONTH_CREATED_AT_MONTH_COLUMN: Final[str] = "created_at_month" +PROGRAMSBYMONTH_LIST_VALUE_FIELD: Final[str] = "listValue" +PROGRAMSBYMONTH_LIST_VALUE_COLUMN: Final[str] = "list_value" +PROGRAMSBYMONTH_PROGRAMS_FIELD: Final[str] = "programs" +PROGRAMSBYMONTH_PROGRAMS_COLUMN: Final[str] = "programs" +PROGRAMSBYMONTH_STATUS_FIELD: Final[str] = "status" +PROGRAMSBYMONTH_STATUS_COLUMN: Final[str] = "status" + +PROGRAMSBYMONTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "createdAtMonth": PROGRAMSBYMONTH_CREATED_AT_MONTH_COLUMN, + "listValue": PROGRAMSBYMONTH_LIST_VALUE_COLUMN, + "programs": PROGRAMSBYMONTH_PROGRAMS_COLUMN, + "status": PROGRAMSBYMONTH_STATUS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_month_router.py b/server/python/tests/codegen/golden_generators/expected/programs_by_month_router.py new file mode 100644 index 0000000000..09113e52ab --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_month_router.py @@ -0,0 +1,189 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByMonth (fitness::ProgramsByMonth) +# Extend in your own module (e.g. ProgramsByMonth_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramsByMonth report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .programs_by_month_filter_allowlist import ( + PROGRAMSBYMONTH_FILTER_FIELDS, + PROGRAMSBYMONTH_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/programs_by_months", tags=["programs_by_months"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "createdAtMonth", + "status", + "programs", + "listValue", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramsByMonthRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramsByMonthRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_programs_by_months( + request: Request, + repo: Annotated[ProgramsByMonthRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMSBYMONTH_FILTER_FIELDS, + PROGRAMSBYMONTH_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_programs_by_month() -> Any: + """GENERATED — programs_by_months is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_week_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/programs_by_week_filter_allowlist.py new file mode 100644 index 0000000000..92aeafd33c --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_week_filter_allowlist.py @@ -0,0 +1,17 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByWeek (fitness::ProgramsByWeek) +# Extend in your own module (e.g. ProgramsByWeek_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramsByWeek. + +PROGRAMSBYWEEK_FILTER_FIELDS lists the filterable field names; PROGRAMSBYWEEK_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSBYWEEK_FILTER_FIELDS: frozenset[str] = frozenset({"createdAtWeek", "programs"}) + +PROGRAMSBYWEEK_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "createdAtWeek": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_week_names.py b/server/python/tests/codegen/golden_generators/expected/programs_by_week_names.py new file mode 100644 index 0000000000..6b96294171 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_week_names.py @@ -0,0 +1,27 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByWeek (fitness::ProgramsByWeek) +# Extend in your own module (e.g. ProgramsByWeek_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramsByWeek (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSBYWEEK_TYPE: Final[str] = "object" +PROGRAMSBYWEEK_SUB_TYPE: Final[str] = "report" +PROGRAMSBYWEEK_NAME: Final[str] = "ProgramsByWeek" + +PROGRAMSBYWEEK_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSBYWEEK_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSBYWEEK_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSBYWEEK_SOURCE_PRIMARY_VIEW: Final[str] = "v_programs_by_week" + +PROGRAMSBYWEEK_CREATED_AT_WEEK_FIELD: Final[str] = "createdAtWeek" +PROGRAMSBYWEEK_CREATED_AT_WEEK_COLUMN: Final[str] = "created_at_week" +PROGRAMSBYWEEK_PROGRAMS_FIELD: Final[str] = "programs" +PROGRAMSBYWEEK_PROGRAMS_COLUMN: Final[str] = "programs" + +PROGRAMSBYWEEK_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "createdAtWeek": PROGRAMSBYWEEK_CREATED_AT_WEEK_COLUMN, + "programs": PROGRAMSBYWEEK_PROGRAMS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_by_week_router.py b/server/python/tests/codegen/golden_generators/expected/programs_by_week_router.py new file mode 100644 index 0000000000..ad59a8ce1c --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_by_week_router.py @@ -0,0 +1,187 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsByWeek (fitness::ProgramsByWeek) +# Extend in your own module (e.g. ProgramsByWeek_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramsByWeek report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .programs_by_week_filter_allowlist import ( + PROGRAMSBYWEEK_FILTER_FIELDS, + PROGRAMSBYWEEK_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/programs_by_weeks", tags=["programs_by_weeks"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "createdAtWeek", + "programs", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramsByWeekRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramsByWeekRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_programs_by_weeks( + request: Request, + repo: Annotated[ProgramsByWeekRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMSBYWEEK_FILTER_FIELDS, + PROGRAMSBYWEEK_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_programs_by_week() -> Any: + """GENERATED — programs_by_weeks is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_filter_allowlist.py new file mode 100644 index 0000000000..48da8732cb --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_filter_allowlist.py @@ -0,0 +1,21 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsEmptyScope (fitness::ProgramsEmptyScope) +# Extend in your own module (e.g. ProgramsEmptyScope_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramsEmptyScope. + +PROGRAMSEMPTYSCOPE_FILTER_FIELDS lists the filterable field names; PROGRAMSEMPTYSCOPE_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSEMPTYSCOPE_FILTER_FIELDS: frozenset[str] = frozenset( + {"programs", "avgPriceOrMinusOne"}, +) + +PROGRAMSEMPTYSCOPE_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgPriceOrMinusOne": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_names.py b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_names.py new file mode 100644 index 0000000000..d9a5a52aef --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_names.py @@ -0,0 +1,27 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsEmptyScope (fitness::ProgramsEmptyScope) +# Extend in your own module (e.g. ProgramsEmptyScope_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramsEmptyScope (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSEMPTYSCOPE_TYPE: Final[str] = "object" +PROGRAMSEMPTYSCOPE_SUB_TYPE: Final[str] = "report" +PROGRAMSEMPTYSCOPE_NAME: Final[str] = "ProgramsEmptyScope" + +PROGRAMSEMPTYSCOPE_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSEMPTYSCOPE_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSEMPTYSCOPE_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSEMPTYSCOPE_SOURCE_PRIMARY_VIEW: Final[str] = "v_programs_empty_scope" + +PROGRAMSEMPTYSCOPE_AVG_PRICE_OR_MINUS_ONE_FIELD: Final[str] = "avgPriceOrMinusOne" +PROGRAMSEMPTYSCOPE_AVG_PRICE_OR_MINUS_ONE_COLUMN: Final[str] = "avg_price_or_minus_one" +PROGRAMSEMPTYSCOPE_PROGRAMS_FIELD: Final[str] = "programs" +PROGRAMSEMPTYSCOPE_PROGRAMS_COLUMN: Final[str] = "programs" + +PROGRAMSEMPTYSCOPE_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgPriceOrMinusOne": PROGRAMSEMPTYSCOPE_AVG_PRICE_OR_MINUS_ONE_COLUMN, + "programs": PROGRAMSEMPTYSCOPE_PROGRAMS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_router.py b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_router.py new file mode 100644 index 0000000000..fddc4923fc --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_empty_scope_router.py @@ -0,0 +1,191 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsEmptyScope (fitness::ProgramsEmptyScope) +# Extend in your own module (e.g. ProgramsEmptyScope_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramsEmptyScope report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .programs_empty_scope_filter_allowlist import ( + PROGRAMSEMPTYSCOPE_FILTER_FIELDS, + PROGRAMSEMPTYSCOPE_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/programs_empty_scopes", tags=["programs_empty_scopes"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programs", + "avgPriceOrMinusOne", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "avgPriceOrMinusOne", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramsEmptyScopeRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramsEmptyScopeRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_programs_empty_scopes( + request: Request, + repo: Annotated[ProgramsEmptyScopeRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMSEMPTYSCOPE_FILTER_FIELDS, + PROGRAMSEMPTYSCOPE_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_programs_empty_scope() -> Any: + """GENERATED — programs_empty_scopes is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/programs_over_time_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/programs_over_time_filter_allowlist.py new file mode 100644 index 0000000000..4728c48694 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_over_time_filter_allowlist.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsOverTime (fitness::ProgramsOverTime) +# Extend in your own module (e.g. ProgramsOverTime_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ProgramsOverTime. + +PROGRAMSOVERTIME_FILTER_FIELDS lists the filterable field names; PROGRAMSOVERTIME_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +PROGRAMSOVERTIME_FILTER_FIELDS: frozenset[str] = frozenset( + { + "createdAtDay", + "createdAtQuarter", + "createdAtYear", + "programs", + "avgPrice", + "cheapest", + "priciest", + }, +) + +PROGRAMSOVERTIME_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "createdAtDay": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "createdAtQuarter": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), + "createdAtYear": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "avgPrice": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "cheapest": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "priciest": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_over_time_names.py b/server/python/tests/codegen/golden_generators/expected/programs_over_time_names.py new file mode 100644 index 0000000000..90f20452e9 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_over_time_names.py @@ -0,0 +1,42 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsOverTime (fitness::ProgramsOverTime) +# Extend in your own module (e.g. ProgramsOverTime_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ProgramsOverTime (#248).""" + +from __future__ import annotations + +from typing import Final + +PROGRAMSOVERTIME_TYPE: Final[str] = "object" +PROGRAMSOVERTIME_SUB_TYPE: Final[str] = "report" +PROGRAMSOVERTIME_NAME: Final[str] = "ProgramsOverTime" + +PROGRAMSOVERTIME_SOURCE_PRIMARY_TYPE: Final[str] = "source" +PROGRAMSOVERTIME_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +PROGRAMSOVERTIME_SOURCE_PRIMARY_KIND: Final[str] = "view" +PROGRAMSOVERTIME_SOURCE_PRIMARY_VIEW: Final[str] = "v_programs_over_time" + +PROGRAMSOVERTIME_AVG_PRICE_FIELD: Final[str] = "avgPrice" +PROGRAMSOVERTIME_AVG_PRICE_COLUMN: Final[str] = "avg_price" +PROGRAMSOVERTIME_CHEAPEST_FIELD: Final[str] = "cheapest" +PROGRAMSOVERTIME_CHEAPEST_COLUMN: Final[str] = "cheapest" +PROGRAMSOVERTIME_CREATED_AT_DAY_FIELD: Final[str] = "createdAtDay" +PROGRAMSOVERTIME_CREATED_AT_DAY_COLUMN: Final[str] = "created_at_day" +PROGRAMSOVERTIME_CREATED_AT_QUARTER_FIELD: Final[str] = "createdAtQuarter" +PROGRAMSOVERTIME_CREATED_AT_QUARTER_COLUMN: Final[str] = "created_at_quarter" +PROGRAMSOVERTIME_CREATED_AT_YEAR_FIELD: Final[str] = "createdAtYear" +PROGRAMSOVERTIME_CREATED_AT_YEAR_COLUMN: Final[str] = "created_at_year" +PROGRAMSOVERTIME_PRICIEST_FIELD: Final[str] = "priciest" +PROGRAMSOVERTIME_PRICIEST_COLUMN: Final[str] = "priciest" +PROGRAMSOVERTIME_PROGRAMS_FIELD: Final[str] = "programs" +PROGRAMSOVERTIME_PROGRAMS_COLUMN: Final[str] = "programs" + +PROGRAMSOVERTIME_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "avgPrice": PROGRAMSOVERTIME_AVG_PRICE_COLUMN, + "cheapest": PROGRAMSOVERTIME_CHEAPEST_COLUMN, + "createdAtDay": PROGRAMSOVERTIME_CREATED_AT_DAY_COLUMN, + "createdAtQuarter": PROGRAMSOVERTIME_CREATED_AT_QUARTER_COLUMN, + "createdAtYear": PROGRAMSOVERTIME_CREATED_AT_YEAR_COLUMN, + "priciest": PROGRAMSOVERTIME_PRICIEST_COLUMN, + "programs": PROGRAMSOVERTIME_PROGRAMS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/programs_over_time_router.py b/server/python/tests/codegen/golden_generators/expected/programs_over_time_router.py new file mode 100644 index 0000000000..eb6e13cc90 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/programs_over_time_router.py @@ -0,0 +1,196 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ProgramsOverTime (fitness::ProgramsOverTime) +# Extend in your own module (e.g. ProgramsOverTime_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the ProgramsOverTime report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .programs_over_time_filter_allowlist import ( + PROGRAMSOVERTIME_FILTER_FIELDS, + PROGRAMSOVERTIME_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/programs_over_times", tags=["programs_over_times"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "createdAtDay", + "createdAtQuarter", + "createdAtYear", + "programs", + "avgPrice", + "cheapest", + "priciest", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset( + { + "avgPrice", + } +) +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class ProgramsOverTimeRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> ProgramsOverTimeRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_programs_over_times( + request: Request, + repo: Annotated[ProgramsOverTimeRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + PROGRAMSOVERTIME_FILTER_FIELDS, + PROGRAMSOVERTIME_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_programs_over_time() -> Any: + """GENERATED — programs_over_times is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/recent_programs_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/recent_programs_filter_allowlist.py new file mode 100644 index 0000000000..60fe427363 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/recent_programs_filter_allowlist.py @@ -0,0 +1,16 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: RecentPrograms (fitness::RecentPrograms) +# Extend in your own module (e.g. RecentPrograms_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for RecentPrograms. + +RECENTPROGRAMS_FILTER_FIELDS lists the filterable field names; RECENTPROGRAMS_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +RECENTPROGRAMS_FILTER_FIELDS: frozenset[str] = frozenset({"programs"}) + +RECENTPROGRAMS_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programs": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/recent_programs_names.py b/server/python/tests/codegen/golden_generators/expected/recent_programs_names.py new file mode 100644 index 0000000000..d9d78be5d1 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/recent_programs_names.py @@ -0,0 +1,24 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: RecentPrograms (fitness::RecentPrograms) +# Extend in your own module (e.g. RecentPrograms_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for RecentPrograms (#248).""" + +from __future__ import annotations + +from typing import Final + +RECENTPROGRAMS_TYPE: Final[str] = "object" +RECENTPROGRAMS_SUB_TYPE: Final[str] = "report" +RECENTPROGRAMS_NAME: Final[str] = "RecentPrograms" + +RECENTPROGRAMS_SOURCE_PRIMARY_TYPE: Final[str] = "source" +RECENTPROGRAMS_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +RECENTPROGRAMS_SOURCE_PRIMARY_KIND: Final[str] = "view" +RECENTPROGRAMS_SOURCE_PRIMARY_VIEW: Final[str] = "v_recent_programs" + +RECENTPROGRAMS_PROGRAMS_FIELD: Final[str] = "programs" +RECENTPROGRAMS_PROGRAMS_COLUMN: Final[str] = "programs" + +RECENTPROGRAMS_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "programs": RECENTPROGRAMS_PROGRAMS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/recent_programs_router.py b/server/python/tests/codegen/golden_generators/expected/recent_programs_router.py new file mode 100644 index 0000000000..f8803c17a3 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/recent_programs_router.py @@ -0,0 +1,186 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: RecentPrograms (fitness::RecentPrograms) +# Extend in your own module (e.g. RecentPrograms_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the RecentPrograms report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .recent_programs_filter_allowlist import ( + RECENTPROGRAMS_FILTER_FIELDS, + RECENTPROGRAMS_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/recent_programs", tags=["recent_programs"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programs", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class RecentProgramsRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> RecentProgramsRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_recent_programs( + request: Request, + repo: Annotated[RecentProgramsRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + RECENTPROGRAMS_FILTER_FIELDS, + RECENTPROGRAMS_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_recent_programs() -> Any: + """GENERATED — recent_programs is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/referral_auth_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/referral_auth_filter_allowlist.py new file mode 100644 index 0000000000..46ff7d7782 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/referral_auth_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ReferralAuth (fitness::ReferralAuth) +# Extend in your own module (e.g. ReferralAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for ReferralAuth. + +REFERRALAUTH_FILTER_FIELDS lists the filterable field names; REFERRALAUTH_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +REFERRALAUTH_FILTER_FIELDS: frozenset[str] = frozenset() + +REFERRALAUTH_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/referral_auth_names.py b/server/python/tests/codegen/golden_generators/expected/referral_auth_names.py new file mode 100644 index 0000000000..2223758930 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/referral_auth_names.py @@ -0,0 +1,53 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: ReferralAuth (fitness::ReferralAuth) +# Extend in your own module (e.g. ReferralAuth_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for ReferralAuth (#248).""" + +from __future__ import annotations + +from typing import Final + +from .auth_names import ( + AUTH_ID_COLUMN, + AUTH_ID_FIELD, + AUTH_IDENTITY_ID_NAME, + AUTH_IDENTITY_ID_SUB_TYPE, + AUTH_IDENTITY_ID_TYPE, + AUTH_REFERENCE_COLUMN, + AUTH_REFERENCE_FIELD, + AUTH_SOURCE_PRIMARY_KIND, + AUTH_SOURCE_PRIMARY_SUB_TYPE, + AUTH_SOURCE_PRIMARY_TABLE, + AUTH_SOURCE_PRIMARY_TYPE, + AUTH_TYPE_COLUMN, + AUTH_TYPE_FIELD, +) + +REFERRALAUTH_TYPE: Final[str] = "object" +REFERRALAUTH_SUB_TYPE: Final[str] = "entity" +REFERRALAUTH_NAME: Final[str] = "ReferralAuth" + +REFERRALAUTH_SOURCE_PRIMARY_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_TYPE +REFERRALAUTH_SOURCE_PRIMARY_SUB_TYPE: Final[str] = AUTH_SOURCE_PRIMARY_SUB_TYPE +REFERRALAUTH_SOURCE_PRIMARY_KIND: Final[str] = AUTH_SOURCE_PRIMARY_KIND +REFERRALAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE + +REFERRALAUTH_ID_FIELD: Final[str] = AUTH_ID_FIELD +REFERRALAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +REFERRALAUTH_REFERENCE_FIELD: Final[str] = AUTH_REFERENCE_FIELD +REFERRALAUTH_REFERENCE_COLUMN: Final[str] = AUTH_REFERENCE_COLUMN +REFERRALAUTH_TYPE_FIELD: Final[str] = AUTH_TYPE_FIELD +REFERRALAUTH_TYPE_COLUMN: Final[str] = AUTH_TYPE_COLUMN +REFERRALAUTH_URGENCY_FIELD: Final[str] = "urgency" +REFERRALAUTH_URGENCY_COLUMN: Final[str] = "urgency" + +REFERRALAUTH_IDENTITY_ID_TYPE: Final[str] = AUTH_IDENTITY_ID_TYPE +REFERRALAUTH_IDENTITY_ID_SUB_TYPE: Final[str] = AUTH_IDENTITY_ID_SUB_TYPE +REFERRALAUTH_IDENTITY_ID_NAME: Final[str] = AUTH_IDENTITY_ID_NAME + +REFERRALAUTH_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": REFERRALAUTH_ID_COLUMN, + "reference": REFERRALAUTH_REFERENCE_COLUMN, + "type": REFERRALAUTH_TYPE_COLUMN, + "urgency": REFERRALAUTH_URGENCY_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/session_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/session_filter_allowlist.py new file mode 100644 index 0000000000..817d0f04b6 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/session_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Session (fitness::Session) +# Extend in your own module (e.g. Session_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Session. + +SESSION_FILTER_FIELDS lists the filterable field names; SESSION_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +SESSION_FILTER_FIELDS: frozenset[str] = frozenset() + +SESSION_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/session_names.py b/server/python/tests/codegen/golden_generators/expected/session_names.py new file mode 100644 index 0000000000..3c87c2b5c0 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/session_names.py @@ -0,0 +1,37 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Session (fitness::Session) +# Extend in your own module (e.g. Session_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Session (#248).""" + +from __future__ import annotations + +from typing import Final + +SESSION_TYPE: Final[str] = "object" +SESSION_SUB_TYPE: Final[str] = "entity" +SESSION_NAME: Final[str] = "Session" + +SESSION_SOURCE_PRIMARY_TYPE: Final[str] = "source" +SESSION_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +SESSION_SOURCE_PRIMARY_KIND: Final[str] = "table" +SESSION_SOURCE_PRIMARY_TABLE: Final[str] = "sessions" + +SESSION_ID_FIELD: Final[str] = "id" +SESSION_ID_COLUMN: Final[str] = "id" +SESSION_MINUTES_FIELD: Final[str] = "minutes" +SESSION_MINUTES_COLUMN: Final[str] = "minutes" +SESSION_WEEK_ID_FIELD: Final[str] = "weekId" +SESSION_WEEK_ID_COLUMN: Final[str] = "week_id" + +SESSION_IDENTITY_FK_WEEK_TYPE: Final[str] = "identity" +SESSION_IDENTITY_FK_WEEK_SUB_TYPE: Final[str] = "reference" +SESSION_IDENTITY_FK_WEEK_NAME: Final[str] = "fkWeek" +SESSION_IDENTITY_ID_TYPE: Final[str] = "identity" +SESSION_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +SESSION_IDENTITY_ID_NAME: Final[str] = "id" + +SESSION_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": SESSION_ID_COLUMN, + "minutes": SESSION_MINUTES_COLUMN, + "weekId": SESSION_WEEK_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/session_router.py b/server/python/tests/codegen/golden_generators/expected/session_router.py new file mode 100644 index 0000000000..3057243af6 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/session_router.py @@ -0,0 +1,329 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Session (fitness::Session) +# Extend in your own module (e.g. Session_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Session entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Session import SessionCreate, SessionPatch +from .session_filter_allowlist import SESSION_FILTER_FIELDS, SESSION_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/sessions", tags=["sessions"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "weekId", + "minutes", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "weekId", + "minutes", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "weekId", + "minutes", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class SessionRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_sessions_by_week(self, week_id: Any) -> _list[Any]: ... + def find_sessions_by_week_in(self, week_id_values: _list[Any]) -> _list[Any]: ... + + +def get_repository() -> SessionRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_sessions( + request: Request, + repo: Annotated[SessionRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, SESSION_FILTER_FIELDS, SESSION_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{session_id}") +def get_session( + session_id: int, + repo: Annotated[SessionRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(session_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_session( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[SessionRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = SessionCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{session_id}") +@router.put("/{session_id}") +def update_session( + session_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[SessionRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = SessionPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(session_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{session_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_session( + session_id: int, + repo: Annotated[SessionRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(session_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/sessions_by_program_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_filter_allowlist.py new file mode 100644 index 0000000000..c3505773db --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_filter_allowlist.py @@ -0,0 +1,21 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: SessionsByProgram (fitness::SessionsByProgram) +# Extend in your own module (e.g. SessionsByProgram_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for SessionsByProgram. + +SESSIONSBYPROGRAM_FILTER_FIELDS lists the filterable field names; SESSIONSBYPROGRAM_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +SESSIONSBYPROGRAM_FILTER_FIELDS: frozenset[str] = frozenset( + {"programTitle", "weekKey", "sessions", "sessionMinutes"}, +) + +SESSIONSBYPROGRAM_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programTitle": frozenset({"eq", "ne", "in", "like", "isNull"}), + "weekKey": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "sessions": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "sessionMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/sessions_by_program_names.py b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_names.py new file mode 100644 index 0000000000..1d03165a59 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_names.py @@ -0,0 +1,33 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: SessionsByProgram (fitness::SessionsByProgram) +# Extend in your own module (e.g. SessionsByProgram_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for SessionsByProgram (#248).""" + +from __future__ import annotations + +from typing import Final + +SESSIONSBYPROGRAM_TYPE: Final[str] = "object" +SESSIONSBYPROGRAM_SUB_TYPE: Final[str] = "report" +SESSIONSBYPROGRAM_NAME: Final[str] = "SessionsByProgram" + +SESSIONSBYPROGRAM_SOURCE_PRIMARY_TYPE: Final[str] = "source" +SESSIONSBYPROGRAM_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +SESSIONSBYPROGRAM_SOURCE_PRIMARY_KIND: Final[str] = "view" +SESSIONSBYPROGRAM_SOURCE_PRIMARY_VIEW: Final[str] = "v_sessions_by_program" + +SESSIONSBYPROGRAM_PROGRAM_TITLE_FIELD: Final[str] = "programTitle" +SESSIONSBYPROGRAM_PROGRAM_TITLE_COLUMN: Final[str] = "program_title" +SESSIONSBYPROGRAM_SESSION_MINUTES_FIELD: Final[str] = "sessionMinutes" +SESSIONSBYPROGRAM_SESSION_MINUTES_COLUMN: Final[str] = "session_minutes" +SESSIONSBYPROGRAM_SESSIONS_FIELD: Final[str] = "sessions" +SESSIONSBYPROGRAM_SESSIONS_COLUMN: Final[str] = "sessions" +SESSIONSBYPROGRAM_WEEK_KEY_FIELD: Final[str] = "weekKey" +SESSIONSBYPROGRAM_WEEK_KEY_COLUMN: Final[str] = "week_key" + +SESSIONSBYPROGRAM_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "programTitle": SESSIONSBYPROGRAM_PROGRAM_TITLE_COLUMN, + "sessionMinutes": SESSIONSBYPROGRAM_SESSION_MINUTES_COLUMN, + "sessions": SESSIONSBYPROGRAM_SESSIONS_COLUMN, + "weekKey": SESSIONSBYPROGRAM_WEEK_KEY_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/sessions_by_program_router.py b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_router.py new file mode 100644 index 0000000000..e7f7325cf6 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/sessions_by_program_router.py @@ -0,0 +1,189 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: SessionsByProgram (fitness::SessionsByProgram) +# Extend in your own module (e.g. SessionsByProgram_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the SessionsByProgram report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .sessions_by_program_filter_allowlist import ( + SESSIONSBYPROGRAM_FILTER_FIELDS, + SESSIONSBYPROGRAM_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/sessions_by_programs", tags=["sessions_by_programs"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programTitle", + "weekKey", + "sessions", + "sessionMinutes", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class SessionsByProgramRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> SessionsByProgramRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_sessions_by_programs( + request: Request, + repo: Annotated[SessionsByProgramRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, + SESSIONSBYPROGRAM_FILTER_FIELDS, + SESSIONSBYPROGRAM_FILTER_OPS_BY_FIELD, + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_sessions_by_program() -> Any: + """GENERATED — sessions_by_programs is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/golden_generators/expected/tag_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/tag_filter_allowlist.py new file mode 100644 index 0000000000..b3d872e439 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/tag_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Tag (fitness::Tag) +# Extend in your own module (e.g. Tag_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Tag. + +TAG_FILTER_FIELDS lists the filterable field names; TAG_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +TAG_FILTER_FIELDS: frozenset[str] = frozenset() + +TAG_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/tag_names.py b/server/python/tests/codegen/golden_generators/expected/tag_names.py new file mode 100644 index 0000000000..ad185697e1 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/tag_names.py @@ -0,0 +1,31 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Tag (fitness::Tag) +# Extend in your own module (e.g. Tag_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Tag (#248).""" + +from __future__ import annotations + +from typing import Final + +TAG_TYPE: Final[str] = "object" +TAG_SUB_TYPE: Final[str] = "entity" +TAG_NAME: Final[str] = "Tag" + +TAG_SOURCE_PRIMARY_TYPE: Final[str] = "source" +TAG_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +TAG_SOURCE_PRIMARY_KIND: Final[str] = "table" +TAG_SOURCE_PRIMARY_TABLE: Final[str] = "tags" + +TAG_ID_FIELD: Final[str] = "id" +TAG_ID_COLUMN: Final[str] = "id" +TAG_NAME_FIELD: Final[str] = "name" +TAG_NAME_COLUMN: Final[str] = "name" + +TAG_IDENTITY_ID_TYPE: Final[str] = "identity" +TAG_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +TAG_IDENTITY_ID_NAME: Final[str] = "id" + +TAG_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "id": TAG_ID_COLUMN, + "name": TAG_NAME_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/tag_router.py b/server/python/tests/codegen/golden_generators/expected/tag_router.py new file mode 100644 index 0000000000..42956eec33 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/tag_router.py @@ -0,0 +1,324 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Tag (fitness::Tag) +# Extend in your own module (e.g. Tag_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Tag entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Tag import TagCreate, TagPatch +from .tag_filter_allowlist import TAG_FILTER_FIELDS, TAG_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/tags", tags=["tags"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "name", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "name", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "name", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class TagRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + + +def get_repository() -> TagRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_tags( + request: Request, + repo: Annotated[TagRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, TAG_FILTER_FIELDS, TAG_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{tag_id}") +def get_tag( + tag_id: int, + repo: Annotated[TagRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(tag_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_tag( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[TagRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = TagCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{tag_id}") +@router.put("/{tag_id}") +def update_tag( + tag_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[TagRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = TagPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(tag_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{tag_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_tag( + tag_id: int, + repo: Annotated[TagRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(tag_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/week_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/week_filter_allowlist.py new file mode 100644 index 0000000000..da68f6232a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_filter_allowlist.py @@ -0,0 +1,14 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Week (fitness::Week) +# Extend in your own module (e.g. Week_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for Week. + +WEEK_FILTER_FIELDS lists the filterable field names; WEEK_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +WEEK_FILTER_FIELDS: frozenset[str] = frozenset() + +WEEK_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = {} diff --git a/server/python/tests/codegen/golden_generators/expected/week_names.py b/server/python/tests/codegen/golden_generators/expected/week_names.py new file mode 100644 index 0000000000..fc4c83333a --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_names.py @@ -0,0 +1,43 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Week (fitness::Week) +# Extend in your own module (e.g. Week_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for Week (#248).""" + +from __future__ import annotations + +from typing import Final + +WEEK_TYPE: Final[str] = "object" +WEEK_SUB_TYPE: Final[str] = "entity" +WEEK_NAME: Final[str] = "Week" + +WEEK_SOURCE_PRIMARY_TYPE: Final[str] = "source" +WEEK_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +WEEK_SOURCE_PRIMARY_KIND: Final[str] = "table" +WEEK_SOURCE_PRIMARY_TABLE: Final[str] = "weeks" + +WEEK_DELOAD_FIELD: Final[str] = "deload" +WEEK_DELOAD_COLUMN: Final[str] = "deload" +WEEK_DURATION_MINUTES_FIELD: Final[str] = "durationMinutes" +WEEK_DURATION_MINUTES_COLUMN: Final[str] = "duration_minutes" +WEEK_ID_FIELD: Final[str] = "id" +WEEK_ID_COLUMN: Final[str] = "id" +WEEK_LABEL_FIELD: Final[str] = "label" +WEEK_LABEL_COLUMN: Final[str] = "label" +WEEK_PROGRAM_ID_FIELD: Final[str] = "programId" +WEEK_PROGRAM_ID_COLUMN: Final[str] = "program_id" + +WEEK_IDENTITY_FK_PROGRAM_TYPE: Final[str] = "identity" +WEEK_IDENTITY_FK_PROGRAM_SUB_TYPE: Final[str] = "reference" +WEEK_IDENTITY_FK_PROGRAM_NAME: Final[str] = "fkProgram" +WEEK_IDENTITY_ID_TYPE: Final[str] = "identity" +WEEK_IDENTITY_ID_SUB_TYPE: Final[str] = "primary" +WEEK_IDENTITY_ID_NAME: Final[str] = "id" + +WEEK_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "deload": WEEK_DELOAD_COLUMN, + "durationMinutes": WEEK_DURATION_MINUTES_COLUMN, + "id": WEEK_ID_COLUMN, + "label": WEEK_LABEL_COLUMN, + "programId": WEEK_PROGRAM_ID_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/week_router.py b/server/python/tests/codegen/golden_generators/expected/week_router.py new file mode 100644 index 0000000000..739e7d2337 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_router.py @@ -0,0 +1,333 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: Week (fitness::Week) +# Extend in your own module (e.g. Week_extra.py) — nothing imports it for you. +"""GENERATED — REST router for Week entity. Implements the cross-port API contract. + +Auth: these endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request, status +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ValidationError + +from metaobjects.codegen.runtime.constraint_errors import ( + classify_constraint_error, + pydantic_issues, + required_null_issues, + unknown_body_keys, + unreadable_body_issues, + validation_envelope, + value_error_issues, +) +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_fields, + coerce_decimal_predicates, + parse_json_object, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .Week import WeekCreate, WeekPatch +from .week_filter_allowlist import WEEK_FILTER_FIELDS, WEEK_FILTER_OPS_BY_FIELD + +router = APIRouter(prefix="/api/weeks", tags=["weeks"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "id", + "programId", + "label", + "durationMinutes", + "deload", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_REQUIRED_FIELDS: frozenset[str] = frozenset( + { + "programId", + "durationMinutes", + } +) + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_DECIMAL_LIMITS: dict[str, tuple[int, int]] = {} + + +_NESTED_DECIMALS: dict[str, Any] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +async def _json_body(request: Request) -> dict[str, Any] | None: + """GENERATED — the request body as a JSON object (non-integer numbers are exact `Decimal`s), or None.""" + try: + return parse_json_object(await request.body()) + except ValueError: + return None + + +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + +_FROZEN_FIELDS: frozenset[str] = frozenset() + + +_KNOWN_FIELDS: frozenset[str] = frozenset( + { + "id", + "programId", + "label", + "durationMinutes", + "deload", + } +) + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class WeekRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + def find_by_id(self, id: int) -> Any | None: ... + def create(self, dto: Any) -> Any: ... + def update(self, id: int, dto: Any) -> Any | None: ... + def delete(self, id: int) -> bool: ... + def find_weeks_by_program(self, program_id: Any) -> _list[Any]: ... + def find_weeks_by_program_in(self, program_id_values: _list[Any]) -> _list[Any]: ... + + +def get_repository() -> WeekRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_weeks( + request: Request, + repo: Annotated[WeekRepository, Depends(get_repository)], + limit: int | None = Query(None), + offset: int | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + actual_limit = limit if limit is not None else 50 + actual_offset = offset if offset is not None else 0 + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, WEEK_FILTER_FIELDS, WEEK_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + rows = repo.list(actual_limit, actual_offset, sort_clause, predicates) + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.get("/{week_id}") +def get_week( + week_id: int, + repo: Annotated[WeekRepository, Depends(get_repository)], +) -> Any: + row = repo.find_by_id(week_id) + if row is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(row, _WIRE) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_week( + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[WeekRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-036: run the generated field constraints (length / pattern / + # numeric bounds) before persisting; a violation is the cross-port 400. + try: + _valid = WeekCreate(**dto) + except ValidationError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(pydantic_issues(_exc.errors())) + ) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + return render_wire(repo.create(dto), _WIRE) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + + +@router.patch("/{week_id}") +@router.put("/{week_id}") +def update_week( + week_id: int, + dto: Annotated[dict[str, Any] | None, Depends(_json_body)], + repo: Annotated[WeekRepository, Depends(get_repository)], +) -> Any: + if ( + dto is None + ): # the body was not a JSON object: the cross-port 400, not FastAPI's 422 + return JSONResponse( + status_code=400, content=validation_envelope(unreadable_body_issues()) + ) + _unknown = unknown_body_keys(dto, _KNOWN_FIELDS) + if _unknown: + return JSONResponse( + status_code=400, content={"error": "unknown_fields", "fields": _unknown} + ) + try: + dto = coerce_decimal_fields( + dto, _DECIMAL_FIELDS, _DECIMAL_LIMITS, _NESTED_DECIMALS + ) + except ValueError as _exc: + return JSONResponse( + status_code=400, content=validation_envelope(value_error_issues(_exc)) + ) + # FR-035 PATCH-2: an explicit null on a @required field is a 400 — a present + # null on a NON-required field falls through and clears it, and an OMITTED + # required field is untouched (never a 400). + # FR-036: validate PRESENT, non-null values with the create rules (the + # all-optional patch model never fires required-checks on ABSENT fields). + _issues = required_null_issues(dto, _REQUIRED_FIELDS) + try: + _valid = WeekPatch(**dto) + except ValidationError as _exc: + _issues += pydantic_issues(_exc.errors()) + if _issues: + return JSONResponse(status_code=400, content=validation_envelope(_issues)) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) + try: + saved = repo.update(week_id, dto) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if saved is None: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return render_wire(saved, _WIRE) + + +@router.delete("/{week_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_week( + week_id: int, + repo: Annotated[WeekRepository, Depends(get_repository)], +) -> Response: + try: + deleted = repo.delete(week_id) + except Exception as exc: + failure = classify_constraint_error(exc) + if failure is None: + raise + return JSONResponse(status_code=failure.status, content=failure.body()) + if not deleted: + return JSONResponse(status_code=404, content={"error": "not_found"}) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/server/python/tests/codegen/golden_generators/expected/week_shapes_filter_allowlist.py b/server/python/tests/codegen/golden_generators/expected/week_shapes_filter_allowlist.py new file mode 100644 index 0000000000..911dcbaa5e --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_shapes_filter_allowlist.py @@ -0,0 +1,34 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: WeekShapes (fitness::WeekShapes) +# Extend in your own module (e.g. WeekShapes_extra.py) — nothing imports it for you. +"""GENERATED — per-entity FR-009 filter allowlist for WeekShapes. + +WEEKSHAPES_FILTER_FIELDS lists the filterable field names; WEEKSHAPES_FILTER_OPS_BY_FIELD +constrains the operator vocabulary for each field by its subtype. +""" + +from __future__ import annotations + +WEEKSHAPES_FILTER_FIELDS: frozenset[str] = frozenset( + { + "programTitle", + "weeks", + "unlabelled", + "labelledMinutes", + "shortWeeks", + "midWeeks", + "longWMinutes", + }, +) + +WEEKSHAPES_FILTER_OPS_BY_FIELD: dict[str, frozenset[str]] = { + "programTitle": frozenset({"eq", "ne", "in", "like", "isNull"}), + "weeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "unlabelled": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "labelledMinutes": frozenset( + {"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}, + ), + "shortWeeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "midWeeks": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), + "longWMinutes": frozenset({"eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"}), +} diff --git a/server/python/tests/codegen/golden_generators/expected/week_shapes_names.py b/server/python/tests/codegen/golden_generators/expected/week_shapes_names.py new file mode 100644 index 0000000000..938362f376 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_shapes_names.py @@ -0,0 +1,42 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: WeekShapes (fitness::WeekShapes) +# Extend in your own module (e.g. WeekShapes_extra.py) — nothing imports it for you. +"""GENERATED — per-object physical database names for WeekShapes (#248).""" + +from __future__ import annotations + +from typing import Final + +WEEKSHAPES_TYPE: Final[str] = "object" +WEEKSHAPES_SUB_TYPE: Final[str] = "report" +WEEKSHAPES_NAME: Final[str] = "WeekShapes" + +WEEKSHAPES_SOURCE_PRIMARY_TYPE: Final[str] = "source" +WEEKSHAPES_SOURCE_PRIMARY_SUB_TYPE: Final[str] = "rdb" +WEEKSHAPES_SOURCE_PRIMARY_KIND: Final[str] = "view" +WEEKSHAPES_SOURCE_PRIMARY_VIEW: Final[str] = "v_week_shapes" + +WEEKSHAPES_LABELLED_MINUTES_FIELD: Final[str] = "labelledMinutes" +WEEKSHAPES_LABELLED_MINUTES_COLUMN: Final[str] = "labelled_minutes" +WEEKSHAPES_LONG_W_MINUTES_FIELD: Final[str] = "longWMinutes" +WEEKSHAPES_LONG_W_MINUTES_COLUMN: Final[str] = "long_w_minutes" +WEEKSHAPES_MID_WEEKS_FIELD: Final[str] = "midWeeks" +WEEKSHAPES_MID_WEEKS_COLUMN: Final[str] = "mid_weeks" +WEEKSHAPES_PROGRAM_TITLE_FIELD: Final[str] = "programTitle" +WEEKSHAPES_PROGRAM_TITLE_COLUMN: Final[str] = "program_title" +WEEKSHAPES_SHORT_WEEKS_FIELD: Final[str] = "shortWeeks" +WEEKSHAPES_SHORT_WEEKS_COLUMN: Final[str] = "short_weeks" +WEEKSHAPES_UNLABELLED_FIELD: Final[str] = "unlabelled" +WEEKSHAPES_UNLABELLED_COLUMN: Final[str] = "unlabelled" +WEEKSHAPES_WEEKS_FIELD: Final[str] = "weeks" +WEEKSHAPES_WEEKS_COLUMN: Final[str] = "weeks" + +WEEKSHAPES_COLUMNS_BY_FIELD: Final[dict[str, str]] = { + "labelledMinutes": WEEKSHAPES_LABELLED_MINUTES_COLUMN, + "longWMinutes": WEEKSHAPES_LONG_W_MINUTES_COLUMN, + "midWeeks": WEEKSHAPES_MID_WEEKS_COLUMN, + "programTitle": WEEKSHAPES_PROGRAM_TITLE_COLUMN, + "shortWeeks": WEEKSHAPES_SHORT_WEEKS_COLUMN, + "unlabelled": WEEKSHAPES_UNLABELLED_COLUMN, + "weeks": WEEKSHAPES_WEEKS_COLUMN, +} diff --git a/server/python/tests/codegen/golden_generators/expected/week_shapes_router.py b/server/python/tests/codegen/golden_generators/expected/week_shapes_router.py new file mode 100644 index 0000000000..4d3fd9da76 --- /dev/null +++ b/server/python/tests/codegen/golden_generators/expected/week_shapes_router.py @@ -0,0 +1,190 @@ +# @generated by metaobjects — DO NOT EDIT. +# Source metadata: WeekShapes (fitness::WeekShapes) +# Extend in your own module (e.g. WeekShapes_extra.py) — nothing imports it for you. +"""GENERATED — read-only REST router for the WeekShapes report. + +Implements the cross-port API contract: GET list only (the resource has no +identity, so no item route); POST answers 405 {"error": "method_not_allowed"}. + +Auth: these read endpoints are unauthenticated. To guard them, include the router with a +dependency, e.g. `app.include_router(router, dependencies=[Depends(require_auth)])`. + +A row-ownership rule ("only the owner may read this row") cannot be expressed as a +router dependency: eject this generator with `metaobjects eject` and hand-write +those endpoints. +""" + +from __future__ import annotations + +from builtins import list as _list +from typing import Annotated, Any, Protocol + +from fastapi import APIRouter, Depends, Query, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from metaobjects.codegen.runtime.decimal_wire import ( + WireOutput, + coerce_decimal_predicates, + render_wire, +) +from metaobjects.codegen.runtime.filter_parser import ( + FilterPredicate, + parse_filter, +) + +from .week_shapes_filter_allowlist import ( + WEEKSHAPES_FILTER_FIELDS, + WEEKSHAPES_FILTER_OPS_BY_FIELD, +) + +router = APIRouter(prefix="/api/week_shapes", tags=["week_shapes"]) + + +class _SortClause(BaseModel): + """GENERATED — parsed sort directive (field + asc/desc).""" + + field: str + direction: str + + +_SORT_ALLOWLIST: set[str] = { + "programTitle", + "weeks", + "unlabelled", + "labelledMinutes", + "shortWeeks", + "midWeeks", + "longWMinutes", +} + + +_SORT_DEFAULT_ORDER: dict[str, str] = {} + + +_DECIMAL_FIELDS: frozenset[str] = frozenset() +_DURATION_FIELDS: dict[str, object] = {} + + +_WIRE = WireOutput(decimals="string", null_members="omit") + + +def _parse_sort(raw: str) -> _SortClause | None: + """Parse `field:asc|desc`; return None for malformed / disallowed input.""" + parts = raw.split(":", 1) + if not parts or parts[0] not in _SORT_ALLOWLIST: + return None + direction = ( + parts[1].lower() + if len(parts) == 2 + else _SORT_DEFAULT_ORDER.get(parts[0], "asc") + ) + if direction not in ("asc", "desc"): + return None + return _SortClause(field=parts[0], direction=direction) + + +class WeekShapesRepository(Protocol): + """GENERATED — consumer implements with their preferred persistence layer. + + Read-only: a report is not writable, so the seam offers no + create / update / delete.""" + + def list( + self, + limit: int, + offset: int, + sort: _SortClause | None, + filters: _list[FilterPredicate], + ) -> _list[Any]: ... + def count(self, filters: _list[FilterPredicate]) -> int: ... + + +def get_repository() -> WeekShapesRepository: + """GENERATED — consumer overrides via `app.dependency_overrides[get_repository]`.""" + raise NotImplementedError( + "Override get_repository via FastAPI dependency_overrides in the consumer app" + ) + + +@router.get("") +def list_week_shapes( + request: Request, + repo: Annotated[WeekShapesRepository, Depends(get_repository)], + limit: str | None = Query(None), + offset: str | None = Query(None), + sort: str | None = Query(None), + with_count: int | None = Query(None, alias="withCount"), +) -> Any: + max_rows = 10000 + too_large = JSONResponse( + status_code=400, content={"error": "report_too_large", "maxRows": max_rows} + ) + requested_limit: int | None = None + if limit is not None: + if not (limit.isascii() and limit.isdigit()) or int(limit) < 1: + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "limit", + "value": limit, + "expected": f"an integer from 1 to {max_rows}", + }, + ) + requested_limit = int(limit) + if requested_limit > max_rows: + return too_large + actual_offset = 0 + if offset is not None: + if not (offset.isascii() and offset.isdigit()): + return JSONResponse( + status_code=400, + content={ + "error": "pagination.invalid_value", + "param": "offset", + "value": offset, + "expected": "a non-negative integer (0 or more)", + }, + ) + actual_offset = int(offset) + sort_clause: _SortClause | None = None + if sort is not None: + sort_clause = _parse_sort(sort) + if sort_clause is None: + return JSONResponse( + status_code=400, + content={"error": "invalid_sort", "field": sort.split(":", 1)[0]}, + ) + filter_result = parse_filter( + request.query_params, WEEKSHAPES_FILTER_FIELDS, WEEKSHAPES_FILTER_OPS_BY_FIELD + ) + if filter_result.error_envelope is not None: + return JSONResponse(status_code=400, content=filter_result.error_envelope) + predicates, decimal_error = coerce_decimal_predicates( + filter_result.predicates, _DECIMAL_FIELDS, _DURATION_FIELDS + ) + if decimal_error is not None: + return JSONResponse(status_code=400, content=decimal_error) + # With no limit the repository is asked for one row past the cap, so the + # refusal comes before any body is written. + fetch_limit = requested_limit if requested_limit is not None else max_rows + 1 + rows = repo.list(fetch_limit, actual_offset, sort_clause, predicates) + if requested_limit is None and len(rows) > max_rows: + return too_large + if with_count == 1: + total = repo.count(predicates) + return {"rows": render_wire(rows, _WIRE), "total": total} + return render_wire(rows, _WIRE) + + +@router.post("") +def create_week_shapes() -> Any: + """GENERATED — week_shapes is a read-only report; writes are rejected.""" + return JSONResponse( + status_code=405, + content={ + "error": "method_not_allowed", + "message": "POST is not supported on a report (read-only).", + }, + ) diff --git a/server/python/tests/codegen/layout_ratchet/__init__.py b/server/python/tests/codegen/layout_ratchet/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/server/python/tests/codegen/layout_ratchet/allowlist.json b/server/python/tests/codegen/layout_ratchet/allowlist.json new file mode 100644 index 0000000000..66c1384b74 --- /dev/null +++ b/server/python/tests/codegen/layout_ratchet/allowlist.json @@ -0,0 +1,23 @@ +{ + "$comment": "The Python layout ratchet's allowlist (ADR-0063). `unconverted`: generator source that still types its own layout; each entry names what it emits and the writer change that converts it, and is removed when that change lands (the test fails while a converted file keeps its entry). `exempt`: source that writes text which is not generated code; each says why. Neither list may grow: test_layout_ratchet.py compares it with the copy at the branch's merge base. Paths are relative to src/metaobjects/codegen.", + "unconverted": { + "generators/entity_model.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Entity model: W-PY-2.", + "generators/extractor_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Extractor tier.", + "generators/names_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Names tier.", + "generators/output_parser_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Output parser tier.", + "generators/render_helper_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Render helper tier.", + "generators/requirement_tests_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Requirement tests tier.", + "generators/router_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Router (2,409 lines, its own PR): W-PY-3.", + "generators/trace_helper_generator.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Trace helper tier.", + "runtime/api_docs_renderer.py": "Renders the API docs page text with typed line breaks; converts with the docs-emitter slice of the writer work (ADR-0063).", + "runtime/extract_delegate_emitter.py": "Types its own layout into emitted Python; converts with the Python writer PR for this generator (ADR-0063). Extract delegate tier.", + "runtime/extract_schema_emitter.py": "Types the all-nullable mirror dataclass as indented source lines that the unconverted extractor and output parser generators splice in; converts with them (ADR-0063)." + }, + "exempt": { + "eject.py": "Writes the lines `eject` prints to the terminal (what was copied, kept or removed); it is a message for people, not generated code.", + "model_key.py": "Joins lines into the text a hash is taken over; the text is never written to a file, so its separator is not layout.", + "overwrite_policy.py": "Writes the hash manifest (JSON) and re-joins hand-edited lines for a three-way merge; neither is generated source code.", + "requirement_walk.py": "Builds the digest input a requirement hash is taken over; the text is never written to a file, so its line breaks are not layout.", + "skip.py": "Hashes the skip list and writes its one-per-line manifest file; the manifest is data, not generated source code." + } +} diff --git a/server/python/tests/codegen/layout_ratchet/analyze.py b/server/python/tests/codegen/layout_ratchet/analyze.py new file mode 100644 index 0000000000..6ff0b9572b --- /dev/null +++ b/server/python/tests/codegen/layout_ratchet/analyze.py @@ -0,0 +1,207 @@ +"""The layout ratchet's analyzer (ADR-0063): finds layout a generator typed by hand. + +Generators say what a line contains and the writer decides where it sits, so generator +source should never spell a line break or an indentation run. This reads a source file with +Python's own parser (``ast``) and walks the syntax tree. Working on the tree, not the text, +is what makes the rules exact: comments are never nodes, a string's value is the parser's +value (so ``"\\n"`` and a line break inside a triple-quoted string are the same finding), and +a constant is followed to its same-file assignment, so ``NL = "\\n"; NL.join(xs)`` is a +finding at the join as well as at the assignment. + +Four rules (the same four as every port's ratchet): + + newline-literal a string, or one part of an f-string, whose value contains a line break. + indent-literal a string (or the head of an f-string) that begins with an indentation run: + two or more spaces, or a tab. + newline-join ``sep.join(xs)`` whose separator contains a line break, the separator + resolved through same-file constants. + indent-repeat ``s * n`` where ``s`` resolves to whitespace: building indentation. + +Places a literal is not output, and so is not layout, are ruled out by position: + + - a docstring (the first statement of a module, class or function); + - a search pattern: the first argument of ``split``, ``rsplit``, ``find``, ``rfind``, + ``index``, ``count``, ``startswith``, ``endswith``, ``replace``, ``partition``, + ``strip``, ``lstrip`` or ``rstrip``; + - a comparison operand (``x == "\\n"``, ``"\\n" in x``): it is read, not written; + - a writer snippet: the argument of a ``.text(...)`` call, the writer's entry for fixed code + written as it should read. +""" +from __future__ import annotations + +import ast +import re +from dataclasses import dataclass +from pathlib import Path + +LINE_BREAK = re.compile(r"[\r\n]") +INDENT_RUN = re.compile(r"^(?: {2,}|\t)") +WHITESPACE = re.compile(r"^[ \t\r\n]+$") +SEARCH_METHODS = frozenset( + { + "split", "rsplit", "splitlines", "find", "rfind", "index", "rindex", "count", + "startswith", "endswith", "replace", "partition", "rpartition", "strip", "lstrip", + "rstrip", + } +) +SNIPPET_METHOD = "text" +MAX_RESOLVE_DEPTH = 8 + + +@dataclass(frozen=True) +class Finding: + kind: str + line: int + column: int + excerpt: str + + +@dataclass(frozen=True) +class _Resolved: + text: str + complete: bool + + +def analyze_source(source: str, filename: str = "") -> list[Finding]: + return _Analyzer(source, filename).run() + + +def is_generator_source(relative: Path) -> bool: + """Scope by rule, not by list: every module under ``codegen/`` except the writer.""" + parts = relative.parts + return relative.suffix == ".py" and "writer" not in parts and "__pycache__" not in parts + + +class _Analyzer: + def __init__(self, source: str, filename: str) -> None: + self.tree = ast.parse(source, filename) + self.lines = source.splitlines() + self.findings: list[Finding] = [] + self.skip: set[int] = set() + self.consts: dict[str, ast.expr] = {} + + def run(self) -> list[Finding]: + for node in ast.walk(self.tree): + if isinstance(node, ast.Assign) and len(node.targets) == 1: + t = node.targets[0] + if isinstance(t, ast.Name): + self.consts[t.id] = node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value: + self.consts[node.target.id] = node.value + self._mark_skips() + for node in ast.walk(self.tree): + self._visit(node) + self.findings.sort(key=lambda f: (f.line, f.column, f.kind)) + return self.findings + + # ── positions that are not output ──────────────────────────────────────────────── + + def _skip_tree(self, node: ast.AST) -> None: + for n in ast.walk(node): + self.skip.add(id(n)) + + def _mark_skips(self) -> None: + for node in ast.walk(self.tree): + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + body = node.body + if ( + body + and isinstance(body[0], ast.Expr) + and isinstance(body[0].value, ast.Constant) + and isinstance(body[0].value.value, str) + ): + self._skip_tree(body[0].value) + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): + if node.func.attr in SEARCH_METHODS and node.args: + self._skip_tree(node.args[0]) + elif node.func.attr == SNIPPET_METHOD: + for a in node.args: + self._skip_tree(a) + elif isinstance(node, ast.Compare): + self._skip_tree(node.left) + for c in node.comparators: + self._skip_tree(c) + + # ── the rules ──────────────────────────────────────────────────────────────────── + + def _add(self, kind: str, node: ast.AST) -> None: + line = getattr(node, "lineno", 1) + col = getattr(node, "col_offset", 0) + 1 + text = self.lines[line - 1].strip() if 0 < line <= len(self.lines) else "" + self.findings.append(Finding(kind, line, col, text[:80])) + + def _visit(self, node: ast.AST) -> None: + if isinstance(node, ast.Constant) and isinstance(node.value, str): + if id(node) in self.skip: + return + if LINE_BREAK.search(node.value): + self._add("newline-literal", node) + if self._starts_a_line(node) and INDENT_RUN.match(node.value): + self._add("indent-literal", node) + elif isinstance(node, ast.Call): + f = node.func + if isinstance(f, ast.Attribute) and f.attr == "join" and id(node) not in self.skip: + r = self._resolve(f.value) + if r is not None and LINE_BREAK.search(r.text): + self._add("newline-join", node) + elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult): + if id(node) in self.skip: + return + for side, other in ((node.left, node.right), (node.right, node.left)): + r = self._resolve(side) + if r is not None and r.complete and r.text and WHITESPACE.match(r.text): + if not self._is_string(other): + self._add("indent-repeat", node) + break + + def _starts_a_line(self, node: ast.Constant) -> bool: + """A string is the head of its output unless it is a later part of an f-string.""" + parent = self.parents.get(id(node)) if hasattr(self, "parents") else None + if isinstance(parent, ast.JoinedStr): + return parent.values[0] is node + return True + + @property + def parents(self) -> dict[int, ast.AST]: + if "_parents" not in self.__dict__: + m: dict[int, ast.AST] = {} + for p in ast.walk(self.tree): + for c in ast.iter_child_nodes(p): + m[id(c)] = p + self.__dict__["_parents"] = m + return self.__dict__["_parents"] + + def _is_string(self, node: ast.expr) -> bool: + r = self._resolve(node) + return r is not None and r.complete + + # ── a constant cannot hide a line break ────────────────────────────────────────── + + def _resolve(self, node: ast.expr, depth: int = 0) -> _Resolved | None: + if depth > MAX_RESOLVE_DEPTH: + return None + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return _Resolved(node.value, True) + if isinstance(node, ast.Name) and node.id in self.consts: + return self._resolve(self.consts[node.id], depth + 1) + if isinstance(node, ast.JoinedStr): + text, complete = "", True + for v in node.values: + if isinstance(v, ast.Constant) and isinstance(v.value, str): + text += v.value + else: + complete = False + return _Resolved(text, complete) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + a, b = self._resolve(node.left, depth + 1), self._resolve(node.right, depth + 1) + if a is None and b is None: + return None + return _Resolved((a.text if a else "") + (b.text if b else ""), bool(a and b and a.complete and b.complete)) + if isinstance(node, ast.IfExp): + a, b = self._resolve(node.body, depth + 1), self._resolve(node.orelse, depth + 1) + if a is None and b is None: + return None + # Either branch of a conditional separator counts. + text = (a.text if a else "") if (a and LINE_BREAK.search(a.text)) else (b.text if b else "") + return _Resolved(text, False) + return None diff --git a/server/python/tests/codegen/manifest_helpers.py b/server/python/tests/codegen/manifest_helpers.py index 47fc1620f1..66f658ec37 100644 --- a/server/python/tests/codegen/manifest_helpers.py +++ b/server/python/tests/codegen/manifest_helpers.py @@ -27,5 +27,17 @@ def read_manifest(gen_state: Path) -> dict[str, object]: return merged +def record_entry(gen_state: Path, rel: str, digest: str = "0" * 64) -> None: + """Add a write record for ``rel`` to the root manifest file in ``.hashes/``, the way the + product files an entry no package claims (ADR-0064 Amendment 1).""" + from metaobjects.codegen.overwrite_policy import HASHES_DIR, ROOT_MANIFEST + + path = gen_state / HASHES_DIR / ROOT_MANIFEST + entries = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + entries[rel] = digest + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(entries, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + def has_manifest(gen_state: Path) -> bool: return (gen_state / ".hashes.json").exists() or bool(manifest_files(gen_state)) diff --git a/server/python/tests/codegen/test_cli_config_verify.py b/server/python/tests/codegen/test_cli_config_verify.py index 511b06500f..d612d7298f 100644 --- a/server/python/tests/codegen/test_cli_config_verify.py +++ b/server/python/tests/codegen/test_cli_config_verify.py @@ -8,6 +8,7 @@ from metaobjects.cli import main from tests.codegen.gen_suite import GEN_SUITE from tests.codegen.config_helpers import as_config +from tests.codegen.manifest_helpers import record_entry CANONICAL = Path(__file__).parents[4] / "fixtures" / "persistence-conformance" / "canonical" FITNESS = CANONICAL / "meta.fitness.json" @@ -130,11 +131,7 @@ def _record_as_written(tmp_path: Path, rel: str) -> None: look like something MetaObjects WROTE on an earlier run. That is what makes a committed file a STALE artifact rather than a stranger, and the two now have different verdicts (see the jurisdiction rule in ``cli._is_ours_for``).""" - manifest = tmp_path / ".metaobjects" / ".gen-state" / ".hashes.json" - hashes = json.loads(manifest.read_text()) if manifest.exists() else {} - hashes[rel] = "0" * 64 - manifest.parent.mkdir(parents=True, exist_ok=True) - manifest.write_text(json.dumps(hashes, indent=2, sort_keys=True) + "\n") + record_entry(tmp_path / ".metaobjects" / ".gen-state", rel) def test_verify_codegen_shared_outdir_detects_stale_extra(tmp_path: Path, capsys) -> None: diff --git a/server/python/tests/codegen/test_cli_registry.py b/server/python/tests/codegen/test_cli_registry.py index 4f8ae2c1ff..92a67c892b 100644 --- a/server/python/tests/codegen/test_cli_registry.py +++ b/server/python/tests/codegen/test_cli_registry.py @@ -40,8 +40,8 @@ def test_gen_list_prints_all_and_exits_zero(capsys, tmp_path: Path) -> None: # Every registered stable name appears in the listing. for name in GENERATOR_REGISTRY: assert name in out, f"--list omitted {name!r}" - # Exactly the 12 python-slice names are registered (ADR-0056 removed `payload`). - assert len(GENERATOR_REGISTRY) == 13 + # Exactly the 14 registered names (ADR-0056 removed `payload`; FR-023 added `shared-model`) + assert len(GENERATOR_REGISTRY) == 14 assert "payload" not in GENERATOR_REGISTRY # A template-tier generator says it needs the entity generator's models. assert "output-parser — " in out diff --git a/server/python/tests/codegen/test_config_run_settings.py b/server/python/tests/codegen/test_config_run_settings.py index 1762909c3b..78422f220e 100644 --- a/server/python/tests/codegen/test_config_run_settings.py +++ b/server/python/tests/codegen/test_config_run_settings.py @@ -5,7 +5,7 @@ Through 1.1.0's release candidates the column naming was a flag, then briefly a ``columnNaming`` key in ``metaobjects.config.yaml`` — that key never shipped and is refused outright (ADR-0058 Decision 4), same as the ``--column-naming`` flag and -``ObjectManager(column_naming=...)``. The migration guide replaced a script's +``ObjectManagerDb(column_naming=...)``. The migration guide replaced a script's ``metaobjects gen --out ... --generators ...`` with a plain ``metaobjects gen`` once the config declared the generator list, and that plain run used this port's old default, ``literal``: it rewrote every ``*_names.py`` with camelCase column names the diff --git a/server/python/tests/codegen/test_eject_alone.py b/server/python/tests/codegen/test_eject_alone.py index ad767376e7..ca3849ef10 100644 --- a/server/python/tests/codegen/test_eject_alone.py +++ b/server/python/tests/codegen/test_eject_alone.py @@ -90,9 +90,13 @@ def test_eject_writes_the_generator_and_the_helpers_its_entry_lists(name: str, t } -def _model_project(root: Path, generators: str) -> Path: +#: Options a generator cannot run without; the entry is written as a mapping that carries them. +_REQUIRED_OPTIONS = {"shared-model": '{name: depth, include: ["**"], version: "1.0.0", files: [metaobjects/meta.fitness.json]}'} + + +def _model_project(root: Path, generators: str, options: str | None = None) -> Path: """A project over every metadata shape the ejectable generators read, with one target - that runs *generators*.""" + that runs *generators* (given *options*, as a ``generators`` entry mapping).""" meta = root / "metaobjects" meta.mkdir(parents=True) canonical = FIXTURES / "persistence-conformance" / "canonical" / "meta.fitness.json" @@ -107,7 +111,8 @@ def _model_project(root: Path, generators: str) -> Path: shop = FIXTURES / "requirement-test-identity-conformance" / "worked-example" / "input" for doc in shop.iterdir(): (meta / doc.name).write_text(doc.read_text(encoding="utf-8"), encoding="utf-8") - config = f"libraries: [ai]\ntargets:\n main:\n outDir: gen\n generators: [{generators}]\n" + entry = generators if options is None else f'{{name: "{generators}", options: {options}}}' + config = f"libraries: [ai]\ntargets:\n main:\n outDir: gen\n generators: [{entry}]\n" (root / "metaobjects.config.yaml").write_text(config, encoding="utf-8") return root @@ -170,11 +175,11 @@ def test_an_ejected_generator_writes_what_the_packaged_one_writes(name: str, tmp argv = ["gen"] out = "gen" - packaged_root = _model_project(tmp_path / "packaged", name) + packaged_root = _model_project(tmp_path / "packaged", name, _REQUIRED_OPTIONS.get(name)) packaged = _run(packaged_root, argv, out, block=[]) assert packaged, f"{name} wrote nothing over the test model, so it proves nothing" - owned_root = _model_project(tmp_path / "owned", owned.owned_token(entry)) + owned_root = _model_project(tmp_path / "owned", owned.owned_token(entry), _REQUIRED_OPTIONS.get(name)) assert owned.eject([name], owned_root).code == 0 mine = _run(owned_root, argv, out, block=_packaged_modules()) diff --git a/server/python/tests/codegen/test_entity_model.py b/server/python/tests/codegen/test_entity_model.py index 2e2fbd7500..0ac2a03465 100644 --- a/server/python/tests/codegen/test_entity_model.py +++ b/server/python/tests/codegen/test_entity_model.py @@ -135,7 +135,7 @@ def test_column_attr_does_not_rename_the_read_model_field() -> None: The read model used to key by ``@column``. Everything else in this port keys by ``field.name``: the FR-036 create/patch models, the generated router (it stamps - ``dto["createdAt"]``), and the runtime — ``ObjectManager`` maps + ``dto["createdAt"]``), and the runtime — ``ObjectManagerDb`` maps ``{_column_of(f): f.name}`` on every read and RETURNING clause, commented "for cross-port row-shape parity". So the read model's stated reason ("the Python model field IS the column, so it binds straight to the row") was false: the runtime never diff --git a/server/python/tests/codegen/test_generator_settings.py b/server/python/tests/codegen/test_generator_settings.py new file mode 100644 index 0000000000..d4ee21cc2b --- /dev/null +++ b/server/python/tests/codegen/test_generator_settings.py @@ -0,0 +1,369 @@ +"""``packages``, ``entities`` and ``options`` on a ``generators`` entry (L-PY-0). + +An entry written as a mapping may limit one generator to some packages and objects and hand it +its own settings, packaged generator or a team's own. A name the model does not hold and an +option the generator does not take are refused, never ignored: a typo here would otherwise drop +a generator's output and the run would still say it succeeded. +""" +from __future__ import annotations + +import json +import textwrap +from pathlib import Path + +import pytest + +from metaobjects.cli import main +from metaobjects.codegen.generator_registry import GeneratorOption, resolve_options, snake_case_option +from metaobjects.codegen.project_config import ConfigError, GeneratorSettings, load_project_config + + +def _value(name: str) -> dict: + return { + "object.entity": { + "name": name, + "children": [ + {"source.rdb": {"@table": name.lower() + "s"}}, + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ], + } + } + + +def _model(root: Path) -> None: + meta = root / "metaobjects" + meta.mkdir(parents=True, exist_ok=True) + for pkg, names in (("acme::sales", ["Order", "Invoice"]), ("acme::hr", ["Person"])): + (meta / f"meta.{pkg.split('::')[1]}.json").write_text( + json.dumps({"metadata.root": {"package": pkg, "children": [_value(n) for n in names]}}), + encoding="utf-8", + ) + + +def _project(root: Path, generators: str, extra: str = "") -> Path: + _model(root) + (root / "metaobjects.config.yaml").write_text( + f"targets:\n app:\n outDir: gen\n generators:\n{textwrap.indent(generators, ' ')}\n{extra}", + encoding="utf-8", + ) + return root / "gen" + + +def _stems(out: Path) -> set[str]: + return {p.stem for p in out.rglob("*.py") if p.stem != "__init__"} + + +def test_the_config_reads_the_three_keys(tmp_path: Path) -> None: + cfg = tmp_path / "metaobjects.config.yaml" + cfg.write_text( + "targets:\n app:\n outDir: gen\n generators:\n - entity\n" + " - name: names\n packages: [acme::sales]\n entities: [Order]\n" + " options: {a: 1}\n", + encoding="utf-8", + ) + [target] = load_project_config(cfg).targets + assert target.generators == ["entity", "names"] + assert target.generator_settings == { + "names": GeneratorSettings(packages=("acme::sales",), entities=("Order",), options={"a": 1}) + } + + +@pytest.mark.parametrize( + "generators", + [ + "- {name: names, packages: [acme::sales]}\n- {name: names, packages: [acme::hr]}", + "- names\n- {name: names, entities: [Order]}", + "- {name: names, options: {a: 1}}\n- names", + "- {name: names, handEdits: overwrite}\n- {name: names}", + ], +) +def test_a_generator_listed_twice_with_settings_is_refused(tmp_path: Path, generators: str) -> None: + cfg = tmp_path / "metaobjects.config.yaml" + cfg.write_text( + f"targets:\n app:\n outDir: gen\n generators:\n{textwrap.indent(generators, ' ')}\n", + encoding="utf-8", + ) + with pytest.raises(ConfigError, match="'names' is listed twice"): + load_project_config(cfg) + + +def test_a_generator_listed_twice_with_no_settings_is_allowed(tmp_path: Path) -> None: + cfg = tmp_path / "metaobjects.config.yaml" + cfg.write_text( + "targets:\n app:\n outDir: gen\n generators:\n - names\n - names\n", + encoding="utf-8", + ) + [target] = load_project_config(cfg).targets + assert target.generators == ["names", "names"] + + +@pytest.mark.parametrize( + ("entry", "fragment"), + [ + ("packages: []", "'packages' must be a non-empty list"), + ("packages: acme", "'packages' must be a non-empty list"), + ("entities: [1]", "'entities' must be a non-empty list"), + ("options: [a]", "'options' must be a mapping"), + ("selection: [A]", "unknown key(s) ['selection']"), + ], +) +def test_a_malformed_entry_is_refused(tmp_path: Path, entry: str, fragment: str) -> None: + cfg = tmp_path / "metaobjects.config.yaml" + cfg.write_text( + f"targets:\n app:\n outDir: gen\n generators:\n - name: names\n {entry}\n", + encoding="utf-8", + ) + with pytest.raises(ConfigError, match=fragment.replace("[", r"\[").replace("]", r"\]").replace("(", r"\(").replace(")", r"\)")): + load_project_config(cfg) + + +def test_a_generator_is_limited_to_its_packages_and_entities( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _project( + tmp_path, + "- entity\n- name: names\n packages: [acme::sales]\n", + ) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + stems = _stems(out) + assert {"order", "invoice", "person"} <= {s.lower() for s in stems} + names = {s for s in stems if s.endswith("_names")} + assert names == {"order_names", "invoice_names"} + + +def test_entities_select_by_short_name(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + out = _project(tmp_path, "- name: names\n entities: [Person]\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert {s for s in _stems(out) if s.endswith("_names")} == {"person_names"} + + +@pytest.mark.parametrize( + ("entry", "fragment"), + [ + ("entities: [Nobody]", "entities ['Nobody'] name no object in this target"), + ("packages: [acme::nope]", "packages ['acme::nope'] hold no object in this target"), + ], +) +def test_a_name_the_model_does_not_hold_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], + entry: str, fragment: str, +) -> None: + out = _project(tmp_path, f"- name: names\n {entry}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + assert fragment in capsys.readouterr().err + assert not out.exists() or not _stems(out) + + +def test_a_generator_may_not_cover_what_its_required_generator_is_limited_away_from( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + # `routes` imports the filter allowlist of each entity it routes. Limiting the allowlist to + # Invoice while routes covers Order and Person would emit routers that fail to import. + out = _project( + tmp_path, "- entity\n- {name: filter-allowlist, entities: [Invoice]}\n- routes\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + err = capsys.readouterr().err + assert "'routes' requires 'filter-allowlist', which is limited away from" in err + assert "'Order'" in err and "'Person'" in err and "'Invoice'" not in err + assert not out.exists() or not _stems(out) + + +def test_limiting_a_generator_and_the_one_it_requires_to_the_same_entity_is_accepted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _project( + tmp_path, + "- entity\n- {name: filter-allowlist, entities: [Invoice]}\n" + "- {name: routes, entities: [Invoice]}\n", + ) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert "invoice_router" in _stems(out) and "order_router" not in _stems(out) + + +def test_the_selection_stays_inside_the_targets_entities( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _project(tmp_path, "- name: names\n entities: [Person]\n", "") + cfg = tmp_path / "metaobjects.config.yaml" + cfg.write_text(cfg.read_text(encoding="utf-8").replace(" outDir: gen\n", " outDir: gen\n entities: [Order]\n"), encoding="utf-8") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + assert "name no object in this target" in capsys.readouterr().err + + +def test_a_packaged_generators_options_reach_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + _model(tmp_path) + out = _project( + tmp_path, + "- entity\n- routes\n- name: report-export\n options: {maxRows: 7, xmlNulls: nil, csvBom: true}\n", + ) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + # No report is served here, so the shared writer is not written; the options still had to + # build the generator, which is what a bad value would have failed. + assert out.exists() + + +def test_a_packaged_option_changes_what_the_generator_is_built_with() -> None: + import dataclasses + + from metaobjects.codegen.generator_registry import GENERATOR_REGISTRY, GeneratorBuildContext + + ctx = dataclasses.replace( + GeneratorBuildContext(), options={"max_rows": 7, "xml_nulls": "nil", "csv_bom": True} + ) + built = GENERATOR_REGISTRY["report-export"].factory(ctx) + assert (built.max_rows, built.xml_nulls, built.csv_bom) == (7, "nil", True) # type: ignore[attr-defined] + routes = GENERATOR_REGISTRY["routes"].factory(dataclasses.replace(ctx, options={"report_max_rows": 5})) + assert routes.report_max_rows == 5 # type: ignore[attr-defined] + + +def test_a_bad_option_is_refused_and_names_what_is_accepted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _project(tmp_path, "- name: report-export\n options: {maxRow: 7}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + err = capsys.readouterr().err + assert "generator 'report-export' takes no option 'maxRow'; options: csvBom, maxRows, xmlNulls" in err + + +def test_a_generator_with_no_options_refuses_any( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _project(tmp_path, "- name: names\n options: {x: 1}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + assert "generator 'names' takes no option 'x'; options: none" in capsys.readouterr().err + + +def test_option_values_are_checked() -> None: + accepted = ( + GeneratorOption("maxRows", "integer", "", minimum=1), + GeneratorOption("xmlNulls", "string", "", choices=("empty", "nil")), + GeneratorOption("csvBom", "boolean", ""), + ) + kwargs, errors = resolve_options("g", accepted, {"maxRows": 5, "xmlNulls": "nil", "csvBom": True}) + assert (kwargs, errors) == ({"max_rows": 5, "xml_nulls": "nil", "csv_bom": True}, []) + _, errors = resolve_options("g", accepted, {"maxRows": 0, "xmlNulls": "x", "csvBom": "yes"}) + assert errors == [ + "generator 'g' option 'maxRows' must be at least 1, got 0", + "generator 'g' option 'xmlNulls' must be one of empty, nil, got 'x'", + "generator 'g' option 'csvBom' must be true or false, got 'yes'", + ] + _, errors = resolve_options("g", accepted, {"maxRows": True}) + assert errors == ["generator 'g' option 'maxRows' must be a whole number, got True"] + + +def test_snake_case_option() -> None: + assert snake_case_option("maxRows") == "max_rows" + assert snake_case_option("reportMaxRows") == "report_max_rows" + assert snake_case_option("csv") == "csv" + + +# --- a team's own generator ------------------------------------------------------------------ + +_OWNED = """\ +from metaobjects.codegen.generator import EmittedFile + + +class Stamp: + name = "stamp" + + def __init__(self, label: str = "none", copies: int = 1) -> None: + self.label = label + self.copies = copies + + def generate(self, ctx): + return [EmittedFile(path="stamp.txt", content=f"{self.label} x{self.copies}\\n")] + + +def stamp(label: str = "none", copies: int = 1): + return Stamp(label, copies) + + +def open_stamp(**options): + return Stamp(**options) + + +def stamp_from_ctx(ctx): + return Stamp(label=str(dict(ctx.options))) + + +INSTANCE = Stamp() +""" + + +def _owned_project(root: Path, entry: str) -> Path: + (root / "stamps.py").write_text(_OWNED, encoding="utf-8") + return _project(root, entry) + + +def _stamp(out: Path) -> str: + return (out / "stamp.txt").read_text(encoding="utf-8") + + +def test_options_reach_a_team_factory_as_snake_case_keywords( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _owned_project(tmp_path, "- name: 'stamps:stamp'\n options: {label: hi, copies: 3}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert _stamp(out) == "hi x3\n" + + +def test_options_reach_a_team_class_and_a_kwargs_factory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _owned_project(tmp_path, "- name: 'stamps:Stamp'\n options: {label: cls}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert _stamp(out) == "cls x1\n" + out = _owned_project(tmp_path / "second", "- name: 'stamps:open_stamp'\n options: {copies: 2}\n") \ + if (tmp_path / "second").mkdir() is None else out + monkeypatch.chdir(tmp_path / "second") + assert main(["gen"]) == 0 + assert _stamp(out) == "none x2\n" + + +def test_a_factory_that_takes_the_context_reads_the_options_there( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _owned_project(tmp_path, "- name: 'stamps:stamp_from_ctx'\n options: {anyKey: 1}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert _stamp(out) == "{'anyKey': 1} x1\n" + + +def test_an_option_a_team_factory_does_not_take_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _owned_project(tmp_path, "- name: 'stamps:stamp'\n options: {lable: hi}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + err = capsys.readouterr().err + assert "stamp() takes no option(s) 'lable'; it takes: copies, label" in err + + +def test_options_on_a_generator_instance_are_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _owned_project(tmp_path, "- name: 'stamps:INSTANCE'\n options: {label: hi}\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) != 0 + assert "is a generator instance, which takes no options" in capsys.readouterr().err + + +def test_a_team_generator_can_be_limited_like_a_packaged_one( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = _owned_project(tmp_path, "- name: 'stamps:stamp'\n packages: [acme::hr]\n") + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + assert _stamp(out) == "none x1\n" diff --git a/server/python/tests/codegen/test_golden_generators.py b/server/python/tests/codegen/test_golden_generators.py new file mode 100644 index 0000000000..8e82eea70d --- /dev/null +++ b/server/python/tests/codegen/test_golden_generators.py @@ -0,0 +1,82 @@ +"""Byte-exact expected files for the router, names and filter-allowlist generators. + +The entity-model generator has had byte-exact goldens (``test_golden.py``) from the +start. These three did not: their tests assert on fragments of the emitted text, so a +change that reflows the output, reorders a section or moves a blank line passes every +one of them. The writer conversion (W-PY-1 onward) rewrites how this text is laid out; +it needs a net that fails on a single changed byte, laid before anything is converted. + +The input is the shared cross-port fitness corpus +(``fixtures/persistence-conformance/canonical/meta.fitness.json``): it already carries +tables, views, projections, reports, enums, value objects, a many-to-many, a TPH +hierarchy and a derived key, which is what the router's branches turn on. + +To refresh after a change that is MEANT to alter the output:: + + METAOBJECTS_UPDATE_GOLDEN=1 uv run pytest tests/codegen/test_golden_generators.py + +and review the diff of ``tests/codegen/golden_generators/expected`` in the PR. +""" +from __future__ import annotations + +import os +from pathlib import Path + +from metaobjects import load_uris +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generators.filter_allowlist_generator import ( + filter_allowlist_generator, +) +from metaobjects.codegen.generators.names_generator import names_generator +from metaobjects.codegen.generators.router_generator import router_generator +from metaobjects.codegen.runner import run_gen + +CORPUS = ( + Path(__file__).parents[4] + / "fixtures" + / "persistence-conformance" + / "canonical" + / "meta.fitness.json" +) +EXPECTED = Path(__file__).parent / "golden_generators" / "expected" + +#: Only the three generators this net covers. Emitting just their files keeps the +#: expected tree small and means an entity-model change cannot move these bytes. +_SUFFIXES = ("_router.py", "_names.py", "_filter_allowlist.py") + + +def _generate(out: Path) -> dict[str, str]: + result = load_uris([CORPUS.as_uri()]) + assert not result.errors, [e.message for e in result.errors] + run_gen( + GenConfig(out_dir=str(out)), + result.root, + generators=[router_generator(), names_generator(), filter_allowlist_generator()], + ) + return { + p.relative_to(out).as_posix(): p.read_text(encoding="utf-8") + for p in sorted(out.rglob("*.py")) + } + + +def test_router_names_and_filter_allowlist_match_the_expected_bytes(tmp_path: Path) -> None: + actual = _generate(tmp_path / "gen") + assert actual, "the corpus generated nothing" + # Every one of the three generators must have emitted something, or the net is empty. + for suffix in _SUFFIXES: + assert any(n.endswith(suffix) for n in actual), f"no {suffix} file was emitted" + + if os.environ.get("METAOBJECTS_UPDATE_GOLDEN") == "1": + EXPECTED.mkdir(parents=True, exist_ok=True) + for stale in EXPECTED.glob("*.py"): + stale.unlink() + for name, text in actual.items(): + (EXPECTED / name).write_text(text, encoding="utf-8") + + expected = { + p.relative_to(EXPECTED).as_posix(): p.read_text(encoding="utf-8") + for p in sorted(EXPECTED.rglob("*.py")) + } + assert sorted(actual) == sorted(expected), "the set of emitted files changed" + for name in sorted(actual): + assert actual[name] == expected[name], f"{name} no longer matches its expected bytes" diff --git a/server/python/tests/codegen/test_layout_ratchet.py b/server/python/tests/codegen/test_layout_ratchet.py new file mode 100644 index 0000000000..8eb230dcec --- /dev/null +++ b/server/python/tests/codegen/test_layout_ratchet.py @@ -0,0 +1,209 @@ +"""The layout ratchet (ADR-0063): generator source never types layout; the writer does. + +Three parts: + 1. the analyzer's own cases: layout it must catch, and writer-based code it must pass; + 2. the scope rule: which files are generator source, by rule, not by list; + 3. the ratchet over the real package: every file with hand-typed layout is on the + allowlist with a reason, every allowlisted file still needs its entry, and the + allowlist only shrinks. +""" +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest + +from tests.codegen.layout_ratchet.analyze import analyze_source, is_generator_source + +CODEGEN = Path(__file__).parents[2] / "src" / "metaobjects" / "codegen" +REPO = Path(__file__).parents[4] +ALLOWLIST_PATH = Path(__file__).parent / "layout_ratchet" / "allowlist.json" +ALLOWLIST_REL = ALLOWLIST_PATH.relative_to(REPO).as_posix() + + +def kinds(source: str) -> list[str]: + return sorted(f.kind for f in analyze_source(source)) + + +# ── 1. the analyzer ────────────────────────────────────────────────────────────────── + +CAUGHT = [ + ("a newline escape in a string", 's = "a\\nb"', ["newline-literal"]), + ("a carriage return", 's = "a\\r"', ["newline-literal"]), + ("a line break inside a triple-quoted string", 's = """a\nb"""', ["newline-literal"]), + ("a line break in an f-string part", 's = f"{a}\\n{b}"', ["newline-literal"]), + ("a string that starts with four spaces", 'rows.append(" x = 1")', ["indent-literal"]), + ("an f-string that starts with an indent", 'rows.append(f" {name}: int")', ["indent-literal"]), + ("a string that starts with a tab", 'rows.append("\\tx")', ["indent-literal"]), + ("a join on a newline", 'out = "\\n".join(rows)', ["newline-join", "newline-literal"]), + ("a join on a comma-newline", 'out = ",\\n".join(rows)', ["newline-join", "newline-literal"]), + ("an indentation repeat", 'pad = " " * depth', ["indent-literal", "indent-repeat"]), + ("a single-space repeat", 'pad = " " * (depth * 2)', ["indent-repeat"]), +] + + +@pytest.mark.parametrize(("source", "expected"), [c[1:] for c in CAUGHT], ids=[c[0] for c in CAUGHT]) +def test_the_analyzer_catches_hand_typed_layout(source: str, expected: list[str]) -> None: + assert kinds(source) == sorted(expected) + + +def test_a_newline_hidden_behind_a_constant_is_caught_where_it_is_used() -> None: + found = analyze_source('NL = "\\n"\nout = NL.join(lines)\n') + assert [(f.kind, f.line) for f in found] == [("newline-literal", 1), ("newline-join", 2)] + + +def test_the_constant_may_be_built_from_other_constants() -> None: + src = 'NL = "\\n"\nSEP = "," + NL\nSEP.join(rows)\n' + assert [f.line for f in analyze_source(src) if f.kind == "newline-join"] == [3] + + +def test_an_indent_unit_hidden_behind_a_constant_is_caught_at_the_repeat() -> None: + assert kinds('UNIT = " "\npad = UNIT * 4\n') == ["indent-repeat"] + + +def test_findings_carry_the_line_and_column_of_the_node() -> None: + (f,) = analyze_source('a = 1\ns = "x\\n"\n') + assert (f.line, f.column) == (2, 5) + + +PASSED = [ + ("a generator written on PyWriter", 'w = PyWriter()\nw.open("class A:")\nw.line("x = 1")\nw.dedent()\n'), + ("a docstring", 'def f():\n """Line one.\n\n Line two."""\n'), + ("a search pattern", 'parts = text.split("\\n")\nif s.startswith(" "): pass\n'), + ("a comparison", 'if ch == "\\n": pass\nif "\\n" in s: pass\n'), + ("a writer snippet", 'w.text("""\n a = 1\n b = 2\n""")\n'), + ("a join on a comma", 'out = ", ".join(names)\n'), + ("a space repeat that is not layout-typed", 'x = [0] * 4\ny = "ab" * 2\n'), + ("a comment", "# a\\n b\n # not code\nx = 1\n"), +] + + +@pytest.mark.parametrize("source", [p[1] for p in PASSED], ids=[p[0] for p in PASSED]) +def test_the_analyzer_passes_code_that_leaves_layout_to_the_writer(source: str) -> None: + assert analyze_source(source) == [] + + +# ── 2. the scope rule ──────────────────────────────────────────────────────────────── + +@pytest.mark.parametrize( + ("path", "scanned"), + [ + ("generators/router_generator.py", True), + ("runtime/api_docs_renderer.py", True), + ("constants.py", True), + ("writer/code_writer.py", False), + ("writer/py_writer.py", False), + ("__pycache__/x.py", False), + ("metaobjects-config.schema.json", False), + ("KNOWN_GAPS.md", False), + ], +) +def test_scope_by_rule(path: str, scanned: bool) -> None: + assert is_generator_source(Path(path)) is scanned + + +# ── 3. the ratchet over the real package ───────────────────────────────────────────── + +ALLOWLIST = json.loads(ALLOWLIST_PATH.read_text(encoding="utf-8")) +ENTRIES = {**ALLOWLIST["unconverted"], **ALLOWLIST["exempt"]} + +SCANNED = sorted( + p.relative_to(CODEGEN).as_posix() + for p in CODEGEN.rglob("*.py") + if is_generator_source(p.relative_to(CODEGEN)) +) +FINDINGS = {f: analyze_source((CODEGEN / f).read_text(encoding="utf-8"), f) for f in SCANNED} + + +def test_it_reads_the_generators() -> None: + assert any(f.startswith("generators/") for f in SCANNED) + assert any(f.startswith("runtime/") for f in SCANNED) + + +def test_no_generator_source_types_layout_unless_its_file_is_allowlisted() -> None: + offenders = [ + "\n".join([f, *(f" {x.line}:{x.column} {x.kind} {x.excerpt}" for x in found)]) + for f, found in FINDINGS.items() + if found and f not in ENTRIES + ] + assert offenders == [], ( + "Write these lines through PyWriter (codegen/writer/) instead of typing line breaks " + "or indentation. A file is never added to the allowlist: it only shrinks." + ) + + +def test_every_allowlisted_file_still_needs_its_entry() -> None: + stale = [f for f in ENTRIES if not FINDINGS.get(f)] + assert stale == [], "these files no longer type layout (or no longer exist): remove their entries" + + +def test_every_allowlisted_path_is_generator_source_that_exists() -> None: + for f in ENTRIES: + assert is_generator_source(Path(f)), f"{f} is not in the ratchet's scope" + assert (CODEGEN / f).exists(), f"{f} does not exist" + + +def test_every_entry_carries_a_written_reason() -> None: + for f, reason in ENTRIES.items(): + assert len(reason) > 40, f"{f} needs a reason" + + +def test_a_file_is_either_unconverted_or_exempt_never_both_and_each_list_is_sorted() -> None: + assert [f for f in ALLOWLIST["unconverted"] if f in ALLOWLIST["exempt"]] == [] + for lst in (ALLOWLIST["unconverted"], ALLOWLIST["exempt"]): + assert list(lst) == sorted(lst) + + +def growth(before: dict, now: dict) -> list[str]: + """How ``now`` grew relative to ``before``: new entries, and unconverted files relabelled exempt.""" + had = set(before["unconverted"]) | set(before.get("exempt", {})) + return [f"added {f}" for f in {**now["unconverted"], **now["exempt"]} if f not in had] + [ + f"relabelled {f} as exempt" for f in now["exempt"] if f in before["unconverted"] + ] + + +def test_growth_is_an_added_entry_or_an_unconverted_file_relabelled_exempt() -> None: + before = {"unconverted": {"a.py": "r", "b.py": "r"}, "exempt": {"c.py": "r"}} + assert growth(before, {"unconverted": {"a.py": "r"}, "exempt": {}}) == [] + assert growth(before, {"unconverted": {"a.py": "r", "d.py": "r"}, "exempt": {"c.py": "r"}}) == ["added d.py"] + assert growth(before, {"unconverted": {"a.py": "r"}, "exempt": {"b.py": "r", "c.py": "r"}}) == [ + "relabelled b.py as exempt" + ] + + +def _git(*args: str) -> str | None: + r = subprocess.run(["git", "-C", str(REPO), *args], capture_output=True, text=True) + return r.stdout.strip() if r.returncode == 0 else None + + +def _merge_base_allowlists() -> list[tuple[str, dict]] | None: + """The allowlist as it stood at the merge base of HEAD with each integration branch; + ``None`` when git or those refs are unavailable (an export or a shallow clone).""" + refs = _git( + "for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/main", "refs/remotes/origin/release/" + ) + if not refs: + return None + out: list[tuple[str, dict]] = [] + reachable = False + for ref in refs.split(): + base = _git("merge-base", "HEAD", ref) + if base is None: + continue + reachable = True + text = _git("show", f"{base}:{ALLOWLIST_REL}") + if text is not None: + out.append((ref, json.loads(text))) + return out if reachable else None + + +def test_the_allowlist_only_shrinks() -> None: + bases = _merge_base_allowlists() + if bases is None: + pytest.skip("no integration branch to compare the allowlist with") + for ref, lst in bases: + assert growth(lst, ALLOWLIST) == [], ( + f"the allowlist grew since the merge base with {ref}; convert the file to the writer instead" + ) diff --git a/server/python/tests/codegen/test_names_generator.py b/server/python/tests/codegen/test_names_generator.py index eeb991a9ec..b4d033fed7 100644 --- a/server/python/tests/codegen/test_names_generator.py +++ b/server/python/tests/codegen/test_names_generator.py @@ -118,7 +118,7 @@ def test_emits_final_constants_for_table_and_columns() -> None: assert "READ_ONLY" not in src # A2: both names, always, always distinguished. assert 'SUBSCRIBER_CREATED_AT_FIELD: Final[str] = "createdAt"' in src - # This port's default strategy is literal, matching ObjectManager. + # This port's default strategy is literal, matching ObjectManagerDb. assert 'SUBSCRIBER_CREATED_AT_COLUMN: Final[str] = "createdAt"' in src # The map's values REFERENCE the constant, never repeat the literal. assert '"createdAt": SUBSCRIBER_CREATED_AT_COLUMN,' in src diff --git a/server/python/tests/codegen/test_project_import.py b/server/python/tests/codegen/test_project_import.py index b14a87314e..24a1e6f2b8 100644 --- a/server/python/tests/codegen/test_project_import.py +++ b/server/python/tests/codegen/test_project_import.py @@ -303,6 +303,7 @@ def test_a_namespace_layout_in_the_project_loses_to_a_regular_package_earlier_lo def test_build_owned_instantiates_a_generator_class(tmp_path: Path) -> None: """MINOR 2: `module:symbol` naming a generator CLASS yields an instance, not the class.""" from metaobjects.codegen.eject import build_owned + from metaobjects.codegen.generator_registry import GeneratorBuildContext pkg = tmp_path / "owned_gen_pkg" pkg.mkdir() @@ -314,7 +315,7 @@ def test_build_owned_instantiates_a_generator_class(tmp_path: Path) -> None: " return []\n" ) try: - gen, err = build_owned("owned_gen_pkg.mine:Mine", tmp_path, None) # type: ignore[arg-type] + gen, err = build_owned("owned_gen_pkg.mine:Mine", tmp_path, GeneratorBuildContext()) assert err is None assert not isinstance(gen, type) and gen is not None and gen.name == "mine" assert gen.generate(None) == [] # type: ignore[arg-type] diff --git a/server/python/tests/codegen/test_report_export.py b/server/python/tests/codegen/test_report_export.py index 2a7cd76b7a..5f31d66308 100644 --- a/server/python/tests/codegen/test_report_export.py +++ b/server/python/tests/codegen/test_report_export.py @@ -3,7 +3,9 @@ ``?format=`` branch only when that generator is in the run.""" from __future__ import annotations +import importlib import importlib.util +import json import shutil import sys import tempfile @@ -128,9 +130,12 @@ def test_request_helper() -> None: # --- generator + router wiring --------------------------------------------------------- -def _gen(names: set[str], **export_opts) -> dict[str, str]: +def _gen(names: set[str], meta: str | None = None, **export_opts) -> dict[str, str]: tmp = Path(tempfile.mkdtemp(prefix="report-export-")) - shutil.copy(_CORPUS / "meta.json", tmp / "meta.json") + if meta is None: + shutil.copy(_CORPUS / "meta.json", tmp / "meta.json") + else: + (tmp / "meta.json").write_text(meta, encoding="utf-8") result = MetaDataLoader.from_directory(str(tmp)) assert not result.errors gens = [ @@ -170,3 +175,32 @@ def test_wired_emits_one_writer_and_one_module_per_served_report() -> None: # only a served report's router changes; the entity (writable) routers are untouched assert files["invoice_status_totals_router.py"] != unwired["invoice_status_totals_router.py"] assert files["invoice_router.py"] == unwired["invoice_router.py"] + + +def test_a_report_with_one_exported_column_still_exports() -> None: + model = json.loads((_CORPUS / "meta.json").read_text(encoding="utf-8")) + + def drop_dimensions(node: object) -> None: + if isinstance(node, dict): + if node.get("name") == "ReadingLog": + node.pop("@dimensions", None) + for v in node.values(): + drop_dimensions(v) + elif isinstance(node, list): + for v in node: + drop_dimensions(v) + + drop_dimensions(model) + files = _gen(_BASE | {"report-export"}, meta=json.dumps(model)) + pkg = Path(tempfile.mkdtemp()) / f"pkg_{uuid.uuid4().hex}" + pkg.mkdir() + (pkg / "__init__.py").write_text("", encoding="utf-8") + for name in ("report_export_writer.py", "reading_log_export.py"): + (pkg / name).write_text(files[name], encoding="utf-8") + sys.path.insert(0, str(pkg.parent)) + try: + mod = importlib.import_module(f"{pkg.name}.reading_log_export") + finally: + sys.path.remove(str(pkg.parent)) + assert [c.name for c in mod.EXPORT_COLUMNS] == ["readings"] + assert mod.export_csv([{"readings": 3}]).splitlines() == ["readings", "3"] diff --git a/server/python/tests/codegen/test_router_autoset.py b/server/python/tests/codegen/test_router_autoset.py index 0e9c852ca5..675e8a275d 100644 --- a/server/python/tests/codegen/test_router_autoset.py +++ b/server/python/tests/codegen/test_router_autoset.py @@ -1,7 +1,7 @@ """#203 / ADR-0045 — the generated FastAPI router (the deployed API surface) stamps ``@autoSet`` timestamps ABOVE the consumer repository seam, so an adopter who wires their own persistence into the generated router still gets the shipped stamping -semantics. (The ObjectManager keeps stamping for non-HTTP writes — defense-in-depth, +semantics. (The ObjectManagerDb keeps stamping for non-HTTP writes — defense-in-depth, not the wire-tier guarantee.) A non-``@autoSet`` entity's router stays byte-identical.""" from __future__ import annotations diff --git a/server/python/tests/codegen/test_shared_model_generator.py b/server/python/tests/codegen/test_shared_model_generator.py new file mode 100644 index 0000000000..fc7a2bd36f --- /dev/null +++ b/server/python/tests/codegen/test_shared_model_generator.py @@ -0,0 +1,125 @@ +"""The ``shared-model`` generator through ``metaobjects gen`` (D6): its options, where its files +and its version come from, and how a publish it must refuse fails the run. The bytes it writes +are pinned by ``tests/conformance/test_shared_model_conformance.py``.""" +from __future__ import annotations + +import hashlib +import json +import textwrap +from pathlib import Path + +import pytest + +from metaobjects.cli import main +from metaobjects.codegen.generator_registry import GeneratorOption + +_SOURCE = Path(__file__).resolve().parents[4] / "fixtures" / "shared-model-conformance" / "source" + + +def _project(root: Path, options: str, *, extra_files: bool = True, pyproject: str | None = None) -> Path: + meta = root / "metaobjects" + meta.mkdir(parents=True) + for name in ("meta.base.json", "meta.customer.json"): + (meta / name).write_text((_SOURCE / name).read_text(), encoding="utf-8") + if extra_files: + (meta / "meta.ledger.json").write_text((_SOURCE / "meta.ledger.json").read_text(), encoding="utf-8") + if pyproject is not None: + (root / "pyproject.toml").write_text(pyproject, encoding="utf-8") + (root / "metaobjects.config.yaml").write_text( + "targets:\n publish:\n outDir: published\n generators:\n" + " - name: shared-model\n options:\n" + textwrap.indent(options, " "), + encoding="utf-8", + ) + return root / "published" + + +def _gen(root: Path) -> int: + return main(["gen", "--config", str(root / "metaobjects.config.yaml")]) + + +def test_a_list_option_is_a_list_of_non_empty_strings() -> None: + option = GeneratorOption("include", "stringList", description="d") + assert option.coerce(["a::**", "b"]) == (("a::**", "b"), None) + assert option.coerce("a::**")[1] is not None + assert option.coerce(["a", ""])[1] is not None + assert option.coerce(["a", 3])[1] is not None + assert option.coerce([]) == ((), None) + required = GeneratorOption("include", "stringList", description="d", required=True) + assert "at least one" in (required.coerce([])[1] or "") + + +def test_it_writes_the_artifact_and_the_manifest_pinned_by_the_artifact(tmp_path: Path) -> None: + out = _project( + tmp_path, + "name: acme-common\ninclude: [acme::common::Address, acme::common::Audited]\nversion: 2.1.0\n", + ) + assert _gen(tmp_path) == 0 + artifact = (out / "acme-common.metaobjects.json").read_bytes() + manifest = json.loads((out / "metaobjects.pkg.json").read_text()) + assert manifest["name"] == "acme-common" and manifest["version"] == "2.1.0" + assert manifest["artifact"] == "acme-common.metaobjects.json" + assert manifest["integrity"] == "sha256-" + hashlib.sha256(artifact).hexdigest() + assert manifest["nodes"] == ["acme::common::Address", "acme::common::Audited"] + + +def test_the_version_defaults_to_the_projects_pyproject(tmp_path: Path) -> None: + out = _project( + tmp_path, "name: acme-common\ninclude: [acme::common::Address]\n", + pyproject='[project]\nname = "x"\nversion = "3.4.5"\n', + ) + assert _gen(tmp_path) == 0 + assert json.loads((out / "metaobjects.pkg.json").read_text())["version"] == "3.4.5" + + +def test_no_version_anywhere_fails_the_run(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + out = _project(tmp_path, "name: acme-common\ninclude: [acme::common::Address]\n") + assert _gen(tmp_path) == 1 + assert "no version available" in capsys.readouterr().err + assert not out.exists() + + +def test_files_narrows_which_source_files_contribute(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + # The ledger file declares requirement.* and the Customers object; with `files` limited to + # the base file, a name only the other file holds selects nothing. + _project( + tmp_path, + "name: acme-common\ninclude: [acme::common::Customer]\nversion: 1.0.0\n" + "files: [metaobjects/meta.base.json]\n", + ) + assert _gen(tmp_path) == 1 + assert "selected no nodes" in capsys.readouterr().err + + +def test_a_selection_that_is_not_closed_fails_naming_the_pair( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + _project(tmp_path, "name: acme-common\ninclude: [acme::common::Secret]\nversion: 1.0.0\n") + assert _gen(tmp_path) == 1 + assert "acme::common::Secret -> acme::common::Address" in capsys.readouterr().err + + +def test_name_and_include_are_required(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + _project(tmp_path, "version: 1.0.0\n") + assert _gen(tmp_path) == 1 + err = capsys.readouterr().err + assert "needs the option 'name'" in err and "needs the option 'include'" in err + + +def test_an_unknown_option_is_refused(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + _project(tmp_path, "name: a\ninclude: [acme::common::Address]\nversion: 1.0.0\nincludes: [x]\n") + assert _gen(tmp_path) == 1 + err = capsys.readouterr().err + assert "takes no option 'includes'" in err and "include" in err + + +def test_a_changed_pyproject_version_is_a_changed_input(tmp_path: Path) -> None: + """ADR-0064: the file the version comes from is a declared extra input, so bumping it + regenerates instead of skipping the run.""" + out = _project( + tmp_path, "name: acme-common\ninclude: [acme::common::Address]\n", + pyproject='[project]\nname = "x"\nversion = "1.0.0"\n', + ) + assert _gen(tmp_path) == 0 + (tmp_path / "pyproject.toml").write_text('[project]\nname = "x"\nversion = "1.0.1"\n', encoding="utf-8") + assert _gen(tmp_path) == 0 + assert json.loads((out / "metaobjects.pkg.json").read_text())["version"] == "1.0.1" diff --git a/server/python/tests/codegen/test_source_resolution.py b/server/python/tests/codegen/test_source_resolution.py index 04c04dcc4f..c71e4a2b4a 100644 --- a/server/python/tests/codegen/test_source_resolution.py +++ b/server/python/tests/codegen/test_source_resolution.py @@ -1,6 +1,6 @@ """Task 8 — one primary-source resolver, not four with two answers. -The runtime (``ObjectManager._table_name``) filters ``source.rdb`` children on +The runtime (``ObjectManagerDb._table_name``) filters ``source.rdb`` children on ``@role: primary``. The three codegen copies (router generator, filter-allowlist generator, M:N descriptor resolver) each took the FIRST ``source.*`` child, with no role filter at all. On any entity declaring a ``@role: replica`` source those @@ -25,7 +25,7 @@ from metaobjects.meta.persistence.source.meta_source import MetaSource from metaobjects.meta.meta_root import MetaRoot from metaobjects.meta.persistence.source.source_constants import SOURCE_ROLE_PRIMARY -from metaobjects.runtime import ObjectManager +from metaobjects.runtime import ObjectManagerDb from metaobjects.shared.base_types import TYPE_OBJECT _META = { @@ -159,14 +159,14 @@ def test_no_primary_source_resolves_to_none() -> None: def test_codegen_and_runtime_agree_on_every_sourced_entity() -> None: """The property that matters is AGREEMENT, not either answer alone. - ``ObjectManager._table_name`` already filtered by role; the generators did + ``ObjectManagerDb._table_name`` already filtered by role; the generators did not. Pin them together on a model containing the divergent (replica-declared-first) shape so they cannot drift apart again. Scoped to entities that declare a primary source: ``resolve_table_name``'s contract for "no primary source" is ``None`` (see ``test_no_primary_source_resolves_to_none``), while - ``ObjectManager._table_name`` -- a private runtime helper only ever called + ``ObjectManagerDb._table_name`` -- a private runtime helper only ever called internally on entities the caller already knows are persistable -- falls back to the bare entity name for that case instead. That's a deliberate difference in what the two return for a NON-participating object, not a @@ -174,7 +174,7 @@ def test_codegen_and_runtime_agree_on_every_sourced_entity() -> None: is the property this test exists to pin. """ root, entities = _load() - om = ObjectManager(root, driver=None) # type: ignore[arg-type] + om = ObjectManagerDb(root, driver=None) # type: ignore[arg-type] checked = 0 for entity in entities.values(): diff --git a/server/python/tests/codegen/test_tph_codegen.py b/server/python/tests/codegen/test_tph_codegen.py index f5d2705e9d..5d2ac4cd41 100644 --- a/server/python/tests/codegen/test_tph_codegen.py +++ b/server/python/tests/codegen/test_tph_codegen.py @@ -132,7 +132,7 @@ def test_base_router_polymorphic_plus_per_subtype(entities, index) -> None: def test_base_seam_states_the_discriminated_union_obligation(entities, index) -> None: # The router returns whatever the consumer's repository returns, and the natural - # repository — ObjectManager — reads a TPH BASE with the base's columns only (the + # repository — ObjectManagerDb — reads a TPH BASE with the base's columns only (the # persistence contract in every port). An adopter wiring one to the other served # `GET /` without any subtype field and nothing errored. The seam says so. src = render_router(entities["Auth"], index) diff --git a/server/python/tests/codegen/test_writer_conformance.py b/server/python/tests/codegen/test_writer_conformance.py new file mode 100644 index 0000000000..826cf30fd0 --- /dev/null +++ b/server/python/tests/codegen/test_writer_conformance.py @@ -0,0 +1,98 @@ +"""Runs ``fixtures/writer-conformance/`` against the Python writer (spec/code-writer.md). + +``core`` cases run on :class:`CodeWriter` with the options the case states; ``python`` cases +run on :class:`PyWriter` with its own defaults unless the case overrides them. A case of +another dialect belongs to another port and is skipped. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from metaobjects.codegen.writer import CodeWriter, PyWriter, WriterError, group + +CASES = Path(__file__).parents[4] / "fixtures" / "writer-conformance" / "cases" +FILES = sorted(CASES.glob("*.json")) + + +def _piece(p): + if isinstance(p, str): + return p + if isinstance(p, list): + return [_piece(x) for x in p] + lst = p["list"] + return group(lst["open"], [_piece(i) for i in lst["items"]], lst["close"], bool(lst.get("pad"))) + + +def _options(options: dict | None) -> dict: + o = options or {} + out = {} + if "indent" in o: + out["indent"] = o["indent"] + if "width" in o: + out["width"] = o["width"] + if "trailingComma" in o: + out["trailing_comma"] = o["trailingComma"] + return out + + +def _run(case: dict) -> str: + w = CodeWriter(**_options(case.get("options"))) if case["dialect"] == "core" else PyWriter( + **_options(case.get("options")) + ) + for op, *args in case["ops"]: + if op in ("line", "open", "close"): + getattr(w, op)(*[_piece(a) for a in args]) + elif op == "blank": + w.blank() + elif op == "text": + w.text(args[0]) + else: + assert isinstance(w, PyWriter), f"op {op} is not a core op" + if op == "use": + w.use(args[0], args[1]) + elif op == "useAs": + w.use(args[0], args[1], as_=args[2]) + elif op == "useModule": + w.use_module(*args) + elif op == "useFuture": + w.use_future(*args) + elif op == "header": + w.header(*args) + elif op == "doc": + w.doc(*args) + elif op == "dedent": + w.dedent() + elif op == "gap": + w.gap() + else: + raise AssertionError(f"unknown op {op}") + return w.to_string() + + +def _cases(): + for f in FILES: + case = json.loads(f.read_text(encoding="utf-8")) + if case["dialect"] in ("core", "python"): + yield pytest.param(case, id=f.stem) + + +def test_the_corpus_is_present() -> None: + assert len(FILES) >= 25 + + +@pytest.mark.parametrize("case", _cases()) +def test_case(case: dict) -> None: + if case["dialect"] == "core": + assert case.get("options") is not None, "a core case states its options" + if "error" in case: + with pytest.raises(WriterError) as e: + _run(case) + assert e.value.code == case["error"] + if "errorQuotes" in case: + assert case["errorQuotes"] in str(e.value) + return + lines = case["expected"] + assert _run(case) == ("" if not lines else "\n".join(lines) + "\n") diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 0fc54dd780..2672849cec 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -1,19 +1,17 @@ { "language": "python", "fixtures": [ - "error-computed-cast-enum-not-int-stored", "error-origin-function-free-sql", "error-projection-grain-not-object-array", "error-projection-union-shape", "projection-view-vocabulary-rc21" ], "_comment_fr024": "FR-024 Phase-E validation parity SHIPPED in this port. The full FR-024 loader contract now holds: object.projection registration + per-subtype projection child rules + dotted Entity.child extends-resolution (type-scoped, ERR_EXTENDS_TARGET_MISMATCH), AND the validation passes \u2014 identity names required + projection identity pass-through/key-correspondence (B3), value-purity + projection-licensing subtype rules (B4a), the entity-primary-source-readonly hard cutover (B4b), @via single-hop-unique inference + origin cardinality (B5), and extends/origin agreement + derived-field providability (B6). Every former FR-024 error fixture (error-identity-name-required, error-projection-identity-not-extended, error-identity-key-mismatch, error-projection-extends-entity, error-projection-source-writable, error-value-with-identity-secondary, error-value-with-source, error-origin-via-ambiguous, error-origin-passthrough-to-many, error-origin-aggregate-no-to-many, error-extends-origin-mismatch, error-derived-field-no-read-source, error-entity-primary-source-readonly) now emits its expected code with the byte-identical source envelope and is un-ledgered.", - "notes": "No expected failures remain. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", + "notes": "The Python expected failures are the keys of \"reasons\" below. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", "reasons": { - "error-computed-cast-enum-not-int-stored": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", "error-origin-function-free-sql": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", "error-projection-grain-not-object-array": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", "error-projection-union-shape": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "projection-view-vocabulary-rc21": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp" + "projection-view-vocabulary-rc21": "Python accepts the view functions and the cast node (C2) but not yet the rest of what this fixture declares: a dotted path in an origin.computed @expr (customerId.zip), a scalar origin.aggregate read from a computed field, a path operand in an origin.first @filter, an origin.passthrough through a path, and a derived field on an entity that declares a read source; implementedIn: typescript, csharp" } } diff --git a/server/python/tests/conformance/test_eject_contract.py b/server/python/tests/conformance/test_eject_contract.py index c603a41c42..fc42c475f5 100644 --- a/server/python/tests/conformance/test_eject_contract.py +++ b/server/python/tests/conformance/test_eject_contract.py @@ -58,6 +58,13 @@ }, } +#: Options a generator needs to run at all (it has no default for them): the depth test hands +#: them to the packaged generator and to the owned copy alike. ``shared-model`` publishes a +#: named selection, so it is told which nodes and which version. +DEPTH_OPTIONS_BY_NAME: dict[str, dict[str, object]] = { + "shared-model": {"name": "depth", "include": ["**"], "version": "1.0.0"}, +} + #: The one difference an owned copy's output is allowed: it imports the helper runtime the #: adopter owns, emitted beside it, where packaged output imports the installed one. PACKAGED_RUNTIME_IMPORT = "from metaobjects.codegen.runtime." @@ -265,6 +272,7 @@ def test_depth_every_engine_surface_entry_names_a_real_module() -> None: from pathlib import Path root, name, corpora = Path(sys.argv[1]), sys.argv[2], json.loads(sys.argv[3]) +DEPTH_OPTIONS = json.loads(sys.argv[4]) from metaobjects import MetaDataLoader from metaobjects.codegen import eject as owned @@ -278,7 +286,12 @@ def test_depth_every_engine_surface_entry_names_a_real_module() -> None: for corpus, spec in corpora.items(): loaded = MetaDataLoader(strict=True).load([FileSource(Path(f)) for f in spec["files"]]) assert not loaded.errors, [str(e) for e in loaded.errors] - ctx = GeneratorBuildContext(template_root=spec.get("templates")) + ctx = GeneratorBuildContext( + template_root=spec.get("templates"), + options=DEPTH_OPTIONS, + project_root=str(root), + source_files=tuple(spec["files"]), + ) mine, err = owned.build_owned(owned.owned_token(entry), root, ctx) assert err is None, err for side, generator in (("owned", mine), ("packaged", entry.factory(ctx))): @@ -302,7 +315,8 @@ def _run_alone(name: str, root: Path) -> dict[str, dict[str, dict[str, str]]]: for corpus, spec in CORPORA.items() } proc = subprocess.run( - [sys.executable, "-c", _DRIVER, str(root), name, json.dumps(corpora)], + [sys.executable, "-c", _DRIVER, str(root), name, json.dumps(corpora), + json.dumps(DEPTH_OPTIONS_BY_NAME.get(name, {}))], cwd=root, env=env, capture_output=True, text=True, ) assert proc.returncode == 0, f"{name}, ejected alone, does not load and run:\n{proc.stderr}" diff --git a/server/python/tests/conformance/test_shared_model_conformance.py b/server/python/tests/conformance/test_shared_model_conformance.py index 0e0682ca6e..19cbc6993e 100644 --- a/server/python/tests/conformance/test_shared_model_conformance.py +++ b/server/python/tests/conformance/test_shared_model_conformance.py @@ -1,13 +1,11 @@ -"""Runs the SERIALIZER arm of the shared publish corpus (FR-023 §4.3) in Python. +"""Runs the shared publish corpus (FR-023 §4.3) in Python: every case of +``fixtures/shared-model-conformance`` through the same ``build_shared_model`` and +``render_shared_model_files`` the ``shared-model`` generator calls. -Python ships no publisher yet (Phase 2, #482, defers it until a Python-only publisher -appears), so it does not run selection, the closure check or the refusals. What it does own -is the document's bytes: load a case's ``files``, take exactly the nodes the pinned manifest -lists, and ``serialize_shared_document`` must reproduce the pinned artifact byte for byte, and -the sha256 the manifest records. - -The refusal cases and the manifest's own bytes are the publisher's, and are run by -``codegen-ts/test/shared-model-conformance.test.ts`` until a second publisher exists. +A publish case must reproduce the pinned artifact byte for byte and the pinned manifest (the +golden carries ``@@METAMODEL_VERSION@@``, replaced here by this port's constant); a refusal case +must raise the pinned reason and, for ``not-closed``, exactly the pinned ``(referrer, target)`` +pairs. The message text is not the contract. """ from __future__ import annotations @@ -18,36 +16,78 @@ import pytest -from metaobjects import MetaDataLoader -from metaobjects.serializer_json import serialize_shared_document +from metaobjects.provider import Provider +from metaobjects.registry import AttrSchema, TypeRegistry +from metaobjects.registry_manifest import METAMODEL_VERSION +from metaobjects.shared_model import ( + SharedModelError, + build_shared_model, + render_shared_model_files, +) _CORPUS_DIR = Path(__file__).resolve().parents[4] / "fixtures" / "shared-model-conformance" _CASES = json.loads((_CORPUS_DIR / "cases.json").read_text())["cases"] _PUBLISHED = [c for c in _CASES if "expectArtifact" in c] +_REFUSED = [c for c in _CASES if "expectRefusal" in c] + + +class _SecretHandling(Provider): + """The corpus's test provider ``secret-handling``: one common string attribute, which is + vocabulary a consumer's core-only toolchain does not have.""" + + def __init__(self) -> None: + super().__init__("secret-handling", dependencies=()) + + def register_types(self, registry: TypeRegistry) -> None: # noqa: D401 + registry.register_common_attrs([AttrSchema("secretHandling", "string")]) + + +_PROVIDERS = {"secret-handling": _SecretHandling} + + +def _build(case: dict): + spec = case["input"] + return build_shared_model( + spec["name"], + [_CORPUS_DIR / f for f in spec["files"]], + spec.get("include", []), + spec.get("exclude", []), + requirements=spec.get("requirements", False), + providers=[_PROVIDERS[p]() for p in spec.get("providers", [])], + ) def test_corpus_is_non_empty() -> None: """A silent zero-case run is a failed gate, not a pass.""" - assert _PUBLISHED + assert len(_PUBLISHED) == 9 + assert len(_REFUSED) == 6 + assert len(_CASES) == len(_PUBLISHED) + len(_REFUSED) @pytest.mark.parametrize("case", _PUBLISHED, ids=[c["name"] for c in _PUBLISHED]) -def test_shared_document_bytes(case: dict) -> None: - manifest = json.loads((_CORPUS_DIR / case["expectManifest"]).read_text()) - expected = (_CORPUS_DIR / case["expectArtifact"]).read_bytes() - - result = MetaDataLoader.from_uris( - [(_CORPUS_DIR / f).as_uri() for f in case["input"]["files"]], - strict=True, - discover_naming=False, +def test_published_artifact_and_manifest_bytes(case: dict) -> None: + expected_artifact = (_CORPUS_DIR / case["expectArtifact"]).read_text() + expected_manifest = (_CORPUS_DIR / case["expectManifest"]).read_text().replace( + "@@METAMODEL_VERSION@@", METAMODEL_VERSION ) - assert not result.errors, [f"{e.code}: {e.message}" for e in result.errors] - # ADR-0039 sanctioned own: the root has no super chain, so its own children are its children. - # Every node the manifest lists, whatever its type: an export may carry requirement.* too. - selected = [c for c in result.root.own_children() if c.resolution_key() in manifest["nodes"]] - assert sorted(c.resolution_key() for c in selected) == manifest["nodes"] + files = render_shared_model_files(_build(case), case["input"]["version"]) + + assert files.artifact[0] == f"{case['input']['name']}.metaobjects.json" + assert files.artifact[1] == expected_artifact + assert files.manifest[0] == "metaobjects.pkg.json" + assert files.manifest[1] == expected_manifest + manifest = json.loads(files.manifest[1]) + assert manifest["integrity"] == "sha256-" + hashlib.sha256(files.artifact[1].encode()).hexdigest() + - document = serialize_shared_document(selected).encode("utf-8") - assert document == expected - assert manifest["integrity"] == "sha256-" + hashlib.sha256(document).hexdigest() +@pytest.mark.parametrize("case", _REFUSED, ids=[c["name"] for c in _REFUSED]) +def test_refusals(case: dict) -> None: + expected = case["expectRefusal"] + with pytest.raises(SharedModelError) as raised: + _build(case) + assert raised.value.reason == expected["reason"] + if expected["reason"] == "not-closed": + assert [ + {"referrer": r, "target": t} for r, t in raised.value.pairs + ] == expected["pairs"] diff --git a/server/python/tests/integration/generated_report_app.py b/server/python/tests/integration/generated_report_app.py index 497536b8f0..bb08f5565f 100644 --- a/server/python/tests/integration/generated_report_app.py +++ b/server/python/tests/integration/generated_report_app.py @@ -4,7 +4,7 @@ (``fixtures/api-contract-conformance/report/``). Runs the REAL generation path (``run_gen``, the one ``metaobjects gen`` takes) for the served reports, writes the emitted package to a temp dir, imports each generated router UNMODIFIED, and mounts it -behind a repository that reads the REAL view through the ``ObjectManager``. +behind a repository that reads the REAL view through the ``ObjectManagerDb``. The generated routers are the artifact under test: what is under test is whether this port's GENERATOR emits a keyless read-only surface for a view-backed ``object.report``, @@ -47,7 +47,7 @@ from metaobjects.codegen.runner import run_gen from metaobjects.codegen.runtime.filter_parser import FilterPredicate from metaobjects.naming import attach_naming -from metaobjects.runtime import Filter, ObjectManager +from metaobjects.runtime import Filter, ObjectManagerDb #: The served reports, as (report name, generated module stem). ``ProductRevenue`` #: declares ``@spine``: its seeded rows include the product with no sale. @@ -161,16 +161,16 @@ def generate_reports(corpus_root: Path, model: LaneModel = REPORT_MODEL) -> Gene def load_runtime_root(corpus_root: Path) -> Any: - """The corpus model for the ObjectManager: the project's pinned naming attached (the + """The corpus model for the ObjectManagerDb: the project's pinned naming attached (the sub-corpus lives under ``api-contract-conformance/``, whose ``.metaobjects/config.json`` pins literal columns, which is what the committed schemas spell).""" return attach_naming(_load_root(corpus_root / "meta.json"), corpus_root.parent) def build_generated_report_app( - corpus_root: Path, om: ObjectManager, model: LaneModel = REPORT_MODEL + corpus_root: Path, om: ObjectManagerDb, model: LaneModel = REPORT_MODEL ) -> tuple[FastAPI, set[str]]: - """Mount the generated routers behind ObjectManager-backed repositories. + """Mount the generated routers behind ObjectManagerDb-backed repositories. Returns ``(app, names of the files generation emitted)``. """ @@ -200,16 +200,16 @@ def provider() -> Any: class ObjectManagerReportRepository: """The adopter-owned seam of a GENERATED read-only ``Repository`` (``list`` / - ``count``), backed by the ``ObjectManager`` reading the report's real view. + ``count``), backed by the ``ObjectManagerDb`` reading the report's real view. The generated router parses the query string into :class:`FilterPredicate` records (values still TEXT: ``"0"``, ``"true"``, a date) and a sort clause; this class only - translates them to the ObjectManager's filter dict and ``sort`` pairs. Typing the text + translates them to the ObjectManagerDb's filter dict and ``sort`` pairs. Typing the text is the runtime's job (it parses a filter operand by the field's declared type), and an - operator is the ObjectManager's own, one for one. + operator is the ObjectManagerDb's own, one for one. """ - def __init__(self, om: ObjectManager, report: str, lock: threading.Lock) -> None: + def __init__(self, om: ObjectManagerDb, report: str, lock: threading.Lock) -> None: self._om = om self._report = report self._lock = lock @@ -234,7 +234,7 @@ def count(self, filters: list[FilterPredicate]) -> int: class ObjectManagerEntityRepository(ObjectManagerReportRepository): """The seam of a GENERATED writable ``Repository``: the report seam plus - ``find_by_id`` / ``create`` / ``update`` / ``delete``, over the ObjectManager.""" + ``find_by_id`` / ``create`` / ``update`` / ``delete``, over the ObjectManagerDb.""" def find_by_id(self, id: Any) -> Any: with self._lock: diff --git a/server/python/tests/integration/normalization.py b/server/python/tests/integration/normalization.py index 1e7e42499a..d46a841051 100644 --- a/server/python/tests/integration/normalization.py +++ b/server/python/tests/integration/normalization.py @@ -4,7 +4,7 @@ compare byte-equal after canonical serialization. This is the **serialization boundary** for the Python port (ADR-0019): the -runtime ``ObjectManager`` returns native pg8000 values (``int`` / ``Decimal`` / +runtime ``ObjectManagerDb`` returns native pg8000 values (``int`` / ``Decimal`` / ``datetime`` / ``date`` / ``time`` / ``timedelta`` / ``uuid.UUID`` / ``dict`` / ``list``); the canonicalization to the cross-port wire form lives HERE, keyed by Python native type — mirroring the other ports' by-native-type runners (Java keys off @@ -14,7 +14,7 @@ The one SQL-type distinction a native Python value cannot carry is int4-vs-int8 (pg8000 returns plain ``int`` for both, and a BIGINT aggregate over an INTEGER column is indistinguishable by value). The boundary recovers it from the -per-column Postgres OID that ``ObjectManager`` surfaces alongside the query +per-column Postgres OID that ``ObjectManagerDb`` surfaces alongside the query (``last_column_oids``) — the same SQL-type discriminator the other ports get from their driver's native typing. A field whose column OID is BIGINT (or any int8 OID) stringifies; an INTEGER/SMALLINT int stays a JSON number. @@ -65,7 +65,7 @@ def normalize_value(v: Any, column_oid: int | None = None, *, actual: bool = Fal # BIGINT → string (the cross-port contract; avoids the JS Number 2^53 # precision cliff). The OID is the authoritative discriminator: pg8000 # returns plain int for both INTEGER and BIGINT, so we key off the column - # OID surfaced by ObjectManager. With no OID (a nested jsonb int, or an + # OID surfaced by ObjectManagerDb. With no OID (a nested jsonb int, or an # `expect` literal), fall back to the value heuristic the TS runner uses # (stringify ints outside the int4 range) so cross-port output stays # stable without column metadata. diff --git a/server/python/tests/integration/query_runner.py b/server/python/tests/integration/query_runner.py index 6d4abc6410..8b7e76634c 100644 --- a/server/python/tests/integration/query_runner.py +++ b/server/python/tests/integration/query_runner.py @@ -13,7 +13,7 @@ from metaobjects import load_directory from metaobjects.naming import attach_naming -from metaobjects.runtime import MySqlDriver, ObjectManager, PostgresDriver, SqliteDriver +from metaobjects.runtime import MySqlDriver, ObjectManagerDb, PostgresDriver, SqliteDriver from .engines import ScenarioEngine, split_statements from .mysql_container import MySqlInfo @@ -43,40 +43,40 @@ def run(scenario: QueryScenario, pg: PostgresContainer, canonical_dir: Path) -> if scenario.seed_data and scenario.seed_data.strip(): _execute(info, scenario.seed_data) - # 3. Run queries through ObjectManager. + # 3. Run queries through ObjectManagerDb. with closing(pg8000.connect( host=info.host, port=info.port, user=info.user, password=info.password, database=info.database, )) as conn: driver = PostgresDriver(conn) - om = ObjectManager(root_for_bootstrap, driver) + om = ObjectManagerDb(root_for_bootstrap, driver) _run_queries(scenario, om) def run_sqlite(scenario: QueryScenario, db_path: Path, canonical_dir: Path) -> None: """Run *scenario* on SQLite (stdlib ``sqlite3``): execute ``canonical/schema.sqlite.sql`` verbatim into the empty database file *db_path*, seed it, and run the queries through the - ObjectManager with the SQLite driver. The expectations are the Postgres wire ones.""" + ObjectManagerDb with the SQLite driver. The expectations are the Postgres wire ones.""" engine = ScenarioEngine.SQLITE with closing(sqlite3.connect(str(db_path))) as conn: _exec_script(conn, (canonical_dir.parent / engine.schema_artifact).read_text()) seed = engine.seed(scenario) if seed and seed.strip(): _exec_script(conn, seed) - om = ObjectManager(_load(canonical_dir), SqliteDriver(conn)) + om = ObjectManagerDb(_load(canonical_dir), SqliteDriver(conn)) _run_queries(scenario, om) def run_mysql(scenario: QueryScenario, info: MySqlInfo, canonical_dir: Path) -> None: """Run *scenario* on MySQL: *info* names an EMPTY database; ``canonical/schema.mysql.sql`` is executed verbatim, the seed is re-spelled for MySQL, and the queries run through the - ObjectManager with the MySQL driver. The expectations are the Postgres wire ones.""" + ObjectManagerDb with the MySQL driver. The expectations are the Postgres wire ones.""" engine = ScenarioEngine.MYSQL with closing(mysql_connect(info)) as conn: _exec_script(conn, (canonical_dir.parent / engine.schema_artifact).read_text()) seed = engine.seed(scenario) if seed and seed.strip(): _exec_script(conn, seed) - om = ObjectManager(_load(canonical_dir), MySqlDriver(conn)) + om = ObjectManagerDb(_load(canonical_dir), MySqlDriver(conn)) _run_queries(scenario, om) @@ -91,7 +91,7 @@ def _exec_script(conn: Any, script: str) -> None: cur.close() -def _run_queries(scenario: QueryScenario, om: ObjectManager) -> None: +def _run_queries(scenario: QueryScenario, om: ObjectManagerDb) -> None: for spec in scenario.queries: # FR-017 TPH: an op marked `expect-error: true` (a cross-subtype write) # MUST be rejected by the runtime — a raise is the pass (mirrors TS/C#). @@ -112,11 +112,11 @@ def _run_queries(scenario: QueryScenario, om: ObjectManager) -> None: # ---------------------------------------------------------------------------- -# DSL → ObjectManager +# DSL → ObjectManagerDb # ---------------------------------------------------------------------------- -def _execute_spec(om: ObjectManager, spec: QuerySpec) -> Any: +def _execute_spec(om: ObjectManagerDb, spec: QuerySpec) -> Any: if spec.op == "create": # FR-017 TPH: INSERT a row through the runtime write path, returning the # inserted row (asserted as a single row, like get/update). A subtype @@ -244,7 +244,7 @@ def _execute(info: Any, sql: str) -> None: cur.close() -def _assert_typed_decimals(scenario_path: str, spec: QuerySpec, actual: Any, om: ObjectManager) -> None: +def _assert_typed_decimals(scenario_path: str, spec: QuerySpec, actual: Any, om: ObjectManagerDb) -> None: """The typed decimal gate (ADR-0019 Amendment 1): BEFORE any normalization, every field the model declares decimal (an entity field, or a report's derived decimal measure) must be ``None`` or a ``Decimal``. A float or a string fails, so the boundary can never launder a diff --git a/server/python/tests/integration/report_lane.py b/server/python/tests/integration/report_lane.py index ebb394522c..162b9a4db1 100644 --- a/server/python/tests/integration/report_lane.py +++ b/server/python/tests/integration/report_lane.py @@ -1,9 +1,9 @@ -"""One database engine of the api-contract ``report/`` lane: schema, seed, ObjectManager. +"""One database engine of the api-contract ``report/`` lane: schema, seed, ObjectManagerDb. The corpus ships a TypeScript-produced schema per engine (``report/schema..sql``: the four base tables and the nine report views). A lane executes it verbatim into an EMPTY database, seeds the base tables from ``seed.json`` (every key but ``reports``; the keys are -listed parents first), and reads the views through the ObjectManager with the engine's driver. +listed parents first), and reads the views through the ObjectManagerDb with the engine's driver. """ from __future__ import annotations @@ -17,7 +17,7 @@ import pg8000.dbapi as pg8000 -from metaobjects.runtime import MySqlDriver, ObjectManager, PostgresDriver, SqliteDriver +from metaobjects.runtime import MySqlDriver, ObjectManagerDb, PostgresDriver, SqliteDriver from metaobjects.runtime.dialect import Dialect, MYSQL, POSTGRES, SQLITE from .engines import split_statements @@ -35,7 +35,7 @@ class ReportLane: engine: str conn: Any - om: ObjectManager + om: ObjectManagerDb #: base tables in seed order (parents first): name -> rows base_tables: dict[str, list[dict[str, Any]]] #: what the views are expected to return for the full seed @@ -137,17 +137,17 @@ def open_lane( password=info.password, database=info.database, )) as conn: _exec_script(conn, schema) - yield ReportLane(engine, conn, ObjectManager(root, PostgresDriver(conn)), base, reports) + yield ReportLane(engine, conn, ObjectManagerDb(root, PostgresDriver(conn)), base, reports) elif engine == "sqlite": assert sqlite_path is not None # check_same_thread=False: the generated sync routes run on the framework's threadpool. with closing(sqlite3.connect(str(sqlite_path), check_same_thread=False)) as conn: _exec_script(conn, schema) - yield ReportLane(engine, conn, ObjectManager(root, SqliteDriver(conn)), base, reports) + yield ReportLane(engine, conn, ObjectManagerDb(root, SqliteDriver(conn)), base, reports) elif engine == "mysql": assert mysql is not None with closing(mysql_connect(mysql)) as conn: _exec_script(conn, schema) - yield ReportLane(engine, conn, ObjectManager(root, MySqlDriver(conn)), base, reports) + yield ReportLane(engine, conn, ObjectManagerDb(root, MySqlDriver(conn)), base, reports) else: raise ValueError(f"unknown engine {engine!r}") diff --git a/server/python/tests/integration/test_api_contract_decimal.py b/server/python/tests/integration/test_api_contract_decimal.py index a9f8aa4df0..917752b6c9 100644 --- a/server/python/tests/integration/test_api_contract_decimal.py +++ b/server/python/tests/integration/test_api_contract_decimal.py @@ -4,7 +4,7 @@ writable ``Entry`` router and the served ``EntryTotals`` report router) on a REAL database: the corpus' TypeScript-produced ``schema..sql`` runs verbatim on Postgres, SQLite and MySQL 8.4, ``entries`` is seeded from ``seed.json`` (amounts are strings, never numbers), and -each generated consumer seam is an ``ObjectManager`` repository. A scenario's top-level +each generated consumer seam is an ``ObjectManagerDb`` repository. A scenario's top-level ``engines:`` is EXACT (an unknown name is an error); without it a scenario runs on every engine the lane has. diff --git a/server/python/tests/integration/test_api_contract_duration.py b/server/python/tests/integration/test_api_contract_duration.py index d10d46964a..a77ea5c8fb 100644 --- a/server/python/tests/integration/test_api_contract_duration.py +++ b/server/python/tests/integration/test_api_contract_duration.py @@ -3,7 +3,7 @@ Drives ``fixtures/api-contract-conformance/duration/`` against the GENERATED ``Timer`` router on a REAL database: the corpus' ``schema..sql`` runs verbatim on Postgres, SQLite and MySQL 8.4, ``timers`` is seeded from ``seed.json`` (empty, so the first POST is id 1), and the -generated consumer seam is an ``ObjectManager`` repository. The corpus config pins +generated consumer seam is an ``ObjectManagerDb`` repository. The corpus config pins ``wire.durations: iso``. A scenario's top-level ``engines:`` is EXACT; without it a scenario runs on every engine the lane has. Same harness as ``test_api_contract_decimal.py``. """ diff --git a/server/python/tests/integration/test_api_contract_report.py b/server/python/tests/integration/test_api_contract_report.py index cef383e7e7..337b1c15fb 100644 --- a/server/python/tests/integration/test_api_contract_report.py +++ b/server/python/tests/integration/test_api_contract_report.py @@ -4,7 +4,7 @@ served reports (the deployed artifact), on a REAL database: the corpus' TypeScript-produced ``schema..sql`` (four tables and nine views) is executed verbatim on Postgres, SQLite and MySQL 8.4, the base tables are seeded from ``seed.json``, and the repository behind each -generated consumer seam is the adopter-owned ``ObjectManager`` implementation reading the +generated consumer seam is the adopter-owned ``ObjectManagerDb`` implementation reading the real view. Every scenario runs on every engine. Generated lane only, by design -- see the corpus README. The thing under test is whether diff --git a/server/python/tests/integration/test_duration_postgres.py b/server/python/tests/integration/test_duration_postgres.py index e20e85789d..16f46d462b 100644 --- a/server/python/tests/integration/test_duration_postgres.py +++ b/server/python/tests/integration/test_duration_postgres.py @@ -1,4 +1,4 @@ -"""field.duration on a live Postgres through the ObjectManager: the shared interval codec +"""field.duration on a live Postgres through the ObjectManagerDb: the shared interval codec vectors against each driver's native read path. Ordering, range filters and the canonical wire form are gated by ``test_api_contract_duration.py`` (the ``api-contract-conformance/duration`` corpus), which replaced the bespoke ordering test that lived here.""" @@ -15,7 +15,7 @@ from metaobjects import load_string from metaobjects.codegen.runtime.duration_wire import format_duration from metaobjects.naming import NamingRules -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver from .postgres_container import PostgresContainer @@ -66,7 +66,7 @@ def _psycopg2(info: Any) -> Any: def test_an_interval_reads_as_its_span_and_one_with_a_month_part_is_refused(connect: Any) -> None: """The shared ``postgres`` / ``postgresRefused`` vectors against the native read path: each interval is stored by Postgres itself and read back through the driver and the - ObjectManager. Left to themselves pg8000 drops the sign of a negative time part + ObjectManagerDb. Left to themselves pg8000 drops the sign of a negative time part (``-00:01:30`` is +90 s) and psycopg makes a month 30 days; neither reaches a duration.""" root: Any = load_string(json.dumps(_META)).root root.naming = NamingRules(columns="literal") @@ -76,7 +76,7 @@ def test_an_interval_reads_as_its_span_and_one_with_a_month_part_is_refused(conn cur.execute('CREATE TABLE "holds" ("id" BIGINT PRIMARY KEY, "holdFor" INTERVAL)') conn.commit() driver = PostgresDriver(conn) - om = ObjectManager(root, driver) + om = ObjectManagerDb(root, driver) dcur = driver._cursor() dcur.execute("SELECT ARRAY[CAST('-01:30:00' AS interval), CAST('-00:00:01.5' AS interval)]") assert [format_duration(d) for d in dcur.fetchone()[0]] == ["-PT1H30M", "-PT1.5S"] diff --git a/server/python/tests/integration/test_enum_default_live.py b/server/python/tests/integration/test_enum_default_live.py index 3f47739a06..59f05a25d9 100644 --- a/server/python/tests/integration/test_enum_default_live.py +++ b/server/python/tests/integration/test_enum_default_live.py @@ -24,7 +24,7 @@ from metaobjects import load_string from metaobjects.codegen.generators.entity_model import render_entity_model from metaobjects.meta.core.object.meta_object import MetaObject -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver from .postgres_container import PostgresContainer @@ -90,7 +90,7 @@ def _setting_model() -> Any: @pytest.fixture -def pg() -> Iterator[tuple[ObjectManager, Any]]: +def pg() -> Iterator[tuple[ObjectManagerDb, Any]]: with PostgresContainer() as container: info = container.info() with closing(pg8000.connect( @@ -100,7 +100,7 @@ def pg() -> Iterator[tuple[ObjectManager, Any]]: cur = conn.cursor() cur.execute(_DDL) conn.commit() - yield ObjectManager(_root(), PostgresDriver(conn)), conn + yield ObjectManagerDb(_root(), PostgresDriver(conn)), conn def _raw(conn: Any, title: str) -> tuple[Any, ...]: @@ -115,21 +115,21 @@ def test_a_model_built_without_the_enum_holds_its_default() -> None: assert [getattr(model, f) for f in _FIELDS] == ["MANUAL", "MANUAL", "HIGH", "HIGH", "HIGH", "HIGH"] -def test_a_create_that_omits_the_enum_stores_its_default(pg: tuple[ObjectManager, Any]) -> None: +def test_a_create_that_omits_the_enum_stores_its_default(pg: tuple[ObjectManagerDb, Any]) -> None: om, conn = pg created = om.create("Setting", {"title": "omitted"}) assert _raw(conn, "omitted") == _DEFAULTED assert created["band"] == "HIGH" -def test_a_model_built_without_the_enum_is_stored_as_its_default(pg: tuple[ObjectManager, Any]) -> None: +def test_a_model_built_without_the_enum_is_stored_as_its_default(pg: tuple[ObjectManagerDb, Any]) -> None: om, conn = pg model = _setting_model()(title="model") om.create("Setting", model.model_dump(mode="json", exclude={"id"})) assert _raw(conn, "model") == _DEFAULTED -def test_an_explicit_first_member_and_null_are_stored_as_set(pg: tuple[ObjectManager, Any]) -> None: +def test_an_explicit_first_member_and_null_are_stored_as_set(pg: tuple[ObjectManagerDb, Any]) -> None: om, conn = pg om.create("Setting", {"title": "set", "mode": "AUTO", "optMode": None, "rank": "LOW", "optRank": None, "band": "LOW", "optBand": None}) diff --git a/server/python/tests/integration/test_generated_decimal_wire.py b/server/python/tests/integration/test_generated_decimal_wire.py index ec857760fe..f47f2b9d8e 100644 --- a/server/python/tests/integration/test_generated_decimal_wire.py +++ b/server/python/tests/integration/test_generated_decimal_wire.py @@ -1,6 +1,6 @@ """The decimal wire rule (ADR-0019 Amendment 1) through a GENERATED router over HTTP. -The router is the real generator's output, mounted unmodified over an ObjectManager on an +The router is the real generator's output, mounted unmodified over an ObjectManagerDb on an in-memory SQLite database, so the three seams are exercised together: the request body (W2), the filter operand (W2) and the SQLite read (W4) in, and the canonical string (W1) out. """ @@ -27,7 +27,7 @@ from metaobjects.codegen.generators.router_generator import render_router from metaobjects.codegen.runtime.filter_parser import FilterPredicate from metaobjects.codegen.runtime.m2m_codegen import build_object_index -from metaobjects.runtime import ObjectManager, SqliteDriver +from metaobjects.runtime import ObjectManagerDb, SqliteDriver from metaobjects.wire import WireFormat @@ -60,7 +60,7 @@ def _is_validation(body: object) -> bool: class _Repo: - def __init__(self, om: ObjectManager) -> None: + def __init__(self, om: ObjectManagerDb) -> None: self.om = om self.lock = threading.Lock() @@ -121,7 +121,7 @@ def _make_client(wire: WireFormat) -> TestClient: sys.path.remove(str(tmp)) db = sqlite3.connect(":memory:", check_same_thread=False) db.execute("CREATE TABLE entries (id INTEGER PRIMARY KEY AUTOINCREMENT, amount NUMERIC, note NUMERIC)") - repo = _Repo(ObjectManager(root, SqliteDriver(db))) # type: ignore[arg-type] + repo = _Repo(ObjectManagerDb(root, SqliteDriver(db))) # type: ignore[arg-type] app = FastAPI() app.include_router(mod.router) app.dependency_overrides[mod.get_repository] = lambda: repo @@ -203,7 +203,7 @@ def test_the_runtime_itself_returns_a_decimal() -> None: root = load_string(json.dumps(_META)).root db = sqlite3.connect(":memory:") db.execute("CREATE TABLE entries (id INTEGER PRIMARY KEY AUTOINCREMENT, amount NUMERIC, note NUMERIC)") - om = ObjectManager(root, SqliteDriver(db)) # type: ignore[arg-type] + om = ObjectManagerDb(root, SqliteDriver(db)) # type: ignore[arg-type] row = om.create("Entry", {"amount": Decimal("0.1") + Decimal("0.2")}) assert row["amount"] == Decimal("0.3") and isinstance(row["amount"], Decimal) @@ -275,7 +275,7 @@ def _make_float_client(wire: WireFormat) -> TestClient: sys.path.remove(str(tmp)) db = sqlite3.connect(":memory:", check_same_thread=False) db.execute("CREATE TABLE samples (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL, series TEXT, fix TEXT, fixes TEXT, tiers TEXT, pricing TEXT)") - om = ObjectManager(root, SqliteDriver(db)) # type: ignore[arg-type] + om = ObjectManagerDb(root, SqliteDriver(db)) # type: ignore[arg-type] class Repo(_Repo): def list(self, limit: int, offset: int, sort: Any, filters: list[FilterPredicate]) -> list[Any]: @@ -369,7 +369,7 @@ def test_a_decimal_array_is_range_checked_element_wise_and_coerced_for_the_drive root = load_string(json.dumps(_FLOAT_META)).root sample = next(c for c in root.children() if c.name.endswith("Sample")) series = next(f for f in sample.fields() if f.name == "series") - from metaobjects.runtime.object_manager import _coerce_write_value + from metaobjects.runtime.values import coerce_write_value as _coerce_write_value assert _coerce_write_value(series, [Decimal("1.5"), "2", 3, None]) == [Decimal("1.5"), Decimal("2"), Decimal("3"), None] diff --git a/server/python/tests/integration/test_int_enum_array_live.py b/server/python/tests/integration/test_int_enum_array_live.py index 56fbe8919c..8319551371 100644 --- a/server/python/tests/integration/test_int_enum_array_live.py +++ b/server/python/tests/integration/test_int_enum_array_live.py @@ -1,6 +1,6 @@ """An int-backed ``field.enum`` ARRAY on a live Postgres: the stored elements are ints. -The unit tests pin the codec in isolation; this drives the real ``ObjectManager`` and pg8000 +The unit tests pin the codec in isolation; this drives the real ``ObjectManagerDb`` and pg8000 against an ``integer[]`` column and reads the RAW column back, so the failure mode the old load-time refusal guarded against (member symbols persisted into the array) cannot hide behind a codec that only round-trips with itself. @@ -23,7 +23,7 @@ import pytest from metaobjects import load_string -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver from .postgres_container import PostgresContainer @@ -55,7 +55,7 @@ @pytest.fixture -def pg() -> Iterator[tuple[ObjectManager, Any]]: +def pg() -> Iterator[tuple[ObjectManagerDb, Any]]: with PostgresContainer() as container: info = container.info() with closing(pg8000.connect( @@ -67,7 +67,7 @@ def pg() -> Iterator[tuple[ObjectManager, Any]]: conn.commit() result = load_string(json.dumps(_META)) assert result.errors == [], result.errors - yield ObjectManager(result.root, PostgresDriver(conn)), conn + yield ObjectManagerDb(result.root, PostgresDriver(conn)), conn def _raw(conn: Any, id_value: int) -> Any: @@ -78,7 +78,7 @@ def _raw(conn: Any, id_value: int) -> Any: return history -def test_int_backed_enum_array_round_trips_and_stores_ints(pg: tuple[ObjectManager, Any]) -> None: +def test_int_backed_enum_array_round_trips_and_stores_ints(pg: tuple[ObjectManagerDb, Any]) -> None: om, conn = pg created = om.create("Order", {"id": 1, "status": "PUBLISHED", "history": ["PUBLISHED", "DRAFT"]}) @@ -108,7 +108,7 @@ def test_int_backed_enum_array_round_trips_and_stores_ints(pg: tuple[ObjectManag assert [r["id"] for r in rows] == [1] -def test_an_unmapped_stored_element_fails_the_read(pg: tuple[ObjectManager, Any]) -> None: +def test_an_unmapped_stored_element_fails_the_read(pg: tuple[ObjectManagerDb, Any]) -> None: om, conn = pg cur = conn.cursor() cur.execute('INSERT INTO "orders" ("id", "history") VALUES (1, \'{0,7}\')') diff --git a/server/python/tests/integration/test_llm_call_trace.py b/server/python/tests/integration/test_llm_call_trace.py index 79463c1a27..7fb4ba5633 100644 --- a/server/python/tests/integration/test_llm_call_trace.py +++ b/server/python/tests/integration/test_llm_call_trace.py @@ -1,6 +1,6 @@ """Real-Postgres round-trip oracle for the AI-trace recorder (Slice 1, Python port). -Proves a typed LLM-call trace persists + reads back through the ObjectManager +Proves a typed LLM-call trace persists + reads back through the ObjectManagerDb runtime against a live Postgres: a trace entity extending the SHIPPED ``metaobjects::ai::LlmCallBase`` (library/ai/model.yaml) plus a typed ``voResponse`` (field.object + @objectRef + @storage:jsonb). Asserts BOTH the raw @@ -8,7 +8,7 @@ voResponse jsonb round-trip. Mirrors test_runtime_return_types: a docker-CLI PostgresContainer + pg8000 + -ObjectManager, schema provisioned by explicit DDL (ADR-0015: pure data-access). +ObjectManagerDb, schema provisioned by explicit DDL (ADR-0015: pure data-access). Not part of the default unit run — requires Docker. """ from __future__ import annotations @@ -20,7 +20,7 @@ from metaobjects.naming import NamingRules from metaobjects.runtime import ( LlmCallInput, - ObjectManager, + ObjectManagerDb, ObjectManagerLlmCallRecorder, PostgresDriver, build_llm_call_row, @@ -74,7 +74,7 @@ def _connect(info): def test_typed_trace_round_trips_through_postgres() -> None: # voResponse is AUTHORED in the fixture (field.object + @objectRef + jsonb). # No derivation: this proves the recorder persists the authored typed column - # through the metadata-driven ObjectManager runtime. + # through the metadata-driven ObjectManagerDb runtime. loader = MetaDataLoader(strict=True) result = loader.load([ FileSource(_repo_file("library/ai/model.yaml")), @@ -95,7 +95,7 @@ def test_typed_trace_round_trips_through_postgres() -> None: conn.commit() cur.close() - om = ObjectManager(result.root, PostgresDriver(conn)) + om = ObjectManagerDb(result.root, PostgresDriver(conn)) # Capture (don't swallow) write failures so the round-trip fails loudly. write_errors: list[BaseException] = [] recorder = ObjectManagerLlmCallRecorder(om, _ENTITY, on_error=write_errors.append) diff --git a/server/python/tests/integration/test_query_scenarios.py b/server/python/tests/integration/test_query_scenarios.py index 9594d815eb..020ec1d78a 100644 --- a/server/python/tests/integration/test_query_scenarios.py +++ b/server/python/tests/integration/test_query_scenarios.py @@ -3,11 +3,11 @@ Postgres: each scenario provisions a fresh Postgres, applies the committed TS-produced ``canonical/schema.postgres.sql`` verbatim (schema migrations are TS-only -- ADR-0015), then -runs the query DSL through the ObjectManager runtime. +runs the query DSL through the ObjectManagerDb runtime. SQLite and MySQL 8.4: the same ``report-*`` scenarios run against the engine's own TS-produced artifact (``canonical/schema.sqlite.sql`` / ``schema.mysql.sql``), through the -ObjectManager's SQLite and MySQL drivers. The ``expect`` blocks stay the Postgres wire ones; +ObjectManagerDb's SQLite and MySQL drivers. The ``expect`` blocks stay the Postgres wire ones; the runtime decodes each engine's values to the declared field types and the same serialization boundary canonicalizes them. ``report-relative-date`` carries a per-engine seed (``seed-data-engine``). One MySQL server serves the whole session; each scenario starts from @@ -30,7 +30,7 @@ # single-table-inheritance support — resolving a discriminator subtype's # inherited fields / identity / shared table via ``extends`` plus discriminator # inject/scope/strip. FR-017 Tier-4: the Python runtime now ships TPH support -# (ObjectManager discriminator inject/scope/strip + runtime/tph.py), so the +# (ObjectManagerDb discriminator inject/scope/strip + runtime/tph.py), so the # ``tph-*`` scenarios run green and are no longer skipped. EXPECTED_FAILURES: dict[str, str] = {} diff --git a/server/python/tests/integration/test_runtime_return_types.py b/server/python/tests/integration/test_runtime_return_types.py index 1df12c313c..dd057fd160 100644 --- a/server/python/tests/integration/test_runtime_return_types.py +++ b/server/python/tests/integration/test_runtime_return_types.py @@ -1,13 +1,13 @@ """SP-D Unit 4 — runtime return-type gate (Python port). -Pins ADR-0019: the ``ObjectManager`` runtime returns NATIVE, in-process Python +Pins ADR-0019: the ``ObjectManagerDb`` runtime returns NATIVE, in-process Python types from its query path — NOT canonicalized wire-strings. Wire canonicalization (the ``normalization.py`` forms) is a boundary concern applied by the persistence runner, never inside the runtime. Unit 3 moved -``_coerce_for_contract`` out of ``ObjectManager`` into the runner, so the +``_coerce_for_contract`` out of ``ObjectManagerDb`` into the runner, so the runtime now hands back pg8000's own native types. -This reads the dict ``ObjectManager.find_by_id`` returns BEFORE any +This reads the dict ``ObjectManagerDb.find_by_id`` returns BEFORE any normalization and asserts each native type: - ``Measurement.id`` (BIGINT) → ``int`` (a native integer). @@ -30,7 +30,7 @@ class of bug Unit 3 fixed: a runtime baking wire-strings into its query path. from metaobjects import load_directory from metaobjects.naming import attach_naming -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver from .postgres_container import PostgresContainer from .query_runner import _apply_schema_artifact, SCHEMA_ARTIFACT_FILE @@ -87,7 +87,7 @@ def test_runtime_returns_native_types_not_wire_strings() -> None: with closing(pg8000.connect( host=info.host, port=info.port, user=info.user, password=info.password, database=info.database, )) as conn: - om = ObjectManager(root, PostgresDriver(conn)) + om = ObjectManagerDb(root, PostgresDriver(conn)) # --- Measurement: native integer + native exact decimal --------------- m = om.find_by_id("Measurement", 1) diff --git a/server/python/tests/integration/test_schema_qualified_live.py b/server/python/tests/integration/test_schema_qualified_live.py index b5337bbf30..e425d9f4e2 100644 --- a/server/python/tests/integration/test_schema_qualified_live.py +++ b/server/python/tests/integration/test_schema_qualified_live.py @@ -1,7 +1,7 @@ """A ``source.rdb @schema`` places the relation the runtime reads and writes, on a live Postgres. ``meta migrate`` creates a table declared with ``@schema: sales`` as ``"sales"."payers"``, so the -ObjectManager must address it there, not as a bare ``"payers"`` (which ``search_path`` resolves to +ObjectManagerDb must address it there, not as a bare ``"payers"`` (which ``search_path`` resolves to ``public``, a different table or none). Two ``Payer`` tables in two schemas are two relations. """ from __future__ import annotations @@ -15,7 +15,7 @@ import pytest from metaobjects import load_string -from metaobjects.runtime import ObjectManager, PostgresDriver +from metaobjects.runtime import ObjectManagerDb, PostgresDriver from .postgres_container import PostgresContainer @@ -47,7 +47,7 @@ def test_a_schema_qualified_entity_is_read_and_written_in_its_schema(pg: Any) -> for schema in ("sales", "billing"): result = load_string(json.dumps(_payer(schema, schema))) assert result.errors == [], result.errors - om = ObjectManager(result.root, PostgresDriver(pg)) + om = ObjectManagerDb(result.root, PostgresDriver(pg)) om.create("Payer", {"id": 1, "label": schema}) assert om.find_by_id("Payer", 1)["label"] == schema assert [r["label"] for r in om.find_many("Payer")] == [schema] diff --git a/server/python/tests/loader/test_expression_functions_and_casts.py b/server/python/tests/loader/test_expression_functions_and_casts.py new file mode 100644 index 0000000000..09575960f2 --- /dev/null +++ b/server/python/tests/loader/test_expression_functions_and_casts.py @@ -0,0 +1,146 @@ +"""The closed expression grammar's functions and casts (C2): every function and the cast node +validate and infer as the TypeScript reference does, and a CHECK condition refuses what only a +view can hold. The shared corpus pins the loader errors; this pins the rules one by one.""" +from __future__ import annotations + +import pytest + +from metaobjects.loader.validation_passes import ( + EXPR_FUNCTIONS, + cast_problem, + expr_view_only_node, + infer_expr_type, + validate_expr_node, +) + +_FIELDS = { + "s": "string", "t": "string", "n": "int", "big": "long", "d": "decimal", "b": "boolean", + "when": "timestamp", "day": "date", "status": "enum", "code": "enum", "blob": "object", +} + + +def _infer(node: object, int_enums: frozenset[str] = frozenset({"code"})): + return infer_expr_type(node, _FIELDS.get, lambda name: name in int_enums) + + +def _fn(name: str, *args: object) -> dict: + return {"fn": name, "args": list(args)} + + +def _f(name: str) -> dict: + return {"field": name} + + +def _v(value: object) -> dict: + return {"value": value} + + +def test_every_function_is_known_and_arity_checked() -> None: + assert set(EXPR_FUNCTIONS) == { + "coalesce", "greatest", "least", "nullif", "lower", "upper", "btrim", "splitPart", + "concat", "concatWs", "substring", "replace", "left", "right", "length", + } + assert validate_expr_node(_fn("lower", _f("s"))) == [] + assert validate_expr_node(_fn("nope", _f("s"))) == ["unknown expression fn 'nope'"] + assert validate_expr_node(_fn("splitPart", _f("s"), _v("-"))) == ["'splitPart' requires at least 3 args"] + assert validate_expr_node(_fn("lower", _f("s"), _f("t"))) == ["'lower' takes at most 1 args, got 2"] + assert validate_expr_node({"fn": "lower"}) == ["'lower' requires a non-empty args array"] + + +@pytest.mark.parametrize( + ("node", "type_"), + [ + (_fn("lower", _f("s")), "string"), + (_fn("length", _f("s")), "int"), + (_fn("concat", _f("s"), _f("n"), _f("d")), "string"), + (_fn("concatWs", _v("-"), _f("s"), _f("n")), "string"), + (_fn("splitPart", _f("s"), _v("-"), _v(1)), "string"), + (_fn("substring", _f("s"), _f("n")), "string"), + (_fn("greatest", _f("when"), _f("when")), "timestamp"), + (_fn("nullif", _f("s"), _v("")), "string"), + (_fn("coalesce", _f("d"), _v(0)), "decimal"), + ], +) +def test_functions_type_cleanly(node: object, type_: str) -> None: + result = _infer(node) + assert result.errors == [] + assert result.type == type_ + + +def test_function_argument_kinds_are_enforced() -> None: + assert _infer(_fn("lower", _f("n"))).errors == ["'lower' argument 1 must be a string, got int"] + assert _infer(_fn("left", _f("s"), _f("big"))).errors == [ + "'left' argument 2 must be an int, got long; cast it ({ cast: , as: int })" + ] + assert _infer(_fn("concat", _f("blob"))).errors == ["'concat' argument 1 must be a scalar, got object"] + assert _infer(_fn("nullif", _f("s"), _f("n"))).errors == [ + "'nullif' arguments have differing types (string, int)" + ] + assert _infer(_fn("greatest", _f("b"), _f("b"))).errors == ["'greatest' needs ordered arguments, got boolean"] + + +def test_a_null_literal_fits_any_parameter() -> None: + result = _infer(_fn("lower", _v(None))) + assert (result.type, result.errors) == ("string", []) + + +def test_cast_validates_its_shape() -> None: + assert validate_expr_node({"cast": _f("n"), "as": "string"}) == [] + assert validate_expr_node({"cast": _f("n")})[0].startswith("'cast' requires 'as': one of string, int") + assert validate_expr_node({"cast": _f("n"), "as": "currency"})[0].startswith("'cast' requires 'as'") + assert validate_expr_node({"cast": _f("n"), "as": "int", "x": 1}) == [ + "expression 'cast' takes only 'as' and 'dbColumnType' beside it, not x" + ] + ok = {"cast": _f("n"), "as": "string", "dbColumnType": "varchar(10)"} + assert validate_expr_node(ok) == [] + for bad in ( + {"cast": _f("n"), "as": "string", "dbColumnType": "uuid"}, + {"cast": _f("n"), "as": "int", "dbColumnType": "text"}, + {"cast": _f("n"), "as": "string", "dbColumnType": "citext"}, + ): + assert validate_expr_node(bad)[0].startswith("'cast' 'dbColumnType' is a text spelling") + assert validate_expr_node({"cast": {"fn": "nope", "args": [_f("n")]}, "as": "int"}) == [ + "unknown expression fn 'nope'" + ] + + +def test_cast_types_to_its_target_and_applies_the_table() -> None: + assert _infer({"cast": _f("n"), "as": "string"}).type == "string" + assert _infer({"cast": _f("n"), "as": "decimal"}).errors == [] + assert _infer({"cast": _v(None), "as": "string"}).errors == [] + assert _infer({"cast": _f("blob"), "as": "string"}).errors == ["'cast': a field.object value cannot be cast"] + assert _infer({"cast": _f("d"), "as": "boolean"}).errors == [ + "'cast': a decimal cannot be cast to boolean; only an int can" + ] + assert _infer({"cast": _f("b"), "as": "decimal"}).errors == ["'cast': a boolean casts only to int, not decimal"] + assert _infer({"cast": _f("n"), "as": "date"}).errors == ["'cast': a int cannot be cast to date"] + + +def test_an_enum_casts_by_how_it_is_stored() -> None: + assert _infer({"cast": _f("code"), "as": "int"}).errors == [] + assert _infer({"cast": _f("status"), "as": "int"}).errors == [ + "'cast': only an enum stored as an integer (@intValueMap) can be cast to a number" + ] + assert _infer({"cast": _f("status"), "as": "string"}).errors == [] + assert _infer({"cast": _f("code"), "as": "string"}).errors[0].startswith( + "'cast': an int-stored enum (@intValueMap) cast to string gives its integer" + ) + assert _infer({"cast": _f("status"), "as": "boolean"}).errors == ["'cast': an enum cannot be cast to boolean"] + + +def test_cast_problem_table() -> None: + assert cast_problem(None, "int", False) is None + assert cast_problem("string", "uuid", False) is None + assert cast_problem("timestamp", "date", False) is None + assert cast_problem("int", "boolean", False) is None + assert cast_problem("uuid", "int", False) == "a uuid cannot be cast to int" + + +def test_a_check_condition_refuses_what_only_a_view_holds() -> None: + assert expr_view_only_node(_fn("coalesce", _f("n"), _v(0))) is None + assert expr_view_only_node({"op": "gt", "left": _f("n"), "right": _v(0)}) is None + assert expr_view_only_node({"op": "gt", "left": _fn("length", _f("s")), "right": _v(0)}) == "length" + assert expr_view_only_node({"op": "isNull", "arg": {"cast": _f("n"), "as": "string"}}) == "cast" + assert expr_view_only_node({"op": "eq", "left": _f("customer.zip"), "right": _v("1")}) == ( + 'the path "customer.zip"' + ) diff --git a/server/python/tests/loader/test_shipped_library_ai.py b/server/python/tests/loader/test_shipped_library_ai.py index d08e5b7e90..9dc60e6a81 100644 --- a/server/python/tests/loader/test_shipped_library_ai.py +++ b/server/python/tests/loader/test_shipped_library_ai.py @@ -290,7 +290,7 @@ def record(self, row: dict[str, object]) -> None: row = captured[0] # The typed columns are the whole point of the feature — and every key the - # helper writes must be a field the entity declares, or ObjectManager raises + # helper writes must be a field the entity declares, or ObjectManagerDb raises # "no field '' in metadata" on insert. assert row["voResponse"] == {"greeting": "hello"} assert row["voRequest"] == {"prompt": "say hi"} diff --git a/server/python/tests/runtime/test_literal_naming_sqlite.py b/server/python/tests/runtime/test_literal_naming_sqlite.py index 29063182e2..0c74b15b49 100644 --- a/server/python/tests/runtime/test_literal_naming_sqlite.py +++ b/server/python/tests/runtime/test_literal_naming_sqlite.py @@ -1,5 +1,5 @@ """B1, end to end on SQLite: `naming.columns: literal` in the project's -`.metaobjects/config.json`, found by `load_directory`, makes the ObjectManager read a +`.metaobjects/config.json`, found by `load_directory`, makes the ObjectManagerDb read a table whose columns are the literal field names.""" from __future__ import annotations @@ -8,7 +8,7 @@ from pathlib import Path from metaobjects import load_directory -from metaobjects.runtime import ObjectManager, SqliteDriver +from metaobjects.runtime import ObjectManagerDb, SqliteDriver _META = { "metadata.root": { @@ -44,14 +44,14 @@ def _db() -> sqlite3.Connection: def test_literal_columns_are_read_through_the_object_manager(tmp_path: Path) -> None: meta = _project(tmp_path, {"columns": "literal"}) - om = ObjectManager(load_directory(meta).root, SqliteDriver(_db())) # type: ignore[arg-type] + om = ObjectManagerDb(load_directory(meta).root, SqliteDriver(_db())) # type: ignore[arg-type] assert om.find_many("Item") == [{"id": 1, "unitPrice": "ten"}] assert om.create("Item", {"unitPrice": "five"})["unitPrice"] == "five" def test_without_the_setting_the_runtime_does_not_read_the_literal_column(tmp_path: Path) -> None: meta = _project(tmp_path, {}) - om = ObjectManager(load_directory(meta).root, SqliteDriver(_db())) # type: ignore[arg-type] + om = ObjectManagerDb(load_directory(meta).root, SqliteDriver(_db())) # type: ignore[arg-type] # SQLite reads an unknown double-quoted identifier as a string literal, so the wrong # name does not error: it answers with the name itself, and the stored value is never read. assert "ten" not in om.find_many("Item")[0].values() diff --git a/server/python/tests/runtime/test_object_manager_contract.py b/server/python/tests/runtime/test_object_manager_contract.py new file mode 100644 index 0000000000..16e63db864 --- /dev/null +++ b/server/python/tests/runtime/test_object_manager_contract.py @@ -0,0 +1,285 @@ +"""The ObjectManager contract (L-PY-1): the abstract class, the DB-API manager that implements it, +transactions and persistence listeners. + +``ObjectManager`` is abstract; ``ObjectManagerDb(root, driver)`` is the one for a DB-API +connection. The constructor the previous release took, ``ObjectManager(root, driver)``, is a +clean break with no shim: it fails and says what to construct instead. +""" +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path +from typing import Any + +import pytest + +from metaobjects import load_directory +from metaobjects.runtime import ( + ObjectManager, + ObjectManagerDb, + PersistenceListener, + SqliteDriver, +) + + +def _model(tmp_path: Path) -> Any: + meta = tmp_path / "metaobjects" + meta.mkdir() + (meta / "meta.notes.json").write_text( + json.dumps({ + "metadata.root": { + "package": "acme::notes", + "children": [{ + "object.entity": { + "name": "Note", + "children": [ + {"source.rdb": {"@table": "notes"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "body"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ], + } + }], + } + }), + encoding="utf-8", + ) + result = load_directory(meta) + assert [e.code for e in result.errors] == [] + return result.root + + +def _om(tmp_path: Path) -> tuple[ObjectManagerDb, sqlite3.Connection]: + conn = sqlite3.connect(":memory:") + conn.execute('CREATE TABLE "notes" ("id" INTEGER PRIMARY KEY NOT NULL, "body" TEXT)') + conn.commit() + return ObjectManagerDb(_model(tmp_path), SqliteDriver(conn)), conn + + +def _count(conn: sqlite3.Connection) -> int: + return conn.execute('SELECT COUNT(*) FROM "notes"').fetchone()[0] + + +# --- the split --------------------------------------------------------------------------------- + + +def test_the_db_manager_is_an_object_manager(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + assert isinstance(om, ObjectManager) + assert om.create("Note", {"id": 1, "body": "a"}) == {"id": 1, "body": "a"} + + +def test_the_abstract_class_cannot_be_constructed_and_names_what_to_construct(tmp_path: Path) -> None: + conn = sqlite3.connect(":memory:") + with pytest.raises(TypeError, match=r"abstract.*ObjectManagerDb\(root, driver\)"): + ObjectManager(_model(tmp_path), SqliteDriver(conn)) # type: ignore[abstract, call-arg] + + +def test_a_manager_for_another_store_is_a_subclass_that_supplies_the_store(tmp_path: Path) -> None: + class Memory(ObjectManager): + def __init__(self, root: Any) -> None: + super().__init__(root) + self.rows: dict[Any, dict[str, Any]] = {} + + def transaction(self) -> Any: + raise NotImplementedError + + def find_many(self, entity_name: str, filter: Any = None, *, sort: Any = None, + limit: Any = None, offset: Any = None) -> list[dict[str, Any]]: + return [r for r in self.rows.values() if all(r.get(k) == v for k, v in (filter or {}).items())] + + def count(self, entity_name: str, filter: Any = None) -> int: + return len(self.find_many(entity_name, filter)) + + def relate(self, entity_name: str, record: dict[str, Any], relation_name: str) -> Any: + return [] + + def _insert_row(self, entity: Any, entity_name: str, data: dict[str, Any]) -> dict[str, Any]: + self.rows[data["id"]] = dict(data) + return dict(data) + + def _update_row(self, entity: Any, entity_name: str, id_value: Any, data: dict[str, Any], + if_missing: str) -> dict[str, Any] | None: + if id_value not in self.rows: + return None + self.rows[id_value].update(data) + return dict(self.rows[id_value]) + + def _delete_row(self, entity: Any, entity_name: str, id_value: Any) -> bool: + return self.rows.pop(id_value, None) is not None + + om = Memory(_model(tmp_path)) + om.create("Note", {"id": 1, "body": "a"}) + assert om.find_by_id("Note", 1) == {"id": 1, "body": "a"} + assert om.update("Note", 1, {"body": "b"}) == {"id": 1, "body": "b"} + assert om.delete("Note", 1) is True + assert om.find_by_id("Note", 1) is None + assert om.primary_key_field("Note") == "id" + + +# --- transactions ------------------------------------------------------------------------------ + + +def test_writes_in_a_transaction_commit_together_when_the_block_ends(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + with om.transaction(): + om.create("Note", {"id": 1, "body": "a"}) + om.create("Note", {"id": 2, "body": "b"}) + assert conn.in_transaction # held open, not committed per write + assert om.count("Note") == 2 # and visible to a read inside the block + assert not conn.in_transaction + assert _count(conn) == 2 + + +def test_an_exception_rolls_back_every_write_in_the_block(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + om.create("Note", {"id": 1, "body": "kept"}) + with pytest.raises(RuntimeError, match="boom"): + with om.transaction(): + om.create("Note", {"id": 2, "body": "lost"}) + om.update("Note", 1, {"body": "changed"}) + om.delete("Note", 1) + raise RuntimeError("boom") + assert [r["body"] for r in om.find_many("Note")] == ["kept"] + + +def test_a_nested_block_joins_the_outer_one(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + with om.transaction(): + with om.transaction(): + om.create("Note", {"id": 1, "body": "a"}) + assert conn.in_transaction # the inner block's end did not commit + assert _count(conn) == 1 + with pytest.raises(RuntimeError): + with om.transaction(): + with om.transaction(): + om.create("Note", {"id": 2, "body": "b"}) + raise RuntimeError("outer fails after inner succeeded") + assert _count(conn) == 1 + + +def test_a_write_outside_a_block_still_commits_on_its_own(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + om.create("Note", {"id": 1, "body": "a"}) + assert not conn.in_transaction + assert _count(conn) == 1 + + +def test_the_transaction_is_reusable_after_a_rollback(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + with pytest.raises(ValueError): + with om.transaction(): + om.create("Note", {"id": 1, "body": "a"}) + raise ValueError + with om.transaction(): + om.create("Note", {"id": 1, "body": "again"}) + assert om.find_by_id("Note", 1) == {"id": 1, "body": "again"} + + +# --- listeners --------------------------------------------------------------------------------- + + +class Recording(PersistenceListener): + def __init__(self) -> None: + self.events: list[tuple[Any, ...]] = [] + + def on_before_create(self, entity_name: str, data: dict[str, Any]) -> None: + self.events.append(("before_create", entity_name, dict(data))) + + def on_after_create(self, entity_name: str, row: dict[str, Any]) -> None: + self.events.append(("after_create", entity_name, dict(row))) + + def on_before_update(self, entity_name: str, id_value: Any, data: dict[str, Any]) -> None: + self.events.append(("before_update", entity_name, id_value, dict(data))) + + def on_after_update(self, entity_name: str, id_value: Any, row: dict[str, Any]) -> None: + self.events.append(("after_update", entity_name, id_value, dict(row))) + + def on_before_delete(self, entity_name: str, id_value: Any) -> None: + self.events.append(("before_delete", entity_name, id_value)) + + def on_after_delete(self, entity_name: str, id_value: Any) -> None: + self.events.append(("after_delete", entity_name, id_value)) + + +def test_listeners_see_each_write_before_and_after(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + rec = Recording() + om.add_listener(rec) + om.create("Note", {"id": 1, "body": "a"}) + om.update("Note", 1, {"body": "b"}) + om.delete("Note", 1) + assert rec.events == [ + ("before_create", "Note", {"id": 1, "body": "a"}), + ("after_create", "Note", {"id": 1, "body": "a"}), + ("before_update", "Note", 1, {"body": "b"}), + ("after_update", "Note", 1, {"id": 1, "body": "b"}), + ("before_delete", "Note", 1), + ("after_delete", "Note", 1), + ] + + +def test_insert_preserving_notifies_as_a_create(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + rec = Recording() + om.add_listener(rec) + om.insert_preserving("Note", {"id": 1, "body": "a"}) + assert [e[0] for e in rec.events] == ["before_create", "after_create"] + + +def test_after_events_are_not_sent_when_nothing_matched(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + rec = Recording() + om.add_listener(rec) + assert om.update("Note", 99, {"body": "x"}) is None + assert om.delete("Note", 99) is False + assert [e[0] for e in rec.events] == ["before_update", "before_delete"] + + +def test_a_before_listener_can_refuse_the_write(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + + class Veto(PersistenceListener): + def on_before_create(self, entity_name: str, data: dict[str, Any]) -> None: + raise PermissionError("not today") + + om.add_listener(Veto()) + with pytest.raises(PermissionError): + om.create("Note", {"id": 1, "body": "a"}) + assert _count(conn) == 0 + + +def test_an_after_listener_failing_inside_a_transaction_rolls_it_back(tmp_path: Path) -> None: + om, conn = _om(tmp_path) + + class Audit(PersistenceListener): + def on_after_create(self, entity_name: str, row: dict[str, Any]) -> None: + if row["id"] == 2: + raise RuntimeError("audit store down") + + om.add_listener(Audit()) + with pytest.raises(RuntimeError, match="audit store down"): + with om.transaction(): + om.create("Note", {"id": 1, "body": "a"}) + om.create("Note", {"id": 2, "body": "b"}) + assert _count(conn) == 0 + + +def test_a_removed_listener_hears_nothing_more(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + rec = Recording() + om.add_listener(rec) + om.remove_listener(rec) + om.remove_listener(rec) # removing one that is not registered is ignored + om.create("Note", {"id": 1, "body": "a"}) + assert rec.events == [] + + +def test_an_unknown_entity_is_refused_before_any_listener_hears_of_it(tmp_path: Path) -> None: + om, _ = _om(tmp_path) + rec = Recording() + om.add_listener(rec) + with pytest.raises(KeyError): + om.create("Nobody", {"id": 1}) + assert rec.events == [] diff --git a/server/python/tests/runtime/test_object_manager_currency_read.py b/server/python/tests/runtime/test_object_manager_db_currency_read.py similarity index 94% rename from server/python/tests/runtime/test_object_manager_currency_read.py rename to server/python/tests/runtime/test_object_manager_db_currency_read.py index 1115271c45..d8268b9159 100644 --- a/server/python/tests/runtime/test_object_manager_currency_read.py +++ b/server/python/tests/runtime/test_object_manager_db_currency_read.py @@ -1,4 +1,4 @@ -"""field.currency read decoding — the Python ObjectManager. +"""field.currency read decoding — the Python ObjectManagerDb. Currency is integer minor units, natively and on the wire. A table column stores it as BIGINT, which pg8000 already hands back as an ``int``. A VIEW column need not: ``SUM`` over @@ -14,7 +14,7 @@ from metaobjects.loader.meta_data_loader import MetaDataLoader from metaobjects.loader.sources import InMemoryStringSource -from metaobjects.runtime.object_manager import _decode_read_value +from metaobjects.runtime.values import decode_read_value as _decode_read_value MODEL = """{"metadata.root": {"package": "acme", "children": [ {"object.entity": {"name": "Leg", "children": [ diff --git a/server/python/tests/runtime/test_object_manager_derived_without_read_source.py b/server/python/tests/runtime/test_object_manager_db_derived_without_read_source.py similarity index 81% rename from server/python/tests/runtime/test_object_manager_derived_without_read_source.py rename to server/python/tests/runtime/test_object_manager_db_derived_without_read_source.py index 1fb0b5155f..5da192d2f9 100644 --- a/server/python/tests/runtime/test_object_manager_derived_without_read_source.py +++ b/server/python/tests/runtime/test_object_manager_db_derived_without_read_source.py @@ -1,7 +1,7 @@ """An entity may carry a derived (``origin.*``) field that only a projection reads, with no read view of its own: the shared fixture ``entity-derived-filter-gate`` (``Member.hasActiveAgreement``, an ``origin.first`` a projection's ``@filter`` reaches). Its table, the one ``meta migrate`` -creates, has no column for that field, so the ObjectManager reads the table without it. Before, +creates, has no column for that field, so the ObjectManagerDb reads the table without it. Before, the SELECT named ``has_active_agreement`` and the read failed on every engine. """ from __future__ import annotations @@ -10,18 +10,18 @@ from pathlib import Path from metaobjects import load_directory -from metaobjects.runtime import ObjectManager, SqliteDriver +from metaobjects.runtime import ObjectManagerDb, SqliteDriver _FIXTURE = Path(__file__).resolve().parents[4] / "fixtures" / "conformance" / "entity-derived-filter-gate" / "input" -def _om() -> ObjectManager: +def _om() -> ObjectManagerDb: result = load_directory(_FIXTURE) assert [e.code for e in result.errors] == [] conn = sqlite3.connect(":memory:") conn.execute('CREATE TABLE "members" ("id" INTEGER PRIMARY KEY NOT NULL)') conn.execute('INSERT INTO "members" ("id") VALUES (7)') - return ObjectManager(result.root, SqliteDriver(conn)) + return ObjectManagerDb(result.root, SqliteDriver(conn)) def test_a_list_read_selects_no_column_for_the_derived_field() -> None: diff --git a/server/python/tests/runtime/test_object_manager_dialects.py b/server/python/tests/runtime/test_object_manager_db_dialects.py similarity index 96% rename from server/python/tests/runtime/test_object_manager_dialects.py rename to server/python/tests/runtime/test_object_manager_db_dialects.py index ab8d374167..216126e5c7 100644 --- a/server/python/tests/runtime/test_object_manager_dialects.py +++ b/server/python/tests/runtime/test_object_manager_db_dialects.py @@ -1,4 +1,4 @@ -"""The ObjectManager on SQLite and MySQL: the SQL each driver's dialect emits, and the values +"""The ObjectManagerDb on SQLite and MySQL: the SQL each driver's dialect emits, and the values it decodes. SQLite runs for real (stdlib ``sqlite3``, in memory) with a recording connection wrapped around @@ -24,7 +24,7 @@ POSTGRES, SQLITE, MySqlDriver, - ObjectManager, + ObjectManagerDb, PostgresDriver, SqliteDriver, ) @@ -95,11 +95,11 @@ def close(self) -> None: ) -def _sqlite_om() -> tuple[ObjectManager, Recording]: +def _sqlite_om() -> tuple[ObjectManagerDb, Recording]: real = sqlite3.connect(":memory:") real.execute(_SQLITE_DDL) rec = Recording(real) - return ObjectManager(_root(), SqliteDriver(rec)), rec # type: ignore[arg-type] + return ObjectManagerDb(_root(), SqliteDriver(rec)), rec # type: ignore[arg-type] # ---------------------------------------------------------------------------- @@ -251,11 +251,11 @@ def close(self) -> None: pass -def _mysql_om() -> tuple[ObjectManager, FakeMySql]: +def _mysql_om() -> tuple[ObjectManagerDb, FakeMySql]: conn = FakeMySql() conn.row = (42, "pen", 3, 1, decimal.Decimal("12.50"), "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", dt.date(2026, 5, 1), dt.datetime(2026, 5, 4, 3, 30)) - return ObjectManager(_root(), MySqlDriver(conn)), conn # type: ignore[arg-type] + return ObjectManagerDb(_root(), MySqlDriver(conn)), conn # type: ignore[arg-type] def test_mysql_read_uses_backticks_and_percent_placeholders() -> None: @@ -350,7 +350,7 @@ class Conn(FakeMySql): pass conn = Conn() - om = ObjectManager(_root(), PostgresDriver(conn)) # type: ignore[arg-type] + om = ObjectManagerDb(_root(), PostgresDriver(conn)) # type: ignore[arg-type] om.find_many("Item", {"label": {"like": "A%"}}, limit=1) assert conn.sql[-1][0] == ( 'SELECT "id", "label", "qty", "active", "price", "ref", "madeOn", "seenAt" FROM "items" ' @@ -388,7 +388,7 @@ def test_sqlite_binds_the_engines_spelling() -> None: def test_a_filter_operand_given_as_text_is_typed_by_the_field() -> None: - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter root = _root() item = next(c for c in root.own_children() if c.name == "Item") @@ -406,7 +406,7 @@ def test_a_mysql_decimal_operand_is_cast_to_a_decimal() -> None: from metaobjects.meta.core.field.meta_field import MetaField from metaobjects.runtime.dialect import MYSQL, POSTGRES - from metaobjects.runtime.object_manager import _op_clause + from metaobjects.runtime.object_manager_db import _op_clause from metaobjects.shared.base_types import TYPE_FIELD f = MetaField(TYPE_FIELD, "decimal", "amount") diff --git a/server/python/tests/runtime/test_object_manager_duration.py b/server/python/tests/runtime/test_object_manager_db_duration.py similarity index 95% rename from server/python/tests/runtime/test_object_manager_duration.py rename to server/python/tests/runtime/test_object_manager_db_duration.py index 6b08834ef9..a0e0a9b8ae 100644 --- a/server/python/tests/runtime/test_object_manager_duration.py +++ b/server/python/tests/runtime/test_object_manager_db_duration.py @@ -1,4 +1,4 @@ -"""field.duration through the ObjectManager: the write codec (an accepted ISO-8601 string becomes a +"""field.duration through the ObjectManagerDb: the write codec (an accepted ISO-8601 string becomes a ``timedelta``; anything else is refused), the per-engine binding (pg8000 binds the ``timedelta`` as an interval, SQLite and MySQL an integer column holding the microsecond count, so it orders) and the read codec (every engine reads back a ``timedelta``; an interval with a month part is @@ -18,9 +18,9 @@ from metaobjects import load_string from metaobjects.naming import NamingRules -from metaobjects.runtime import MYSQL, POSTGRES, SQLITE, ObjectManager, SqliteDriver +from metaobjects.runtime import MYSQL, POSTGRES, SQLITE, ObjectManagerDb, SqliteDriver from metaobjects.runtime.dialect import DurationParam -from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value +from metaobjects.runtime.values import coerce_write_value as _coerce_write_value, decode_read_value as _decode_read_value _META = { "metadata.root": { @@ -53,10 +53,10 @@ def _field(name: str) -> Any: return next(f for f in _root().children()[0].fields() if f.name == name) -def _sqlite_om() -> tuple[ObjectManager, sqlite3.Connection]: +def _sqlite_om() -> tuple[ObjectManagerDb, sqlite3.Connection]: conn = sqlite3.connect(":memory:") conn.execute('CREATE TABLE "holds" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "holdFor" INTEGER, "steps" TEXT)') - return ObjectManager(_root(), SqliteDriver(conn)), conn + return ObjectManagerDb(_root(), SqliteDriver(conn)), conn def test_an_accepted_iso_duration_is_written_as_a_timedelta() -> None: @@ -196,7 +196,7 @@ def spans(rows: list[dict[str, Any]]) -> list[str | None]: } -def _plan_om() -> tuple[ObjectManager, sqlite3.Connection]: +def _plan_om() -> tuple[ObjectManagerDb, sqlite3.Connection]: result = load_string(json.dumps(_VO_META)) assert not result.errors, [str(e) for e in result.errors] root: Any = result.root @@ -206,7 +206,7 @@ def _plan_om() -> tuple[ObjectManager, sqlite3.Connection]: 'CREATE TABLE "plans" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ' '"settings" TEXT, "windows" TEXT, "byName" TEXT)' ) - return ObjectManager(root, SqliteDriver(conn)), conn + return ObjectManagerDb(root, SqliteDriver(conn)), conn def _window(timeout: Any, steps: list[Any], wait: Any) -> dict[str, Any]: diff --git a/server/python/tests/runtime/test_object_manager_enum_intvaluemap.py b/server/python/tests/runtime/test_object_manager_db_enum_intvaluemap.py similarity index 94% rename from server/python/tests/runtime/test_object_manager_enum_intvaluemap.py rename to server/python/tests/runtime/test_object_manager_db_enum_intvaluemap.py index 115d99a49c..704ce9ad51 100644 --- a/server/python/tests/runtime/test_object_manager_enum_intvaluemap.py +++ b/server/python/tests/runtime/test_object_manager_db_enum_intvaluemap.py @@ -1,4 +1,4 @@ -"""field.enum @intValueMap — Python ObjectManager persistence codec. +"""field.enum @intValueMap — Python ObjectManagerDb persistence codec. The metamodel layer ships the attribute; this pins the RUNTIME halves: write encodes the member symbol to its declared int, read decodes it back. @@ -14,7 +14,7 @@ from metaobjects.loader.meta_data_loader import MetaDataLoader from metaobjects.loader.sources import InMemoryStringSource -from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value +from metaobjects.runtime.values import coerce_write_value as _coerce_write_value, decode_read_value as _decode_read_value INT_MAP = ', "@intValueMap": {"DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9}' @@ -162,31 +162,31 @@ def _order_entity(extra: str): def test_filter_eq_on_int_backed_enum_binds_the_int(): - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter _, params = _compile_filter({"status": {"eq": "PUBLISHED"}}, _order_entity(INT_MAP)) assert params == [5] def test_filter_shortcut_equality_on_int_backed_enum_binds_the_int(): - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter _, params = _compile_filter({"status": "DRAFT"}, _order_entity(INT_MAP)) assert params == [0] def test_filter_in_on_int_backed_enum_binds_each_int(): - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter _, params = _compile_filter({"status": {"in": ["DRAFT", "ARCHIVED"]}}, _order_entity(INT_MAP)) assert params == [0, 9] def test_filter_on_string_backed_enum_is_unchanged(): - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter _, params = _compile_filter({"status": {"eq": "PUBLISHED"}}, _order_entity("")) assert params == ["PUBLISHED"] def test_filter_isnull_binds_no_param_and_is_not_coerced(): - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter sql, params = _compile_filter({"status": {"isNull": True}}, _order_entity(INT_MAP)) assert params == [] assert "IS NULL" in sql @@ -281,9 +281,9 @@ def test_int_backed_enum_array_inheriting_the_map_from_a_shared_enum(): def test_filter_equality_on_an_int_backed_enum_array_binds_ints(): """The runtime has no array operators (contains/overlaps) and the loader - refuses @filterable on an array, but a direct ObjectManager filter can still + refuses @filterable on an array, but a direct ObjectManagerDb filter can still compare the whole array; its operand encodes like a write.""" - from metaobjects.runtime.object_manager import _compile_filter + from metaobjects.runtime.object_manager_db import _compile_filter _, params = _compile_filter({"status": {"eq": ["PUBLISHED", "DRAFT"]}}, _order_entity(ARRAY_INT_MAP)) assert params == [[5, 0]] _, params = _compile_filter({"status": ["ARCHIVED"]}, _order_entity(ARRAY_INT_MAP)) diff --git a/server/python/tests/runtime/test_object_manager_numeric_key_text.py b/server/python/tests/runtime/test_object_manager_db_numeric_key_text.py similarity index 97% rename from server/python/tests/runtime/test_object_manager_numeric_key_text.py rename to server/python/tests/runtime/test_object_manager_db_numeric_key_text.py index c5de647d3f..47fb7b3d81 100644 --- a/server/python/tests/runtime/test_object_manager_numeric_key_text.py +++ b/server/python/tests/runtime/test_object_manager_db_numeric_key_text.py @@ -13,7 +13,7 @@ from metaobjects.loader.meta_data_loader import MetaDataLoader from metaobjects.loader.sources import InMemoryStringSource -from metaobjects.runtime.object_manager import _coerce_key_value +from metaobjects.runtime.values import coerce_key_value as _coerce_key_value MODEL = """{"metadata.root": {"package": "acme", "children": [ {"object.entity": {"name": "Thing", "children": [ diff --git a/server/python/tests/runtime/test_object_manager_report.py b/server/python/tests/runtime/test_object_manager_db_report.py similarity index 97% rename from server/python/tests/runtime/test_object_manager_report.py rename to server/python/tests/runtime/test_object_manager_db_report.py index 31224d2c0b..b39d908963 100644 --- a/server/python/tests/runtime/test_object_manager_report.py +++ b/server/python/tests/runtime/test_object_manager_db_report.py @@ -1,4 +1,4 @@ -"""ObjectManager reads a view-backed ``object.report`` (FR-044 Plan 2, Task 14). +"""ObjectManagerDb reads a view-backed ``object.report`` (FR-044 Plan 2, Task 14). A report declares no fields: its read shape is derived (Table B). The runtime reads it through a detached READ MODEL (``report_read_model``) swapped in at @@ -23,7 +23,8 @@ from metaobjects.meta.core.object.object_constants import OBJECT_SUBTYPE_REPORT from metaobjects.meta.core.reporting.report_read_model import report_read_model from metaobjects.naming import NamingRules, attach_naming -from metaobjects.runtime.object_manager import ObjectManager, SelectResult +from metaobjects.runtime.drivers import SelectResult +from metaobjects.runtime.object_manager_db import ObjectManagerDb from metaobjects.serializer_json import canonical_serialize from metaobjects.shared.base_types import TYPE_OBJECT @@ -66,8 +67,8 @@ def _canonical_root(): return attach_naming(result.root, CORPUS) -def _om(root: Any, driver: RecordingDriver, **kw: Any) -> ObjectManager: - return ObjectManager(root, driver, **kw) # type: ignore[arg-type] +def _om(root: Any, driver: RecordingDriver, **kw: Any) -> ObjectManagerDb: + return ObjectManagerDb(root, driver, **kw) # type: ignore[arg-type] def _load(text: str): @@ -166,7 +167,7 @@ def test_count_reads_the_view() -> None: def test_the_naming_strategy_applies_to_the_derived_name() -> None: """The derived field carries no @column, so snake_case turns ``programTitle`` into ``program_title`` (a column the lowering emits under the same strategy).""" - # ADR-0058 — naming is read from the loaded root, not an ObjectManager kwarg. + # ADR-0058 — naming is read from the loaded root, not an ObjectManagerDb kwarg. root = _canonical_root() root.naming = NamingRules(columns="snake_case") drv = RecordingDriver() diff --git a/server/python/tests/runtime/test_object_manager_string_value_map.py b/server/python/tests/runtime/test_object_manager_db_string_value_map.py similarity index 89% rename from server/python/tests/runtime/test_object_manager_string_value_map.py rename to server/python/tests/runtime/test_object_manager_db_string_value_map.py index 0c74f3f66c..147e4aebcf 100644 --- a/server/python/tests/runtime/test_object_manager_string_value_map.py +++ b/server/python/tests/runtime/test_object_manager_db_string_value_map.py @@ -1,4 +1,4 @@ -"""rc.21 — a string-stored ``field.enum`` with ``@stringValueMap``: the ObjectManager writes +"""rc.21 — a string-stored ``field.enum`` with ``@stringValueMap``: the ObjectManagerDb writes the member's stored string and reads the member back; an unmapped stored string raises.""" from __future__ import annotations @@ -9,7 +9,7 @@ import pytest from metaobjects import load_string -from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value +from metaobjects.runtime.values import coerce_write_value as _coerce_write_value, decode_read_value as _decode_read_value _META = {"metadata.root": {"package": "acme", "children": [ {"object.entity": {"name": "Article", "children": [ @@ -42,7 +42,7 @@ def test_an_unmapped_stored_string_raises() -> None: def test_an_unmapped_member_raises_written_or_filtered() -> None: # rc.21 part B (N4): a filter on an unmapped member raises, as a write does, in every port — # passed through, the symbol could equal another member's stored string. - from metaobjects.runtime.object_manager import _coerce_filter_value + from metaobjects.runtime.values import coerce_filter_value as _coerce_filter_value field = _status() with pytest.raises(ValueError, match="cannot write 'Archived': it has no stored string in @stringValueMap"): _coerce_write_value(field, "Archived") diff --git a/server/python/tests/runtime/test_object_manager_table_name.py b/server/python/tests/runtime/test_object_manager_db_table_name.py similarity index 93% rename from server/python/tests/runtime/test_object_manager_table_name.py rename to server/python/tests/runtime/test_object_manager_db_table_name.py index 649278223c..bcfed1b163 100644 --- a/server/python/tests/runtime/test_object_manager_table_name.py +++ b/server/python/tests/runtime/test_object_manager_db_table_name.py @@ -1,4 +1,4 @@ -"""ObjectManager's physical table name comes from a DECLARED source, or nowhere. +"""ObjectManagerDb's physical table name comes from a DECLARED source, or nowhere. #248: participation in persistence derives from a declared ``source.rdb``, never from the object subtype. A concrete ``object.entity`` declaring no source at all @@ -17,7 +17,7 @@ from metaobjects.loader.meta_data_loader import MetaDataLoader from metaobjects.loader.sources import InMemoryStringSource -from metaobjects.runtime.object_manager import ObjectManager +from metaobjects.runtime.object_manager_db import ObjectManagerDb SOURCELESS = """{ "metadata.root": { "package": "acme", "children": [ { "object.entity": { "name": "Ledger", "children": [ @@ -50,10 +50,10 @@ ]} }""" -def _om(json_str: str) -> ObjectManager: +def _om(json_str: str) -> ObjectManagerDb: result = MetaDataLoader().load([InMemoryStringSource(json_str, "test.json")]) assert result.errors == [] - return ObjectManager(result.root, driver=None) + return ObjectManagerDb(result.root, driver=None) def test_a_sourceless_entity_loads_cleanly() -> None: diff --git a/server/python/tests/runtime/test_validator_runner.py b/server/python/tests/runtime/test_validator_runner.py index de2560b20a..c696511136 100644 --- a/server/python/tests/runtime/test_validator_runner.py +++ b/server/python/tests/runtime/test_validator_runner.py @@ -460,11 +460,11 @@ def test_constraints_inherited_through_extends_are_enforced() -> None: assert _rules(post, {"title": "ABCD"}) == ["title:length", "title:regex"] -# ── ObjectManager.validate (standalone, no DB hit) ─────────────────────────── +# ── ObjectManagerDb.validate (standalone, no DB hit) ─────────────────────────── def test_object_manager_validate_returns_the_runner_result() -> None: - from metaobjects.runtime import ObjectManager, PostgresDriver + from metaobjects.runtime import ObjectManagerDb, PostgresDriver doc = {"metadata.root": {"package": "p", "children": [ {"object.entity": {"name": "Post", "children": [_string("title", required=True)]}}, @@ -472,7 +472,7 @@ def test_object_manager_validate_returns_the_runner_result() -> None: result = MetaDataLoader.from_string(json.dumps(doc)) assert not result.errors # validate() never touches the driver, so no connection is needed. - om = ObjectManager(result.root, PostgresDriver(None)) # type: ignore[arg-type] + om = ObjectManagerDb(result.root, PostgresDriver(None)) # type: ignore[arg-type] assert om.validate("Post", {"title": "ok"}).ok is True assert [e.to_dict() for e in om.validate("Post", {}).errors] == [ {"field": "title", "rule": "required", "message": "'title' is required"}, diff --git a/server/python/tests/unit/test_column_naming_strategy.py b/server/python/tests/unit/test_column_naming_strategy.py index 3ffe3780dc..92cdc5af74 100644 --- a/server/python/tests/unit/test_column_naming_strategy.py +++ b/server/python/tests/unit/test_column_naming_strategy.py @@ -111,15 +111,15 @@ def test_a_codegen_column_naming_strategy_is_no_longer_refused() -> None: def test_object_manager_column_naming_argument_is_refused() -> None: """ADR-0058 Decision 4: the 1.0 runtime setter is refused with the shared message, before the manager touches its driver, so the value it held is never silently dropped.""" - from metaobjects.runtime.object_manager import ObjectManager + from metaobjects.runtime.object_manager_db import ObjectManagerDb with pytest.raises(ValueError) as excinfo: - ObjectManager(None, driver=None, column_naming="literal") # type: ignore[arg-type] + ObjectManagerDb(None, driver=None, column_naming="literal") # type: ignore[arg-type] assert str(excinfo.value) == ( - 'ObjectManager(column_naming=...) was removed in 1.1.0. Column and table naming is one ' + 'ObjectManagerDb(column_naming=...) was removed in 1.1.0. Column and table naming is one ' 'project setting now, read by every port: "naming" in .metaobjects/config.json, for ' 'example "naming": { "columns": "literal" }. Move it there and delete ' - "ObjectManager(column_naming=...). See " + "ObjectManagerDb(column_naming=...). See " "https://github.com/metaobjectsdev/metaobjects/blob/v1.1.0/docs/features/migrations/physical-naming.md" ) diff --git a/server/python/tests/unit/test_effective_children_sibling_shadowing.py b/server/python/tests/unit/test_effective_children_sibling_shadowing.py index 83a8cd5929..64f7d38c70 100644 --- a/server/python/tests/unit/test_effective_children_sibling_shadowing.py +++ b/server/python/tests/unit/test_effective_children_sibling_shadowing.py @@ -16,7 +16,7 @@ primary_rdb_source: None `primary_rdb_source` reads `children()`, so the cost was not cosmetic: no table for the -router or the filter allowlist, no names module, and `ObjectManager` falling through to +router or the filter allowlist, no names module, and `ObjectManagerDb` falling through to the replica view. THE APPEND QUEUE WAS ONLY HALF THE FIX, AND THIS FILE SAID OTHERWISE. It claimed diff --git a/server/python/tests/unit/test_n2m_resolver.py b/server/python/tests/unit/test_n2m_resolver.py index afd36d2219..f03f1972ea 100644 --- a/server/python/tests/unit/test_n2m_resolver.py +++ b/server/python/tests/unit/test_n2m_resolver.py @@ -13,8 +13,8 @@ from metaobjects import load_directory from metaobjects.naming import attach_naming -from metaobjects.runtime import ObjectManager -from metaobjects.runtime.object_manager import SelectResult +from metaobjects.runtime import ObjectManagerDb +from metaobjects.runtime.drivers import SelectResult def _corpus_canonical() -> Path: @@ -45,7 +45,7 @@ def scalar(self, sql: str, params: tuple[Any, ...] = ()) -> Any: # pragma: no c return None -def _om(responses: list[tuple[str, list[dict[str, Any]]]]) -> tuple[ObjectManager, FakeDriver]: +def _om(responses: list[tuple[str, list[dict[str, Any]]]]) -> tuple[ObjectManagerDb, FakeDriver]: result = load_directory(_corpus_canonical()) # ADR-0058 — the corpus's project (the canonical dir's PARENT) pins # `naming: {columns: literal}` in its `.metaobjects/config.json`; `load_directory` @@ -54,7 +54,7 @@ def _om(responses: list[tuple[str, list[dict[str, Any]]]]) -> tuple[ObjectManage # do not match. root = attach_naming(result.root, _corpus_canonical().parent) driver = FakeDriver(responses) - return ObjectManager(root, driver), driver # type: ignore[arg-type] + return ObjectManagerDb(root, driver), driver # type: ignore[arg-type] # --- Hetero (Post —tags→ Tag through PostTag) ------------------------------- diff --git a/server/python/tests/unit/test_object_manager_autoset_stamping.py b/server/python/tests/unit/test_object_manager_db_autoset_stamping.py similarity index 96% rename from server/python/tests/unit/test_object_manager_autoset_stamping.py rename to server/python/tests/unit/test_object_manager_db_autoset_stamping.py index fbdfac98ad..d03919883e 100644 --- a/server/python/tests/unit/test_object_manager_autoset_stamping.py +++ b/server/python/tests/unit/test_object_manager_db_autoset_stamping.py @@ -1,4 +1,4 @@ -"""Issue #203 — ObjectManager honors ``field.timestamp @autoSet: onCreate|onUpdate``. +"""Issue #203 — ObjectManagerDb honors ``field.timestamp @autoSet: onCreate|onUpdate``. The runtime write path (``create`` / ``update`` / ``insert_preserving``) owns the ``now()`` stamping so adopters stop hand-writing it in every repository. The @@ -28,8 +28,8 @@ from metaobjects import load_string from metaobjects.naming import NamingRules -from metaobjects.runtime import ObjectManager -from metaobjects.runtime.object_manager import SelectResult +from metaobjects.runtime import ObjectManagerDb +from metaobjects.runtime.drivers import SelectResult # BaseAudit carries the @autoSet timestamps; Doc INHERITS them via extends — the # issue's exact real-world shape (declared once on a base, inherited everywhere). @@ -92,7 +92,7 @@ class FakeWriteDriver: """Captures the write SQL + params; returns a canned single-row result so the - ObjectManager's RETURNING-row mapping does not crash.""" + ObjectManagerDb's RETURNING-row mapping does not crash.""" def __init__(self) -> None: self.inserts: list[tuple[str, tuple[Any, ...]]] = [] @@ -116,14 +116,14 @@ def execute_rowcount(self, sql: str, params: tuple[Any, ...] = ()) -> int: # pr return 1 -def _om() -> tuple[ObjectManager, FakeWriteDriver]: +def _om() -> tuple[ObjectManagerDb, FakeWriteDriver]: root = load_string(json.dumps(_META)).root # This test is about @autoSet stamping, not naming (ADR-0058 flipped the # DEFAULT to snake_case) — pin `literal` so the fixture's field names # (`createdAt`, ...) stay the column names these assertions pin. root.naming = NamingRules(columns="literal") driver = FakeWriteDriver() - return ObjectManager(root, driver), driver # type: ignore[arg-type] + return ObjectManagerDb(root, driver), driver # type: ignore[arg-type] def _insert_cols(sql: str, params: tuple[Any, ...]) -> dict[str, Any]: diff --git a/server/python/tests/unit/test_object_manager_uuid_coercion.py b/server/python/tests/unit/test_object_manager_db_uuid_coercion.py similarity index 97% rename from server/python/tests/unit/test_object_manager_uuid_coercion.py rename to server/python/tests/unit/test_object_manager_db_uuid_coercion.py index 8e592fbb05..6c1d59d0b6 100644 --- a/server/python/tests/unit/test_object_manager_uuid_coercion.py +++ b/server/python/tests/unit/test_object_manager_db_uuid_coercion.py @@ -2,7 +2,7 @@ serialization seam (``tests/integration/normalization.normalize_value``) maps each native Python value to its cross-port wire form. -These were originally tests of ``ObjectManager._coerce_for_contract`` (in-runtime +These were originally tests of ``ObjectManagerDb._coerce_for_contract`` (in-runtime canonicalization). Per ADR-0019 the runtime no longer canonicalizes — ``find_*`` return native pg8000 values (``int`` / ``Decimal`` / ``datetime`` / ``date`` / ``time`` / ``uuid.UUID`` / ``dict`` / ``list``). The wire-form mapping moved to the @@ -18,7 +18,7 @@ from tests.integration.normalization import normalize_value # Stable Postgres type OIDs (see pg_type.dat). The OID is the int4-vs-int8 wire -# discriminator the native Python value cannot carry — ObjectManager surfaces it +# discriminator the native Python value cannot carry — ObjectManagerDb surfaces it # via ``last_column_oids`` so the boundary applies the BIGINT→string rule. _OID_BIGINT = 20 _OID_NUMERIC = 1700 diff --git a/server/python/tests/unit/test_object_manager_write_through.py b/server/python/tests/unit/test_object_manager_db_write_through.py similarity index 95% rename from server/python/tests/unit/test_object_manager_write_through.py rename to server/python/tests/unit/test_object_manager_db_write_through.py index 46447f2203..f0cc1e7387 100644 --- a/server/python/tests/unit/test_object_manager_write_through.py +++ b/server/python/tests/unit/test_object_manager_db_write_through.py @@ -1,4 +1,4 @@ -"""FR-024 §7 (#214) — ObjectManager read-routing for a write-through entity read-view. +"""FR-024 §7 (#214) — ObjectManagerDb read-routing for a write-through entity read-view. A write-through entity (writable table source + read-only replica view source + derived ``origin.*`` fields) routes: READS (find_many / find_by_id / count) through @@ -16,8 +16,8 @@ from metaobjects import load_string from metaobjects.naming import NamingRules -from metaobjects.runtime import ObjectManager -from metaobjects.runtime.object_manager import SelectResult +from metaobjects.runtime import ObjectManagerDb +from metaobjects.runtime.drivers import SelectResult _META = { "metadata.root": { @@ -88,14 +88,14 @@ def execute_rowcount(self, sql: str, params: tuple[Any, ...] = ()) -> int: # pr return 1 -def _om() -> tuple[ObjectManager, FakeDriver]: +def _om() -> tuple[ObjectManagerDb, FakeDriver]: root = load_string(json.dumps(_META)).root # This test is about write-through (table vs replica-view routing), not naming # (ADR-0058 flipped the DEFAULT to snake_case) — pin `literal` so the fixture's # field names stay the column names these assertions pin. root.naming = NamingRules(columns="literal") d = FakeDriver() - return ObjectManager(root, d), d # type: ignore[arg-type] + return ObjectManagerDb(root, d), d # type: ignore[arg-type] def _from(sql: str) -> str: diff --git a/server/python/tests/unit/test_write_coercion_arrays.py b/server/python/tests/unit/test_write_coercion_arrays.py index e9bfa52154..03cdcefac1 100644 --- a/server/python/tests/unit/test_write_coercion_arrays.py +++ b/server/python/tests/unit/test_write_coercion_arrays.py @@ -1,6 +1,6 @@ """Phase 1 — _coerce_write_value for native-array columns. -When a field has isArray=True the ObjectManager write path must convert a +When a field has isArray=True the ObjectManagerDb write path must convert a list of author strings to the native element type so pg8000 binds a native PG array column (text[] / uuid[]). @@ -19,7 +19,7 @@ from metaobjects.meta.core.field.meta_field import MetaField from metaobjects.meta.core.field import field_constants as fc from metaobjects.shared.base_types import TYPE_FIELD -from metaobjects.runtime.object_manager import _coerce_write_value # type: ignore[attr-defined] +from metaobjects.runtime.values import coerce_write_value as _coerce_write_value # type: ignore[attr-defined] def _field(sub_type: str, *, is_array: bool = False) -> MetaField: diff --git a/spec/code-writer.md b/spec/code-writer.md index 45ef909bdc..54fe418418 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -11,7 +11,7 @@ A writer has two parts: snippets, fit-or-break lists and the output form. Every port's core runs the `core` cases. - **A dialect** for the language being written: import collection and ordering, string quoting, doc comments and expression helpers. A dialect runs the cases for its language, - such as `typescript`. + such as `typescript` or `python`. The writer never parses text. It lays out the structure the generator handed it. When a shape comes out badly, the generator breaks it explicitly with a block. The writer is not made @@ -148,6 +148,40 @@ writes the head, indents, and on leaving the `try` dedents and writes `}`. `List` or array of parts, which are concatenated. Anything else (a number, `null`, another object) is **`ERR_WRITER_UNKNOWN_PIECE`**: the writer never guesses how to print it. +## Python dialect (`PyWriter`) + +Defaults: four-space indent, 88 columns, a trailing comma on a broken list. + +- **Imports are collected while the body is written.** `use(name, from)` records + `from m import name` and returns the name to write; `use(name, from, as)` records + `from m import name as as`. `use_module(m)` and `use_module(m, as)` record `import m` and + `import m as as`. `use_future(name)` records `from __future__ import name`. Imports print + before the body, after any `header(...)` lines, with one blank line between each section. +- **Order.** Three sections: `__future__`, then absolute modules, then relative ones (those + starting with `.`). Each section is in code-point order, with one blank line between the + sections. In a section the plain `import m` lines come first, then the `from m import ...` + lines, each group in code-point order, and names in code-point order. +- **Long import lines.** `from m import a, b` stays on one line when it fits; otherwise it + prints as `from m import (`, one name per line, each followed by a comma, and `)`. A single + name never breaks. +- One local name imported from two modules, or naming two different exports, is + **`ERR_WRITER_IMPORT_CONFLICT`**. +- **Suites.** A Python block has no closing token: the block ends when the indent drops. + `open` starts a suite and `dedent` ends it without writing a line. A pending blank-line + request survives a dedent, so the gap before the next definition is kept. (`close` still + writes its line and drops a pending request, as in the core.) A suite still open when the file + is finished ends there: Python needs no closing token, so this is not + `ERR_WRITER_UNCLOSED_BLOCK`. `close` with no suite open, and `dedent` with none open, are + `ERR_WRITER_UNBALANCED_CLOSE`. +- **`gap()`** asks for two blank lines before whatever is written next (the gap between + top-level definitions). A later `blank()` does not shrink it. +- **`doc(lines...)`** writes `"""text"""` when there is one entry and it fits. Otherwise it + writes the opening quotes with the first entry, each further entry on its own line (an + empty entry is a blank line) and the closing quotes on their own line. A backslash is + written as `\\` and `"""` as `\"\"\"`. On one line, a double quote at the end of + the text is written `\"`, so it cannot join the closing quotes. +- Helpers: `str_lit` (a double-quoted string literal), `call`, `seq`, `mapping` and `kwarg`. + ## Extension by subclassing A writer and the generators built on it are meant to be extended in place @@ -188,7 +222,9 @@ Each case in `fixtures/writer-conformance/cases/` is one JSON file: - An op is an array: its name, then its arguments. The core ops are `line`, `open` and `close` (whose arguments are parts), `blank` and `text`. The TypeScript ops are `use`, `useType`, `useDefault`, `useNamespace` and `useSideEffect` (name, then module; `useSideEffect` takes - only the module), `header` and `doc` (lines). + only the module), `header` and `doc` (lines). The Python ops are `use` (name, module), `useAs` (name, module, + alias), `useModule` (module, optional alias), `useFuture` (optional name), `header` and `doc` + (lines), `dedent` and `gap`. - A part is a string, a list (`{"list": {"open", "items", "close", "pad"?}}`, where items are parts) or an array of parts, which are concatenated. - `expected` is the output's lines. The file is those lines joined with `\n` plus a final `\n`, diff --git a/spec/decisions/ADR-0063-generators-own-layout.md b/spec/decisions/ADR-0063-generators-own-layout.md index 759c5ca632..b56b67d467 100644 --- a/spec/decisions/ADR-0063-generators-own-layout.md +++ b/spec/decisions/ADR-0063-generators-own-layout.md @@ -4,8 +4,9 @@ **Accepted** (2026-11-14). Registers no vocabulary: `metamodelVersion` does not move. It sets how every port's generators produce text. This decision ships the TypeScript writer, the shared -writer contract and corpus, and the test that holds generator source to the rule. It converts no -generator and changes no generated output. Each generator is converted in its own later change. +writer contract and corpus, and the test that holds generator source to the rule. It converted no +generator and changed no generated output. Each generator is converted in its own later change; +the Python writer and its first conversions are in [The Python writer](#the-python-writer). ## Context @@ -112,6 +113,18 @@ symbols join the file's import block, and a multi-line fragment is re-indented b sections it has not converted still return `Code`. A `Code` built by a different physical copy of those primitives cannot be read, so it is refused rather than written without its imports. +## The Python writer + +`CodeWriter` and `PyWriter` (`server/python/src/metaobjects/codegen/writer/`) are exported as +`metaobjects.codegen.writer` and listed in `eject.engineSurface.python`. Python lays out at +**88 columns** with a four-space indent and a trailing comma in broken lists. Its runner is +`server/python/tests/codegen/test_writer_conformance.py`. The `output-prompt`, `report-export` and +`filter-allowlist` generators write through it and no longer call `ruff`. Every other Python +generator still types its own layout: `tests/codegen/layout_ratchet/allowlist.json` lists those +files, the layout check (`tests/codegen/test_layout_ratchet.py`) fails on any new one, and an entry +is removed when its generator converts, so the list only shrinks. The dialect contract is in +[`spec/code-writer.md`](../code-writer.md). + ## Consequences - Generation gets faster and becomes deterministic. Once a generator is converted, no formatter