diff --git a/AGENTS.md b/AGENTS.md index b80d7c5b7d..d6ab41cfc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -264,7 +264,7 @@ import { EntityFetcherProvider, EntityGrid } from "@metaobjectsdev/tanstack"; - **TS runtime**: Bun-first for development (zero-config TS, native test runner). Node-compatible for distribution; users install via npm/pnpm/bun without lock-in to Bun's runtime. - **Module system**: ESM only. No CommonJS, no transpile step required. - **Storage format**: JSON files in `metaobjects/meta..json` at project root. `.metaobjects/.gen-state/` holds the codegen merge base: the snapshot **bodies are gitignored** (a second full copy of all generated output), but **`.hashes/` (one file per model package) is COMMITTED** — one hash per generated path, and the only thing that lets `meta gen` tell "this file is exactly what I wrote" from "somebody edited this" on a machine that did not generate it. Ignore it and a fresh clone or CI runner silently overwrites hand edits; commit it and an edited file is refused by name instead. -- **Codegen substrate**: the vendored ts-poet printer (`codegen-ts/src/poet.ts`) for greenfield emit, ts-morph for in-place edits, Biome for format pass, `git merge-file --diff3` for hand-edit-preserving regen. +- **Codegen substrate**: the vendored ts-poet printer (`codegen-ts/src/poet.ts`) for greenfield emit, ts-morph for in-place edits, no formatter in generation (the generator's writer lays out the text, ADR-0063), `git merge-file --diff3` for hand-edit-preserving regen. - **Runtime substrate**: Kysely for TS (user-provided connection, async-only). - **Migration substrate**: Postgres + SQLite for TS v0.3. - **Metadata location**: resolved via `resolveCollection()` (`@metaobjectsdev/sdk`) — the single authority. `metaobjects/` is the **default value of `sources`** and nothing else: no other module, command or user-facing message may assert that a directory of that name exists or is where metadata lives. Exactly five sites may name it — `sdk/src/metadata-files.ts` (`DEFAULT_METADATA_DIR`, its single definition), `sdk/src/sources.ts` (`DEFAULT_SOURCES`, **the** default), `sdk/src/collection.ts` (inside `resolveCollection`, *applying* that default), `sdk/src/index.ts` (the barrel re-export of the constant, no use), and `cli/src/commands/init.ts` (the scaffolder **writing** the layout). Enforced by `sdk/test/no-hardcoded-metadata-dir.test.ts`, whose allowlist demands a written reason per entry. See [docs/features/metadata-sources.md](docs/features/metadata-sources.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index 31e524e19c..d78e932091 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,63 @@ here.** ## [Unreleased] +- **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation + error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that + project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` + would scaffold `RESTART WITH n` and hand out ids live rows hold. The run now fails with + `ERR_DESIGN_TIME_REFERENCE_MISSING`, naming the project and the line to add, instead of warning. A + run that cannot tell (no snapshot on disk yet) and a project that declares no `@sequenceStart` still + get the warning. +- **C#: the filter allowlist, names, callable, output-prompt, output-parser and extractor generators + write through a code writer (ADR-0063).** `MetaObjects.Codegen.Writer.CsWriter` carries the layout + (indent, braces, `using` lines, blank lines), and each of those generators is a class built from + overridable per-piece methods. The output is unchanged except in one place: a parser generated + for a reply declared `@responseFormat: xml` no longer has a blank line right after its opening + `{` (the writer drops a blank line after an opener, as it does in every port). A layout check + with an allowlist that only shrinks keeps new hand-typed layout out of the generator source. + The shared writer-conformance corpus gains six C# cases. +- **C#: the last six generators write through the code writer (ADR-0063).** The routes generator, the + reverse-finder emitter, the expression-indexes, report-export and requirement-tests generators and the + render-helper generator no longer type line breaks or indentation, so the layout check's list of + unconverted generators is empty. Output is byte-identical on the 737 model fixtures in four layouts, + with these exceptions the writer owns: the shared `ReportExportWriter.g.cs` now ends with a newline + like every other generated file; a `// ` comment line for an empty statement is written as `//`; and + an empty requirement-tests witness interface has its braces on two lines. The routes generator's + `AppendOffsetLimit` and `AppendSaveChanges` helpers lose their `indent` argument, and its private + helpers take a `CsWriter`. The requirement-tests collision message indents its list by four spaces. +- **C#: the DbContext generator writes through the code writer (ADR-0063).** `DbContextGenerator` + (the context, its `OnModelCreating` and `ConfigureModelNN` chunks, the enum, map and duration helpers + and the design-time services file) builds each file on a `CsWriter`. Output is byte-identical for the + 737 model fixtures in all four layouts. **An owned or subclassed generator needs a small edit.** The + hooks `EmitUsings`, `EmitDbSetDeclarations` and `EmitOnModelCreatingBody` take a `CsWriter` in place of the + `StringBuilder`, and `EmitUsings` opens the class body with `w.Open("{")`. The hooks that return + text now document their lines as unindented; a line that still carries an indent is accepted, since the + writer removes the common margin. A `ContextUsings` line is a `using ...;` directive, printed once in the + order given. The layout check's allowlist loses the DbContext generator's entry. +- **C#: the entity generator writes through the code writer (ADR-0063).** `EntityGenerator` (mapped + entities, TPH subtypes, abstract shapes, value objects, shared enums and the decimal, duration and + net-validation helper files) builds each file on a `CsWriter`. Output is unchanged for the 737 model + fixtures in all four layouts except three layout details the writer owns: a class with no members + has no blank line between its braces, a blank line before a closing `}` is dropped, and a `///` + doc line has no trailing space. **An owned or subclassed generator needs a small edit.** The hooks + `EmitClassHeader`, `EmitClassAttributes`, `EmitClassDeclarationLine`, `EmitPropertyAttributes`, + `EmitFileUsings` and `EmitClassBodyTrailer` take a `CsWriter` in place of the `StringBuilder`, and write + lines with `w.Line(...)` or `w.Using(...)`, with no typed indentation. The base class still adds + `IValidatableObject` to the declaration line an override wrote. The property emitters are renamed + `WriteScalarProperty`, `WriteEnumProperty`, `WriteObjectNavProperty`, `WriteMapProperty` and the + `WriteTphSubtype*Property` pair, and the validator-attribute writers `Write*ValidatorAttributes`. + `ValueObjectMemberAttributes` returns lines with no indent (it used to return four spaces of it). + `XmlDocBuilder.WriteTo(writer, node)` is the writer form of `AppendTo`. The public statics + `EntityGenerator.M2mNavProperty` and `ExtractDelegateEmitter.DelegatingMembers`, which returned a + string, are now `WriteM2mNavProperty(CsWriter, ...)` and `WriteDelegatingMembers(CsWriter, ...)`, + returning void. `NamesGenerator.Member` and `MemberGroups` are now protected. A flat-layout shared-enum + file that holds two or more namespaces no longer ends with an extra blank line. The layout check no + longer lists `EntityGenerator.cs` as unconverted. +- **`migrate.foreignKeyTargets: "warn"` turns the refusal of a foreign key onto a non-unique target into + a report.** For a database whose unique index on the target is hand-made and not declared in the + metadata. The default, `"refuse"`, is the 1.3.0 behavior; the refusal's hint now names the setting. See + [Migrations and drift](docs/features/migrations-and-drift.md). + ## [1.3.0] — unreleased @@ -108,6 +165,68 @@ Each item below is described in full under Security, Added, Changed or Fixed; th rule that is in force. A pipeline that read `.hashes.json` directly reads every file in `.hashes/` instead. ADR-0064 Amendment 1; [docs/features/migrations/per-package-hash-manifest.md](docs/features/migrations/per-package-hash-manifest.md). +- **Ignore the generation key and keep the hash manifest: two `.gitignore` lines.** `gen` now writes + an uncommitted `.metaobjects/.gen-state/.fingerprint-.json` (one per module on the JVM). In a + project whose root `.gitignore` already ignores generated state, add + `**/.metaobjects/.gen-state/*` and `!**/.metaobjects/.gen-state/.hashes/`; otherwise the key shows + as untracked. The exception matters: the key stays uncommitted and the per-package hash manifest + under `.hashes/` stays committed, so do not ignore the whole `.metaobjects/` directory. A project + that took the 1.2.3 lines (`!**/.metaobjects/.gen-state/.hashes.json`) replaces that one. +- **Every join a generated view or report makes is `LEFT OUTER`.** A row whose reference is null, + or whose related row is missing, now appears with nulls in the joined columns instead of + vanishing. Expect the regenerated view bodies to differ in `meta migrate`: one view replacement + per view that joined through a required reference. +- **TypeScript and C#: a projection that extends another keeps its super's identity anchor.** Over a + table-per-hierarchy root, a projection whose own fields bind a subtype's column used to return + only that subtype's rows; its view now returns **every** row of the shared table, the subtype + column NULL on the others. The load warns when a projection's output widened this way. +- **`meta migrate` and `meta verify --db` refuse a foreign key onto columns the target does not hold + unique** (`FkTargetNotUniqueError`, listing every offending reference at once), where the + database refused it at apply time after earlier statements had run. A foreign key onto a + hand-made unique index can fail `verify --db` that passed before. +- **On Postgres the primary key's name is compared.** A convention switch or a table rename + renames the key in place, and `meta verify --db` reports a mismatch it used to pass. +- **`meta verify` exits 2 when `metaobjects.config.ts` exists but fails to load**, and prints that + load error (and so does `meta prompt-snapshot`), where it used to continue without the + config's providers and report an unknown subtype. +- **TypeScript and Python: two shared enums with one name are `ERR_NAME_COLLISION`.** The second + used to be dropped silently and its fields typed with the first one's members. Rename one. +- **TypeScript: an owned generator that imports one of ts-poet's `def`, `literalOf`, `arrayOf`, + `asOneline`, `Import.fromMaybeString`, `saveFiles`, `conditionalOutput` or its `toString` import + options no longer loads.** The printer is now vendored without them; `code`, `imp`, `joinCode`, + `Import` and the `Code` type still resolve from a bare `ts-poet` import. +- **`docsSiteFile()` builds the model explorer by default.** The site under `site/` changes, with + object pages under `model/`. Pass `docsSiteFile({ site: "classic" })` to keep the earlier site. +- **C#: an int-backed enum throws on write for a value its `@intValueMap` does not describe**, as + the read side already did. A cast such as `(Status)99` used to be stored as the last member's + integer. +- **C# and Java: a names class no longer extends its base's** when that would make a base constant + that is not a column of its own table reachable through it. It is emitted complete instead. +- **TypeScript generation runs no formatter.** `meta gen` used to pass every generated `.ts` file + through Biome after the template had laid it out; it no longer does, so `@metaobjectsdev/codegen-ts` + no longer depends on `@biomejs/js-api` or `@biomejs/wasm-nodejs`. Each file keeps the layout its + generator writes (the ts-poet printer's 120 columns, where a template used it), so the **first + `meta gen` rewrites most generated files once, in layout only**; a hand edit in a generated + file meets the three-way merge against a base with the new layout. The Hono routes no longer + carry a `// biome-ignore` line above `registerAllRoutes` and each `mount...Routes` function; a + project that lints generated code with Biome adds its own ignore. `formatTs` is still exported from + `@metaobjectsdev/codegen-ts` and now returns its input unchanged, so a generator ejected in 1.2 + keeps loading and running. Run your formatter over the generated tree if you want your layout. +- **`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`.** Installing the + CLI no longer installs the ORM (about 17 MB); only the code `meta gen` writes imports it. A + project installs both when it takes a generator that writes code importing them: `meta eject` + and `meta gen --list` print the install set. A project that relied on the CLI pulling them in + adds `drizzle-orm` and `zod` to its own `package.json`. A check installs the packed CLI, fails + when the ORM or a formatter comes back, and holds the install to a size budget that only moves + down (`scripts/check-install-size.mjs`, in the full CI run). +- **The SQLite driver is no longer installed with the CLI.** `@libsql/kysely-libsql` is an + optional peer of `@metaobjectsdev/cli`: it brought its own HTTP client, a polyfill and a native + binary for each libc (about 28 MB), which a Postgres or D1 project never used. `meta init` + now adds it to the `dependencies` of a SQLite project (the default dialect) and says so; a + project that already ran `init` adds it with its package manager. Without it, `meta migrate` and + `meta verify --db` against a SQLite URL stop with the install command. Postgres, MySQL and D1 + projects install nothing new. With the ORM and the formatter gone as well, installing the CLI is + about 51 MB. - **`metamodelVersion` is `1.3`.** Upgrade every port together. ### Security @@ -403,7 +522,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th lists what the approach cannot do. It is an example on the TypeScript port, not a package. - **A working loop first in the agent context.** The always-on file `meta init` scaffolds - (`.metaobjects/AGENTS.md` and `CLAUDE.md`) now opens with the whole loop for the declared + (`.metaobjects/AGENTS.md`) now opens with the whole loop for the declared stack, in order: configure and run the generators (one step per declared server, with the import or class names to wire, plus the web client when one is declared), the schema (`meta migrate --from-db` for the first migration, `apply-pending` at boot, and a later @@ -519,7 +638,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - **A view the lowering cannot express is refused, not shortened.** The TypeScript view extractor skipped any origin it could not lower, so a projection loaded clean and `meta migrate` created a view missing a column its generated type declares. Each such shape now fails, naming the - projection and the field: an aggregate-derived entity field read where a row-level value is + projection and the field, at load where the loader can see it and in the view extractor for a + model built another way: an aggregate-derived entity field read where a row-level value is needed, a computed reference cycle, a relative date on a field that is not temporal, and an unknown origin or aggregate. - **The view vocabulary lowers to SQL.** `meta migrate` builds every port's views, and it now @@ -543,7 +663,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th `error-origin-passthrough-reverse-hop` (new) and `error-origin-passthrough-to-many` pin the message. -- **An int-backed enum can be an array.** `@intValueMap` together with `isArray: true` (the +- **An int-backed enum array loads in every port, and stores in TypeScript, C# and Python.** + `@intValueMap` together with `isArray: true` (the map on the field, or inherited from a shared enum) now loads in every port instead of failing with `ERR_ENUM_INT_VALUE_MAP_ARRAY`, which is removed. Each element is stored as its declared integer and read back as its member: `integer[]` on Postgres, and a JSON array of @@ -749,7 +870,12 @@ Each item below is described in full under Security, Added, Changed or Fixed; th parameters, the error envelope, and those shapes as components. The output follows the REST contract and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen` - (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. + (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. The + document also states this release's own API behaviour: a list's `limit` carries the project's + `api.pagination` default and maximum, a write's body says an undeclared key is refused with + `unknown_fields` (or dropped under `api.unknownFields: drop`), the error envelope carries + `issues`, `fields` and `maxLimit`, and a read-only resource says a write answers `405`. A project + that wires `openApiFile()` sees `openapi.json` change on the next `meta gen`. - **The data spine for a model explorer.** These changes are data only. No screen reads the new data yet. - `meta export --effective` writes the effective canonical JSON. Every field, child and attribute @@ -856,8 +982,10 @@ Each item below is described in full under Security, Added, Changed or Fixed; th migrations and one built by `meta migrate` match. A project can supply its own conventions object from `metaobjects.config.ts`; an unknown preset name, or an object missing a member, is refused by name. The PK name is now introspected too, so a `baseline --from-db` snapshot of a - database whose primary keys are not named `_pkey` records their names (not compared; - nothing churns). See `docs/features/migrations-and-drift.md`, "Schema conventions". + database whose primary keys are not named `
_pkey` records their names. On Postgres the name + is then compared, so a convention switch or a table rename renames the key in place and + `meta verify --db` reports a mismatch it used to pass (see "A constraint or index whose only change + is its name is renamed in place", below). See `docs/features/migrations-and-drift.md`, "Schema conventions". - **`migrate.checks.skipRedundant`: leave out the CHECKs a column type already enforces.** Set in `.metaobjects/config.json` (default `false`), `meta migrate` and `meta verify --db` leave out a `validator.length` maximum the column's `VARCHAR(n)` enforces (not on SQLite or D1, which do not @@ -990,6 +1118,65 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the new `fixtures/writer-conformance/` corpus. No shipped generator uses the writer yet, so generated output does not change in this release. +- **A code writer for Java generators: `CodeWriter` and `JavaWriter` in `metaobjects-codegen-base`** + (ADR-0063). The same contract as the TypeScript writer: `JavaWriter` collects imports while the + body is written (`use("java.util.List")` returns the name to write), skips `java.lang` and + same-package types, prints static imports first, writes Javadoc, and breaks a call that does not + fit 120 columns with no trailing comma. `block` is a `try`-with-resources scope. It runs the + shared `core` cases and nine new `java` cases, and a layout ratchet (a `javac` parse-tree test + 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 @@ -1612,7 +1799,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - **`@metaobjectsdev/cli` no longer installs the native Biome binary.** `codegen-ts-react`, `codegen-ts-tanstack` and the source-only `codegen-ts-angular` declared `@biomejs/biome` as a peer dependency, which npm installs automatically, so every CLI install carried the ~94 MB - `@biomejs/cli-` binary that nothing runs: codegen formats through the WebAssembly + `@biomejs/cli-` binary that nothing runs: the CLI used the WebAssembly build (`@biomejs/wasm-nodejs`). The peer is gone (it stays a devDependency for this repo's own lint gate), and a fresh npm install of the CLI drops from 245 MB to 151 MB of `node_modules`. `scripts/check-peer-ranges.ts` now fails a publishable package that requires `@biomejs/biome` @@ -1776,11 +1963,13 @@ Each item below is described in full under Security, Added, Changed or Fixed; th any build globs or `` items that named the flat files. Python and the JVM ports follow in #544–#549 (`docs/CONFORMANCE.md`, "Generated paths keyed by package"). -- **Breaking, C#: a generated type's namespace is its metadata package (rulings R64, R65).** With - no binding for it, a packaged type's namespace is the package itself, each `::` segment - PascalCased (`acme::alpha` → `Acme.Alpha`), as the Java and Kotlin ports map packages, whether - or not a namespace is configured. `--namespace` / `csharp.namespace` (`GenConfig.Namespace`) now - places only the objects with no package and the artifacts of no single object: the context and +- **C#, opt-in: with `csharp.packageNamespaces: true`, a generated type's namespace is its metadata + package (rulings R64, R65).** This is **not** the default: with the setting off (its default) and + a `csharp.namespace` configured, every type stays in that namespace and the output is + byte-identical to 1.2.0. With the setting on and no binding for a type, a packaged type's + namespace is the package itself, each `::` segment PascalCased (`acme::alpha` → `Acme.Alpha`), + as the Java and Kotlin ports map packages, even when a namespace is configured. + `--namespace` / `csharp.namespace` (`GenConfig.Namespace`) then places only the objects with no package and the artifacts of no single object: the context and its design-time services, the callable wrappers, the template tier (render helpers, parsers, extractors, output prompts) and the shared runtime helpers. A per-object companion follows its object into the package namespace: `Names`, `FilterAllowlist`, `Routes`, `Queries` @@ -1800,7 +1989,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th keeps its meaning (the package mapping applies only to the default `Flatten`). A hook override on `DbContextGenerator` receives the `global::`-qualified type as its `owner` argument (`global::Acme.Alpha.Note`), which it can splice into `Entity<{owner}>` as before. A `@provided` - enum is the adopter's type and is named as configured, unchanged. **Upgrade note:** on the next + enum is the adopter's type and is named as configured, unchanged. **Upgrade note:** none unless you + turn the setting on. When you do, on the next `gen`, every generated type in a package that no `PackageNamespaces`, `TypeOverrides` or `Convention` entry maps moves once, from the configured namespace to its package's namespace, together with its routes, reverse finders, names, filter allowlist and report export; update @@ -1846,6 +2036,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 @@ -1854,6 +2053,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-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index 0ee7406d34..06cfdda9e1 100644 --- a/agent-context/skills/metaobjects-codegen/references/csharp.md +++ b/agent-context/skills/metaobjects-codegen/references/csharp.md @@ -305,7 +305,11 @@ hand, so set its strategy from the root: `ColumnNamingStrategy = load.Root.Physi The generators are subclassable: the per-class emit methods are `protected virtual`, plus finer hooks — `EmitClassHeader` / `EmitClassDeclarationLine` (class declaration: `partial`, marker interfaces), `EmitPropertyAttributes` (per-property C# attributes), -`EmitFileUsings` (extra usings), `EmitClassBodyTrailer` (extra members). Subclass a +`EmitFileUsings` (extra usings), `EmitClassBodyTrailer` (extra members). Each takes the +generator's `CsWriter`: write whole lines with `w.Line(...)` and `using`s with `w.Using(...)`, never +typed indentation or line breaks (the writer lays the file out, ADR-0063). `DbContextGenerator`'s +`EmitUsings`, `EmitDbSetDeclarations` and `EmitOnModelCreatingBody` take it too, and its text hooks +(`ContextMemberLines`, `FieldTypeConfig`, `OwnedTypeConfig`, ...) return unindented lines. Subclass a generator and override only the seam you need rather than forking. `@default` on a scalar emits a literal initializer; an override of `EmitClassDeclarationLine` must not name a concrete parent as the C# base (the child already declares the parent's properties, so a base would diff --git a/agent-context/skills/metaobjects-codegen/references/typescript.md b/agent-context/skills/metaobjects-codegen/references/typescript.md index 588e061158..92401736a4 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript.md @@ -48,7 +48,7 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`, and `formatTs` for TypeScript output. The config's `apiPrefix` is +`pluralize`, and `formatTs` (a no-op kept so an owned copy still loads). The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. @@ -59,6 +59,11 @@ npm install --save-dev @metaobjectsdev/cli @metaobjectsdev/codegen-ts npm install @metaobjectsdev/metadata @metaobjectsdev/runtime-ts ``` +`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`, so npm does not install +them with the CLI. Install them when a generator you take writes code that imports them. +`meta gen --list --format json` gives each generator's `install.dev` and `install.runtime`, and +`meta eject ...` prints the consolidated install set. + For the React + TanStack codegen packages, also: ```bash 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/bun.lock b/bun.lock index 985f139383..8a5ac3b437 100644 --- a/bun.lock +++ b/bun.lock @@ -178,7 +178,6 @@ "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", - "@libsql/kysely-libsql": "^0.4.0", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/codegen-ts-react": "workspace:*", "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", @@ -193,6 +192,7 @@ }, "devDependencies": { "@libsql/client": "^0.14.0", + "@libsql/kysely-libsql": "^0.4.1", "@metaobjectsdev/test-generators": "workspace:*", "@types/node": "^22.0.0", "@types/pg": "^8.0.0", @@ -208,10 +208,12 @@ "zod": "^4.4.3", }, "peerDependencies": { + "@libsql/kysely-libsql": ">=0.4.0 <0.5.0", "kysely": ">=0.27.0 <0.30.0", "pg": ">=8.0.0 <9.0.0", }, "optionalPeers": [ + "@libsql/kysely-libsql", "pg", ], }, @@ -219,8 +221,6 @@ "name": "@metaobjectsdev/codegen-ts", "version": "1.3.0", "dependencies": { - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1", "@metaobjectsdev/docs-site": "workspace:*", @@ -246,6 +246,10 @@ "drizzle-orm": ">=0.38.0 <1.0.0", "zod": ">=3.23.0 <5.0.0", }, + "optionalPeers": [ + "drizzle-orm", + "zod", + ], }, "server/typescript/packages/codegen-ts-angular": { "name": "@metaobjectsdev/codegen-ts-angular", diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 5e5114c432..48cc7f7811 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) | 41 cases (31 core + 10 TypeScript) | ✓ (the first writer; core and TypeScript dialect) | — (writer not built yet) | — (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) | 67 cases (31 core + 10 TypeScript + 9 Java + 6 C# + 11 Python) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | | [`fixtures/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) | — | — | — | — | @@ -203,10 +203,11 @@ the metadata package, so two packages that each declare an object of the same na collide on an output path. State per port: - *Done, C#:* every per-object generator writes through `OutputPaths.Of` - (`/`; root-level objects at the root). The path follows the metadata - package, not `PackageNamespaces`. Since rc.19 R65 the namespace follows the package too - (`acme::alpha` → `Acme.Alpha`) unless a binding maps it; every cross-namespace reference is - `global::`-qualified. Tests: `OutputPathsTests`, `PackageNamespaceTests`. + (`/` under `csharp.outputLayout: "package"`, opt-in; flat otherwise; + root-level objects at the root). The path follows the metadata package, not `PackageNamespaces`. + The namespace follows the package only with `csharp.packageNamespaces: true`, opt-in since + 1.3.0 (R64, R65; `acme::alpha` → `Acme.Alpha`), unless a binding maps it; every cross-namespace + reference is `global::`-qualified. Tests: `OutputPathsTests`, `PackageNamespaceTests`. - *Done, TypeScript:* `outputLayout` defaults to `"flat"`; `"package"` is opt-in (ruling R63). Tests: `barrel-layout.test.ts` (the barrel exports the same names in both layouts), `naming/name-claims.test.ts`. @@ -667,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/RELEASING.md b/docs/RELEASING.md index 3e69c2ab3e..5793e78d22 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -574,6 +574,13 @@ strategy mismatches) that the unit suites missed. ### 2c. Run an adopter estate against the RC (1.0 gate G3d) +> **Staged candidates.** The checklist below is the final-cut gate. Each staged candidate +> (`1.3.0-rc.N`, published to the private registry with `bun run prerelease:candidate`) has its +> own run sheet and a script for its mechanical steps: +> [`tools/prerelease/estate-run.md`](../tools/prerelease/estate-run.md) and +> `tools/prerelease/estate-run.sh`. The commit each candidate was built from is recorded in +> [`tools/prerelease/candidates.md`](../tools/prerelease/candidates.md). + Every corpus in this repo can be green while a real application built on the release is broken — the defects live where features meet, in models no fixture composes. Before promoting, run at least one adopter estate against the candidate, end to end, and treat a @@ -702,6 +709,22 @@ commit on it is an ancestor of `main`. Step 0 checks this and `release.mjs` refu until it holds; a fix that exists only on the maintenance branch would otherwise be missing from the new line. +**A squash forward-port does not satisfy that check.** Re-landing a fix on `main` as a squashed +PR copies the change but not the commit, so the maintenance commit stays "not an ancestor of +`main`" and Step 0 keeps refusing. After the fixes are confirmed present on `main` (by their +tests, not by the commit messages), record the branch as merged with an ancestry-only merge: + +```bash +git checkout -b chore/record-release-1.2-merged origin/main +git merge -s ours --no-ff origin/release/1.2 # records ancestry; changes no file +``` + +Open that as a PR and **merge it with a merge commit, never squash or rebase**: either one +discards the second parent, and the ancestry this exists to record is gone. Check afterwards +that `git rev-list --count origin/main..origin/release/1.2` prints `0`. Use `-s ours`, not a +plain merge: the maintenance branch carries release version bumps and a site payload that must +never reach `main`. + ## Isolated patch (one package) If only one package changed (e.g. a `cli` bugfix), bump just that package, `rm bun.lock && bun diff --git a/docs/features/cli.md b/docs/features/cli.md index e92f5254ac..2cb7085229 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -25,7 +25,7 @@ command surface splits in two: | Capability | Tool | Invocation | Notes | |---|---|---|---| -| Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); `--force` over an existing config does not add it | +| Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); for `--dialect sqlite` it also adds `@libsql/kysely-libsql` to the project's `dependencies`, the SQLite driver the CLI's optional peer names (run your package manager's install afterwards); `--force` over an existing config does not add it | | **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); non-Node CLIs redirect here | | **Schema migrate** | **Node `meta`** | `meta migrate` | **any backend** — schema is Node-only (ADR-0015) | | **Schema drift** (`verify --db`) | **Node `meta`** | `meta verify --db` | **any backend** — live-DB drift, Node-only | @@ -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/contract-emitters.md b/docs/features/contract-emitters.md index fa016e75d7..ac56bd8c13 100644 --- a/docs/features/contract-emitters.md +++ b/docs/features/contract-emitters.md @@ -19,8 +19,8 @@ port actually send and take, under the project's [`wire` setting](api-contract.m **What they do not do.** They generate no client and no server, and they do not validate anything at runtime. Run openapi-generator, Kiota or orval on the document for a client. The protobuf emitter in -the [design](../superpowers/specs/2026-06-11-fr-022-contract-emitters-design.md) is not built; it is -planned with binary protocols for 1.3. +the [design](../superpowers/specs/2026-06-11-fr-022-contract-emitters-design.md) is not built, and no +release is planned for it. **Entirely opt-in.** `meta init` wires no generator. A project that does not list them gets no file. @@ -160,6 +160,21 @@ field's allowed operators, `sort`, `limit`, `offset` and `withCount`, M:N traver and per-subtype mounts, projections, reports (with the `format` parameter when `report-export` is wired), and the error envelope. +It also states what the routes do beyond the happy path: + +- **Page size.** When the project sets `api.pagination`, a list's `limit` carries that `default` and + `maximum`, and the description names the `limit_too_large` answer. Without the setting `limit` + states neither, because the server serves what it always did. A report keeps its own row cap and + states neither either. +- **Undeclared body keys.** A create, `PUT` or `PATCH` body description says an undeclared key is + refused with `400 unknown_fields` (the default) or dropped under `api.unknownFields: drop`. + The shapes stay open: the server still drops a declared key a client may not set, such as the + generated key, so a client that echoes back a row it read keeps working. +- **Validation issues.** `ApiError` carries `issues` (every problem, as `code`, `path` and + `message`), `fields` (the undeclared keys) and `maxLimit`. +- **Read-only resources.** A projection or a report has no write operations, and each of its + operations says a write answers `405 method_not_allowed`. + A list answers an array, or `{ rows, total }` with `withCount=1`, so its response is a `oneOf` of `List` and `Page`. @@ -187,7 +202,8 @@ openApiFile({ - `readOnly` and `writeOnly`: the shapes are separate. - The TypeScript-only `search`, `filter[or]` and `filter[and]` extensions: the document states the cross-port contract ([api-contract.md](api-contract.md)). -- 405 answers: a verb a read-only surface does not serve is absent from the document. +- 405 answers as operations: a verb a read-only surface does not serve is absent from the document, + and the surface's operations say so in prose. - Routes you wrote by hand. Eject `openapi` and add them in `buildOpenApiDocument` if you want them documented. 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-and-drift.md b/docs/features/migrations-and-drift.md index 52ccd50746..e4a959b3e0 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -635,6 +635,28 @@ foreign key nothing leads with, named `
__idx`) or leave the opti otherwise the C# DbContext or Kotlin Exposed tables may declare an index `meta migrate` did not create. +## A foreign key onto a non-unique target: `migrate.foreignKeyTargets` + +A foreign key must reference columns its target table holds unique: the primary key, a plain +`identity.secondary` (no `@where`, no `@expr`) or a single `@unique` field. Postgres refuses any other +foreign key when it is applied, after earlier statements have already run, so `meta migrate` and +`meta verify --db` stop first and list every offending reference at once. + +Some databases hold the unique index by hand, in a form the metadata does not declare. For those, +`migrate.foreignKeyTargets` turns the refusal into a report: + +```json +{ "schema_version": 1, "migrate": { "foreignKeyTargets": "warn" } } +``` + +`"refuse"` is the default. With `"warn"`, each such reference is printed as a warning, naming the +reference, its target and the fix, and the run goes on and still emits the foreign key. The database +then decides: Postgres refuses the foreign key at apply time unless a unique index it already holds +covers the target. Declaring the unique key on the target entity makes the warning go away and keeps +the model honest, so prefer it when the index is yours to declare. SQLite reports the same references +whatever this says, because it accepts the table and checks foreign keys only with `PRAGMA +foreign_keys` on. + ## How CHECK constraints and expression indexes are compared Postgres rewrites an expression before it stores it (`"k" IN ('x')` becomes `k = 'x'::text`, diff --git a/docs/features/migrations/commit-the-gen-state-hash-manifest.md b/docs/features/migrations/commit-the-gen-state-hash-manifest.md index 215343f1b4..542cdf5df2 100644 --- a/docs/features/migrations/commit-the-gen-state-hash-manifest.md +++ b/docs/features/migrations/commit-the-gen-state-hash-manifest.md @@ -48,7 +48,7 @@ meta gen # the regeneration, now on its own ``` **Why `--baseline=adopt` and not a plain `meta gen`.** A plain run works only if your -committed output still matches fresh output. If it does not — an engine or formatter moved +committed output still matches fresh output. If it does not — an engine moved it, which is the usual state of a project that has not regenerated in a few releases — every such file is refused, and a run where *everything* refuses writes **no manifest at all**: there is then nothing to commit, and the next run refuses identically. `--baseline=adopt` @@ -84,7 +84,7 @@ two people who both regenerated do not conflict over ordering. | situation | before | after | |---|---|---| -| File matches its recorded hash (a formatter or engine bump moved the output) | overwritten, reported `NEW` | overwritten, reported `overwrite` | +| File matches its recorded hash (an engine bump moved the output) | overwritten, reported `NEW` | overwritten, reported `overwrite` | | File carries a hand edit | **overwritten silently** | `refused`, path named, exit code 1 | | File we have no record of writing | **overwritten silently** | `refused`, path named, exit code 1 | | Snapshot body present (the machine that generated it) | three-way merge | three-way merge, unchanged | 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/own-your-codegen.md b/docs/features/own-your-codegen.md index cbc55b7a96..e6538fa4b7 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1613,6 +1613,10 @@ namespace: | `output-prompt` | `OutputFormatSpecEmitter.cs`, `Fr010FieldMapping.cs` | | `api-docs` | the page model, builder, renderer and path math (below), `Fr010FieldMapping.cs`, `M2MNavigation.cs` | +The code writer (`MetaObjects.Codegen.Writer.CodeWriter` and `CsWriter`, ADR-0063) is not +copied. It lays a file out and decides nothing about its content, so like the naming tables it +stays in the package, and an owned copy imports it from there. + The copies are the packaged source with the same namespace edit as the generator and no other change. A file two generators share is written once: a later eject finds it, says `[kept — already yours]` and leaves your edits alone, and `--force` replaces it with the diff --git a/docs/features/prerelease.md b/docs/features/prerelease.md index 2131f79d65..3f46c3a581 100644 --- a/docs/features/prerelease.md +++ b/docs/features/prerelease.md @@ -136,6 +136,63 @@ model and never was the durable one. These are: --- +## 2a. Staged candidates + +A release that arrives as a series of candidates (`1.3.0-rc.1`, `-rc.2`, …), each run against +the adopter estates before the next is cut, uses this tool and **not** `bun run release`. +`release.mjs` always publishes to public npm `latest`, commits the version and dates the +CHANGELOG; the private-registry path does none of that, and it does not run the maintenance-branch +check that gates the final cut (`docs/RELEASING.md`, Step 0). + +**A full candidate, every registry:** + +```bash +bun run prerelease:candidate # = bun run prerelease:publish --only all +``` + +The default scope is npm and Maven only, so a Python or a C# estate gets nothing from a bare +`prerelease:publish`. Use the full command for any candidate an estate in those ports will run; +name a narrower `--only` only for a fix you are iterating on one port. + +**The log.** Every run that starts a publish appends one row to +[`tools/prerelease/candidates.md`](../../tools/prerelease/candidates.md): the candidate, the full +`HEAD` it was built from (shortened to 12 characters, `+dirty` when tracked files outside the +version declarations were modified), the UTC date, and the ecosystems published. A run that stops +partway still writes its row: a registry whose publish began but did not finish reads +` (cut short)`, because its candidate number is taken there, and a registry the run +was asked for but never reached reads `stopped before `. A dry run writes no row. It +names ecosystems, never the registry host. The script writes the row after it has restored the +version files, so the row is the only change the run leaves; **commit it**, so the repository +records what each candidate was built from. Build a candidate from a commit that is already +pushed: a sha nobody can fetch is not a record. + +**Estate runs.** What an estate does with a candidate is +[`tools/prerelease/estate-run.md`](../../tools/prerelease/estate-run.md), with +`tools/prerelease/estate-run.sh` for the mechanical part. + +### Rust + +There is no Rust candidate on the private registry: the three crates are `publish = false` and +the registry serves npm, PyPI, NuGet and Maven. A Rust consumer **pins the commit** the +candidate's row in the log names: + +```toml +[dependencies] +metaobjects = { git = "https://github.com/metaobjectsdev/metaobjects", rev = "" } +``` + +```bash +cargo install --git https://github.com/metaobjectsdev/metaobjects --rev metaobjects-cli +``` + +Cargo finds each crate by name inside the repository, so the same `rev` serves +`metaobjects`, `metaobjects-codegen` and `metaobjects-cli`. Use the full 40-character sha for +`rev` (the log shortens it; `git rev-parse ` expands it in a clone). `cargo meta --version` prints +only the crate version, so read the commit back from `Cargo.lock`'s `source` line (it ends in +`#`), the way the other ports read their resolved versions. + +--- + ## 3. Consuming — one command in each direction ```bash 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/csharp.md b/docs/ports/csharp.md index 3f1e6653b4..ede23a890d 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -327,6 +327,17 @@ a project whose `codegen/Codegen.csproj` pins an older `MetaObjects.Codegen` tha prints a warning naming the line to change. See [Own your codegen → C#](../features/own-your-codegen.md#c-dotnet-meta-eject). +**Generators write through a code writer.** `MetaObjects.Codegen.Writer.CsWriter` is where a +generator's layout lives (ADR-0063): it owns the indent, the braces, the `using` lines and the +blank lines, so a generator states what the file says and not how many spaces it takes. The +filter allowlist, names, callable, output-prompt, output-parser and extractor generators are +written on it, and so is the mirror record they share. Each is a class whose file is built from +one overridable method per piece (`WriteFileHeader`, `WriteTypeDoc`, `WriteMembers` and so on), +so an owned copy, or a subclass of the shipped one, changes the piece it wants and keeps the rest. +Those methods are not a stability contract. A test keeps new hand-typed layout out of the +generator source: a file that still builds text with `AppendLine` is on an allowlist with a +written reason, and the list only gets shorter. + **Give a copy back.** `dotnet meta eject --undo` drops every owned copy that is identical to the shipped generator (the comparison ignores blank lines, order and trailing whitespace, and covers the emitters eject handed over with it); `dotnet meta eject --undo ...` drops only those. @@ -470,11 +481,32 @@ so the declaration and every reference agree. The hooks `EntityGenerator.Propert `DbContextGenerator.PropertyName` default to it; a subclass that overrides one must override the other the same way. The routes generator, the filter map and the credential stripping read the same resolver, and a hook that disagrees with it is refused. -**Class attributes.** `EntityGenerator.EmitClassAttributes(sb, entity, className, kind, ctx)` is +**Class attributes.** `EntityGenerator.EmitClassAttributes(w, entity, className, kind, ctx)` (`w` is the `CsWriter`) is called for every class it emits (mapped entity, TPH subtype, abstract shape, value object), after the framework's own attributes and right before the declaration line. Override it to add an attribute without re-implementing `EmitClassHeader`. +**The writer owns layout (ADR-0063).** `EntityGenerator` writes every file on a +`MetaObjects.Codegen.Writer.CsWriter`, and its hooks (`EmitClassHeader`, `EmitClassAttributes`, +`EmitClassDeclarationLine`, `EmitPropertyAttributes`, `EmitFileUsings`, `EmitClassBodyTrailer`) +take that writer instead of a `StringBuilder`. A hook writes complete lines with `w.Line(...)` or a +`using` with `w.Using(...)` and never types an indent or a line break: the writer indents the line to +where it is written. `ValueObjectMemberAttributes` returns lines with no indent for the same reason. +A class that carries cross-field validators gets `IValidatableObject` added to its declaration line by +the base class, even when an override of `EmitClassHeader` or `EmitClassDeclarationLine` wrote the line. +The base class adds it to the last line written, so an override must write the declaration as its last +line. The hooks are not a stability contract; an owned copy ejected with `dotnet meta eject` is yours to change. + +`DbContextGenerator` writes on the same writer. Its three file-shape hooks (`EmitUsings`, +`EmitDbSetDeclarations`, `EmitOnModelCreatingBody`) take the `CsWriter` in place of the `StringBuilder`; +`EmitUsings` leaves the class body open with `w.Open("{")` and the generator writes the closing `}`. The +hooks that return text (`ContextUsings`, `ContextMemberLines`, `ContextPreambleLines`, +`ContextTrailerLines`, `DbSetLine`, `EntityConfigTrailer`, `FieldTypeConfig`, `OwnedTypeConfig` and the +rest) return lines with no indent: each model entry is one statement, and the writer indents it where it is +written. An entry that already carries an indent still reads right, because the writer removes an entry's +common margin before it indents. A `ContextUsings` line is a `using ...;` directive, which the writer +prints once, in the order given. + **One line at a time.** Each of these is a `protected virtual` hook whose default is the line it replaces; override it, call base, and adjust. On `EntityGenerator`: `ValueObjectMemberAttributes` (the `[JsonPropertyName]` before each value-object member), `ColumnAttributeArguments` (the @@ -533,8 +565,11 @@ already holds. EF finds the services through `[assembly: DesignTimeServicesRefer is generated beside the class when the context's assembly name is known (the single `.csproj` in the output directory or above it, or `GenConfig.ContextAssemblyName`). That covers EF's default layout, where the migrations live in the context's project. When the migrations or startup project -is another one, `dotnet meta gen` warns and prints the one line to add to that project; without it -a changed start scaffolds as `RESTART`. `dotnet ef migrations add --verbose` prints "Using +is another one and `dotnet meta gen` can see it (the `ModelSnapshot.cs` is there) without the +line, a project that declares an `@sequenceStart` fails with `ERR_DESIGN_TIME_REFERENCE_MISSING`, which +names the project and the one line to add: without it a changed start scaffolds as `RESTART`. A run +that cannot tell (no snapshot on disk yet), and a project that declares no start, get the warning +with the same line instead. `dotnet ef migrations add --verbose` prints "Using design-time services from assembly …" when they are found. The start in the model, and the services, are emitted only for a project whose 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/docs/ports/rust.md b/docs/ports/rust.md index 29666cd447..a68f8ca742 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -39,6 +39,12 @@ from the checkout: cargo install --path /server/rust/metaobjects-cli ``` +To use a candidate or any other commit without a checkout, pin it from git +(`cargo install --git https://github.com/metaobjectsdev/metaobjects --rev metaobjects-cli`, +and the same `git` + `rev` on a `metaobjects` dependency). The candidate log +(`tools/prerelease/candidates.md`) names the commit each staged candidate was built from; see +[Pre-releases, "Rust"](../features/prerelease.md#rust). + | Command | What it does | |---|---| | `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed) and a first `metaobjects/meta.app.yaml`. It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index ae0af49d13..06add2c7ee 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -84,11 +84,18 @@ npm install --save-dev @metaobjectsdev/codegen-ts-react @metaobjectsdev/codegen- npm install @metaobjectsdev/react @metaobjectsdev/tanstack @metaobjectsdev/runtime-web ``` -`@metaobjectsdev/codegen-ts` declares `drizzle-orm` and `zod` as non-optional -peer dependencies, so npm installs both automatically. The default Fastify -routes generator (`routesFile()`) additionally needs `fastify` at runtime — it -is an **optional** peer of `@metaobjectsdev/runtime-ts` (so it is *not* -auto-installed); add it explicitly: +`@metaobjectsdev/codegen-ts` declares `drizzle-orm` and `zod` as **optional** peer +dependencies, so npm installs neither with it. Install them when the generators you +take write code that imports them; `meta gen --list --format json` gives each +generator's install set. The stock `entity`, `queries` and `routes` pair needs both: + +```bash +npm install drizzle-orm zod +``` + +The default Fastify routes generator (`routesFile()`) additionally needs `fastify` +at runtime — it is an **optional** peer of `@metaobjectsdev/runtime-ts` (so it is +*not* auto-installed); add it explicitly: ```bash npm install fastify diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json index c67f9bf9ad..b960c50d96 100644 --- a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json @@ -5,22 +5,22 @@ "sourceNode": "acme::learn::Author" }, "src/generated/Author.queries.ts": { - "hash": "42cc1ab2fd442559e1e9c5c3f14978f306efcda5472f8b5370d3339753e5a36f", + "hash": "bea4d154f02ed1b93679acde9ece817be80c625b65f5b4efa2d6aaba712b9185", "generatedBy": "queries-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.routes.ts": { - "hash": "38d9a39b2fc93dc63ba0bc11d91d151f2a24b0af808a10dfdddf61a2d58356de", + "hash": "777c863287967d273a91afc4c1b706ab87c6c178fb995fe911ffce3360b53747", "generatedBy": "routes-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.ts": { - "hash": "36f28e09c3633848bf3bdb45372e03ae8b036792dec05f503a6f0d3abc1bb1cc", + "hash": "a1669e4eec814446e5da4561636312698cce75d2ee5c8afd1d38016a616d2f98", "generatedBy": "entity-file", "sourceNode": "acme::learn::Author" }, "src/generated/InstructorProfile.ts": { - "hash": "2643b88401edf303789461d7d05bafd7cb1979b0ff19c27958d156192265986a", + "hash": "3559df25112ecb00911c2668a2fce07770b213fee9455fce80906162814b2c17", "generatedBy": "entity-file", "sourceNode": "acme::learn::InstructorProfile" }, @@ -30,17 +30,17 @@ "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.queries.ts": { - "hash": "bc8e9bff3cb70c2c47ecfd07619f90d3f26a3981aca8ce6828f75e2a80fb9273", + "hash": "d6fa0b0c29b65afd52e69423e79dc478b3dcde505fac55bca7057cb00f46eb1a", "generatedBy": "queries-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.routes.ts": { - "hash": "a706159a09e459f44f1dd0721cf26320862768a4305363d94cf66b5fb8b5ae2a", + "hash": "b57f413c9b5582fee2cf9150064f879d106b0e94c0b4e75448b0a1fce3e7e708", "generatedBy": "routes-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.ts": { - "hash": "404b7d27b2ec7a6158c6915dbe289c09e36b8fafe8ed82b14871a3bbfa117db8", + "hash": "c699a4d4a0584e9206d7562ea16116c34c5dc85ee4027acaf9cb0b01d2222f06", "generatedBy": "entity-file", "sourceNode": "acme::learn::Lesson" }, @@ -50,17 +50,17 @@ "sourceNode": "acme::learn::Program" }, "src/generated/Program.queries.ts": { - "hash": "07bde6eda6ec265f3b9b61b73b379ed2a066a9b852ecbda2c6bf7ee5d5d079cf", + "hash": "d0b4b7d598cf4da0c7200e78198cf81fc807edf5563f83028b31a01b1da0288b", "generatedBy": "queries-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.routes.ts": { - "hash": "c0b0b5cf1761371480aa90d613c5170212b4b4ef63fd265f1362ff4051b50af9", + "hash": "a0b184a3475fbe3c5f06cc88007a76fa298e375f4c1be8b6037a781f2aef7860", "generatedBy": "routes-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.ts": { - "hash": "a658aad738aa33578fa5e5091494137f0268ea497a6daf5c61422861cdf04806", + "hash": "95c5f5a951d1b219b4f3a4cef6dfc5fc0ea4612c3b18529fc3defaf27aa7e952", "generatedBy": "entity-file", "sourceNode": "acme::learn::Program" }, @@ -71,17 +71,17 @@ "sourceNode": "acme::learn::ProgramDescriptionPayload" }, "src/generated/ProgramSummary.queries.ts": { - "hash": "743e8ce74eee85bb821cf3d909957fae630085fb1f5a7567dd6bfdcae4364910", + "hash": "8902cbac50396109867e90d2e973d850e0d1e211d9d2f21c0e5f4b2882fd0dd9", "generatedBy": "queries-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.routes.ts": { - "hash": "995e893a6b21e65d7bc031761c18bb7bb0c790abb31cb72546bf95573c980099", + "hash": "3aa58a1722e50378410e05e43e797b67f7ef80ab16ec0bc6711c222787a16578", "generatedBy": "routes-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.ts": { - "hash": "181f48ed374dfdf2f5b3213e0064833f071fd7029ed9357a6eef764616c2429c", + "hash": "615eb82032aaf686bc3e5b1484bf2b70174ded81da0310c5a6939e6fdb33bc8d", "generatedBy": "entity-file", "sourceNode": "acme::learn::ProgramSummary" }, @@ -91,22 +91,22 @@ "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.queries.ts": { - "hash": "ae7896ebdf3a57332e2c79dc9dd99fef9547054371547d6a469a752a7fc64ad6", + "hash": "9527a9cae7157415d78c64d21164779272d731827efa807505dc3552728be1e9", "generatedBy": "queries-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.routes.ts": { - "hash": "7590c063acdabcd86eec67d3d8abc6390dde576aca733944dbb1edaf1dfde5bb", + "hash": "9d634c477225b01f3873815e01423f8ae06673830b4f63f1c19df4e3222dda3f", "generatedBy": "routes-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.ts": { - "hash": "fa88def0af1a85b18a1d9d7bb99588f0d71273ce0ee4ce633615ab0724a6bf69", + "hash": "ee57e04fa03ff23675e1a80be5beb984fee268b423ac1ecd80452d857a22d30a", "generatedBy": "entity-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/SyllabusSection.ts": { - "hash": "655f1fdd3c2f104fe48e8fb9a4147c3977a820f82e2b0a6ce1db8e4bd1b3ca2c", + "hash": "d57e6668f79f6577986b2558fe57badc3f87ce8e5d55340f3063c3db57d7d367", "generatedBy": "entity-file", "sourceNode": "acme::learn::SyllabusSection" } diff --git a/examples/advanced-modeling/codegen/generators/barrel.ts b/examples/advanced-modeling/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/advanced-modeling/codegen/generators/barrel.ts +++ b/examples/advanced-modeling/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/entity.ts b/examples/advanced-modeling/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/advanced-modeling/codegen/generators/entity.ts +++ b/examples/advanced-modeling/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/advanced-modeling/codegen/generators/queries.ts b/examples/advanced-modeling/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/advanced-modeling/codegen/generators/queries.ts +++ b/examples/advanced-modeling/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index e687d1acdb..026d00f5be 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/examples/advanced-modeling/codegen/templates/routes-index.ts b/examples/advanced-modeling/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/advanced-modeling/codegen/templates/routes-index.ts +++ b/examples/advanced-modeling/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/advanced-modeling/codegen/templates/view-decl.ts b/examples/advanced-modeling/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/advanced-modeling/codegen/templates/view-decl.ts +++ b/examples/advanced-modeling/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/advanced-modeling/src/generated/Author.queries.ts b/examples/advanced-modeling/src/generated/Author.queries.ts index b365185b65..e19d0d8624 100644 --- a/examples/advanced-modeling/src/generated/Author.queries.ts +++ b/examples/advanced-modeling/src/generated/Author.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Author, - AuthorInsertSchema, - type AuthorPatch, - authors, - AuthorUpdateSchema, -} from "./Author"; -export async function findAuthorById( - db: Db, - id: string, -): Promise { - const [author] = await db - .select() - .from(authors) - .where(eq(authors.id, id)) - .limit(1); +import { type Author, AuthorInsertSchema, type AuthorPatch, authors, AuthorUpdateSchema } from "./Author"; +export async function findAuthorById(db: Db, id: string): Promise { + const [author] = await db.select().from(authors).where(eq(authors.id, id)).limit(1); return author ?? null; } -export async function listAuthors( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listAuthors(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(authors).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listAuthors( } return q; } -export async function createAuthor( - db: Db, - data: z.input, -): Promise { +export async function createAuthor(db: Db, data: z.input): Promise { const validated = AuthorInsertSchema.parse(data); const [author] = await db.insert(authors).values(validated).returning(); return author!; } -export async function updateAuthor( - db: Db, - id: string, - patch: AuthorPatch, -): Promise { +export async function updateAuthor(db: Db, id: string, patch: AuthorPatch): Promise { const validated = AuthorUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findAuthorById(db, id); } - const [author] = await db - .update(authors) - .set(validated) - .where(eq(authors.id, id)) - .returning(); + const [author] = await db.update(authors).set(validated).where(eq(authors.id, id)).returning(); return author ?? null; } export async function deleteAuthorById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(authors) - .where(eq(authors.id, id)) - .returning(); + const deleted = await db.delete(authors).where(eq(authors.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/advanced-modeling/src/generated/Author.routes.ts b/examples/advanced-modeling/src/generated/Author.routes.ts index e2a9645ce0..d61cfcb331 100644 --- a/examples/advanced-modeling/src/generated/Author.routes.ts +++ b/examples/advanced-modeling/src/generated/Author.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function authorRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Author.$path, - db, - table: authors, - insertSchema: AuthorInsertSchema, - updateSchema: AuthorUpdateSchema, - filterAllowlist: AuthorFilterAllowlist, - sortAllowlist: AuthorSortAllowlist, - dialect: "postgres", - knownFields: ["id", "name", "email", "bio"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Author.$path, + db, + table: authors, + insertSchema: AuthorInsertSchema, + updateSchema: AuthorUpdateSchema, + filterAllowlist: AuthorFilterAllowlist, + sortAllowlist: AuthorSortAllowlist, + dialect: "postgres", + knownFields: ["id", "name", "email", "bio"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Author.ts b/examples/advanced-modeling/src/generated/Author.ts index 94dd4d81e7..68e7d8db5b 100644 --- a/examples/advanced-modeling/src/generated/Author.ts +++ b/examples/advanced-modeling/src/generated/Author.ts @@ -22,12 +22,7 @@ export const AuthorInsertSchema = z.object({ export const AuthorUpdateSchema = z.object({ name: z.string().min(1).max(120).optional(), - email: z - .string() - .min(1) - .max(320) - .regex(new RegExp("^(?:[^@]+@[^@]+)$")) - .optional(), + email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(), bio: z.string().max(500).optional().nullable(), }); @@ -71,10 +66,7 @@ export const Author = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, email: { name: "email", diff --git a/examples/advanced-modeling/src/generated/InstructorProfile.ts b/examples/advanced-modeling/src/generated/InstructorProfile.ts index 4ee0b9bb91..169c326d7b 100644 --- a/examples/advanced-modeling/src/generated/InstructorProfile.ts +++ b/examples/advanced-modeling/src/generated/InstructorProfile.ts @@ -34,17 +34,13 @@ export const InstructorProfile = { label: "Bio", view: "text", htmlType: "text", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, credentialsSummary: { name: "credentialsSummary", label: "Credentials Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 300, message: "Must be 300 characters or fewer" }, - }, + rules: { maxLength: { value: 300, message: "Must be 300 characters or fewer" } }, }, } as const; diff --git a/examples/advanced-modeling/src/generated/Lesson.queries.ts b/examples/advanced-modeling/src/generated/Lesson.queries.ts index 787d1dfaf5..1f01305eae 100644 --- a/examples/advanced-modeling/src/generated/Lesson.queries.ts +++ b/examples/advanced-modeling/src/generated/Lesson.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Lesson, - LessonInsertSchema, - type LessonPatch, - lessons, - LessonUpdateSchema, -} from "./Lesson"; -export async function findLessonById( - db: Db, - id: string, -): Promise { - const [lesson] = await db - .select() - .from(lessons) - .where(eq(lessons.id, id)) - .limit(1); +import { type Lesson, LessonInsertSchema, type LessonPatch, lessons, LessonUpdateSchema } from "./Lesson"; +export async function findLessonById(db: Db, id: string): Promise { + const [lesson] = await db.select().from(lessons).where(eq(lessons.id, id)).limit(1); return lesson ?? null; } -export async function listLessons( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listLessons(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(lessons).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listLessons( } return q; } -export async function createLesson( - db: Db, - data: z.input, -): Promise { +export async function createLesson(db: Db, data: z.input): Promise { const validated = LessonInsertSchema.parse(data); const [lesson] = await db.insert(lessons).values(validated).returning(); return lesson!; } -export async function updateLesson( - db: Db, - id: string, - patch: LessonPatch, -): Promise { +export async function updateLesson(db: Db, id: string, patch: LessonPatch): Promise { const validated = LessonUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findLessonById(db, id); } - const [lesson] = await db - .update(lessons) - .set(validated) - .where(eq(lessons.id, id)) - .returning(); + const [lesson] = await db.update(lessons).set(validated).where(eq(lessons.id, id)).returning(); return lesson ?? null; } export async function deleteLessonById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(lessons) - .where(eq(lessons.id, id)) - .returning(); + const deleted = await db.delete(lessons).where(eq(lessons.id, id)).returning(); return deleted.length > 0; } -export async function findLessonsByProgram( - db: Db, - programId: string, -): Promise { +export async function findLessonsByProgram(db: Db, programId: string): Promise { return db.select().from(lessons).where(eq(lessons.programId, programId)); } -export async function findLessonsByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findLessonsByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(lessons) - .where(inArray(lessons.programId, programIds)); + return db.select().from(lessons).where(inArray(lessons.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Lesson.routes.ts b/examples/advanced-modeling/src/generated/Lesson.routes.ts index 3faa54390e..c5da461295 100644 --- a/examples/advanced-modeling/src/generated/Lesson.routes.ts +++ b/examples/advanced-modeling/src/generated/Lesson.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function lessonRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Lesson.$path, - db, - table: lessons, - insertSchema: LessonInsertSchema, - updateSchema: LessonUpdateSchema, - filterAllowlist: LessonFilterAllowlist, - sortAllowlist: LessonSortAllowlist, - dialect: "postgres", - knownFields: ["id", "programId", "title", "position"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Lesson.$path, + db, + table: lessons, + insertSchema: LessonInsertSchema, + updateSchema: LessonUpdateSchema, + filterAllowlist: LessonFilterAllowlist, + sortAllowlist: LessonSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "title", "position"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Lesson.ts b/examples/advanced-modeling/src/generated/Lesson.ts index c337e0ca25..025a7ab641 100644 --- a/examples/advanced-modeling/src/generated/Lesson.ts +++ b/examples/advanced-modeling/src/generated/Lesson.ts @@ -2,21 +2,13 @@ // Source metadata: Lesson (Lesson) // Extend in your own module (e.g. Lesson.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - type AnyPgColumn, - integer, - pgTable, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, integer, pgTable, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; export const lessons = pgTable("lessons", { id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), title: varchar("title", { length: 200 }).notNull(), position: integer("position").notNull(), }); @@ -24,24 +16,19 @@ export type Lesson = InferSelectModel; export type LessonInsert = InferInsertModel; export type LessonUpdate = Partial; export const LessonInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), title: z.string().min(1).max(200), position: z.number().int(), }); export const LessonUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), title: z.string().min(1).max(200).optional(), position: z.number().int().optional(), }); @@ -93,10 +80,7 @@ export const Lesson = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, position: { name: "position", diff --git a/examples/advanced-modeling/src/generated/Program.queries.ts b/examples/advanced-modeling/src/generated/Program.queries.ts index 55c228b3fe..cad3c64d26 100644 --- a/examples/advanced-modeling/src/generated/Program.queries.ts +++ b/examples/advanced-modeling/src/generated/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: string, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: string): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: string, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: string, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } -export async function findProgramsByAuthor( - db: Db, - authorId: string, -): Promise { +export async function findProgramsByAuthor(db: Db, authorId: string): Promise { return db.select().from(programs).where(eq(programs.authorId, authorId)); } -export async function findProgramsByAuthorIn( - db: Db, - authorIds: string[], -): Promise { +export async function findProgramsByAuthorIn(db: Db, authorIds: string[]): Promise { if (authorIds.length === 0) { return []; } - return db - .select() - .from(programs) - .where(inArray(programs.authorId, authorIds)); + return db.select().from(programs).where(inArray(programs.authorId, authorIds)); } diff --git a/examples/advanced-modeling/src/generated/Program.routes.ts b/examples/advanced-modeling/src/generated/Program.routes.ts index 4f9df9c3cd..d7f53b2bd5 100644 --- a/examples/advanced-modeling/src/generated/Program.routes.ts +++ b/examples/advanced-modeling/src/generated/Program.routes.ts @@ -35,31 +35,28 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function programRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Program.$path, - db, - table: programs, - insertSchema: ProgramInsertSchema, - updateSchema: ProgramUpdateSchema, - filterAllowlist: ProgramFilterAllowlist, - sortAllowlist: ProgramSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "title", - "status", - "summary", - "priceCents", - "coverKey", - "authorId", - "syllabus", - "instructorProfile", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Program.$path, + db, + table: programs, + insertSchema: ProgramInsertSchema, + updateSchema: ProgramUpdateSchema, + filterAllowlist: ProgramFilterAllowlist, + sortAllowlist: ProgramSortAllowlist, + dialect: "postgres", + knownFields: [ + "id", + "title", + "status", + "summary", + "priceCents", + "coverKey", + "authorId", + "syllabus", + "instructorProfile", + ], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Program.ts b/examples/advanced-modeling/src/generated/Program.ts index 3479546516..601e7ff873 100644 --- a/examples/advanced-modeling/src/generated/Program.ts +++ b/examples/advanced-modeling/src/generated/Program.ts @@ -2,51 +2,23 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - jsonb, - pgTable, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { authors } from "./Author"; -import { - type InstructorProfile, - InstructorProfileInsertSchema, -} from "./InstructorProfile"; -import { - type SyllabusSection, - SyllabusSectionInsertSchema, -} from "./SyllabusSection"; +import { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile"; +import { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection"; -export const programs = pgTable( - "programs", - { - id: uuid("id").primaryKey().defaultRandom(), - title: varchar("title", { length: 200 }).notNull(), - status: text("status", { - enum: ["draft", "published", "archived"] as const, - }), - summary: varchar("summary", { length: 2000 }), - priceCents: bigint("price_cents", { mode: "number" }), - coverKey: varchar("cover_key", { length: 80 }), - authorId: uuid("author_id") - .notNull() - .references((): AnyPgColumn => authors.id), - syllabus: jsonb("syllabus").$type(), - instructorProfile: jsonb("instructor_profile").$type(), - }, - (table) => [ - check( - "programs_status_chk", - sql`status IN ('draft', 'published', 'archived')`, - ), - ], -); +export const programs = pgTable("programs", { + id: uuid("id").primaryKey().defaultRandom(), + title: varchar("title", { length: 200 }).notNull(), + status: text("status", { enum: ["draft", "published", "archived"] as const }), + summary: varchar("summary", { length: 2000 }), + priceCents: bigint("price_cents", { mode: "number" }), + coverKey: varchar("cover_key", { length: 80 }), + authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id), + syllabus: jsonb("syllabus").$type(), + instructorProfile: jsonb("instructor_profile").$type(), +}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; export type ProgramUpdate = Partial; @@ -58,12 +30,10 @@ export const ProgramInsertSchema = z.object({ summary: z.string().max(2000).optional(), priceCents: z.number().int().optional(), coverKey: z.string().max(80).optional(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), syllabus: z.array(SyllabusSectionInsertSchema).optional(), instructorProfile: InstructorProfileInsertSchema.optional(), }); @@ -74,13 +44,10 @@ export const ProgramUpdateSchema = z.object({ summary: z.string().max(2000).optional().nullable(), priceCents: z.number().int().optional().nullable(), coverKey: z.string().max(80).optional().nullable(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(), instructorProfile: InstructorProfileInsertSchema.optional().nullable(), }); @@ -125,39 +92,21 @@ export const Program = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["draft", "published", "archived"] as const, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const }, summary: { name: "summary", label: "Summary", view: "textarea", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, - }, - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, coverKey: { name: "coverKey", label: "Cover Key", view: "image", - rules: { - maxLength: { value: 80, message: "Must be 80 characters or fewer" }, - }, + rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, }, authorId: { name: "authorId", @@ -166,18 +115,8 @@ export const Program = { htmlType: "text", rules: { required: "Author Id is required" }, }, - syllabus: { - name: "syllabus", - label: "Syllabus", - view: "text", - htmlType: "text", - }, - instructorProfile: { - name: "instructorProfile", - label: "Instructor Profile", - view: "text", - htmlType: "text", - }, + syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" }, + instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts index 2d3fcf25a3..02040e061f 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts @@ -7,15 +7,8 @@ import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; import { type ProgramSummary, programSummaryView } from "./ProgramSummary"; -export async function findProgramSummaryById( - db: Db, - id: string, -): Promise { - const [row] = await db - .select() - .from(programSummaryView) - .where(eq(programSummaryView.id, id)) - .limit(1); +export async function findProgramSummaryById(db: Db, id: string): Promise { + const [row] = await db.select().from(programSummaryView).where(eq(programSummaryView.id, id)).limit(1); return row ?? null; } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts index 1050e44196..e2e18e3d9a 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts @@ -31,18 +31,15 @@ import { mountReadOnlyCrudRoutes } from "../../codegen/runtime/drizzle-fastify/i * mount. Hand-write those reads rather than exposing this one open. */ export async function programSummaryRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountReadOnlyCrudRoutes({ - fastify: instance, - path: ProgramSummary.$path, - db, - view: programSummaryView, - filterAllowlist: ProgramSummaryFilterAllowlist, - sortAllowlist: ProgramSummarySortAllowlist, - dialect: "postgres", - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountReadOnlyCrudRoutes({ + fastify: instance, + path: ProgramSummary.$path, + db, + view: programSummaryView, + filterAllowlist: ProgramSummaryFilterAllowlist, + sortAllowlist: ProgramSummarySortAllowlist, + dialect: "postgres", + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.ts b/examples/advanced-modeling/src/generated/ProgramSummary.ts index 5d2aa001af..1576fe2edd 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.ts @@ -1,13 +1,6 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: ProgramSummary (ProgramSummary) -import { - bigint, - boolean, - pgView, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; // View declaration — Drizzle uses this for typed SELECT queries. @@ -36,18 +29,8 @@ export const ProgramSummary = { $path: "/program_summaries", id: { name: "id", label: "Id", view: "text", dbCol: "id" }, title: { name: "title", label: "Title", view: "text", dbCol: "title" }, - authorName: { - name: "authorName", - label: "Author Name", - view: "text", - dbCol: "author_name", - }, - lessonCount: { - name: "lessonCount", - label: "Lesson Count", - view: "number", - dbCol: "lesson_count", - }, + authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" }, + lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" }, completedRevenueCents: { name: "completedRevenueCents", label: "Completed Revenue Cents", @@ -56,17 +39,11 @@ export const ProgramSummary = { currency: "USD", locale: "en-US", }, - hasCoverArt: { - name: "hasCoverArt", - label: "Has Cover Art", - view: "checkbox", - dbCol: "has_cover_art", - }, + hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; -export const ProgramSummaryFilterAllowlist = - {} as const satisfies FilterAllowlist; +export const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; export const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist; diff --git a/examples/advanced-modeling/src/generated/Purchase.queries.ts b/examples/advanced-modeling/src/generated/Purchase.queries.ts index 85fa7e2c92..8d125b9e21 100644 --- a/examples/advanced-modeling/src/generated/Purchase.queries.ts +++ b/examples/advanced-modeling/src/generated/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: string, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: string): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: string, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: string, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesByProgram( - db: Db, - programId: string, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: string): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Purchase.routes.ts b/examples/advanced-modeling/src/generated/Purchase.routes.ts index 767fac818a..e76a7d187f 100644 --- a/examples/advanced-modeling/src/generated/Purchase.routes.ts +++ b/examples/advanced-modeling/src/generated/Purchase.routes.ts @@ -35,27 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function purchaseRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Purchase.$path, - db, - table: purchases, - insertSchema: PurchaseInsertSchema, - updateSchema: PurchaseUpdateSchema, - filterAllowlist: PurchaseFilterAllowlist, - sortAllowlist: PurchaseSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "programId", - "amountCents", - "status", - "purchasedAt", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Purchase.$path, + db, + table: purchases, + insertSchema: PurchaseInsertSchema, + updateSchema: PurchaseUpdateSchema, + filterAllowlist: PurchaseFilterAllowlist, + sortAllowlist: PurchaseSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "amountCents", "status", "purchasedAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Purchase.ts b/examples/advanced-modeling/src/generated/Purchase.ts index 5e1ecd53ac..3ac361e202 100644 --- a/examples/advanced-modeling/src/generated/Purchase.ts +++ b/examples/advanced-modeling/src/generated/Purchase.ts @@ -2,41 +2,17 @@ // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - pgTable, - text, - timestamp, - uuid, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; -export const purchases = pgTable( - "purchases", - { - id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), - amountCents: bigint("amount_cents", { mode: "number" }), - status: text("status", { - enum: ["pending", "completed", "refunded"] as const, - }), - purchasedAt: timestamp("purchased_at", { - mode: "string", - withTimezone: true, - }), - }, - (table) => [ - check( - "purchases_status_chk", - sql`status IN ('pending', 'completed', 'refunded')`, - ), - ], -); +export const purchases = pgTable("purchases", { + id: uuid("id").primaryKey().defaultRandom(), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), + amountCents: bigint("amount_cents", { mode: "number" }), + status: text("status", { enum: ["pending", "completed", "refunded"] as const }), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }), +}, (table) => [check("purchases_status_chk", sql`status IN ('pending', 'completed', 'refunded')`)]); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -49,10 +25,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -61,49 +35,33 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), amountCents: z.number().int().optional(), status: z.enum(["pending", "completed", "refunded"]).optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), amountCents: z.number().int().optional().nullable(), status: z.enum(["pending", "completed", "refunded"]).optional().nullable(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional() - .nullable(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional().nullable(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A @@ -148,25 +106,9 @@ export const Purchase = { htmlType: "text", rules: { required: "Program Id is required" }, }, - amountCents: { - name: "amountCents", - label: "Amount Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["pending", "completed", "refunded"] as const, - }, - purchasedAt: { - name: "purchasedAt", - label: "Purchased At", - view: "date", - htmlType: "datetime-local", - }, + amountCents: { name: "amountCents", label: "Amount Cents", view: "currency", currency: "USD", locale: "en-US" }, + status: { name: "status", label: "Status", view: "dropdown", options: ["pending", "completed", "refunded"] as const }, + purchasedAt: { name: "purchasedAt", label: "Purchased At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/SyllabusSection.ts b/examples/advanced-modeling/src/generated/SyllabusSection.ts index ae049c1ad0..74f353ccd0 100644 --- a/examples/advanced-modeling/src/generated/SyllabusSection.ts +++ b/examples/advanced-modeling/src/generated/SyllabusSection.ts @@ -24,19 +24,14 @@ export const SyllabusSection = { label: "Heading", view: "text", htmlType: "text", - rules: { - required: "Heading is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Heading is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, summary: { name: "summary", label: "Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 500, message: "Must be 500 characters or fewer" }, - }, + rules: { maxLength: { value: 500, message: "Must be 500 characters or fewer" } }, }, orderIndex: { name: "orderIndex", diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index 1c71c30927..774179acca 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -10,17 +10,17 @@ "generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561", "generated/python/subscriber_router.py": "16502ff815bf9ae29c7dba4700d0465d06058a9fd7ea8db5f98334d52d284851", "generated/ts/Subscriber.queries.ts": { - "hash": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562", + "hash": "63adba7ac4415f5e9962c4da100ffd97816524580a513e8350d14bc7a9f3507c", "generatedBy": "queries-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.routes.ts": { - "hash": "f76f592c98bd0ac5c07c4fe9c26cd88659793141e6620310dc725c7edcf68099", + "hash": "c26d2e8e146c5e310fabefa16d1a413109716544a3f817f20f4536cf09e2585e", "generatedBy": "routes-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.ts": { - "hash": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96", + "hash": "760b3d76d100d05f289070ce483f63ee022a3c6fc8d6356e691e4d17f0593734", "generatedBy": "entity-file", "sourceNode": "acme::Subscriber" }, diff --git a/examples/showcase/codegen/generators/barrel.ts b/examples/showcase/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/showcase/codegen/generators/barrel.ts +++ b/examples/showcase/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/showcase/codegen/generators/entity.ts b/examples/showcase/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/showcase/codegen/generators/entity.ts +++ b/examples/showcase/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/showcase/codegen/generators/queries.ts b/examples/showcase/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/showcase/codegen/generators/queries.ts +++ b/examples/showcase/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index e687d1acdb..026d00f5be 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/examples/showcase/codegen/templates/routes-index.ts b/examples/showcase/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/showcase/codegen/templates/routes-index.ts +++ b/examples/showcase/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/showcase/codegen/templates/view-decl.ts b/examples/showcase/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/showcase/codegen/templates/view-decl.ts +++ b/examples/showcase/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/showcase/generated/ts/Subscriber.queries.ts b/examples/showcase/generated/ts/Subscriber.queries.ts index caa8047243..93325d905a 100644 --- a/examples/showcase/generated/ts/Subscriber.queries.ts +++ b/examples/showcase/generated/ts/Subscriber.queries.ts @@ -5,11 +5,7 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; import { type Subscriber, @@ -19,21 +15,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -43,15 +29,9 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } export async function insertPreservingSubscriber( @@ -59,39 +39,22 @@ export async function insertPreservingSubscriber( data: z.input, ): Promise { const validated = SubscriberInsertPreservingSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/showcase/generated/ts/Subscriber.routes.ts b/examples/showcase/generated/ts/Subscriber.routes.ts index efd2cb12ee..c4b84b3775 100644 --- a/examples/showcase/generated/ts/Subscriber.routes.ts +++ b/examples/showcase/generated/ts/Subscriber.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function subscriberRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Subscriber.$path, - db, - table: subscribers, - insertSchema: SubscriberInsertSchema, - updateSchema: SubscriberUpdateSchema, - filterAllowlist: SubscriberFilterAllowlist, - sortAllowlist: SubscriberSortAllowlist, - dialect: "sqlite", - knownFields: ["id", "email", "name", "status", "createdAt"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Subscriber.$path, + db, + table: subscribers, + insertSchema: SubscriberInsertSchema, + updateSchema: SubscriberUpdateSchema, + filterAllowlist: SubscriberFilterAllowlist, + sortAllowlist: SubscriberSortAllowlist, + dialect: "sqlite", + knownFields: ["id", "email", "name", "status", "createdAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/showcase/generated/ts/Subscriber.ts b/examples/showcase/generated/ts/Subscriber.ts index 68907c6ce7..61079d18dc 100644 --- a/examples/showcase/generated/ts/Subscriber.ts +++ b/examples/showcase/generated/ts/Subscriber.ts @@ -5,24 +5,13 @@ import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; import { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, - (table) => [ - check( - "subscribers_status_chk", - sql`status IN ('active', 'paused', 'cancelled')`, - ), - ], -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export type SubscriberUpdate = Partial; @@ -35,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -47,19 +34,14 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .optional() - .transform(() => new Date().toISOString()), + createdAt: z.string().optional().transform(() => new Date().toISOString()), }); export const SubscriberUpdateSchema = z.object({ @@ -84,20 +66,14 @@ export const SubscriberInsertPreservingSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */ -export type SubscriberCreatePreserving = z.input< - typeof SubscriberInsertPreservingSchema ->; +export type SubscriberCreatePreserving = z.input; /** * Metadata constants for Subscriber. * @@ -130,10 +106,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 320, message: "Must be 320 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } }, }, name: { name: "name", label: "Name", view: "text", htmlType: "text" }, status: { @@ -143,12 +116,7 @@ export const Subscriber = { rules: { required: "Status is required" }, options: ["active", "paused", "cancelled"] as const, }, - createdAt: { - name: "createdAt", - label: "Created At", - view: "date", - htmlType: "datetime-local", - }, + createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/showcase/inline/deep-currency.txt b/examples/showcase/inline/deep-currency.txt index 43a89436d5..c05418fd13 100644 --- a/examples/showcase/inline/deep-currency.txt +++ b/examples/showcase/inline/deep-currency.txt @@ -1,7 +1 @@ - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, diff --git a/examples/showcase/inline/ts-entity.txt b/examples/showcase/inline/ts-entity.txt index 4747cfe1d0..e43fc0a083 100644 --- a/examples/showcase/inline/ts-entity.txt +++ b/examples/showcase/inline/ts-entity.txt @@ -1,16 +1,11 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export const SubscriberInsertSchema = z.object({ diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index de8940334c..1ba85b43c7 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -20,9 +20,9 @@ }, "ts-entity": { "lang": "ts", - "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n…\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n (table) => [\n check(\n "subscribers_status_chk",\n sql`status IN ('active', 'paused', 'cancelled')`,\n ),\n ],\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m =\n /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/.exec(\n v,\n );\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t)\n ? v\n : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .optional()\n .transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n )\n .transform(utcIsoTimestamp)\n .optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<\n typeof SubscriberInsertPreservingSchema\n>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: {\n name: "createdAt",\n label: "Created At",\n view: "date",\n htmlType: "datetime-local",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", - "lineCount": 165 + "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m = /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/\n .exec(v);\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().optional().transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n ).transform(utcIsoTimestamp).optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<typeof SubscriberInsertPreservingSchema>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", + "lineCount": 133 }, "python-model": { "lang": "python", @@ -87,20 +87,20 @@ "deep-validators": { "lang": "ts", "inline": "…\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z\n .string()\n .min(1)\n .max(320)\n .regex(new RegExp("^(?:[^@]+@[^@]+)$"))\n .optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Name is required",\n maxLength: { value: 120, message: "Must be 120 characters or fewer" },\n },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", - "lineCount": 113 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", + "lineCount": 105 }, "deep-currency": { "lang": "ts", - "inline": "…\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport {\n type AnyPgColumn,\n bigint,\n check,\n jsonb,\n pgTable,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport {\n type InstructorProfile,\n InstructorProfileInsertSchema,\n} from "./InstructorProfile";\nimport {\n type SyllabusSection,\n SyllabusSectionInsertSchema,\n} from "./SyllabusSection";\n\nexport const programs = pgTable(\n "programs",\n {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", {\n enum: ["draft", "published", "archived"] as const,\n }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id")\n .notNull()\n .references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n },\n (table) => [\n check(\n "programs_status_chk",\n sql`status IN ('draft', 'published', 'archived')`,\n ),\n ],\n);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n )\n .optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Title is required",\n maxLength: { value: 200, message: "Must be 200 characters or fewer" },\n },\n },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n options: ["draft", "published", "archived"] as const,\n },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: {\n maxLength: { value: 2000, message: "Must be 2000 characters or fewer" },\n },\n },\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: {\n maxLength: { value: 80, message: "Must be 80 characters or fewer" },\n },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: {\n name: "syllabus",\n label: "Syllabus",\n view: "text",\n htmlType: "text",\n },\n instructorProfile: {\n name: "instructorProfile",\n label: "Instructor Profile",\n view: "text",\n htmlType: "text",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", - "lineCount": 194 + "inline": "…\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile";\nimport { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection";\n\nexport const programs = pgTable("programs", {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", { enum: ["draft", "published", "archived"] as const }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ).optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } },\n },\n status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } },\n },\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" },\n instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", + "lineCount": 133 }, "deep-projection": { "lang": "ts", "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport {\n bigint,\n boolean,\n pgView,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: {\n name: "authorName",\n label: "Author Name",\n view: "text",\n dbCol: "author_name",\n },\n lessonCount: {\n name: "lessonCount",\n label: "Lesson Count",\n view: "number",\n dbCol: "lesson_count",\n },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: {\n name: "hasCoverArt",\n label: "Has Cover Art",\n view: "checkbox",\n dbCol: "has_cover_art",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist =\n {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", - "lineCount": 79 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" },\n lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", + "lineCount": 56 } } } diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md index 0ee7406d34..06cfdda9e1 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md @@ -305,7 +305,11 @@ hand, so set its strategy from the root: `ColumnNamingStrategy = load.Root.Physi The generators are subclassable: the per-class emit methods are `protected virtual`, plus finer hooks — `EmitClassHeader` / `EmitClassDeclarationLine` (class declaration: `partial`, marker interfaces), `EmitPropertyAttributes` (per-property C# attributes), -`EmitFileUsings` (extra usings), `EmitClassBodyTrailer` (extra members). Subclass a +`EmitFileUsings` (extra usings), `EmitClassBodyTrailer` (extra members). Each takes the +generator's `CsWriter`: write whole lines with `w.Line(...)` and `using`s with `w.Using(...)`, never +typed indentation or line breaks (the writer lays the file out, ADR-0063). `DbContextGenerator`'s +`EmitUsings`, `EmitDbSetDeclarations` and `EmitOnModelCreatingBody` take it too, and its text hooks +(`ContextMemberLines`, `FieldTypeConfig`, `OwnedTypeConfig`, ...) return unindented lines. Subclass a generator and override only the seam you need rather than forking. `@default` on a scalar emits a literal initializer; an override of `EmitClassDeclarationLine` must not name a concrete parent as the C# base (the child already declares the parent's properties, so a base would 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/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md index 588e061158..92401736a4 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md @@ -48,7 +48,7 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`, and `formatTs` for TypeScript output. The config's `apiPrefix` is +`pluralize`, and `formatTs` (a no-op kept so an owned copy still loads). The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. @@ -59,6 +59,11 @@ npm install --save-dev @metaobjectsdev/cli @metaobjectsdev/codegen-ts npm install @metaobjectsdev/metadata @metaobjectsdev/runtime-ts ``` +`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`, so npm does not install +them with the CLI. Install them when a generator you take writes code that imports them. +`meta gen --list --format json` gives each generator's `install.dev` and `install.runtime`, and +`meta eject ...` prints the consolidated install set. + For the React + TanStack codegen packages, also: ```bash diff --git a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts index 78746992c5..1dee1424a1 100644 --- a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts +++ b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts @@ -30,11 +30,7 @@ import type { Hono } from "hono"; * mount. Hand-write those verbs and narrow this file with * routesFileHono({ expose: ["list", "get"] }) rather than mounting them open. */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables -export function registerAuthorRoutes( - app: Hono, - deps: { db: unknown }, -): void { +export function registerAuthorRoutes(app: Hono, deps: { db: unknown }): void { mountCrudRoutes({ app, path: Author.$path, diff --git a/fixtures/contract-conformance/README.md b/fixtures/contract-conformance/README.md index e86c11df10..969958122f 100644 --- a/fixtures/contract-conformance/README.md +++ b/fixtures/contract-conformance/README.md @@ -11,7 +11,7 @@ Each case is a directory. corpus model, because that is the surface every port's routes are held to. - `case.json` keys: `meta` (repository-relative), `wire` (the setting, as in `.metaobjects/config.json`; a case on an api-contract model pins what that corpus pins, because the - integration suite holds that corpus's answers to this document), `strictExclude` (objects the strict profile leaves out, because the + integration suite holds that corpus's answers to this document), `api` (the `api` block of the config: `pagination`, `unknownFields`), `strictExclude` (objects the strict profile leaves out, because the strict subset cannot state them) and `reportExport` (the project wires `report-export`). - `expected/`: the exact tree the emitters write: the canonical schemas, the strict schemas and `openapi.json`. Or `expected-error.txt`: the exact refusal. @@ -30,6 +30,8 @@ document for that corpus. | `all-fields` | Every wire type, every constraint, a value object, a map, a recursive value object, a credential, and the write-mode fields. | | `all-fields-wire-string-emit` | `all-fields` under `wire: { decimals: "string", nullMembers: "emit" }`. | | `all-fields-wire-string-omit` | `all-fields` under `wire: { decimals: "string", nullMembers: "omit" }`. | +| `api-settings` | The `blog` model under `api.pagination`: the list's `limit` has a default and a maximum. | +| `api-settings-drop` | The `blog` model under `api.unknownFields: drop`: a write body says undeclared keys are dropped. | | `blog` | The api-contract corpus's root model: CRUD, filter, sort and paging. | | `decimal` | The api-contract `decimal/` model. | | `error-name-collision` | Refused: a real object takes the name of another object's create shape. | diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json index abb6483b2d..98fbb6c457 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2269,6 +2275,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json index 0df2287e3d..d5e6d19590 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2261,6 +2267,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/all-fields/expected/openapi.json b/fixtures/contract-conformance/all-fields/expected/openapi.json index 5a0735ad62..6db67e917e 100644 --- a/fixtures/contract-conformance/all-fields/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2266,6 +2272,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/api-settings-drop/case.json b/fixtures/contract-conformance/api-settings-drop/case.json new file mode 100644 index 0000000000..8b712ad580 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/case.json @@ -0,0 +1 @@ +{ "meta": "fixtures/api-contract-conformance/meta.json", "wire": {"decimals": "string", "nullMembers": "omit", "durations": "iso"}, "api": { "unknownFields": "drop" } } diff --git a/fixtures/contract-conformance/api-settings-drop/expected/openapi.json b/fixtures/contract-conformance/api-settings-drop/expected/openapi.json new file mode 100644 index 0000000000..7c50b01f62 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/openapi.json @@ -0,0 +1,773 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "api-settings-drop", + "version": "1.0.0" + }, + "paths": { + "/api/authors": { + "get": { + "operationId": "listAuthor", + "tags": [ + "Author" + ], + "parameters": [ + { + "name": "filter[id]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][eq]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][ne]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[id][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[name]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[name][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[bio]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[bio][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[createdAt]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][eq]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][ne]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[createdAt][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "sort", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "id", + "id:asc", + "id:desc", + "name", + "name:asc", + "name:desc", + "createdAt", + "createdAt:asc", + "createdAt:desc" + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "withCount", + "in": "query", + "description": "Answer { rows, total } instead of the array.", + "schema": { + "type": "integer", + "enum": [ + 1 + ] + } + } + ], + "responses": { + "200": { + "description": "The rows.", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/AuthorList" + }, + { + "$ref": "#/components/schemas/AuthorPage" + } + ] + } + } + } + }, + "400": { + "description": "The request was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "post": { + "operationId": "createAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorCreate" + } + } + } + }, + "responses": { + "201": { + "description": "The new row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/authors/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "get": { + "operationId": "getAuthor", + "tags": [ + "Author" + ], + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "patch": { + "operationId": "updateAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "put": { + "operationId": "putAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAuthor", + "tags": [ + "Author" + ], + "responses": { + "204": { + "description": "Deleted." + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApiError": { + "title": "ApiError", + "description": "The error envelope. `error` is the stable code; `message` is free prose.", + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." + } + } + }, + "Author": { + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] + }, + "AuthorCreate": { + "title": "AuthorCreate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] + }, + "AuthorList": { + "title": "AuthorList", + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "AuthorPage": { + "title": "AuthorPage", + "type": "object", + "required": [ + "rows", + "total" + ], + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "total": { + "type": "integer" + } + } + }, + "AuthorUpdate": { + "title": "AuthorUpdate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } + } + } + } +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json new file mode 100644 index 0000000000..dd93120f2e --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.create.schema.json", + "title": "Author.create", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json new file mode 100644 index 0000000000..15e9f54982 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.schema.json", + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json new file mode 100644 index 0000000000..58723ebbb6 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json @@ -0,0 +1,35 @@ +{ + "title": "Author", + "type": "object", + "properties": { + "name": { + "description": "Minimum length: 1. Maximum length: 100.", + "type": "string" + }, + "bio": { + "description": "Maximum length: 1000.", + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "description": "An instant. A value with no offset is read as UTC. Pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$.", + "type": "string" + }, + "issuedCurrency": { + "description": "Maximum length: 3.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "bio", + "createdAt", + "issuedCurrency" + ], + "additionalProperties": false +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json new file mode 100644 index 0000000000..3f3c050341 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.update.schema.json", + "title": "Author.update", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } +} diff --git a/fixtures/contract-conformance/api-settings/case.json b/fixtures/contract-conformance/api-settings/case.json new file mode 100644 index 0000000000..067383d2e1 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/case.json @@ -0,0 +1 @@ +{ "meta": "fixtures/api-contract-conformance/meta.json", "wire": {"decimals": "string", "nullMembers": "omit", "durations": "iso"}, "api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 } } } diff --git a/fixtures/contract-conformance/api-settings/expected/openapi.json b/fixtures/contract-conformance/api-settings/expected/openapi.json new file mode 100644 index 0000000000..6622ad8527 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/openapi.json @@ -0,0 +1,776 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "api-settings", + "version": "1.0.0" + }, + "paths": { + "/api/authors": { + "get": { + "operationId": "listAuthor", + "tags": [ + "Author" + ], + "parameters": [ + { + "name": "filter[id]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][eq]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][ne]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[id][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[name]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[name][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[bio]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[bio][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[createdAt]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][eq]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][ne]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[createdAt][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "sort", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "id", + "id:asc", + "id:desc", + "name", + "name:asc", + "name:desc", + "createdAt", + "createdAt:asc", + "createdAt:desc" + ] + } + }, + { + "name": "limit", + "in": "query", + "description": "Rows per page. Absent, the server answers 50; above 1000 it answers 400 limit_too_large.", + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 1000, + "default": 50 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "withCount", + "in": "query", + "description": "Answer { rows, total } instead of the array.", + "schema": { + "type": "integer", + "enum": [ + 1 + ] + } + } + ], + "responses": { + "200": { + "description": "The rows.", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/AuthorList" + }, + { + "$ref": "#/components/schemas/AuthorPage" + } + ] + } + } + } + }, + "400": { + "description": "The request was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "post": { + "operationId": "createAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorCreate" + } + } + } + }, + "responses": { + "201": { + "description": "The new row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/authors/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "get": { + "operationId": "getAuthor", + "tags": [ + "Author" + ], + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "patch": { + "operationId": "updateAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "put": { + "operationId": "putAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAuthor", + "tags": [ + "Author" + ], + "responses": { + "204": { + "description": "Deleted." + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApiError": { + "title": "ApiError", + "description": "The error envelope. `error` is the stable code; `message` is free prose.", + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." + } + } + }, + "Author": { + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] + }, + "AuthorCreate": { + "title": "AuthorCreate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] + }, + "AuthorList": { + "title": "AuthorList", + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "AuthorPage": { + "title": "AuthorPage", + "type": "object", + "required": [ + "rows", + "total" + ], + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "total": { + "type": "integer" + } + } + }, + "AuthorUpdate": { + "title": "AuthorUpdate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } + } + } + } +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json new file mode 100644 index 0000000000..dd93120f2e --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.create.schema.json", + "title": "Author.create", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json new file mode 100644 index 0000000000..15e9f54982 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.schema.json", + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json new file mode 100644 index 0000000000..58723ebbb6 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json @@ -0,0 +1,35 @@ +{ + "title": "Author", + "type": "object", + "properties": { + "name": { + "description": "Minimum length: 1. Maximum length: 100.", + "type": "string" + }, + "bio": { + "description": "Maximum length: 1000.", + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "description": "An instant. A value with no offset is read as UTC. Pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$.", + "type": "string" + }, + "issuedCurrency": { + "description": "Maximum length: 3.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "bio", + "createdAt", + "issuedCurrency" + ], + "additionalProperties": false +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json new file mode 100644 index 0000000000..3f3c050341 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.update.schema.json", + "title": "Author.update", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } +} diff --git a/fixtures/contract-conformance/blog/expected/openapi.json b/fixtures/contract-conformance/blog/expected/openapi.json index b9840d0b52..2ecab7e4f0 100644 --- a/fixtures/contract-conformance/blog/expected/openapi.json +++ b/fixtures/contract-conformance/blog/expected/openapi.json @@ -334,6 +334,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -354,7 +355,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -423,6 +424,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -443,7 +445,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -481,6 +483,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -501,7 +504,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -584,6 +587,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/decimal/expected/openapi.json b/fixtures/contract-conformance/decimal/expected/openapi.json index a742bb695a..d3383a8c53 100644 --- a/fixtures/contract-conformance/decimal/expected/openapi.json +++ b/fixtures/contract-conformance/decimal/expected/openapi.json @@ -283,6 +283,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -303,7 +304,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -372,6 +373,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -392,7 +394,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -430,6 +432,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -450,7 +453,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -519,6 +522,7 @@ "tags": [ "EntryTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[bucket]", @@ -1316,6 +1320,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1336,7 +1341,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1405,6 +1410,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1425,7 +1431,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1463,6 +1469,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1483,7 +1490,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1566,6 +1573,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/jsonb/expected/openapi.json b/fixtures/contract-conformance/jsonb/expected/openapi.json index 11ff07dcaa..4a8e9bc478 100644 --- a/fixtures/contract-conformance/jsonb/expected/openapi.json +++ b/fixtures/contract-conformance/jsonb/expected/openapi.json @@ -208,6 +208,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -228,7 +229,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -297,6 +298,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -317,7 +319,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -355,6 +357,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -375,7 +378,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -458,6 +461,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/m2m/expected/openapi.json b/fixtures/contract-conformance/m2m/expected/openapi.json index 813d6036ee..b8e1cfe858 100644 --- a/fixtures/contract-conformance/m2m/expected/openapi.json +++ b/fixtures/contract-conformance/m2m/expected/openapi.json @@ -586,6 +586,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -606,7 +607,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -675,6 +676,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -695,7 +697,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -733,6 +735,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -753,7 +756,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1128,6 +1131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1148,7 +1152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1217,6 +1221,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1237,7 +1242,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1275,6 +1280,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1295,7 +1301,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1532,6 +1538,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1552,7 +1559,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1621,6 +1628,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1641,7 +1649,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1679,6 +1687,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1699,7 +1708,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1834,6 +1843,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1854,7 +1864,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1923,6 +1933,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1943,7 +1954,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1981,6 +1992,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2001,7 +2013,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2136,6 +2148,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2156,7 +2169,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2225,6 +2238,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2245,7 +2259,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2283,6 +2297,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2303,7 +2318,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2438,6 +2453,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2458,7 +2474,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2527,6 +2543,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2547,7 +2564,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2585,6 +2602,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2605,7 +2623,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2740,6 +2758,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2760,7 +2779,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2829,6 +2848,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2849,7 +2869,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2887,6 +2907,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2907,7 +2928,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3110,6 +3131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3130,7 +3152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3199,6 +3221,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3219,7 +3242,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3257,6 +3280,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3277,7 +3301,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3480,6 +3504,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3500,7 +3525,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3569,6 +3594,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3589,7 +3615,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3627,6 +3653,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3647,7 +3674,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3782,6 +3809,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3802,7 +3830,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3871,6 +3899,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3891,7 +3920,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3929,6 +3958,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3949,7 +3979,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4084,6 +4114,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4104,7 +4135,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4173,6 +4204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4193,7 +4225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4231,6 +4263,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4251,7 +4284,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4386,6 +4419,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4406,7 +4440,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4475,6 +4509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4495,7 +4530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4533,6 +4568,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4553,7 +4589,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4688,6 +4724,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4708,7 +4745,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4777,6 +4814,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4797,7 +4835,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4835,6 +4873,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4855,7 +4894,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5049,6 +5088,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/nullable-members/expected/openapi.json b/fixtures/contract-conformance/nullable-members/expected/openapi.json index fb552752b5..ff90896b05 100644 --- a/fixtures/contract-conformance/nullable-members/expected/openapi.json +++ b/fixtures/contract-conformance/nullable-members/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "SensorSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "limit", @@ -390,6 +394,7 @@ "tags": [ "SensorSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -434,6 +439,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/projection/expected/openapi.json b/fixtures/contract-conformance/projection/expected/openapi.json index fa22cc89b5..43c2b093b5 100644 --- a/fixtures/contract-conformance/projection/expected/openapi.json +++ b/fixtures/contract-conformance/projection/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "InvoiceLedger" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[number]", @@ -671,6 +675,7 @@ "tags": [ "InvoiceLedger" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -701,6 +706,7 @@ "tags": [ "InvoiceRegister" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[regNo]", @@ -909,6 +915,7 @@ "tags": [ "InvoiceRegister" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -939,6 +946,7 @@ "tags": [ "InvoiceStub" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[id]", @@ -1136,6 +1144,7 @@ "tags": [ "InvoiceSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[id]", @@ -1463,6 +1472,7 @@ "tags": [ "InvoiceSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -1507,6 +1517,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/report/expected/openapi.json b/fixtures/contract-conformance/report/expected/openapi.json index ebd15ce842..28e9960f1d 100644 --- a/fixtures/contract-conformance/report/expected/openapi.json +++ b/fixtures/contract-conformance/report/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "ExportCells" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[label]", @@ -673,6 +677,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -693,7 +698,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -762,6 +767,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -782,7 +788,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -820,6 +826,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -840,7 +847,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -975,6 +982,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -995,7 +1003,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1064,6 +1072,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1084,7 +1093,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1122,6 +1131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1142,7 +1152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1211,6 +1221,7 @@ "tags": [ "InvoiceCalendar" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[issuedOnDay]", @@ -1608,6 +1619,7 @@ "tags": [ "InvoiceDisputes" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[disputed]", @@ -1880,6 +1892,7 @@ "tags": [ "InvoiceStatusTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[status]", @@ -2264,6 +2277,7 @@ "tags": [ "InvoiceTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[invoices]", @@ -2586,6 +2600,7 @@ "tags": [ "InvoicesByMonth" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[issuedOnMonth]", @@ -2974,6 +2989,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2994,7 +3010,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3063,6 +3079,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3083,7 +3100,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3121,6 +3138,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3141,7 +3159,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3210,6 +3228,7 @@ "tags": [ "ProductRefunds" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productId]", @@ -3554,6 +3573,7 @@ "tags": [ "ProductRevenue" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productId]", @@ -4064,6 +4084,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4084,7 +4105,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4153,6 +4174,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4173,7 +4195,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4211,6 +4233,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4231,7 +4254,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4300,6 +4323,7 @@ "tags": [ "ReadingLog" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[seq]", @@ -4613,6 +4637,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4633,7 +4658,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4702,6 +4727,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4722,7 +4748,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4760,6 +4786,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4780,7 +4807,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4849,6 +4876,7 @@ "tags": [ "SalesByCategory" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[categoryName]", @@ -5293,6 +5321,7 @@ "tags": [ "SalesBySku" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productSku]", @@ -5649,6 +5678,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5669,7 +5699,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5738,6 +5768,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5758,7 +5789,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5796,6 +5827,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5816,7 +5848,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5885,6 +5917,7 @@ "tags": [ "TicketsByTags" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[tickets]", @@ -6071,6 +6104,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/secret-fields/expected/openapi.json b/fixtures/contract-conformance/secret-fields/expected/openapi.json index 5be082d05d..a62c8ad8e1 100644 --- a/fixtures/contract-conformance/secret-fields/expected/openapi.json +++ b/fixtures/contract-conformance/secret-fields/expected/openapi.json @@ -208,6 +208,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -228,7 +229,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -297,6 +298,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -317,7 +319,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -355,6 +357,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -375,7 +378,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -543,6 +546,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } } diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json index 0c7c63df7b..05051958bc 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json @@ -184,6 +184,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -204,7 +205,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -273,6 +274,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -293,7 +295,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -331,6 +333,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -351,7 +354,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -486,6 +489,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -506,7 +510,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -575,6 +579,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -595,7 +600,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -633,6 +638,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -653,7 +659,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -736,6 +742,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/tph/expected/openapi.json b/fixtures/contract-conformance/tph/expected/openapi.json index f3f7c876ce..d09a4fd042 100644 --- a/fixtures/contract-conformance/tph/expected/openapi.json +++ b/fixtures/contract-conformance/tph/expected/openapi.json @@ -583,6 +583,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -603,7 +604,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -672,6 +673,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -692,7 +694,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -730,6 +732,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -750,7 +753,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1091,6 +1094,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1111,7 +1115,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1180,6 +1184,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1200,7 +1205,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1238,6 +1243,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1258,7 +1264,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1571,6 +1577,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1591,7 +1598,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1660,6 +1667,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1680,7 +1688,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1718,6 +1726,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1738,7 +1747,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1821,6 +1830,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/write-through/expected/openapi.json b/fixtures/contract-conformance/write-through/expected/openapi.json index 567483d952..1b28602b87 100644 --- a/fixtures/contract-conformance/write-through/expected/openapi.json +++ b/fixtures/contract-conformance/write-through/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -379,6 +382,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -399,7 +403,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -468,6 +472,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -488,7 +493,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -526,6 +531,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -546,7 +552,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -629,6 +635,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index ebdba74ce3..b7ffc75cdf 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.", @@ -459,7 +459,9 @@ "MetaObjects.Codegen.RequirementTestClaim", "MetaObjects.Codegen.SourceNames", "MetaObjects.Codegen.SuperNames", - "MetaObjects.Codegen.ValueObjectNames" + "MetaObjects.Codegen.ValueObjectNames", + "MetaObjects.Codegen.Writer.CodeWriter", + "MetaObjects.Codegen.Writer.CsWriter" ] }, "java": { @@ -554,7 +556,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 e6fbe73d4f..cc286b3465 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,9 +7,21 @@ 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"`) pin that language's writer: import - collection and ordering, doc comments and its defaults. +- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`) pin that + language's writer: import or `using` collection and ordering, doc comments and its defaults. A + runner runs the `core` cases and its own dialect's, and skips the others by name. -Runner: TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts`. -The other ports run the `core` cases when their writers land, and add cases for their own -dialect beside these. +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`). +- C#, `server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs` (`core` and `csharp`). + +The ports without a writer yet (Kotlin) run the `core` cases when their writers +land, and add cases for their own dialect beside these. + +The `csharp` ops are `header` (lines), `using`, `usingStatic` (a namespace or type), `usingAlias` +(alias, target) and `docSummary` (lines), beside the core ops. A `csharp` case may state +`"options": {"usingOrder": "sorted"}`; the default order is the order the generator named them. diff --git a/fixtures/writer-conformance/cases/cs-doc-summary.json b/fixtures/writer-conformance/cases/cs-doc-summary.json new file mode 100644 index 0000000000..3da15f02a1 --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-doc-summary.json @@ -0,0 +1,39 @@ +{ + "description": "A doc summary writes /// lines between summary tags, with a bare /// for an empty entry, at the current indent.", + "dialect": "csharp", + "ops": [ + [ + "line", + "public class A" + ], + [ + "open", + "{" + ], + [ + "docSummary", + "First line.", + "", + "Third line." + ], + [ + "line", + "public int X { get; set; }" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "public class A", + "{", + " /// ", + " /// First line.", + " ///", + " /// Third line.", + " /// ", + " public int X { get; set; }", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/cs-header-usings-body.json b/fixtures/writer-conformance/cases/cs-header-usings-body.json new file mode 100644 index 0000000000..4c6e03d2ba --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-header-usings-body.json @@ -0,0 +1,59 @@ +{ + "description": "Header lines print first, then the collected using directives (each once, in the order named), a blank line, then the body written with the C# defaults.", + "dialect": "csharp", + "ops": [ + [ + "header", + "// ", + "#nullable enable" + ], + [ + "using", + "System.Collections.Generic" + ], + [ + "using", + "System" + ], + [ + "using", + "System.Collections.Generic" + ], + [ + "line", + "namespace Demo;" + ], + [ + "blank" + ], + [ + "line", + "public static class A" + ], + [ + "open", + "{" + ], + [ + "line", + "public static int X;" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "// ", + "#nullable enable", + "using System.Collections.Generic;", + "using System;", + "", + "namespace Demo;", + "", + "public static class A", + "{", + " public static int X;", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/cs-header-without-usings.json b/fixtures/writer-conformance/cases/cs-header-without-usings.json new file mode 100644 index 0000000000..6c7e5f9242 --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-header-without-usings.json @@ -0,0 +1,19 @@ +{ + "description": "With no using directive, the header is followed by one blank line and the body.", + "dialect": "csharp", + "ops": [ + [ + "header", + "// " + ], + [ + "line", + "class A { }" + ] + ], + "expected": [ + "// ", + "", + "class A { }" + ] +} diff --git a/fixtures/writer-conformance/cases/cs-using-alias-conflict.json b/fixtures/writer-conformance/cases/cs-using-alias-conflict.json new file mode 100644 index 0000000000..358edf1520 --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-using-alias-conflict.json @@ -0,0 +1,18 @@ +{ + "description": "One alias naming two different targets is an import conflict.", + "dialect": "csharp", + "ops": [ + [ + "usingAlias", + "Json", + "System.Text.Json.JsonSerializer" + ], + [ + "usingAlias", + "Json", + "Newtonsoft.Json.JsonConvert" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT", + "errorQuotes": "Json" +} diff --git a/fixtures/writer-conformance/cases/cs-using-static-and-alias.json b/fixtures/writer-conformance/cases/cs-using-static-and-alias.json new file mode 100644 index 0000000000..2495af7d61 --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-using-static-and-alias.json @@ -0,0 +1,30 @@ +{ + "description": "A static using and an alias print as their own directives; naming the same alias twice for one target prints it once.", + "dialect": "csharp", + "ops": [ + [ + "usingStatic", + "System.Math" + ], + [ + "usingAlias", + "Json", + "System.Text.Json.JsonSerializer" + ], + [ + "usingAlias", + "Json", + "System.Text.Json.JsonSerializer" + ], + [ + "line", + "class A { }" + ] + ], + "expected": [ + "using static System.Math;", + "using Json = System.Text.Json.JsonSerializer;", + "", + "class A { }" + ] +} diff --git a/fixtures/writer-conformance/cases/cs-usings-sorted.json b/fixtures/writer-conformance/cases/cs-usings-sorted.json new file mode 100644 index 0000000000..664142388a --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-usings-sorted.json @@ -0,0 +1,37 @@ +{ + "description": "With the sorted order, System namespaces print first, then the rest, each in code-unit order of the namespace.", + "dialect": "csharp", + "options": { + "usingOrder": "sorted" + }, + "ops": [ + [ + "using", + "Microsoft.EntityFrameworkCore" + ], + [ + "using", + "System.Linq" + ], + [ + "using", + "System" + ], + [ + "using", + "Acme.Models" + ], + [ + "line", + "class A { }" + ] + ], + "expected": [ + "using System;", + "using System.Linq;", + "using Acme.Models;", + "using Microsoft.EntityFrameworkCore;", + "", + "class A { }" + ] +} diff --git a/fixtures/writer-conformance/cases/java-defaults.json b/fixtures/writer-conformance/cases/java-defaults.json new file mode 100644 index 0000000000..fa8d7eef04 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-defaults.json @@ -0,0 +1,61 @@ +{ + "description": "The Java dialect indents four spaces, breaks at 120 columns and puts no comma after the last item of a broken list.", + "dialect": "java", + "ops": [ + [ + "open", + "class A {" + ], + [ + "line", + "static final List NAMES = ", + { + "list": { + "open": "List.of(", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"" + ], + "close": ")" + } + }, + ";" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "class A {", + " static final List NAMES = List.of(", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\"", + " );", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-doc-comment.json b/fixtures/writer-conformance/cases/java-doc-comment.json new file mode 100644 index 0000000000..359f7c200a --- /dev/null +++ b/fixtures/writer-conformance/cases/java-doc-comment.json @@ -0,0 +1,44 @@ +{ + "description": "A one-entry doc comment that fits is one line; more entries, or one that does not fit, make a block. An empty entry is a bare ` *` line, and a comment terminator inside the text is neutralised.", + "dialect": "java", + "ops": [ + [ + "doc", + "The user." + ], + [ + "line", + "a();" + ], + [ + "doc", + "First line.", + "", + "@see other" + ], + [ + "line", + "b();" + ], + [ + "doc", + "ends */ here" + ], + [ + "line", + "c();" + ] + ], + "expected": [ + "/** The user. */", + "a();", + "/**", + " * First line.", + " *", + " * @see other", + " */", + "b();", + "/** ends */ here */", + "c();" + ] +} diff --git a/fixtures/writer-conformance/cases/java-header-package-imports-body.json b/fixtures/writer-conformance/cases/java-header-package-imports-body.json new file mode 100644 index 0000000000..2b382f6f0f --- /dev/null +++ b/fixtures/writer-conformance/cases/java-header-package-imports-body.json @@ -0,0 +1,41 @@ +{ + "description": "Header lines print first, then a blank line, the package line, a blank line, the imports, a blank line and the body. A file with no imports has no import block.", + "dialect": "java", + "ops": [ + [ + "header", + "// Generated by MetaObjects. Do not edit." + ], + [ + "package", + "com.acme.api" + ], + [ + "use", + "java.util.List" + ], + [ + "open", + "interface A {" + ], + [ + "line", + "List names();" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "// Generated by MetaObjects. Do not edit.", + "", + "package com.acme.api;", + "", + "import java.util.List;", + "", + "interface A {", + " List names();", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json b/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json new file mode 100644 index 0000000000..4db35f89ae --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json @@ -0,0 +1,50 @@ +{ + "description": "Imports print in code-unit order, one per line, after the package line. Static imports come first, then a blank line, then the others. A name used twice is imported once.", + "dialect": "java", + "ops": [ + [ + "package", + "com.acme" + ], + [ + "use", + "java.util.Map" + ], + [ + "use", + "com.acme.other.Zed" + ], + [ + "useStatic", + "org.junit.Assert.assertEquals" + ], + [ + "use", + "java.util.List" + ], + [ + "use", + "java.util.List" + ], + [ + "useStatic", + "java.util.Objects.requireNonNull" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "package com.acme;", + "", + "import static java.util.Objects.requireNonNull;", + "import static org.junit.Assert.assertEquals;", + "", + "import com.acme.other.Zed;", + "import java.util.List;", + "import java.util.Map;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-conflict.json b/fixtures/writer-conformance/cases/java-imports-conflict.json new file mode 100644 index 0000000000..aa0405d9ae --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-conflict.json @@ -0,0 +1,15 @@ +{ + "description": "One simple name imported from two types is an error, not a silent shadow.", + "dialect": "java", + "ops": [ + [ + "use", + "java.util.Date" + ], + [ + "use", + "java.sql.Date" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} diff --git a/fixtures/writer-conformance/cases/java-imports-nested-type.json b/fixtures/writer-conformance/cases/java-imports-nested-type.json new file mode 100644 index 0000000000..671a362695 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-nested-type.json @@ -0,0 +1,19 @@ +{ + "description": "A nested type is imported as written and used by its last segment.", + "dialect": "java", + "ops": [ + [ + "use", + "java.util.Map.Entry" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "import java.util.Map.Entry;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json b/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json new file mode 100644 index 0000000000..675ce0a617 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json @@ -0,0 +1,33 @@ +{ + "description": "A type in java.lang or in the file's own package is written by its simple name and imports nothing, whichever order the package and the types were named in.", + "dialect": "java", + "ops": [ + [ + "use", + "java.lang.String" + ], + [ + "use", + "com.acme.Sibling" + ], + [ + "use", + "java.util.UUID" + ], + [ + "package", + "com.acme" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "package com.acme;", + "", + "import java.util.UUID;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-package-without-imports.json b/fixtures/writer-conformance/cases/java-package-without-imports.json new file mode 100644 index 0000000000..c7b28cdc7d --- /dev/null +++ b/fixtures/writer-conformance/cases/java-package-without-imports.json @@ -0,0 +1,19 @@ +{ + "description": "A file with a package line and no imports has no import block.", + "dialect": "java", + "ops": [ + [ + "package", + "com.acme.api" + ], + [ + "line", + "interface A {}" + ] + ], + "expected": [ + "package com.acme.api;", + "", + "interface A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-static-imports-conflict.json b/fixtures/writer-conformance/cases/java-static-imports-conflict.json new file mode 100644 index 0000000000..365ac18e33 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-static-imports-conflict.json @@ -0,0 +1,15 @@ +{ + "description": "One static member name imported from two types is an error.", + "dialect": "java", + "ops": [ + [ + "useStatic", + "a.A.of" + ], + [ + "useStatic", + "b.B.of" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} 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/package.json b/package.json index 2051a2ba7c..0fa436d54b 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ "site:preview": "bun scripts/site-preview.ts", "clean": "rm -rf server/typescript/packages/*/dist server/typescript/packages/*/*.tsbuildinfo client/web/packages/*/dist client/web/packages/*/*.tsbuildinfo", "release": "bun scripts/release.mjs", - "prerelease:publish": "bun scripts/prerelease.mjs" + "prerelease:publish": "bun scripts/prerelease.mjs", + "prerelease:candidate": "bun scripts/prerelease.mjs --only all" }, "devDependencies": { "bun-types": "latest", diff --git a/scripts/check-install-size.mjs b/scripts/check-install-size.mjs new file mode 100644 index 0000000000..cb3e286da6 --- /dev/null +++ b/scripts/check-install-size.mjs @@ -0,0 +1,207 @@ +#!/usr/bin/env node +// The install-size budget: what `npm install @metaobjectsdev/cli` puts on an adopter's disk, +// measured by installing it, and held to a number that only moves down. +// +// WHY A REAL INSTALL. `scripts/check-peer-ranges.ts` reads manifests, which catches a package +// that REQUIRES something unused. It cannot see what a dependency of a dependency drags in +// (libSQL pulls its own HTTP client and a polyfill for web streams; a native binary comes once per +// libc), and it cannot see a package that doubled in size. This installs the packed CLI the way +// an adopter's package manager does and counts the bytes. +// +// node scripts/check-install-size.mjs # check against the budget (the full CI lane) +// node scripts/check-install-size.mjs --update # lower the budget to what was measured +// +// THE RULES +// 1. The install must not exceed `budgetBytes`. +// 2. It must not sit more than `slackBytes` UNDER it. A saving that is not written down is a +// saving the next change can spend, so a smaller install fails until the budget is lowered +// with --update. That is the ratchet: the budget has no way to rise. +// 3. `budgetBytes` may not be higher than it is on `main`. Raising it to make a change pass +// is the one edit this file exists to refuse; raise it only with a ruling that says why. +// 4. None of the packages in FORBIDDEN is in the tree (a fresh-install test: the install-time +// guard in check-peer-ranges.ts reads manifests, this reads the result). +// +// The budget is for the platform it names (`platform`): native binaries differ by platform and +// by libc, so on another platform the check reports the number and passes. It needs the registry +// for third-party packages, which is why it runs in the full CI lane and not in `--only gates`. +// The packages under test are this checkout's, packed with `bun pm pack` (which writes `workspace:` +// ranges as versions), so nothing here depends on a release having been published. +// +// Build first (`bun run --filter '*' build`): a package is packed from its built `dist/`. + +import { execFileSync } from "node:child_process"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { enumerateWorkspacePackages } from "./publish-set.mjs"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const BUDGET_FILE = "scripts/install-size-budget.json"; +const BUDGET_PATH = join(ROOT, BUDGET_FILE); +const ENTRY = "@metaobjectsdev/cli"; +const SCOPE = "@metaobjectsdev/"; +const MB = 1024 * 1024; + +/** Packages that must not be installed by installing the CLI, and why. */ +const FORBIDDEN = { + "drizzle-orm": "only generated code imports it; codegen-ts lists it as an optional peer", + "@biomejs/biome": "generation runs no formatter; the CLI compares owned copies through the WebAssembly build", + "dprint-node": "seven native binaries; codegen-ts runs dprint as WebAssembly", + "ts-poet": "requires dprint-node on load; codegen-ts vendors the printer", + "@libsql/kysely-libsql": "an optional peer: a SQLite project declares it (`meta init` does), because it carries a native binary per platform and libc", + "libsql": "the native SQLite binding behind @libsql/kysely-libsql, installed only with it", +}; + +const update = process.argv.includes("--update"); + +function platformKey() { + return `${process.platform}-${process.arch}`; +} + +/** The workspace packages the CLI installs: it, and every `@metaobjectsdev/*` it requires, transitively. */ +function closureOf(entry, byName) { + const seen = new Set(); + const queue = [entry]; + while (queue.length > 0) { + const name = queue.pop(); + if (seen.has(name)) continue; + seen.add(name); + const pkg = byName.get(name); + if (pkg === undefined) continue; + const required = [ + ...Object.keys(pkg.dependencies ?? {}), + ...Object.keys(pkg.optionalDependencies ?? {}), + ...Object.keys(pkg.peerDependencies ?? {}).filter((d) => pkg.peerDependenciesMeta?.[d]?.optional !== true), + ]; + for (const dep of required) if (dep.startsWith(SCOPE)) queue.push(dep); + } + return [...seen].sort(); +} + +/** Bytes of every regular file under `dir`, what `du -sb` counts. */ +function bytesUnder(dir) { + let total = 0; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) total += bytesUnder(path); + else if (entry.isFile()) total += lstatSync(path).size; + } + return total; +} + +/** The top-level package directories of `node_modules`, scopes opened, largest first. */ +function breakdown(modules) { + const rows = []; + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === ".bin") continue; + const path = join(modules, entry.name); + if (entry.name.startsWith("@")) { + for (const inner of readdirSync(path, { withFileTypes: true })) { + if (inner.isDirectory()) rows.push({ name: `${entry.name}/${inner.name}`, bytes: bytesUnder(join(path, inner.name)) }); + } + } else { + rows.push({ name: entry.name, bytes: bytesUnder(path) }); + } + } + return rows.sort((a, b) => b.bytes - a.bytes); +} + +function installedNames(modules) { + const names = []; + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === ".bin") continue; + if (entry.name.startsWith("@")) { + for (const inner of readdirSync(join(modules, entry.name), { withFileTypes: true })) names.push(`${entry.name}/${inner.name}`); + } else names.push(entry.name); + } + return names; +} + +function mainBudget() { + try { + const text = execFileSync("git", ["show", `main:${BUDGET_FILE}`], { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + return JSON.parse(text).budgetBytes; + } catch { + return undefined; // no `main` here, or the file is new on this branch + } +} + +function measure() { + const packages = enumerateWorkspacePackages(ROOT).map(({ dir, pkg }) => ({ dir, pkg })); + const byName = new Map(packages.map(({ pkg }) => [pkg.name, pkg])); + const wanted = closureOf(ENTRY, byName); + const dirs = new Map(packages.map(({ dir, pkg }) => [pkg.name, dir])); + // Throwaway data goes to RAM when the machine has set it aside for that. + const scratch = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "mo-install-size-")); + try { + const tarballs = join(scratch, "tarballs"); + const project = join(scratch, "project"); + mkdirSync(tarballs); + mkdirSync(project); + for (const name of wanted) { + const dir = dirs.get(name); + if (dir === undefined) throw new Error(`${name} is required by ${ENTRY} but is not a workspace package`); + if (!existsSync(join(ROOT, dir, "dist"))) { + throw new Error(`${name} has no dist/: run \`bun run --filter '*' build\` first`); + } + execFileSync("bun", ["pm", "pack", "--destination", tarballs, "--quiet"], { cwd: join(ROOT, dir), stdio: ["ignore", "ignore", "inherit"] }); + } + writeFileSync(join(project, "package.json"), JSON.stringify({ name: "install-size", version: "1.0.0", private: true, type: "module" })); + const files = readdirSync(tarballs).map((f) => join(tarballs, f)); + execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund", "--no-progress", ...files], { cwd: project, stdio: ["ignore", "ignore", "inherit"] }); + const modules = join(project, "node_modules"); + return { bytes: bytesUnder(modules), rows: breakdown(modules), names: installedNames(modules), packed: wanted.length }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +function fail(message) { + console.error(`\n✖ ${message}\n`); + process.exit(1); +} + +const budget = JSON.parse(readFileSync(BUDGET_PATH, "utf8")); +const { bytes, rows, names, packed } = measure(); +const mb = (n) => (n / MB).toFixed(1); + +console.log(`install size: ${mb(bytes)} MB installing ${ENTRY} (${packed} workspace packages, ${names.length} top-level packages)`); +for (const row of rows.slice(0, 8)) console.log(` ${mb(row.bytes).padStart(6)} MB ${row.name}`); + +const forbidden = Object.keys(FORBIDDEN).filter((name) => names.includes(name)); +if (forbidden.length > 0) { + fail(`installing ${ENTRY} put packages in the tree that it must not:\n${forbidden.map((n) => ` ${n}: ${FORBIDDEN[n]}`).join("\n")}`); +} + +if (budget.platform !== platformKey()) { + console.log(`install-size budget: ${mb(budget.budgetBytes)} MB is for ${budget.platform}; this is ${platformKey()}, so the number above is reported and not checked`); + process.exit(0); +} + +const onMain = mainBudget(); +if (onMain !== undefined && budget.budgetBytes > onMain) { + fail(`the budget rose: ${BUDGET_FILE} says ${mb(budget.budgetBytes)} MB and main says ${mb(onMain)} MB. The budget only moves down.`); +} + +if (bytes > budget.budgetBytes) { + fail(`the install is ${mb(bytes - budget.budgetBytes)} MB over the budget (${mb(bytes)} MB, budget ${mb(budget.budgetBytes)} MB). Find what grew in the list above; the budget is not the thing to change.`); +} + +if (bytes < budget.budgetBytes - budget.slackBytes) { + if (!update) { + fail(`the install is ${mb(budget.budgetBytes - bytes)} MB under the budget (${mb(bytes)} MB, budget ${mb(budget.budgetBytes)} MB). Lower it, so the saving cannot be spent again: node scripts/check-install-size.mjs --update`); + } +} + +if (update) { + if (bytes >= budget.budgetBytes) { + console.log(`install-size budget: ${mb(budget.budgetBytes)} MB stays (measured ${mb(bytes)} MB; --update only lowers it)`); + } else { + writeFileSync(BUDGET_PATH, `${JSON.stringify({ ...budget, budgetBytes: bytes }, null, 2)}\n`); + console.log(`install-size budget: lowered from ${mb(budget.budgetBytes)} MB to ${mb(bytes)} MB`); + } + process.exit(0); +} + +console.log(`install-size budget: OK (${mb(bytes)} MB of ${mb(budget.budgetBytes)} MB)`); diff --git a/scripts/check-peer-ranges.test.ts b/scripts/check-peer-ranges.test.ts index e370a44eea..ab135f9d3b 100644 --- a/scripts/check-peer-ranges.test.ts +++ b/scripts/check-peer-ranges.test.ts @@ -42,9 +42,28 @@ describe("install-time guard — optionalDependencies are installed by default", ]); }); + test("drizzle-orm and zod are refused as dependencies and as required peers", () => { + const report = peerRangeReport(workspaceWith({ + dependencies: { zod: "^4.0.0" }, + peerDependencies: { "drizzle-orm": ">=0.38.0 <1.0.0" }, + })); + expect(report.installOnlyDeps).toEqual([ + expect.objectContaining({ dep: "zod", field: "dependencies" }), + expect.objectContaining({ dep: "drizzle-orm", field: "peerDependencies (required)" }), + ]); + }); + + test("drizzle-orm and zod as optional peers pass, which is how codegen-ts declares them", () => { + const report = peerRangeReport(workspaceWith({ + peerDependencies: { "drizzle-orm": ">=0.38.0 <1.0.0", zod: ">=3.23.0 <5.0.0" }, + peerDependenciesMeta: { "drizzle-orm": { optional: true }, zod: { optional: true } }, + })); + expect(report.installOnlyDeps).toEqual([]); + }); + test("a clean package passes: real dep, bounded peer counted", () => { const report = peerRangeReport(workspaceWith({ - dependencies: { "drizzle-orm": "^0.36.0" }, + dependencies: { kysely: "^0.27.0" }, peerDependencies: { react: "^18.0.0" }, })); expect(report.installOnlyDeps).toEqual([]); diff --git a/scripts/check-peer-ranges.ts b/scripts/check-peer-ranges.ts index cbc6800ad8..b2fbc45a82 100755 --- a/scripts/check-peer-ranges.ts +++ b/scripts/check-peer-ranges.ts @@ -33,17 +33,20 @@ * declaration lands it in every `@metaobjectsdev/cli` install: * * - the native Biome formatter (`@biomejs/biome`, which pulls a ~94 MB per-platform - * `@biomejs/cli-*` binary). Codegen formats through the WebAssembly build - * (`@biomejs/wasm-nodejs` + `@biomejs/js-api`, see `codegen-ts/src/format.ts`). + * `@biomejs/cli-*` binary). Generation runs no formatter; the CLI's owned-copy + * comparison uses the WebAssembly build (`@biomejs/wasm-nodejs` + `@biomejs/js-api`). * - `dprint-node` (~25 MB: all seven platform binaries in one package) and `ts-poet`, * which `require`s it on load. codegen-ts vendors the printer (`codegen-ts/src/poet.ts`) * and runs dprint as WebAssembly (`@dprint/typescript`). + * - `drizzle-orm` and `zod`, which only the code `meta gen` writes imports. `codegen-ts` lists + * them as optional peers, and `meta eject` prints the install set for the generators taken. + * `@metaobjectsdev/sdk` validates its config with zod at run time and is the one exception. * - any `@types/*` package. Type definitions do nothing at run time; one belongs in * `dependencies` only when a published `.d.ts` imports it, so a consumer's compile * needs it — and then it goes in `ALLOWED_TYPES_DEPS` below, with that reason. * - * Development use belongs in `devDependencies`; a genuine run-time need for the first two - * must be an optional peer (`peerDependenciesMeta`). + * Development use belongs in `devDependencies`; a genuine run-time need for the + * first three must be an optional peer (`peerDependenciesMeta`). */ import { join } from "node:path"; import { enumerateWorkspacePackages } from "./publish-set.mjs"; @@ -54,11 +57,17 @@ const BEYOND_ANY_REAL_VERSION = "9999.0.0"; /** Packages no publishable package may require at install time, with why. */ function installOnly(name: string): string | undefined { if (name === "@biomejs/biome" || name.startsWith("@biomejs/cli-")) { - return "the native Biome formatter (~94 MB binary); codegen formats through @biomejs/wasm-nodejs"; + return "the native Biome formatter (~94 MB binary); the CLI's owned-copy comparison uses the @biomejs/wasm-nodejs WASM build"; } if (name === "dprint-node" || name === "ts-poet") { return "dprint-node's seven native binaries (~25 MB; ts-poet requires it on load); codegen-ts vendors the printer and runs dprint as WebAssembly"; } + if (name === "drizzle-orm") { + return "~17 MB of ORM that only the generated code imports; the adopter's project installs it when it takes a generator (meta eject prints the set)"; + } + if (name === "zod") { + return "~8 MB that only generated code imports; the adopter's project installs it when it takes a generator (meta eject prints the set)"; + } if (name.startsWith("@types/")) { return "type definitions, unused at run time; list it in ALLOWED_TYPES_DEPS only if a published .d.ts imports it"; } @@ -66,10 +75,14 @@ function installOnly(name: string): string | undefined { } /** - * `@types/*` run-time dependencies that are deliberate: `" "` → why a - * consumer's compile needs it (a published `.d.ts` that imports it). Empty today. + * Deliberate exceptions to the install-only rule: `" "` → why. A `@types/*` + * entry is there because a published `.d.ts` imports it; any other entry is a package that + * uses the dependency at run time. */ -const ALLOWED_TYPES_DEPS: Record = {}; +const ALLOWED_TYPES_DEPS: Record = { + // Not a types package: the one deliberate run-time use of zod in the install set. + "@metaobjectsdev/sdk zod": "the sdk validates .metaobjects/config.json and package manifests with zod schemas at run time", +}; interface Violation { pkg: string; peer: string; range: string } export interface InstallOnlyDep { pkg: string; dep: string; field: string; why: string } diff --git a/scripts/check-reference-templates-lint.ts b/scripts/check-reference-templates-lint.ts index 9602ca7da0..6bacf13943 100644 --- a/scripts/check-reference-templates-lint.ts +++ b/scripts/check-reference-templates-lint.ts @@ -19,8 +19,8 @@ * trivially fixable with no behaviour change. * * Nothing could see them. The templates are excluded from each package's BUILD - * tsconfig, this repo ships no `biome.json` of its own (biome is a dependency here for - * `formatTs`, the codegen format pass — not a repo linter), and the gates that DO read + * tsconfig, this repo ships no `biome.json` of its own (biome is a devDependency here so + * the template lint below can run, not a repo linter), and the gates that DO read * these files — `test/reference-byte-identical.test.ts` in each package — compare * EMITTED OUTPUT, which is byte-identical whether a template asserts non-null or * narrows. The only reader who ever saw them was an adopter. @@ -76,9 +76,8 @@ export async function discoverTemplates(repo: string = REPO): Promise return found.sort(); } -/** biome is a devDependency of the codegen packages (shipped code formats through the - * WASM build instead), so a binary is present after `bun install`. Any of them is the - * same pinned version. */ +/** biome is a devDependency of the codegen packages, so a binary is present after + * `bun install`. Any of them is the same pinned version. */ export function resolveBiomeBin(repo: string = REPO): string | undefined { for (const root of PACKAGE_ROOTS) { const rootDir = join(repo, root); diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index a2962f53cd..22db44d6d2 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -424,6 +424,12 @@ gate_assess_prompt() { node scripts/build-assess-prompt.mjs --out /dev/null && n # dependencies, optionalDependencies or a required peer; see scripts/check-peer-ranges.ts. gate_peer_ranges() { bun scripts/check-peer-ranges.ts && bun test scripts/check-peer-ranges.test.ts; } +# What `npm install @metaobjectsdev/cli` puts on disk, held to a budget that only moves down +# (scripts/check-install-size.mjs). It packs this checkout's built packages and installs them, +# so it needs dist/, npm and the registry for third-party packages: the full run's ts-slow +# lane, never `--only gates`, which has to work offline. +gate_install_size() { node scripts/check-install-size.mjs; } + # ── this repo's OWNED copies of the reference templates must BE the templates ── # owned-copies-current.test.ts already asserts byte-identity; this runs the same check # from the gates lane so a stale copy is named with the command that fixes it. Changing @@ -544,7 +550,7 @@ gate_site_reference() { bun_install && bun scripts/build-site-reference.ts --che # exercised) are the ones worth a test at all. See scripts/maven-coordinate.mjs. # And the publish workflows' tag check (scripts/check-release-tag.mjs), whose test also reads # each real manifest, so a layout change fails here rather than on a release tag. -gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && bash tools/prerelease/test-prerelease-link.sh; } +gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && bash tools/prerelease/test-prerelease-link.sh && bash tools/prerelease/test-estate-run.sh; } # ── repo-root scripts/ typechecks ───────────────────────────────────────────── # `bun test` transpiles per file and never typechecks, and `bun run --filter '*' @@ -1366,6 +1372,7 @@ lane_ts() { lane_mutation() { if want ts; then step_if bun "completeness-gate (mutation, full)" gate_completeness; fi; } # ts-slow's half: the two real-PG suites plus the TS integration suite. lane_ts_integ() { + step_if npm "install size budget" gate_install_size integ_ready || return 0 use_pg_sidecar step_if bun "migrate-ts real-PG suite" gate_migrate_ts_pg @@ -1621,6 +1628,7 @@ elif [ "$PARALLEL" -eq 0 ]; then # Ordered BEFORE the docker integration step so a container-readiness flake there # can never prevent the migrate verdict from being produced. if in_lane_any ts ts-slow && docker info >/dev/null 2>&1; then ensure_pg_sidecar; fi + in_lane_any ts ts-slow && step_if npm "install size budget" gate_install_size in_lane_any ts ts-slow && step_if bun "migrate-ts real-PG suite" gate_migrate_ts_pg in_lane_any ts ts-slow && step_if bun "runtime-ts real-PG dialect matrix" gate_runtime_ts_pg in_lane_any ts ts-slow && step_if bun "prisma real-PG round trip" gate_prisma_pg diff --git a/scripts/install-size-budget.json b/scripts/install-size-budget.json new file mode 100644 index 0000000000..540e5e2222 --- /dev/null +++ b/scripts/install-size-budget.json @@ -0,0 +1,5 @@ +{ + "platform": "linux-x64", + "budgetBytes": 53470878, + "slackBytes": 2097152 +} diff --git a/scripts/prerelease-version.mjs b/scripts/prerelease-version.mjs index e54510abf0..ca9813b2b1 100644 --- a/scripts/prerelease-version.mjs +++ b/scripts/prerelease-version.mjs @@ -6,6 +6,8 @@ // does this cut get?" from a source that cannot be wrong in the way the old one was. import { spawn } from "node:child_process"; +import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; /** Compare two plain x.y.z versions: negative, zero or positive. */ export function cmpVer(a, b) { @@ -99,6 +101,45 @@ export async function collectPages(fetchPage, limit = 50, maxPages = 1000) { throw new Error(`the listing did not end within ${maxPages} pages`); } +/** The header of the committed candidate log (tools/prerelease/candidates.md). */ +export const CANDIDATE_LOG_HEADER = + "# Staged candidates\n\n" + + "One row per `bun run prerelease:publish` that published or was cut short. The columns, and the rule\n" + + "to commit each row, are in docs/features/prerelease.md, section 2a.\n\n" + + "| Candidate | Commit | Date (UTC) | Registries |\n|---|---|---|---|\n"; + +/** + * One row of the candidate log. `candidate` is the canonical `-rc.`; `registries` the + * ecosystems actually published (npm, python, csharp, java). + */ +export function candidateLogRow({ candidate, commit, dirty, date, registries }) { + if (!/^\d+\.\d+\.\d+-rc\.\d+$/.test(candidate)) throw new Error(`not a candidate version: ${candidate}`); + if (!/^[0-9a-f]{40}$/.test(commit)) throw new Error(`not a full commit sha: ${commit}`); + if (!registries.length) throw new Error("a candidate row names at least one registry"); + const day = date.toISOString().slice(0, 16).replace("T", " "); + return `| ${candidate} | \`${commit.slice(0, 12)}${dirty ? "+dirty" : ""}\` | ${day} | ${registries.join(", ")} |\n`; +} + +/** + * The registries a run names in its log row. `published` finished, `started` began a publish call, + * `only` is the ordered selection the run was asked for. One that started and did not finish was + * cut short, and its candidate number is burned there; one never started is reported as stopped before. + */ +export function candidateRegistries({ published, started, only }) { + const cutShort = started.filter((p) => !published.includes(p)).map((p) => `${p} (cut short)`); + const stopped = only.filter((p) => !started.includes(p)); + return [...published, ...cutShort, ...(stopped.length ? [`stopped before ${stopped.join(", ")}`] : [])]; +} + +/** Append `row` to the log at `path`, creating it with its header when it does not exist. */ +export function appendCandidateLog(path, row) { + if (!existsSync(path)) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, CANDIDATE_LOG_HEADER); + } + appendFileSync(path, row); +} + const active = new Set(); /** diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index db5c71a18f..a0c5c9b0ec 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -6,6 +6,7 @@ // bun run prerelease:publish # next iteration, npm + Maven (the default scope) // bun run prerelease:publish --only npm,csharp # pick ports // bun run prerelease:publish --only all # all four +// bun run prerelease:candidate # the same: a FULL candidate, every registry // bun run prerelease:publish --iter 5 # pin the iteration number // bun run prerelease:publish --base 0.25.0 # override the in-development version // @@ -64,7 +65,7 @@ import { join } from "node:path"; import { mavenVersion } from "./maven-coordinate.mjs"; import { TIER_ORDER } from "./publish-set.mjs"; import { - changelogVersions, collectPages, decideBase, installRestoreHandlers, releasedVersion, run as runStep, + appendCandidateLog, candidateLogRow, candidateRegistries, changelogVersions, collectPages, decideBase, installRestoreHandlers, releasedVersion, run as runStep, } from "./prerelease-version.mjs"; const argv = process.argv.slice(2); @@ -277,6 +278,14 @@ const VERSION_FILES = [ const dirty = sh(`git status --porcelain -- ${VERSION_FILES.map((f) => `'${f}'`).join(" ")}`).trim(); if (dirty) die(`version-bearing files are dirty — commit or stash first:\n${dirty}`); ok("version-bearing files clean"); +// Whether the tree the candidate is built from has uncommitted work, taken now, before any +// version edit and before restore(). New untracked files count; the candidate log itself does not. +const CANDIDATE_LOG = "tools/prerelease/candidates.md"; +const builtFromDirtyTree = sh("git status --porcelain --untracked-files=all").split("\n") + .some((l) => l.trim() && l.slice(3) !== CANDIDATE_LOG); +const published = []; // registries this run published to completely, in order +const started = []; // registries whose first publish call began; one that is not in `published` was cut short +const begin = (eco) => { if (!DRY) started.push(eco); }; // The tracked files those same pathspecs cover — restore() may only revert files whose // pre-run cleanliness this gate actually verified. const covered = new Set( @@ -299,7 +308,23 @@ const restore = () => { if (!touched.length) return; try { sh(`git checkout -- ${touched.map((f) => `'${f}'`).join(" ")}`); } catch {} }; -installRestoreHandlers(restore); +// The repository's record of which commit each candidate was built from. It is written however the +// run ends, because a run that stops after one registry has still burned the candidate number +// there, and a Rust consumer pins the commit this row names. Written after restore(), so the +// entry is the only change the run leaves behind. +let recorded = false; +const recordCandidate = () => { + if (recorded || DRY || !started.length) return; recorded = true; + try { + appendCandidateLog(join(ROOT, CANDIDATE_LOG), candidateLogRow({ + candidate: CANON, commit: sh("git rev-parse HEAD").trim(), dirty: builtFromDirtyTree, date: new Date(), + registries: candidateRegistries({ published, started, only: ONLY }), + })); + console.log(`recorded ${CANON} in ${CANDIDATE_LOG} — commit that line`); + } catch (e) { console.error(`could not record ${CANON} in ${CANDIDATE_LOG}: ${e.message}`); } +}; +const restoreAndRecord = () => { restore(); recordCandidate(); }; +installRestoreHandlers(restoreAndRecord); const scratch = (name) => { const d = join(SCRATCH, name); rmSync(d, { recursive: true, force: true }); mkdirSync(d, { recursive: true }); return d; }; // Kept between runs (so Maven does not re-download the world every time) and deliberately @@ -348,12 +373,14 @@ if (wants("npm")) { if (seen !== NPM_REG) die(`bun would publish to ${seen}, not ${NPM_REG} — aborting`); ok(`bun publish target verified by dry-run: ${seen}`); + begin("npm"); if (!DRY) for (const pkg of ordered) { await run("bun publish --tag prerelease", { cwd: join(ROOT, pkg.dir), env: { ...process.env, HOME: home } }); info(`published ${pkg.short}@${V.npm}`); } ok(DRY ? "npm: dry run, nothing published" : `npm: ${ordered.length} packages @ ${V.npm} (dist-tag prerelease)`); + if (!DRY) published.push("npm"); } // ── python ──────────────────────────────────────────────────────────────────────────── @@ -364,10 +391,12 @@ if (wants("python")) { const dist = scratch("pydist"); await run(`cd server/python && uv build --out-dir ${dist}`); ok(`python built ${V.pypi}`); + begin("python"); if (!DRY) { await run(`cd server/python && uv publish --publish-url "${PYPI_URL}" --username "${OWNER}" --password "${TOKEN}" ${dist}/*`); ok(`python: metaobjects ${V.pypi} → ${expectedHost}`); } else ok("python: dry run, nothing published"); + if (!DRY) published.push("python"); } // ── csharp ──────────────────────────────────────────────────────────────────────────── @@ -378,10 +407,12 @@ if (wants("csharp")) { "MetaObjects.Codegen/MetaObjects.Codegen", "MetaObjects.Cli/MetaObjects.Cli"]; for (const p of projs) await run(`cd server/csharp && dotnet pack ${p}.csproj -c Release -o ${out} -p:Version=${V.nuget} --nologo -v q`); ok(`csharp packed ${V.nuget} (4 packages)`); + begin("csharp"); if (!DRY) { await run(`dotnet nuget push "${out}/*.nupkg" --source "${NUGET_SRC}" --api-key "${TOKEN}"`); ok(`csharp: 4 packages @ ${V.nuget} → ${expectedHost}`); } else ok("csharp: dry run, nothing published"); + if (!DRY) published.push("csharp"); } // ── java / kotlin ───────────────────────────────────────────────────────────────────── @@ -410,13 +441,15 @@ if (wants("java")) { // `package` for a dry run, not `install`: a dry run must not write artifacts anywhere. const goal = DRY ? "package" : "deploy"; const repo = keptScratch("m2repo"); + begin("java"); await run(`cd server/java && mvn -B -s ${settings} -Dmaven.repo.local=${repo} ${goal} -DskipTests` + ` -DaltDeploymentRepository="mo-prerelease::${MAVEN_URL}"`, { stdio: "inherit" }); ok(DRY ? "java: dry run, built (package), nothing deployed" : `java: reactor @ ${V.maven} → ${expectedHost}`); + if (!DRY) published.push("java"); } -restore(); +restoreAndRecord(); if (DRY) { console.log(`\n\x1b[32m\x1b[1m✔ dry run of ${CANON} passed; nothing was published.\x1b[0m\n`); } else { diff --git a/scripts/regen-showcase.ts b/scripts/regen-showcase.ts index 7871334355..ddd52d1880 100644 --- a/scripts/regen-showcase.ts +++ b/scripts/regen-showcase.ts @@ -382,11 +382,9 @@ function pristineProject(): string { join(tmp, ".metaobjects", "config.json"), { recursive: true }); // A project with no `node_modules` anywhere above it switches Bun into auto-install: the // config's `@metaobjectsdev/*` imports would then resolve to a copy fetched into the - // machine-wide cache, not this tree, and that copy's formatter dependency cannot find its - // sibling `@biomejs/wasm-nodejs` ("Biome formatter error"), so every ts file comes out - // unformatted and the gate reports the whole committed tree as stale. An empty - // `node_modules` turns auto-install off; the CLI's own package aliases then resolve the - // workspace packages, which is what this check is meant to exercise. + // machine-wide cache, not this tree, so the gate would check that copy's output instead of + // the committed tree. An empty `node_modules` turns auto-install off; the CLI's own package + // aliases then resolve the workspace packages, which is what this check is meant to exercise. mkdirSync(join(tmp, "node_modules")); return tmp; } diff --git a/scripts/test-prerelease-version.mjs b/scripts/test-prerelease-version.mjs index 0b07f458bd..5a94e3d18d 100644 --- a/scripts/test-prerelease-version.mjs +++ b/scripts/test-prerelease-version.mjs @@ -9,6 +9,7 @@ // P2 the iteration counter reads every page of the registry's listing. // P3 a SIGTERM restores the version files, as exit and SIGINT already did, and stops a step that // is still running instead of letting the run publish the remaining registries first. +// P5 every published candidate leaves one row in the committed log: candidate, commit, date, registries. // P4 only CHANGELOG sections on the released major line or the next one count; the old Maven-only [7.x] sections // made a cut after 1.2.0 propose 7.20.12. import assert from "node:assert/strict"; @@ -18,7 +19,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { - changelogVersions, collectPages, decideBase, latestReleaseTag, releasedVersion, run, + CANDIDATE_LOG_HEADER, appendCandidateLog, candidateLogRow, candidateRegistries, changelogVersions, collectPages, decideBase, + latestReleaseTag, releasedVersion, run, } from "./prerelease-version.mjs"; let fails = 0; @@ -168,5 +170,43 @@ await test("a step resolves to its stdout and rejects on a non-zero exit", async await assert.rejects(run("echo boom >&2; exit 3"), /exit 3.*\n.*boom/s); }); +await test("a candidate row names the commit, the date and the registries, and never a host", () => { + const sha = "0123456789abcdef0123456789abcdef01234567"; + assert.equal( + candidateLogRow({ candidate: "1.3.0-rc.1", commit: sha, dirty: false, date: new Date("2026-11-20T09:05:59Z"), registries: ["npm", "java"] }), + "| 1.3.0-rc.1 | `0123456789ab` | 2026-11-20 09:05 | npm, java |\n"); + assert.match(candidateLogRow({ candidate: "1.3.0-rc.2", commit: sha, dirty: true, date: new Date(0), registries: ["npm"] }), /`0123456789ab\+dirty`/); + assert.throws(() => candidateLogRow({ candidate: "1.3.0", commit: sha, dirty: false, date: new Date(0), registries: ["npm"] }), /not a candidate/); + assert.throws(() => candidateLogRow({ candidate: "1.3.0-rc.1", commit: "abc", dirty: false, date: new Date(0), registries: ["npm"] }), /full commit sha/); + assert.throws(() => candidateLogRow({ candidate: "1.3.0-rc.1", commit: sha, dirty: false, date: new Date(0), registries: [] }), /at least one registry/); +}); + +await test("the candidate log is created with its header once and then only appended to", () => { + const dir = mkdtempSync(join(tmpdir(), "mo-candidate-log-")); + try { + const path = join(dir, "nested", "candidates.md"); + appendCandidateLog(path, "| a |\n"); + appendCandidateLog(path, "| b |\n"); + assert.equal(readFileSync(path, "utf8"), `${CANDIDATE_LOG_HEADER}| a |\n| b |\n`); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +await test("a registry cut short mid-publish is named in the row, and later ones as stopped before", () => { + // npm began and never finished (package k of 14 failed): the number is burned there. + assert.deepEqual(candidateRegistries({ published: [], started: ["npm"], only: ["npm", "python", "csharp", "java"] }), + ["npm (cut short)", "stopped before python, csharp, java"]); + // npm done, python cut short. + assert.deepEqual(candidateRegistries({ published: ["npm"], started: ["npm", "python"], only: ["npm", "python", "java"] }), + ["npm", "python (cut short)", "stopped before java"]); + // A clean full run has no qualifier. + assert.deepEqual(candidateRegistries({ published: ["npm", "java"], started: ["npm", "java"], only: ["npm", "java"] }), ["npm", "java"]); + // A cut-short npm still yields a row a Rust consumer can pin. + const sha = "0123456789abcdef0123456789abcdef01234567"; + const registries = candidateRegistries({ published: [], started: ["npm"], only: ["npm"] }); + assert.match(candidateLogRow({ candidate: "1.3.0-rc.1", commit: sha, dirty: false, date: new Date(0), registries }), /npm \(cut short\) \|\n$/); +}); + if (fails) { console.error(`${fails} failure(s)`); process.exit(1); } console.log("all prerelease-version tests passed"); diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs index b8e9e8bc82..a5e4e6b0d7 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs @@ -170,10 +170,11 @@ public void Edited_ejected_copy_changes_gen_output_and_verify_codegen_passes() // file's header, proving CUSTOM LOGIC (not just the unmodified reference) // flows through a real compile into real output. var original = File.ReadAllText(GeneratorCopy); - Assert.Contains("sb.AppendLine(\"// \");", original); + const string headerCall = "w.GeneratedFileHeader(\"entity-generator\");"; + Assert.Contains(headerCall, original); var edited = original.Replace( - "sb.AppendLine(\"// \");", - "sb.AppendLine(\"// \");\n sb.AppendLine(\"// EJECTED-E2E-MARKER\");"); + headerCall, + headerCall + "\n w.Header(\"// EJECTED-E2E-MARKER\");"); Assert.NotEqual(original, edited); File.WriteAllText(GeneratorCopy, edited); diff --git a/server/csharp/MetaObjects.Codegen.Tests/CsWriterHangingTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CsWriterHangingTests.cs new file mode 100644 index 0000000000..7dacdb03b0 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/CsWriterHangingTests.cs @@ -0,0 +1,54 @@ +using MetaObjects.Codegen.Writer; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// The hanging continuation of : a statement that carries on one level in. +/// Not a shared-corpus case, because it is a scope rather than a line, so the cases of the other +/// ports have no op to name it by. +public class CsWriterHangingTests +{ + [Fact] + public void A_statement_continues_one_level_in_and_returns_to_its_own_level() + { + var w = new CsWriter(); + w.Line("public class A"); + using (w.Block("{")) + { + w.Line("var x = items"); + using (w.Hanging()) + { + w.Line(".Where(i => i.Ok)"); + w.Line(".ToList();"); + } + w.Line("return x;"); + } + Assert.Equal( + "public class A\n{\n var x = items\n .Where(i => i.Ok)\n .ToList();\n return x;\n}\n", + w.ToString()); + } + + [Fact] + public void A_continuation_can_hang_inside_another() + { + var w = new CsWriter(); + w.Line("a ="); + using (w.Hanging()) + { + w.Line("b"); + using (w.Hanging()) w.Line("?? c;"); + } + Assert.Equal("a =\n b\n ?? c;\n", w.ToString()); + } + + [Fact] + public void A_continuation_ended_with_a_block_still_open_inside_it_is_refused() + { + var w = new CsWriter(); + w.Line("a ="); + var hang = w.Hanging(); + w.Open("{"); + var e = Assert.Throws(() => hang.Dispose()); + Assert.Equal(WriterErrors.UnbalancedClose, e.Code); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs index e73d486ce6..f7f331e203 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs @@ -65,6 +65,10 @@ public class EjectedGeneratorsAloneTests ["MetaObjects.Codegen.OutputPaths"] = "where an object's file lands under the output layout, and the claim that no two share a path: a path table, ruled engine", ["MetaObjects.Codegen.OutputLayout"] = "the output layout setting (flat or package) OutputPaths reads", ["MetaObjects.Codegen.NameClaims"] = "the claim registry: the code a clash raises and the scopes it keys on, one answer for every generator in the run", + // The code writer (ADR-0063): the dialect an owned generator writes through. It writes no + // text of its own, so an owned copy that calls it still holds every line it emits. + ["MetaObjects.Codegen.Writer.CodeWriter"] = "the language-neutral code writer: lines, blocks, blank-line requests, fit-or-break lists", + ["MetaObjects.Codegen.Writer.CsWriter"] = "the C# dialect of the writer: usings, braced blocks, doc summaries", // Questions about the model. ["MetaObjects.Codegen.InstanceArtifacts"] = "the predicate: does this object produce instance artifacts", ["MetaObjects.Codegen.ReportRows"] = "the row model a view-backed report is generated from: a model derivation", diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorExtensibilityTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorExtensibilityTests.cs index 2ef63565f1..e1bf902a82 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorExtensibilityTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorExtensibilityTests.cs @@ -8,6 +8,7 @@ // drift gate is the strong enforcer of that; these tests assert the override seams // work and the base is unchanged for the same input. +using MetaObjects.Codegen.Writer; using System.Text; using MetaObjects.Codegen; using MetaObjects.Codegen.Generators; @@ -49,12 +50,12 @@ private static MetaRoot Load() private sealed class PartialEntityGenerator : EntityGenerator { protected override void EmitClassHeader( - StringBuilder sb, MetaObject entity, string className, bool isProjection, + CsWriter w, MetaObject entity, string className, bool isProjection, IReadOnlyList pkFields, GenContext ctx) { if (!isProjection) - sb.AppendLine($"[Table(\"{CSharpNaming.Table(entity)}\")]"); - sb.AppendLine($"public partial class {className} : IAdopterEntity"); + w.Line($"[Table(\"{CSharpNaming.Table(entity)}\")]"); + w.Line($"public partial class {className} : IAdopterEntity"); } } @@ -62,9 +63,9 @@ protected override void EmitClassHeader( private sealed class AttributedEntityGenerator : EntityGenerator { protected override void EmitPropertyAttributes( - StringBuilder sb, MetaObject owner, MetaField field, GenContext ctx) + CsWriter w, MetaObject owner, MetaField field, GenContext ctx) { - sb.AppendLine(" [Adopter]"); + w.Line("[Adopter]"); } } @@ -79,6 +80,22 @@ public void Subclass_can_override_class_header_to_emit_partial_class() Assert.DoesNotContain("public class Subscriber\n", src); } + // An entity with a cross-field validator needs IValidatableObject, or DataAnnotations never runs + // Validate(). A header override that wrote its own declaration must not lose it. + [Fact] + public void A_header_override_still_gets_IValidatableObject_when_the_entity_has_a_cross_field_validator() + { + var model = Model.Replace( + "{ \"identity.primary\": { \"@fields\": \"id\" } }", + "{ \"identity.primary\": { \"@fields\": \"id\" } },\n { \"validator.atLeastOne\": { \"name\": \"r\", \"@fields\": [\"email\", \"subscribed\"] } }"); + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "ext.json")]); + Assert.Empty(r.Errors); + var src = Assert.Single(new PartialEntityGenerator().Generate(Ctx(r.Root))).Content; + + Assert.Contains("public partial class Subscriber : IAdopterEntity, IValidatableObject\n", src); + Assert.Contains("IEnumerable Validate(", src); + } + [Fact] public void Subclass_can_override_property_attribute_hook_to_append_attributes() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs index c522e3f977..4c52883e4a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorRound2Tests.cs @@ -4,6 +4,7 @@ // (unsubclassed) generator stays byte-stable — the IntegrationFixture drift gate is // the strong enforcer of that, these lock the new behavior. +using MetaObjects.Codegen.Writer; using System.Linq; using System.Text; using MetaObjects.Codegen; @@ -38,11 +39,11 @@ private static string File(System.Collections.Generic.IEnumerable f // Subclass overriding the two new round-2 hooks: an extra using + a class-body trailer. private sealed class HookedGenerator : EntityGenerator { - protected override void EmitFileUsings(StringBuilder sb, MetaObject entity, GenContext ctx) => - sb.AppendLine("using Acme.Adopter;"); + protected override void EmitFileUsings(CsWriter w, MetaObject entity, GenContext ctx) => + w.Using("Acme.Adopter"); - protected override void EmitClassBodyTrailer(StringBuilder sb, MetaObject entity, GenContext ctx) => - sb.AppendLine(" public int Marker() => 42;"); + protected override void EmitClassBodyTrailer(CsWriter w, MetaObject entity, GenContext ctx) => + w.Line("public int Marker() => 42;"); } private const string SimpleModel = """ @@ -78,10 +79,10 @@ public void EmitFileUsings_and_BodyTrailer_hooks_apply_and_base_is_unchanged() private sealed class DeclMarkerGenerator : EntityGenerator { protected override void EmitClassDeclarationLine( - StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) + CsWriter w, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) { - sb.AppendLine("// adopter-decl"); - base.EmitClassDeclarationLine(sb, entity, className, kind, ctx); + w.Line("// adopter-decl"); + base.EmitClassDeclarationLine(w, entity, className, kind, ctx); } } @@ -202,8 +203,12 @@ public void Literal_defaults_emit_property_initializers() // the per-property helpers are no longer private. private sealed class HelperReachingGenerator : EntityGenerator { - public string CallScalar(MetaObject owner, MetaField field) => - ScalarProperty(owner, field, new[] { "id" }, withAttributes: false); + public string CallScalar(MetaObject owner, MetaField field) + { + var w = new CsWriter(); + WriteScalarProperty(w, owner, field, new[] { "id" }, withAttributes: false); + return w.ToString(); + } } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs index 7e01af8988..0300bdc810 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs @@ -60,11 +60,11 @@ private static MetaRoot Load(string model) private sealed class TaggedDbContextGenerator : DbContextGenerator { protected override void EmitOnModelCreatingBody( - StringBuilder sb, IReadOnlyList modelLines, GenContext ctx) + MetaObjects.Codegen.Writer.CsWriter w, IReadOnlyList modelLines, GenContext ctx) { - sb.AppendLine(); - sb.AppendLine(" // ADOPTER MODEL CONFIG"); - base.EmitOnModelCreatingBody(sb, modelLines, ctx); + w.Blank(); + w.Line("// ADOPTER MODEL CONFIG"); + base.EmitOnModelCreatingBody(w, modelLines, ctx); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs index 2c516fe2c9..9df1304717 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs @@ -166,4 +166,4 @@ private static string XmlSafe(string text) } return fixedUp?.ToString() ?? text; } -} \ No newline at end of file +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs index e02e1ef87c..5b1d2950e4 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs @@ -165,7 +165,14 @@ private static List DesignTimeWarnings(string repo, string? assembly = n Run("postgres", assembly: assembly, outDir: Path.Combine(repo, "Acme.Data", "Generated")).Warnings .Where(w => w.Contains("DesignTimeServicesReference")).ToList(); - // The check errs toward warning — a false all-clear is a silent RESTART. + /// The generation error a context whose migrations provably lack the line gets: its message. + private static string MissingLineError(string repo, string? assembly = null) => + Assert.Throws(() => + Run("postgres", assembly: assembly, outDir: Path.Combine(repo, "Acme.Data", "Generated"))).Message; + + // The check errs toward warning for what it cannot prove — a false all-clear is a silent RESTART — + // and toward an error for what it can: a start declared while the migrations project provably lacks + // the line is a RESTART waiting for the next `dotnet ef migrations add`. [Fact] public void A_stale_snapshot_copy_in_the_contexts_project_does_not_hide_migrations_elsewhere() @@ -176,8 +183,7 @@ public void A_stale_snapshot_copy_in_the_contexts_project_does_not_hide_migratio var stale = Path.Combine(repo, "Acme.Data", "Old"); Directory.CreateDirectory(stale); File.WriteAllText(Path.Combine(stale, "AppDbContextModelSnapshot.cs"), Snapshot("Acme")); - var warning = Assert.Single(DesignTimeWarnings(repo)); - Assert.Contains("Acme.Migrations.csproj", warning); + Assert.Contains("Acme.Migrations.csproj", MissingLineError(repo)); } finally { Directory.Delete(repo, recursive: true); } } @@ -211,7 +217,7 @@ public void A_same_named_context_of_another_namespace_does_not_clear_this_one() public void A_line_in_a_comment_or_an_if_block_is_not_carried(string source) { var repo = Repo(snapshotIn: "Acme.Migrations", migrationsSource: source); - try { Assert.Contains("Acme.Migrations.csproj", Assert.Single(DesignTimeWarnings(repo))); } + try { Assert.Contains("Acme.Migrations.csproj", MissingLineError(repo)); } finally { Directory.Delete(repo, recursive: true); } } @@ -219,7 +225,7 @@ public void A_line_in_a_comment_or_an_if_block_is_not_carried(string source) public void A_line_naming_another_assembly_is_not_carried() { var repo = Repo(snapshotIn: "Acme.Migrations", migrationsSource: Line.Replace(", Acme.Data\"", ", Acme.OldData\"") + "\n"); - try { Assert.Contains("Acme.Migrations.csproj", Assert.Single(DesignTimeWarnings(repo, assembly: "Acme.Data"))); } + try { Assert.Contains("Acme.Migrations.csproj", MissingLineError(repo, assembly: "Acme.Data")); } finally { Directory.Delete(repo, recursive: true); } } @@ -240,15 +246,33 @@ public void Migrations_in_the_contexts_project_need_no_line() } [Fact] - public void Migrations_in_another_project_without_the_line_warn_with_the_line_and_the_project() + public void Migrations_in_another_project_without_the_line_are_an_error_naming_the_line_and_the_project() { var repo = Repo(snapshotIn: "Acme.Migrations"); try { - var warning = Assert.Single(DesignTimeWarnings(repo)); + var error = MissingLineError(repo); + Assert.StartsWith(DbContextGenerator.ErrDesignTimeReferenceMissing + ":", error); + Assert.Contains(Line, error); + Assert.Contains("Acme.Migrations.csproj", error); + Assert.Contains("RESTART", error); + } + finally { Directory.Delete(repo, recursive: true); } + } + + // The error is for a project that declares a start. A Postgres project with an increment key and no + // @sequenceStart has nothing to restart until it adds one, so the missing line stays a warning. + [Fact] + public void Migrations_in_another_project_without_the_line_warn_when_no_start_is_declared() + { + var repo = Repo(snapshotIn: "Acme.Migrations"); + try + { + var model = Model.Replace(", \"@sequenceStart\": 100", ""); + var (_, warnings) = Run("postgres", model, outDir: Path.Combine(repo, "Acme.Data", "Generated")); + var warning = Assert.Single(warnings.Where(w => w.Contains("DesignTimeServicesReference"))); Assert.Contains(Line, warning); Assert.Contains("Acme.Migrations.csproj", warning); - Assert.Contains("RESTART", warning); } finally { Directory.Delete(repo, recursive: true); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutAnalyzer.cs b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutAnalyzer.cs new file mode 100644 index 0000000000..aef1247010 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutAnalyzer.cs @@ -0,0 +1,308 @@ +// 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 Roslyn's +// parser and walks the syntax tree. Working on the tree, not the text, is what makes the rules +// exact: a comment is never a node, so never a finding; a string's value is the parser's cooked +// value, so "\n", "\u000a" and a verbatim literal that spans lines are the same finding; and a +// constant is followed to its declaration, so `const string NL = "\n"; Join(NL, xs)` is a finding +// at the join as well as at the declaration. +// +// Six rules: +// +// newline-literal a string, interpolated-string text or char literal whose value holds a line break. +// indent-literal a string that starts a line of output (a whole string, or the head of an +// interpolated one) and begins with an indentation run: two or more spaces, or a tab. +// newline-join string.Join(sep, ...) whose separator holds a line break, resolved through +// same-file constants. +// indent-repeat new string(' ', n), Enumerable.Repeat(" ", n) or "".PadLeft(n): building indentation. +// append-line StringBuilder.AppendLine: the line break is typed by the platform, not the writer. +// environment-newline Environment.NewLine, for the same reason (and it differs between platforms). +// +// Three places a literal is not output, and so is not layout, are ruled out by position: +// +// - a search pattern: the first argument of Split, IndexOf, LastIndexOf, IndexOfAny, Contains, +// StartsWith, EndsWith, Replace, Trim, TrimStart or TrimEnd, and anything given to Regex; +// - a writer snippet: the argument of a `.Text(...)` call, the writer's entry for fixed code +// written as it should read (it removes the margin and re-indents). +// - an attribute argument and a `nameof`. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace MetaObjects.Codegen.Tests.LayoutRatchet; + +public enum FindingKind +{ + NewlineLiteral, + IndentLiteral, + NewlineJoin, + IndentRepeat, + AppendLine, + EnvironmentNewline, +} + +public sealed record Finding(FindingKind Kind, int Line, int Column, string Excerpt); + +internal static class LayoutAnalyzer +{ + private static readonly HashSet SearchMethods = new(StringComparer.Ordinal) + { + "Split", "IndexOf", "LastIndexOf", "IndexOfAny", "Contains", "StartsWith", "EndsWith", + "Replace", "Trim", "TrimStart", "TrimEnd", + }; + + private const string SnippetMethod = "Text"; + private const int MaxResolveDepth = 8; + + /// What a string expression is known to contain. Complete is false when part of it is unknown. + private readonly record struct Resolved(string Text, bool Complete); + + internal static IReadOnlyList Analyze(string source) + { + var tree = CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Latest)); + var root = tree.GetRoot(); + var consts = CollectConsts(root); + var findings = new List(); + + void Report(FindingKind kind, SyntaxNode node) + { + var pos = tree.GetLineSpan(node.Span).StartLinePosition; + var raw = string.Join(' ', node.ToString().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + findings.Add(new Finding(kind, pos.Line + 1, pos.Character + 1, raw.Length > 60 ? raw[..57] + "..." : raw)); + } + + Resolved? Resolve(ExpressionSyntax? expr, int depth = 0) + { + if (expr is null || depth > MaxResolveDepth) return null; + switch (expr) + { + case LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression) || lit.IsKind(SyntaxKind.CharacterLiteralExpression): + return new Resolved(lit.Token.ValueText, true); + case ParenthesizedExpressionSyntax p: + return Resolve(p.Expression, depth + 1); + case BinaryExpressionSyntax b when b.IsKind(SyntaxKind.AddExpression): + { + var l = Resolve(b.Left, depth + 1); + var r = Resolve(b.Right, depth + 1); + if (l is null && r is null) return null; + return new Resolved((l?.Text ?? "") + (r?.Text ?? ""), l?.Complete == true && r?.Complete == true); + } + case InterpolatedStringExpressionSyntax interp: + { + var text = ""; + var complete = true; + foreach (var part in interp.Contents) + { + if (part is InterpolatedStringTextSyntax t) text += t.TextToken.ValueText; + else if (part is InterpolationSyntax i) + { + var sub = Resolve(i.Expression, depth + 1); + text += sub?.Text ?? ""; + complete &= sub?.Complete == true; + } + } + return new Resolved(text, complete); + } + case ConditionalExpressionSyntax c: + { + var a = Resolve(c.WhenTrue, depth + 1); + var b = Resolve(c.WhenFalse, depth + 1); + if (a is null && b is null) return null; + // Either branch may be written; for "does it contain a line break" both count. + return new Resolved((a?.Text ?? "") + (b?.Text ?? ""), false); + } + case IdentifierNameSyntax id: + return consts.TryGetValue(id.Identifier.ValueText, out var init) ? Resolve(init, depth + 1) : null; + case MemberAccessExpressionSyntax m when IsEnvironmentNewline(m): + return new Resolved("\n", true); + default: + return null; + } + } + + void CheckLiteral(SyntaxNode literal, string value, bool startsALine, SyntaxNode whole) + { + if (IsSearchPattern(whole) || IsSnippet(whole) || InAttributeOrNameof(whole)) return; + if (value.IndexOfAny(['\r', '\n']) >= 0) Report(FindingKind.NewlineLiteral, literal); + else if (startsALine && StartsWithIndentRun(value)) Report(FindingKind.IndentLiteral, literal); + } + + foreach (var node in root.DescendantNodes()) + { + switch (node) + { + case LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression): + CheckLiteral(lit, lit.Token.ValueText, true, lit); + break; + case LiteralExpressionSyntax ch when ch.IsKind(SyntaxKind.CharacterLiteralExpression): + if (ch.Token.ValueText is "\n" or "\r" && !IsSearchPattern(ch) && !InAttributeOrNameof(ch)) Report(FindingKind.NewlineLiteral, ch); + break; + case InterpolatedStringExpressionSyntax interp: + { + var first = true; + foreach (var part in interp.Contents) + { + if (part is InterpolatedStringTextSyntax t) CheckLiteral(t, t.TextToken.ValueText, first, interp); + first = false; + } + break; + } + case InvocationExpressionSyntax call: + CheckCall(call); + break; + case MemberAccessExpressionSyntax m when IsEnvironmentNewline(m): + Report(FindingKind.EnvironmentNewline, m); + break; + case ObjectCreationExpressionSyntax created when IsStringCtor(created) && created.ArgumentList is { Arguments.Count: 2 } args: + { + var unit = Resolve(args.Arguments[0].Expression); + if (unit is { Complete: true } u && IsWhitespace(u.Text)) Report(FindingKind.IndentRepeat, created); + break; + } + } + } + + return findings; + + void CheckCall(InvocationExpressionSyntax call) + { + var method = CalledName(call); + var args = call.ArgumentList.Arguments; + switch (method) + { + case "AppendLine": + Report(FindingKind.AppendLine, call); + break; + case "Join" when IsStringJoin(call) && args.Count > 0: + { + var sep = Resolve(args[0].Expression); + if (sep is { } s && s.Text.IndexOfAny(['\r', '\n']) >= 0) Report(FindingKind.NewlineJoin, call); + break; + } + case "Repeat" when call.Expression is MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax { Identifier.ValueText: "Enumerable" } } && args.Count == 2: + { + var unit = Resolve(args[0].Expression); + if (unit is { Complete: true } u && IsWhitespace(u.Text)) Report(FindingKind.IndentRepeat, call); + break; + } + case "PadLeft" or "PadRight" when call.Expression is MemberAccessExpressionSyntax pad: + { + var unit = Resolve(pad.Expression); + if (unit is { Complete: true } u && (u.Text.Length == 0 || IsWhitespace(u.Text))) Report(FindingKind.IndentRepeat, call); + break; + } + } + } + } + + // ── helpers ────────────────────────────────────────────────────────────────────────── + + private static bool StartsWithIndentRun(string value) => + value.StartsWith(" ", StringComparison.Ordinal) || value.StartsWith('\t'); + + private static bool IsWhitespace(string value) => value.Length > 0 && value.All(c => c is ' ' or '\t' or '\r' or '\n'); + + private static bool IsEnvironmentNewline(MemberAccessExpressionSyntax m) => + m.Name.Identifier.ValueText == "NewLine" + && m.Expression is IdentifierNameSyntax { Identifier.ValueText: "Environment" } + or MemberAccessExpressionSyntax { Name.Identifier.ValueText: "Environment" }; + + private static bool IsStringCtor(ObjectCreationExpressionSyntax created) => + created.Type is PredefinedTypeSyntax { Keyword.RawKind: (int)SyntaxKind.StringKeyword } + or IdentifierNameSyntax { Identifier.ValueText: "String" }; + + private static bool IsStringJoin(InvocationExpressionSyntax call) => + call.Expression is MemberAccessExpressionSyntax + { + Expression: PredefinedTypeSyntax { Keyword.RawKind: (int)SyntaxKind.StringKeyword } + or IdentifierNameSyntax { Identifier.ValueText: "String" } + }; + + /// The method name a call invokes: x.Join(...) is "Join", Join(...) is "Join". + private static string? CalledName(InvocationExpressionSyntax call) => call.Expression switch + { + MemberAccessExpressionSyntax m => m.Name.Identifier.ValueText, + IdentifierNameSyntax i => i.Identifier.ValueText, + _ => null, + }; + + /// The argument slot a node fills, when it is directly an argument of a call. + private static (InvocationExpressionSyntax Call, int Index)? ArgumentOf(SyntaxNode expr) + { + if (expr.Parent is ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax call } list } arg) + return (call, list.Arguments.IndexOf(arg)); + return null; + } + + private static bool IsSearchPattern(SyntaxNode expr) + { + if (expr.Parent is ArgumentSyntax { Parent: ArgumentListSyntax { Parent: ObjectCreationExpressionSyntax created } } + && created.Type.ToString() is "Regex" or "System.Text.RegularExpressions.Regex") + return true; + if (ArgumentOf(expr) is not { } slot) return false; + if (slot.Call.Expression is MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax { Identifier.ValueText: "Regex" } }) return true; + var name = CalledName(slot.Call); + return name is not null && slot.Index == 0 && SearchMethods.Contains(name); + } + + private static bool IsSnippet(SyntaxNode expr) => + ArgumentOf(expr) is { Index: 0 } slot && CalledName(slot.Call) == SnippetMethod; + + private static bool InAttributeOrNameof(SyntaxNode node) => + node.AncestorsAndSelf().Any(n => n is AttributeSyntax) + || (ArgumentOf(node) is { } slot && CalledName(slot.Call) == "nameof"); + + /// Every const string name = expr in the file. A name declared more than once is left out: it is shadowed somewhere. + private static Dictionary CollectConsts(SyntaxNode root) + { + var seen = new Dictionary(StringComparer.Ordinal); + void Note(string name, ExpressionSyntax? init) => seen[name] = seen.ContainsKey(name) ? null : init; + + foreach (var node in root.DescendantNodes()) + { + switch (node) + { + case FieldDeclarationSyntax f: + foreach (var v in f.Declaration.Variables) + Note(v.Identifier.ValueText, f.Modifiers.Any(SyntaxKind.ConstKeyword) || IsStaticReadonly(f) ? v.Initializer?.Value : null); + break; + case LocalDeclarationStatementSyntax l: + foreach (var v in l.Declaration.Variables) + Note(v.Identifier.ValueText, l.IsConst ? v.Initializer?.Value : null); + break; + case ParameterSyntax p: + Note(p.Identifier.ValueText, null); + break; + } + } + return seen.Where(kv => kv.Value is not null).ToDictionary(kv => kv.Key, kv => kv.Value!, StringComparer.Ordinal); + } + + private static bool IsStaticReadonly(FieldDeclarationSyntax f) => + f.Modifiers.Any(SyntaxKind.StaticKeyword) && f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword); + + // ── which files the ratchet reads ──────────────────────────────────────────────────── + + /// The project whose source is generator source, relative to server/csharp/. + internal const string ScannedProject = "MetaObjects.Codegen"; + + /// + /// Whether a file (relative to server/csharp/) is generator source the ratchet reads. + /// Excluded by rule, never by listing: anything outside the codegen project, build output, the + /// writer itself (the one module family that lays text out), the helper runtime that generated + /// code calls (it is shipped source, not a generator), and the documentation emitters + /// (Docs/, ApiDocs/: markdown is not generated code). + /// + internal static bool IsGeneratorSource(string rel) + { + var path = rel.Replace('\\', '/'); + if (!path.StartsWith(ScannedProject + "/", StringComparison.Ordinal) || !path.EndsWith(".cs", StringComparison.Ordinal)) return false; + var inside = path[(ScannedProject.Length + 1)..]; + if (inside.StartsWith("bin/") || inside.StartsWith("obj/")) return false; + foreach (var dir in new[] { "Writer/", "Runtime/", "Docs/", "ApiDocs/" }) + if (inside.StartsWith(dir, StringComparison.Ordinal)) return false; + return true; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutRatchetTests.cs b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutRatchetTests.cs new file mode 100644 index 0000000000..134727f1ac --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutRatchetTests.cs @@ -0,0 +1,274 @@ +// 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 and not by list; +// 3. the ratchet over the real project: 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. +// +// Lint-gate exception (ADR-0063): part 3 reads the real generator source on purpose. The ratchet is +// a chartered lint gate over source layout, the same per-port gate the TypeScript and Rust ports run, +// so scanning the source tree is its contract and not a proxy for behavior. The behavior of the +// writer itself is covered by the writer-conformance and CsWriter tests. The allowlist-only-shrinks +// check compares against local git refs and passes when they are absent, as on a fresh clone. + +using System.Diagnostics; +using System.Text.Json; +using Xunit; + +namespace MetaObjects.Codegen.Tests.LayoutRatchet; + +public class LayoutRatchetTests +{ + private static List Kinds(string source) => + LayoutAnalyzer.Analyze(source).Select(f => f.Kind).OrderBy(k => k).ToList(); + + // ── 1. the analyzer ────────────────────────────────────────────────────────────────── + + public static TheoryData Caught => new() + { + { "a newline escape in a string", """var s = "a\nb";""", [FindingKind.NewlineLiteral] }, + { "a unicode newline escape", """var s = "a\u000ab";""", [FindingKind.NewlineLiteral] }, + { "a carriage return", """var s = "a\r";""", [FindingKind.NewlineLiteral] }, + { "a newline char", """sb.Append('\n');""", [FindingKind.NewlineLiteral] }, + { "a verbatim string that spans lines", "var s = @\"a\nb\";", [FindingKind.NewlineLiteral] }, + { "a line break inside an interpolated string", "var s = $\"{a}\\n{b}\";", [FindingKind.NewlineLiteral] }, + { "a string that starts with two spaces", """rows.Add(" " + name);""", [FindingKind.IndentLiteral] }, + { "a string that starts with a tab", """rows.Add("\tx");""", [FindingKind.IndentLiteral] }, + { "an interpolated string that starts with an indentation run", "rows.Add($\" {name};\");", [FindingKind.IndentLiteral] }, + { "a join on a newline literal", """var s = string.Join("\n", xs);""", [FindingKind.NewlineJoin, FindingKind.NewlineLiteral] }, + { "a join on Environment.NewLine", "var s = string.Join(Environment.NewLine, xs);", [FindingKind.EnvironmentNewline, FindingKind.NewlineJoin] }, + { "a StringBuilder line", """sb.AppendLine("class A");""", [FindingKind.AppendLine] }, + { "Environment.NewLine", "sb.Append(Environment.NewLine);", [FindingKind.EnvironmentNewline] }, + { "new string of spaces", "var pad = new string(' ', depth * 4);", [FindingKind.IndentRepeat] }, + { "Enumerable.Repeat of spaces", """var pad = string.Concat(Enumerable.Repeat(" ", depth));""", [FindingKind.IndentRepeat, FindingKind.IndentLiteral] }, + { "PadLeft on an empty string", """var pad = "".PadLeft(depth * 2);""", [FindingKind.IndentRepeat] }, + }; + + [Theory] + [MemberData(nameof(Caught))] + public void The_analyzer_catches_hand_typed_layout(string name, string source, FindingKind[] expected) + { + _ = name; + Assert.Equal(expected.OrderBy(k => k).ToList(), Kinds(source)); + } + + [Fact] + public void A_newline_hidden_behind_a_same_file_constant_is_caught_where_it_is_used() + { + var found = LayoutAnalyzer.Analyze("const string NL = \"\\n\";\nvar s = string.Join(NL, xs);\n"); + Assert.Equal([(FindingKind.NewlineLiteral, 1), (FindingKind.NewlineJoin, 2)], found.Select(f => (f.Kind, f.Line)).ToArray()); + } + + [Fact] + public void The_constant_may_be_built_from_other_constants() + { + var source = "const string NL = \"\\n\";\nconst string SEP = \",\" + NL;\nvar a = string.Join(SEP, xs);\n"; + Assert.Equal([3], LayoutAnalyzer.Analyze(source).Where(f => f.Kind == FindingKind.NewlineJoin).Select(f => f.Line).ToArray()); + } + + [Fact] + public void An_indentation_unit_hidden_behind_a_constant_is_caught_at_the_repeat() + { + Assert.Equal([FindingKind.IndentRepeat], Kinds("const string UNIT = \" \";\nvar pad = new string(' ', 4); var q = string.Concat(Enumerable.Repeat(UNIT, 4));").Take(1)); + } + + [Fact] + public void Findings_carry_the_line_and_column_of_the_node() + { + var f = Assert.Single(LayoutAnalyzer.Analyze("var a = 1;\n var s = \"x\\ny\";\n")); + Assert.Equal((2, 11), (f.Line, f.Column)); + } + + public static TheoryData Passed => new() + { + "w.Line(\"public class A\"); w.Line(\"{\");", + "using (w.Braced(\"public class A\")) { w.Line(\"int X;\"); }", + "// a comment may say \"a\\nb\" and sb.AppendLine(\"x\")\nvar x = 1;", + "var parts = text.Split('\\n');", + "var parts = text.Split(\"\\r\\n\");", + "var has = text.Contains(\"\\n\");", + "var cleaned = text.Replace(\"\\n\", \" \");", + "var m = new Regex(\"a\\n\");", + "w.Text(\"\"\"\n fixed\n code\n \"\"\");", + "var name = nameof(Foo);", + "var s = string.Join(\", \", xs);", + "var s = $\"{a} and {b}\";", + "[Obsolete(\"a\\nb\")] class A { }", + }; + + [Theory] + [MemberData(nameof(Passed))] + public void The_analyzer_passes_code_that_leaves_layout_to_the_writer(string source) => + Assert.Empty(LayoutAnalyzer.Analyze(source)); + + // ── 2. the scope rule ──────────────────────────────────────────────────────────────── + + [Theory] + [InlineData("MetaObjects.Codegen/Generators/NamesGenerator.cs", true)] + [InlineData("MetaObjects.Codegen/CSharpNaming.cs", true)] + [InlineData("MetaObjects.Codegen/Writer/CodeWriter.cs", false)] + [InlineData("MetaObjects.Codegen/Writer/CsWriter.cs", false)] + [InlineData("MetaObjects.Codegen/Runtime/FilterParser.cs", false)] + [InlineData("MetaObjects.Codegen/Docs/XmlDocBuilder.cs", false)] + [InlineData("MetaObjects.Codegen/ApiDocs/CSharpApiDocsRenderer.cs", false)] + [InlineData("MetaObjects.Codegen/obj/Debug/net8.0/A.cs", false)] + [InlineData("MetaObjects.Codegen.Tests/WriterConformanceTests.cs", false)] + [InlineData("MetaObjects.Cli/Program.cs", false)] + [InlineData("MetaObjects.Codegen/README.md", false)] + public void Scope_is_decided_by_rule(string path, bool scanned) => Assert.Equal(scanned, LayoutAnalyzer.IsGeneratorSource(path)); + + // ── 3. the ratchet over the real project ───────────────────────────────────────────── + + private sealed record Allowlist(Dictionary Unconverted, Dictionary Exempt); + + private static string Csharp => Path.Combine(CorpusPaths.RepoRoot(), "server", "csharp"); + + private static string AllowlistPath => Path.Combine(Csharp, "MetaObjects.Codegen.Tests", "LayoutRatchet", "allowlist.json"); + + private static Allowlist ReadAllowlist(string json) + { + using var doc = JsonDocument.Parse(json); + Dictionary Section(string name) => + doc.RootElement.TryGetProperty(name, out var e) + ? e.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.GetString()!, StringComparer.Ordinal) + : new Dictionary(StringComparer.Ordinal); + return new Allowlist(Section("unconverted"), Section("exempt")); + } + + private static readonly Lazy Current = new(() => ReadAllowlist(File.ReadAllText(AllowlistPath))); + + private static Dictionary Entries => + Current.Value.Unconverted.Concat(Current.Value.Exempt).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.Ordinal); + + private static readonly Lazy>> Findings = new(() => + { + var found = new SortedDictionary>(StringComparer.Ordinal); + var root = Path.Combine(Csharp, LayoutAnalyzer.ScannedProject); + foreach (var file in Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)) + { + var rel = Path.GetRelativePath(Csharp, file).Replace('\\', '/'); + if (LayoutAnalyzer.IsGeneratorSource(rel)) found[rel] = LayoutAnalyzer.Analyze(File.ReadAllText(file)); + } + return found; + }); + + [Fact] + public void It_reads_the_generator_project() + { + Assert.Contains(Findings.Value.Keys, k => k.StartsWith("MetaObjects.Codegen/Generators/", StringComparison.Ordinal)); + Assert.DoesNotContain(Findings.Value.Keys, k => k.Contains("/Writer/", StringComparison.Ordinal)); + } + + [Fact] + public void No_generator_source_types_layout_unless_its_file_is_allowlisted() + { + var offenders = Findings.Value + .Where(kv => kv.Value.Count > 0 && !Entries.ContainsKey(kv.Key)) + .Select(kv => string.Join('\n', new[] { kv.Key }.Concat(kv.Value.Take(5).Select(f => $" {f.Line}:{f.Column} {f.Kind} {f.Excerpt}")))) + .ToList(); + Assert.True(offenders.Count == 0, + "Write these lines through CsWriter (Writer/) instead of typing line breaks or indentation. " + + "A file is never added to the allowlist: it only shrinks.\n" + string.Join('\n', offenders)); + } + + [Fact] + public void Every_allowlisted_file_still_needs_its_entry() + { + var stale = Entries.Keys.Where(f => !Findings.Value.TryGetValue(f, out var found) || found.Count == 0).ToList(); + Assert.True(stale.Count == 0, "these files no longer type layout (or no longer exist): remove their allowlist entries: " + string.Join(", ", stale)); + } + + [Fact] + public void Every_allowlisted_path_is_generator_source_that_exists() + { + foreach (var file in Entries.Keys) + { + Assert.True(LayoutAnalyzer.IsGeneratorSource(file), $"{file} is not in the ratchet's scope"); + Assert.True(File.Exists(Path.Combine(Csharp, file)), $"{file} does not exist"); + } + } + + [Fact] + public void Every_entry_carries_a_written_reason() + { + foreach (var (file, reason) in Entries) Assert.True(reason.Length > 40, $"{file} needs a reason"); + } + + [Fact] + public void A_file_is_either_unconverted_or_exempt_never_both_and_each_list_is_sorted() + { + Assert.Empty(Current.Value.Unconverted.Keys.Where(Current.Value.Exempt.ContainsKey)); + foreach (var list in new[] { Current.Value.Unconverted, Current.Value.Exempt }) + Assert.Equal(list.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(), list.Keys.ToList()); + } + + [Fact] + public void Growth_is_an_added_entry_or_an_unconverted_file_relabelled_exempt_removal_is_not() + { + var before = new Allowlist(new() { ["a.cs"] = "r", ["b.cs"] = "r" }, new() { ["c.cs"] = "r" }); + Assert.Empty(Growth(before, new Allowlist(new() { ["a.cs"] = "r" }, new()))); + Assert.Equal(["added d.cs"], Growth(before, new Allowlist(new() { ["a.cs"] = "r", ["d.cs"] = "r" }, new() { ["c.cs"] = "r" }))); + Assert.Equal(["relabelled b.cs as exempt"], Growth(before, new Allowlist(new() { ["a.cs"] = "r" }, new() { ["b.cs"] = "r", ["c.cs"] = "r" }))); + } + + // The allowlist may only shrink. Compared with the copy at the merge base of every + // integration branch this checkout knows: an entry that is not there was added here. Skipped + // (and quiet) when git or those refs are unavailable, as in an export or a shallow clone, and + // for the branch that introduces the allowlist, which has no earlier copy to compare with. + [Fact] + public void The_allowlist_only_shrinks() + { + foreach (var (reference, before) in MergeBaseAllowlists()) + { + var grown = Growth(before, Current.Value); + Assert.True(grown.Count == 0, $"the allowlist grew since the merge base with {reference}; convert the file to the writer instead: {string.Join(", ", grown)}"); + } + } + + private static List Growth(Allowlist before, Allowlist now) + { + var had = before.Unconverted.Keys.Concat(before.Exempt.Keys).ToHashSet(StringComparer.Ordinal); + return now.Unconverted.Keys.Concat(now.Exempt.Keys).Where(f => !had.Contains(f)).Select(f => $"added {f}") + .Concat(now.Exempt.Keys.Where(before.Unconverted.ContainsKey).Select(f => $"relabelled {f} as exempt")) + .ToList(); + } + + private static List<(string Ref, Allowlist List)> MergeBaseAllowlists() + { + var repo = CorpusPaths.RepoRoot(); + var rel = Path.GetRelativePath(repo, AllowlistPath).Replace('\\', '/'); + var refs = Git(repo, "for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/main", "refs/remotes/origin/release/"); + var found = new List<(string, Allowlist)>(); + if (string.IsNullOrWhiteSpace(refs)) return found; + foreach (var reference in refs.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)) + { + var baseSha = Git(repo, "merge-base", "HEAD", reference)?.Trim(); + if (string.IsNullOrEmpty(baseSha)) continue; + var text = Git(repo, "show", $"{baseSha}:{rel}"); + if (text is not null) found.Add((reference, ReadAllowlist(text))); + } + return found; + } + + private static string? Git(string repo, params string[] args) + { + var info = new ProcessStartInfo("git") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; + info.ArgumentList.Add("-C"); + info.ArgumentList.Add(repo); + foreach (var a in args) info.ArgumentList.Add(a); + try + { + using var p = Process.Start(info); + if (p is null) return null; + var output = p.StandardOutput.ReadToEnd(); + p.StandardError.ReadToEnd(); + p.WaitForExit(); + return p.ExitCode == 0 ? output : null; + } + catch (System.ComponentModel.Win32Exception) + { + return null; + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/allowlist.json b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/allowlist.json new file mode 100644 index 0000000000..aaa636743c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/allowlist.json @@ -0,0 +1,13 @@ +{ + "unconverted": { + }, + "exempt": { + "MetaObjects.Codegen/CSharpNaming.cs": "naming tables: the line-break characters it names are inputs it splits identifiers and comments on, and it writes no generated file", + "MetaObjects.Codegen/CodegenCli.cs": "the command line: its newlines and indents are console messages and usage text, not generated code", + "MetaObjects.Codegen/EjectableGenerators.cs": "eject rewrites the namespace and usings of a generator's own C# source as text; that is a source-to-source copy, not generated code", + "MetaObjects.Codegen/FrameworkQualifier.cs": "a post-pass that rewrites bare System.* references in already-written text; it splits and rejoins lines of any file and lays out none", + "MetaObjects.Codegen/GenFingerprint.cs": "the generation fingerprint: newline-joined records are the bytes that get hashed, a contract with the stored key, not generated code", + "MetaObjects.Codegen/HashManifest.cs": "the committed hash manifest: its line format is a stored contract with earlier runs, not generated code", + "MetaObjects.Codegen/ModelHash.cs": "the model hash: newline-joined records are the bytes that get hashed, a contract with the stored hash, not generated code" + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs index 029fd93b04..8f65b63caf 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs @@ -6,6 +6,7 @@ // declared one name and a context that configured another: a generated tree that does not // compile. GenConfig.PropertyNaming is the one resolver; both generators' hooks default to it. +using MetaObjects.Codegen.Writer; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -207,10 +208,10 @@ public void Reverse_finders_can_be_turned_off() private sealed class MarkedEntities : EntityGenerator { protected override void EmitClassAttributes( - StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) + CsWriter w, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) { if (kind is ClassDeclarationKind.MappedEntity or ClassDeclarationKind.TphSubtype) - sb.AppendLine("[global::System.Serializable]"); + w.Line("[global::System.Serializable]"); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs index c93614ea43..a82a035b81 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs @@ -108,6 +108,31 @@ public void It_writes_one_shared_writer_and_one_module_per_served_report_only() Assert.Contains("XmlNil = true;", files["ReportExportWriter.g.cs"]); } + // A report whose package maps to a namespace other than the configured one gets that namespace as a + // `using`, printed in the one using block with the others, directly before `namespace`. + [Fact] + public void A_home_namespace_using_sits_in_the_using_block_before_the_namespace_line() + { + var root = Load(); + var ctx = new GenContext + { + Entities = root.Objects().Where(o => !o.IsReport()).ToList(), + Root = root, + Config = new GenConfig + { + OutDir = "/unused", Namespace = "Acme.Gen", ColumnNamingStrategy = ColumnNamingStrategy.Literal, + PackageNamespaces = new() { ["acme::shop"] = "Acme.Shop" }, + }, + }; + var module = new ReportExportGenerator().Generate(ctx) + .Single(f => System.IO.Path.GetFileName(f.Path) == "LineTotalsExport.g.cs").Content; + var lines = module.Split('\n').SkipWhile(l => !l.StartsWith("using ", StringComparison.Ordinal)).ToList(); + var header = lines.TakeWhile(l => !l.StartsWith("namespace ", StringComparison.Ordinal)).ToList(); + Assert.Contains("using Acme.Shop;", header); + Assert.Equal(["using System.Collections.Generic;", "using System.IO;", "using System.Linq;", "using Acme.Shop;", ""], header); + Assert.StartsWith("namespace ", lines[header.Count]); + } + [Fact] public void Options_reach_the_shared_writer() { @@ -170,7 +195,8 @@ private static string Writer(string model) => new ReportExportGenerator().Generate(Ctx(Load(model))).Single(f => f.Path == "ReportExportWriter.g.cs").Content; // field.duration: the writer of a model with no duration column is the writer from before - // durations existed, byte for byte (the hash of that writer for this model, pinned). + // durations existed, byte for byte (the hash of that writer for this model, pinned) bar the one + // newline the code writer ends every file with, which the hash leaves out. [Fact] public void The_writer_of_a_model_without_a_duration_column_is_unchanged() { @@ -178,7 +204,7 @@ public void The_writer_of_a_model_without_a_duration_column_is_unchanged() Assert.DoesNotContain("TimeSpan ts", writer); Assert.DoesNotContain("duration", writer, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("@DURATION", writer); - var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(writer.Replace("\r\n", "\n")))); + var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(writer.Replace("\r\n", "\n").TrimEnd('\n')))); Assert.Equal("78913C645BB9D25C334F2285C210D0192510618A63C564AA7833C8AEA4A0B5AF", hash); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs index f06e5e8cef..e2448a045f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -74,6 +74,32 @@ public class SecretFieldsCodegenTests ]}} """; + // Author has no credential of its own; its M:N target Account does. + private const string M2mToCredentialModel = """ + { "metadata.root": { "package": "acme::secrets", "children": [ + { "object.entity": { "name": "Author", "children": [ + { "source.rdb": { "@table": "authors" } }, + { "field.long": { "name": "id" } }, + { "relationship.association": { "name": "accounts", "@cardinality": "many", "@objectRef": "Account", "@through": "AuthorAccount" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "AuthorAccount", "children": [ + { "source.rdb": { "@table": "author_accounts" } }, + { "field.long": { "name": "authorId" } }, + { "field.long": { "name": "accountId" } }, + { "identity.primary": { "@fields": ["authorId", "accountId"] } }, + { "identity.reference": { "name": "fkAuthor", "@fields": "authorId", "@references": "Author" } }, + { "identity.reference": { "name": "fkAccount", "@fields": "accountId", "@references": "Account" } } + ]}} + ]}} + """; + private static string Routes(string model, string file = "AccountRoutes.g.cs") { var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "secrets.json")]); @@ -87,6 +113,15 @@ private static string Routes(string model, string file = "AccountRoutes.g.cs") return new RoutesGenerator().Generate(ctx).Single(f => System.IO.Path.GetFileName(f.Path) == file).Content; } + [Fact] + public void An_m2m_route_returning_credential_rows_ships_the_omitting_result_class() + { + var src = Routes(M2mToCredentialModel, "AuthorRoutes.g.cs"); + + Assert.Contains("new CredentialOmittingResult(rows, new string[] { \"PinHash\" }", src); + Assert.Contains("private sealed class CredentialOmittingResult : IResult", src); + } + [Fact] public void A_tph_column_marked_on_another_subtype_is_hidden_and_ignored_on_this_one() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs new file mode 100644 index 0000000000..1fb2d52c2c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs @@ -0,0 +1,131 @@ +// The shared code-writer corpus (fixtures/writer-conformance/, ADR-0063): the `core` cases and +// the `csharp` dialect's. A case of another port's dialect (`typescript`) belongs to that port's +// writer and is not run here. + +using System.Text.Json; +using MetaObjects.Codegen.Writer; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class WriterConformanceTests +{ + private const string DialectCore = "core"; + private const string DialectCsharp = "csharp"; + + private static string CasesDir => Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "writer-conformance", "cases"); + + private static List CaseNames() + { + var names = new List(); + foreach (var path in Directory.GetFiles(CasesDir, "*.json").OrderBy(p => p, StringComparer.Ordinal)) + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + var dialect = doc.RootElement.GetProperty("dialect").GetString(); + if (dialect is DialectCore or DialectCsharp) names.Add(Path.GetFileNameWithoutExtension(path)); + } + return names; + } + + public static TheoryData Cases + { + get + { + var data = new TheoryData(); + foreach (var n in CaseNames()) data.Add(n); + return data; + } + } + + [Fact] + public void The_corpus_is_present_for_both_dialects() + { + var names = CaseNames(); + Assert.True(names.Count(n => !n.StartsWith("cs-", StringComparison.Ordinal) && !n.StartsWith("ts-", StringComparison.Ordinal)) >= 25); + Assert.Contains("cs-header-usings-body", names); + } + + [Theory] + [MemberData(nameof(Cases))] + public void Case_passes(string name) + { + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(CasesDir, name + ".json"))); + var c = doc.RootElement; + var dialect = c.GetProperty("dialect").GetString(); + if (dialect == DialectCore) Assert.True(c.TryGetProperty("options", out _), "a core case states its options"); + + if (c.TryGetProperty("error", out var error)) + { + var thrown = Assert.Throws(() => Run(c, dialect!)); + Assert.Equal(error.GetString(), thrown.Code); + if (c.TryGetProperty("errorQuotes", out var quotes)) Assert.Contains(quotes.GetString()!, thrown.Message); + return; + } + + var lines = c.GetProperty("expected").EnumerateArray().Select(l => l.GetString()!).ToList(); + var want = lines.Count == 0 ? "" : string.Join('\n', lines) + "\n"; + Assert.Equal(want, Run(c, dialect!)); + } + + private static string Run(JsonElement c, string dialect) + { + var options = c.TryGetProperty("options", out var o) ? o : default; + CodeWriter w = dialect == DialectCore ? new CodeWriter(CoreOptions(options)) : new CsWriter { UsingOrder = CsOrder(options) }; + foreach (var op in c.GetProperty("ops").EnumerateArray()) + { + var items = op.EnumerateArray().ToList(); + var name = items[0].GetString()!; + var args = items.Skip(1).ToList(); + switch (name) + { + case "line": w.Line(Parts(args)); break; + case "open": w.Open(Parts(args)); break; + case "close": w.Close(Parts(args)); break; + case "blank": w.Blank(); break; + case "text": w.Text(args[0].GetString()!); break; + default: + var cs = w as CsWriter ?? throw new InvalidOperationException($"op {name} is not a core op"); + var s = args.Select(a => a.GetString()!).ToArray(); + switch (name) + { + case "header": cs.Header(s); break; + case "using": cs.Using(s[0]); break; + case "usingStatic": cs.UsingStatic(s[0]); break; + case "usingAlias": cs.UsingAlias(s[0], s[1]); break; + case "docSummary": cs.DocSummary(s); break; + default: throw new InvalidOperationException($"unknown op {name}"); + } + break; + } + } + return w.ToString(); + } + + private static CodeWriterOptions CoreOptions(JsonElement o) => new() + { + Indent = o.GetProperty("indent").GetString()!, + Width = o.GetProperty("width").GetInt32(), + TrailingComma = o.GetProperty("trailingComma").GetBoolean(), + }; + + // A csharp case runs with the C# defaults and states only the using order, when it changes it. + private static UsingOrder CsOrder(JsonElement o) => + o.ValueKind == JsonValueKind.Object && o.TryGetProperty("usingOrder", out var u) && u.GetString() == "sorted" + ? UsingOrder.Sorted + : UsingOrder.AsWritten; + + private static Piece[] Parts(IEnumerable args) => args.Select(ToPiece).ToArray(); + + private static Piece ToPiece(JsonElement p) => p.ValueKind switch + { + JsonValueKind.String => p.GetString()!, + JsonValueKind.Array => Piece.Seq(p.EnumerateArray().Select(ToPiece).ToArray()), + _ => ToGroup(p.GetProperty("list")), + }; + + private static Piece ToGroup(JsonElement l) => new Group( + l.GetProperty("open").GetString()!, + l.GetProperty("items").EnumerateArray().Select(ToPiece).ToList(), + l.GetProperty("close").GetString()!, + l.TryGetProperty("pad", out var pad) && pad.GetBoolean()); +} diff --git a/server/csharp/MetaObjects.Codegen/CSharpProjectAssembly.cs b/server/csharp/MetaObjects.Codegen/CSharpProjectAssembly.cs index 803152e06e..f8aac80406 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpProjectAssembly.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpProjectAssembly.cs @@ -221,22 +221,31 @@ public static class DesignTimeServicesReferences /// The migrations are found by <contextName>ModelSnapshot.cs in the repository of /// 's project. /// - public static string? Warning(GenConfig config, string generator, string contextName, string servicesTypeName, string line, string consequence) + public static string? Warning(GenConfig config, string generator, string contextName, string servicesTypeName, string line, string consequence) => + Check(config, generator, contextName, servicesTypeName, line, consequence).Message; + + /// + /// The same answer as , plus whether the line is PROVEN missing: the + /// migrations were found in another project, and that project does not reference + /// . A run that cannot tell (no snapshot on disk) is not + /// proven; it stays a warning, because a project with no migrations yet has nothing to restart. + /// + public static (string? Message, bool Missing) Check(GenConfig config, string generator, string contextName, string servicesTypeName, string line, string consequence) { var assembly = config.ContextAssemblyName; var (need, migrations) = CSharpProjectAssembly.DesignTimeReference(config.OutDir, contextName, servicesTypeName, assembly); return need switch { DesignTimeReferenceNeed.Needed => - $"{generator}: the migrations of {contextName} are in {migrations}, not in the context's project ({assembly}), " + + ($"{generator}: the migrations of {contextName} are in {migrations}, not in the context's project ({assembly}), " + $"and that project does not reference {servicesTypeName}. EF reads [assembly: DesignTimeServicesReference] only " + $"from the startup and migrations assemblies, so it never reads the one generated beside the context; {consequence}. " + - $"Add this line to a .cs file of that project: {line}", + $"Add this line to a .cs file of that project: {line}", true), DesignTimeReferenceNeed.Unknown => - $"{generator}: cannot tell whether EF reads the DesignTimeServicesReference generated beside {contextName}: EF reads it " + + ($"{generator}: cannot tell whether EF reads the DesignTimeServicesReference generated beside {contextName}: EF reads it " + $"only from the startup and migrations assemblies, and no {contextName}ModelSnapshot.cs was found to show that " + - $"{assembly} holds the migrations. If the migrations are in another project, add this line to it ({consequence}): {line}", - _ => null, + $"{assembly} holds the migrations. If the migrations are in another project, add this line to it ({consequence}): {line}", false), + _ => (null, false), }; } } diff --git a/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs b/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs index d35619f3f7..c87b8a81d6 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs @@ -2,6 +2,7 @@ // notes is intentionally NEVER read — D5 contract. using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Core.Documentation; using MetaObjects.Meta; @@ -107,6 +108,20 @@ public static void AppendTo(StringBuilder sb, MetaData node, string indent = "") } } + /// + /// Write 's doc block and [Obsolete] (if any) on the writer, one + /// line each, at the writer's current indent. Writes nothing when neither attribute is present. + /// + public static void WriteTo(CsWriter w, MetaData node) + { + (string doc, string? obsolete) = Render(node); + if (!string.IsNullOrEmpty(doc)) + { + foreach (var line in doc.Split('\n')) w.Line(line.TrimEnd('\r')); + } + if (obsolete is not null) w.Line(obsolete); + } + /// /// Return with 's doc block + /// [Obsolete] prepended (each line prefixed by ). Returns diff --git a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs index 084d416391..67dc3307ab 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs @@ -21,7 +21,7 @@ // // Mirrors the TS callable generator's stable name ("callable") + return contract. -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Persistence.Source.SourceConstants; @@ -121,13 +121,6 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) var resultType = pkgMode ? ValueObjectNames.GlobalRef(entity, ctx.Config) : cls; var signature = hasArgs ? $"{ctxType} db, {argsType} args" : $"{ctxType} db"; - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects callable-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using System.Threading.Tasks;"); - sb.AppendLine("using Microsoft.EntityFrameworkCore;"); // Package-binding — the callable's home namespace + the args VO's namespace, when split. // The callable file declares a `static class {cls}Callable` referencing the // result type and the args type; both can live in different per-package @@ -140,19 +133,15 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) // pull in usings for both the entity's home and the args object's home when // they differ. var fileNs = ctx.Config.Namespace; - foreach (var ns in new[] { callableNs, argsNs } + var extraUsings = new[] { callableNs, argsNs } .Where(n => !pkgMode) .Where(n => !string.IsNullOrEmpty(n) && n != fileNs) .Distinct(StringComparer.Ordinal) - .OrderBy(n => n, StringComparer.Ordinal)) - { - sb.AppendLine($"using {ns};"); - } - sb.AppendLine(); + .OrderBy(n => n, StringComparer.Ordinal) + .Select(n => n!) + .ToList(); ctx.Claim($"the C# namespace {fileNs}", $"{cls}Callable", entity.ResolutionKey(), "rename one (a callable wrapper is declared in the configured namespace, GenConfig.Namespace, whatever its package, " + "so the two packages do not keep them apart)"); - sb.AppendLine($"namespace {ctx.Config.Namespace};"); - sb.AppendLine(); var kindNoun = source.EffectiveKind == SOURCE_KIND_STORED_PROC ? "stored procedure" : "table function"; // The doc summary names the procedure the same way the SQL does — by the constant on // the names-ON arm (with the schema, when any, still spelled), literally otherwise. @@ -161,21 +150,52 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) var procDoc = procDocMember is null ? $"the {procName} {kindNoun}" : $"the {kindNoun} named by {procDocMember}{(schemaDocMember is null ? "" : $" in schema {schemaDocMember}")}"; - sb.AppendLine("/// "); - sb.AppendLine($"/// FR-015: typed wrapper around {procDoc}. Arguments bind in"); - sb.AppendLine($"/// declaration order from the @parameterRef value-object{(hasArgs ? $" ({argsObjectName})" : string.Empty)}."); - sb.AppendLine("/// "); - sb.AppendLine($"public static class {cls}Callable"); - sb.AppendLine("{"); - sb.AppendLine($" public static async Task> Call({signature})"); - sb.AppendLine(" {"); - sb.AppendLine($" return await db.Set<{resultType}>()"); - sb.AppendLine($" .{fromSql}"); - sb.AppendLine(" .AsNoTracking()"); - sb.AppendLine(" .ToListAsync();"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.callable.g.cs"), sb.ToString()); + + var w = NewWriter(); + WriteFileHeader(w, extraUsings); + w.Blank(); + w.Line($"namespace {fileNs};"); + w.Blank(); + w.DocSummary( + $"FR-015: typed wrapper around {procDoc}. Arguments bind in", + $"declaration order from the @parameterRef value-object{(hasArgs ? $" ({argsObjectName})" : string.Empty)}."); + using (w.Braced($"public static class {cls}Callable")) + { + WriteCall(w, resultType, signature, fromSql); + } + + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.callable.g.cs"), w.ToString()); + } + + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker, the nullable context and the usings, with the namespaces of + /// the result and args types when they are not the file's own. + protected virtual void WriteFileHeader(CsWriter w, IReadOnlyList extraUsings) + { + w.GeneratedFileHeader("callable-generator"); + w.Using("System.Collections.Generic"); + w.Using("System.Threading.Tasks"); + w.Using("Microsoft.EntityFrameworkCore"); + foreach (var ns in extraUsings) w.Using(ns); + } + + /// The Call method: is the FromSql* call that runs the procedure. + protected virtual void WriteCall(CsWriter w, string resultType, string signature, string fromSql) + { + using (w.Braced($"public static async Task> Call({signature})")) + { + w.Line($"return await db.Set<{resultType}>()"); + using (w.Hanging()) + { + w.Line($".{fromSql}"); + w.Line(".AsNoTracking()"); + w.Line(".ToListAsync();"); + } + } } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index fbe963095a..a781e9a712 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -9,6 +9,7 @@ #pragma warning disable CS0618 using System.Text; using MetaObjects.Codegen.Docs; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using MetaObjects.Persistence.Db; using static MetaObjects.Core.Field.FieldConstants; @@ -90,6 +91,10 @@ public static bool AppliesTo(MetaObject obj, MetaRoot root) => /// and mapping. null, the default, accepts every object. See . public Func? Include { get; init; } + /// The writer the context files are written through. Override to hand back a subclass + /// (a different using order, say); every method of the writer is public or protected. + protected virtual CsWriter NewWriter() => new(); + public virtual IEnumerable Generate(GenContext ctx) { ctx = ctx.Narrow(Include); @@ -120,7 +125,7 @@ public virtual IEnumerable Generate(GenContext ctx) } ClaimPhysicalAddresses(objects, ctx); - // OnModelCreating body lines (8-space indented), in a stable order. INVARIANT: each entry is + // OnModelCreating body lines, one statement per entry and none indented (the writer indents each at its place), in a stable order. INVARIANT: each entry is // one complete C# statement — a guard and the statement it guards are ONE entry — because a // large model is split into ConfigureModelNN methods at any entry boundary. var modelLines = new List(); @@ -129,7 +134,7 @@ public virtual IEnumerable Generate(GenContext ctx) // relationships and re-derives the junction FK columns on every call, and both the // junction map below and the per-entity UsingEntity emission need the same answer. // Self-joins are excluded here, in one place rather than two: their navigation is - // [NotMapped] (route-traversed — see EntityGenerator.M2mNavProperty), so they get + // [NotMapped] (route-traversed — see EntityGenerator.WriteM2mNavProperty), so they get // NO UsingEntity call and the junction's own references are the only thing that // can carry their actions. var m2mNavs = new Dictionary>(); @@ -167,7 +172,7 @@ public virtual IEnumerable Generate(GenContext ctx) // narrowed --generators selection. Falls back to the bare literal view name // (p.DbView, non-null in this branch) otherwise -- exactly what this line // emitted before Program A added the constant. - modelLines.Add($" modelBuilder.Entity<{name}>(){noKey}.ToView({CSharpNaming.NameRef(p, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, p.DbView!, qualify: ctx.Config)}{CSharpNaming.ViewSchemaArg(p, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, qualify: ctx.Config)});"); + modelLines.Add($"modelBuilder.Entity<{name}>(){noKey}.ToView({CSharpNaming.NameRef(p, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, p.DbView!, qualify: ctx.Config)}{CSharpNaming.ViewSchemaArg(p, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, qualify: ctx.Config)});"); // Enum-typed projection columns persist as their string symbol in the view // (string-backed enums, CHECK-constrained varchar/text). Without an explicit // string conversion EF defaults to the int-ordinal mapping and reads the text @@ -188,8 +193,8 @@ public virtual IEnumerable Generate(GenContext ctx) continue; } modelLines.Add(f.ResolvedIsArray() - ? $" modelBuilder.Entity<{name}>().PrimitiveCollection(x => x.{PropertyName(f)}).ElementType().{conversion};" - : $" modelBuilder.Entity<{name}>().Property(x => x.{PropertyName(f)}).{conversion};"); + ? $"modelBuilder.Entity<{name}>().PrimitiveCollection(x => x.{PropertyName(f)}).ElementType().{conversion};" + : $"modelBuilder.Entity<{name}>().Property(x => x.{PropertyName(f)}).{conversion};"); } // A field.map column on a view needs its jsonb mapping for the SAME reason: // EntityGenerator emits the Dictionary property for a projection too, so without @@ -234,7 +239,7 @@ public virtual IEnumerable Generate(GenContext ctx) // build an identity column the model never asked for. if (AssignedKeyField(e) is { } assignedKey) modelLines.Add( - $" modelBuilder.Entity<{owner}>().Property(x => x.{PropertyName(assignedKey)}).ValueGeneratedNever();"); + $"modelBuilder.Entity<{owner}>().Property(x => x.{PropertyName(assignedKey)}).ValueGeneratedNever();"); // FR-037 R1 — both non-readWrite modes are excluded from UPDATE, which EF // expresses the same way: SetAfterSaveBehavior(Ignore). They differ on INSERT, @@ -248,7 +253,7 @@ public virtual IEnumerable Generate(GenContext ctx) { var prop = PropertyName(f); modelLines.Add( - $" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);"); + $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);"); } // FR-018 M:N — wire a hetero (source != target) navigation as an EF skip @@ -257,7 +262,7 @@ public virtual IEnumerable Generate(GenContext ctx) // l => l.HasOne().WithMany().HasForeignKey(""), // r => r.HasOne().WithMany().HasForeignKey("")); // Self-joins (directed/symmetric) are [NotMapped] (route-traversed) — see - // EntityGenerator.M2mNavProperty — so they are skipped here. + // EntityGenerator.WriteM2mNavProperty — so they are skipped here. // Self-joins are already excluded from m2mNavs (see above). foreach (var nav in m2mNavs[e]) modelLines.Add(UsingEntityConfig(nav, ctx)); @@ -314,7 +319,7 @@ public virtual IEnumerable Generate(GenContext ctx) var replicaRole = wt.ReplicaSource!.Role; var viewRef = CSharpNaming.NameRef( wt, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, wt.ReplicaViewName!, replicaRole, ctx.Config); - modelLines.Add($" modelBuilder.Entity<{view}>().ToView({viewRef}{CSharpNaming.ViewSchemaArg(wt, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, replicaRole, ctx.Config)});"); + modelLines.Add($"modelBuilder.Entity<{view}>().ToView({viewRef}{CSharpNaming.ViewSchemaArg(wt, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, replicaRole, ctx.Config)});"); // #214 [0] — the read model exposes ALL fields (incl. the derived origin.* fields), // so it needs the SAME per-field TYPE converters the write entity gets, or EF Core // fails model finalization (a field.uri / @dbColumnType:uuid / decimal-precision / @@ -344,6 +349,9 @@ public virtual IEnumerable Generate(GenContext ctx) var written = objects.Where(o => o.IsEntity() && !o.IsReadOnlyProjection()).ToList(); var declaresStart = written.Any(o => IdentityStartOf(o) is not null); var identityStart = IdentityStartOn(ctx) && written.Any(o => IncrementKeyOf(o) is not null); + // A declared start is what a RESTART would hit; a context that only has a JSON column's + // comment to scaffold loses a comment, not ids, so it keeps the warning. + var restartRisk = identityStart && declaresStart; if (declaresStart && !IdentityStartOn(ctx)) ctx.Warn($"{Name}: @sequenceStart is not in the EF model: the project names no Postgres " + "dialect (.metaobjects/config.json migrate.dialect: \"postgres\"; a self-hosted runner sets GenConfig.Dialect), " + @@ -359,87 +367,95 @@ public virtual IEnumerable Generate(GenContext ctx) ctx.Warn($"{Name}: @sequenceName is not in the EF model ({string.Join(", ", namedSequences)}): EF never names an " + "identity's sequence and Npgsql cannot express it. The database keeps the name it has, and meta migrate uses it."); - var sb = new StringBuilder(); - EmitUsings(sb, needsMetadataUsing, ctx); - EmitDbSetDeclarations(sb, objects, ctx); - EmitOnModelCreatingBody(sb, modelLines, ctx); + var w = NewWriter(); + EmitUsings(w, needsMetadataUsing, ctx); + EmitDbSetDeclarations(w, objects, ctx); + EmitOnModelCreatingBody(w, modelLines, ctx); // The model lines are complete here, so the emitted text decides too: a TPH subtype's own // int-backed enum is configured although the subtype is not in `objects`. if (NeedsUnmappedEnumHelper(objects, ctx.Root) || modelLines.Any(l => l.Contains(UnmappedEnumMemberHelperName + "(", StringComparison.Ordinal))) - EmitUnmappedEnumHelper(sb); + EmitUnmappedEnumHelper(w); if (modelLines.Any(l => l.Contains(UnmappedEnumStoredMemberHelperName + "(", StringComparison.Ordinal))) - EmitUnmappedStoredEnumHelper(sb); + EmitUnmappedStoredEnumHelper(w); // Gated on the EMITTED text, not on a second derivation of it. Every site that uses the // helper appends to modelLines (entity, read-only projection, and the flattened-VO member // block, which lands here as one OwnedTypeConfig string), and modelLines is complete by // now — so this is exact by construction. The predicate it replaces had to hand-mirror // three emission sites, and had already been wrong twice: it undercounted them, and it // did not model jsonbObjectsOnly suppressing the flattened arm on a read model. - if (modelLines.Any(l => l.Contains(MapJsonbHelperName))) EmitMapJsonbHelper(sb); - sb.AppendLine("}"); - if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(sb); + if (modelLines.Any(l => l.Contains(MapJsonbHelperName))) EmitMapJsonbHelper(w); + w.Close("}"); + if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(w); // The design-time services also scaffold a JSON column's comment (ruling R59). identityStart |= IdentityStartOn(ctx) && modelLines.Any(l => l.Contains(JsonColumnCommentAnnotation, StringComparison.Ordinal)); - if (!identityStart) return [new EmittedFile("AppDbContext.g.cs", sb.ToString())]; + if (!identityStart) return [new EmittedFile("AppDbContext.g.cs", w.ToString())]; var contextName = ContextClassName(ctx); var services = contextName + DesignTimeServicesSuffix; - return [new EmittedFile("AppDbContext.g.cs", sb.ToString()), new EmittedFile($"{services}.g.cs", DesignTimeServicesFile(ctx, contextName, services))]; + return [new EmittedFile("AppDbContext.g.cs", w.ToString()), new EmittedFile($"{services}.g.cs", DesignTimeServicesFile(ctx, contextName, services, restartRisk))]; } /// - /// Extension hook — emits the file header, usings, namespace, and the opening of + /// Extension hook — writes the file header, usings, namespace, and the opening of /// the public class AppDbContext : DbContext declaration through its primary /// constructor and any (leaving the class body open for /// + ; the caller - /// emits the closing }). The shell is assembled from , + /// writes the closing }, so an override must open the class with w.Open("{")). + /// The shell is assembled from , /// , , /// and , so changing one of them needs no copy of this body. /// is true when a @readOnly field - /// requires the Microsoft.EntityFrameworkCore.Metadata import. The default - /// body reproduces the inline emission, so default output is byte-identical. - /// Override to add usings, a base interface, or class-level attributes. + /// requires the Microsoft.EntityFrameworkCore.Metadata import. The writer owns indentation, + /// braces and blank lines. Override to add usings, a base interface, or class-level attributes. /// - protected virtual void EmitUsings(StringBuilder sb, bool needsMetadataUsing, GenContext ctx) + protected virtual void EmitUsings(CsWriter w, bool needsMetadataUsing, GenContext ctx) { - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects dbcontext-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); + w.GeneratedFileHeader("dbcontext-generator"); var dbCtxNs = ContextNamespace(ctx); _usingSite = (needsMetadataUsing, dbCtxNs); try { foreach (var line in ContextUsings(ctx)) { - sb.AppendLine(line); + WriteUsingDirective(w, line); } } finally { _usingSite = null; } - sb.AppendLine(); - sb.AppendLine($"namespace {dbCtxNs};"); - sb.AppendLine(); + w.Line($"namespace {dbCtxNs};"); + w.Blank(); var name = ContextClassName(ctx); - sb.AppendLine($"public {(ContextIsPartial(ctx) ? "partial " : "")}class {name} : {ContextBaseClass(ctx)}"); - sb.AppendLine("{"); + w.Line($"public {(ContextIsPartial(ctx) ? "partial " : "")}class {name} : {ContextBaseClass(ctx)}"); + w.Open("{"); if (EmitContextConstructor(ctx)) { - sb.AppendLine($" public {name}(DbContextOptions<{name}> options) : base(options) {{ }}"); - sb.AppendLine(); + w.Line($"public {name}(DbContextOptions<{name}> options) : base(options) {{ }}"); + w.Blank(); } var members = ContextMemberLines(ctx).ToList(); foreach (var line in members) { - sb.AppendLine(line); + w.Text(line); } if (members.Count > 0) { - sb.AppendLine(); + w.Blank(); } } + // A `using X;` / `using static X;` / `using A = B;` line is recorded on the writer, which prints the block + // once, in the order named. A line of any other shape is written as a header line, as given. + private static void WriteUsingDirective(CsWriter w, string line) + { + var directive = line.Trim(); + if (directive.StartsWith("using ", StringComparison.Ordinal) && directive.EndsWith(';')) + w.Using(directive["using ".Length..^1]); + else + w.Header(directive); + } + // What EmitUsings knows that ContextUsings' signature does not carry: whether a read-only field // needs the Metadata namespace, and the namespace the context is declared in (asked once, of // ContextNamespace). Null when ContextUsings is called on its own. @@ -507,7 +523,7 @@ protected virtual IEnumerable ContextUsings(GenContext ctx) protected virtual bool ContextIsPartial(GenContext ctx) => false; /// - /// Hook — extra class members, as complete lines (4-space indent included), placed after the + /// Hook — extra class members, as complete lines (unindented: the writer indents them), placed after the /// constructor and before the DbSet declarations; a blank line follows them when there /// are any. Default none. An adopter declares a partial method here /// (partial void OnModelCreatingExtensions(ModelBuilder modelBuilder);) that its @@ -521,20 +537,20 @@ protected virtual IEnumerable ContextUsings(GenContext ctx) /// . The default body reproduces the inline emission, so /// default output is byte-identical. /// - protected virtual void EmitDbSetDeclarations(StringBuilder sb, IReadOnlyList objects, GenContext ctx) + protected virtual void EmitDbSetDeclarations(CsWriter w, IReadOnlyList objects, GenContext ctx) { foreach (var o in objects) { var name = CSharpNaming.Pascal(o.Name); - XmlDocBuilder.AppendTo(sb, o, indent: " "); - sb.AppendLine(DbSetLine(o, ctx)); + XmlDocBuilder.WriteTo(w, o); + w.Text(DbSetLine(o, ctx)); // #214 — a write-through entity additionally exposes a read-model DbSet mapped to // its replica view (reads route here; the derived fields live on the view row). if (o.IsWriteThrough()) { var view = ValueObjectNames.RefOf(o, ctx.Config, CSharpNaming.ViewModelClassName(o)); - sb.AppendLine($" /// Read-model view for write-through entity {name} (reads route here; carries the derived fields)."); - sb.AppendLine($" public DbSet<{view}> {CSharpNaming.ViewDbSetName(o)} {{ get; set; }} = default!;"); + w.Line($"/// Read-model view for write-through entity {name} (reads route here; carries the derived fields)."); + w.Line($"public DbSet<{view}> {CSharpNaming.ViewDbSetName(o)} {{ get; set; }} = default!;"); } } } @@ -553,7 +569,7 @@ protected virtual void EmitDbSetDeclarations(StringBuilder sb, IReadOnlyList public int ModelConfigChunkSize { get; init; } = 200; - protected virtual void EmitOnModelCreatingBody(StringBuilder sb, IReadOnlyList modelLines, GenContext ctx) + protected virtual void EmitOnModelCreatingBody(CsWriter w, IReadOnlyList modelLines, GenContext ctx) { // Materialized once: a hook may enumerate lazily, and each is asked exactly once per context. var preamble = ContextPreambleLines(ctx).ToList(); @@ -562,42 +578,39 @@ protected virtual void EmitOnModelCreatingBody(StringBuilder sb, IReadOnlyList ModelConfigChunkSize; + var chunks = split ? modelLines.Chunk(Math.Max(1, ModelConfigChunkSize)).ToList() : []; + using (w.Braced("protected override void OnModelCreating(ModelBuilder modelBuilder)")) { - sb.AppendLine(line); - } - if (modelLines.Count <= ModelConfigChunkSize) - { - foreach (var line in modelLines) sb.AppendLine(line); + // Order is part of the contract: preamble first, the model lines (or the ConfigureModelNN + // calls that stand for them) in order, trailer last. + foreach (var line in preamble) + { + w.Text(line); + } + if (!split) + { + foreach (var line in modelLines) w.Text(line); + } + for (var i = 0; i < chunks.Count; i++) + { + w.Line($"ConfigureModel{i + 1:D2}(modelBuilder);"); + } foreach (var line in trailer) { - sb.AppendLine(line); + w.Text(line); } - sb.AppendLine(" }"); - return; } - var chunks = modelLines.Chunk(Math.Max(1, ModelConfigChunkSize)).ToList(); for (var i = 0; i < chunks.Count; i++) { - sb.AppendLine($" ConfigureModel{i + 1:D2}(modelBuilder);"); - } - foreach (var line in trailer) - { - sb.AppendLine(line); - } - sb.AppendLine(" }"); - for (var i = 0; i < chunks.Count; i++) - { - sb.AppendLine(); - sb.AppendLine($" private void ConfigureModel{i + 1:D2}(ModelBuilder modelBuilder)"); - sb.AppendLine(" {"); - foreach (var line in chunks[i]) sb.AppendLine(line); - sb.AppendLine(" }"); + w.Blank(); + using (w.Braced($"private void ConfigureModel{i + 1:D2}(ModelBuilder modelBuilder)")) + { + foreach (var line in chunks[i]) w.Text(line); + } } } @@ -608,7 +621,7 @@ protected virtual void EmitOnModelCreatingBody(StringBuilder sb, IReadOnlyList "DbContext"; /// - /// Hook — complete lines (8-space indent included, as modelLines are) placed FIRST in + /// Hook — complete lines (unindented, as modelLines are) placed FIRST in /// OnModelCreating, before any model configuration or ConfigureModelNN call. /// Default none. An adopter returns base.OnModelCreating(modelBuilder); here. /// These lines are NOT scanned when the file decides whether it needs the PropertySaveBehavior @@ -632,14 +645,14 @@ protected virtual void EmitOnModelCreatingBody(StringBuilder sb, IReadOnlyList false; /// - /// Hook — the whole DbSet declaration line for an entity (indent included), so an + /// Hook — the whole DbSet declaration line for an entity (unindented), so an /// override can add virtual or change the name. The XML doc above it is emitted by the /// caller. A write-through entity's read-model DbSet is not routed through here. /// protected virtual string DbSetLine(MetaObject entity, GenContext ctx) { var name = ValueObjectNames.Ref(entity, ctx.Config); - return $" public DbSet<{name}> {DbSetPropertyName(entity, ctx)} {{ get; set; }} = default!;"; + return $"public DbSet<{name}> {DbSetPropertyName(entity, ctx)} {{ get; set; }} = default!;"; } /// @@ -674,7 +687,7 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) protected virtual string? DbColumnTypeConfig(string owner, MetaField f) { var prop = PropertyName(f); - var lhs = $" modelBuilder.Entity<{owner}>().Property(x => x.{prop})"; + var lhs = $"modelBuilder.Entity<{owner}>().Property(x => x.{prop})"; return f.DbColumnType switch { // `v!` is safe even for a nullable `string?` property: EF Core skips @@ -727,7 +740,7 @@ private string HasDiscriminatorConfig(string owner, MetaObject baseEntity, TphPl : null; var sb = new StringBuilder(); - sb.Append($" modelBuilder.Entity<{owner}>().HasDiscriminator(e => e.{discProp})"); + sb.Append($"modelBuilder.Entity<{owner}>().HasDiscriminator(e => e.{discProp})"); foreach (var st in tph.Subtypes) { var subCls = ValueObjectNames.Ref(st.Entity, config); @@ -896,7 +909,7 @@ protected virtual IEnumerable DefaultValueConfig(MetaObject entity, Meta { return []; } - var lhs = $" modelBuilder.Entity<{className}>().Property(x => x.{PropertyName(f)})"; + var lhs = $"modelBuilder.Entity<{className}>().Property(x => x.{PropertyName(f)})"; if (DefaultLiteral(className, entity, f, raw, ctx.Config) is { } literal) { return [$"{lhs}.HasDefaultValue({literal}).HasSentinel({literal});"]; @@ -964,7 +977,7 @@ private void EmitIdentityStartConfig(string owner, MetaObject entity, List().Property(x => x.{PropertyName(start.Field)}).HasAnnotation(" + + modelLines.Add($"if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().Property(x => x.{PropertyName(start.Field)}).HasAnnotation(" + $"\"{NpgsqlIdentityOptionsAnnotation}\", \"'{start.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)}', '1', '', '', 'False', '1'\");"); } @@ -979,12 +992,14 @@ protected virtual void EmitCheckConfig(string owner, MetaObject entity, GenConte { if (entity.DbTable is null) return; foreach (var check in CheckConstraints.For(entity, ctx.Config)) - modelLines.Add($" modelBuilder.Entity<{owner}>().ToTable(t => t.HasCheckConstraint(\"{CSharpNaming.CSharpStringLiteral(check.Name)}\", " + + modelLines.Add($"modelBuilder.Entity<{owner}>().ToTable(t => t.HasCheckConstraint(\"{CSharpNaming.CSharpStringLiteral(check.Name)}\", " + $"\"{CSharpNaming.CSharpStringLiteral(check.Expression)}\"));"); } private const string NpgsqlIdentityOptionsAnnotation = "Npgsql:IdentitySequenceOptions"; private const string DesignTimeServicesSuffix = "DesignTimeServices"; + /// The generation error for a context whose migrations project provably lacks the design-time services reference. + public const string ErrDesignTimeReferenceMissing = "ERR_DESIGN_TIME_REFERENCE_MISSING"; /// /// Whether this run emits @sequenceStart and the design-time services: the project's @@ -1031,7 +1046,7 @@ private static (MetaField Field, long Value)? IdentityStartOf(MetaObject entity) /// (), so EF's default layout, where the migrations /// live in the context's assembly, needs no adopter code. /// - private string DesignTimeServicesFile(GenContext ctx, string contextName, string className) + private string DesignTimeServicesFile(GenContext ctx, string contextName, string className, bool restartRisk) { var ns = ContextNamespace(ctx); var assembly = ctx.Config.ContextAssemblyName; @@ -1046,31 +1061,34 @@ private string DesignTimeServicesFile(GenContext ctx, string contextName, string $"only when the context's project is the startup project; {consequence}. " + $"Add [assembly: DesignTimeServicesReference(\"{ns}.{className}, \")] to the migrations or startup project."); } - else if (DesignTimeServicesReferences.Warning(ctx.Config, Name, contextName, $"{ns}.{className}", line, consequence) is { } warning) - { - // rc.19 fix round (I4): EF reads the reference only from the startup and migrations - // assemblies, so the one generated here is read only when this project holds the - // migrations. The run warns whenever that cannot be proved, with the line to add. - ctx.Warn(warning); - } - return $$""" - // - // Generated by MetaObjects db-context. Do not edit by hand. - #nullable enable - using System; - using System.Collections.Generic; - using System.Linq; - using Microsoft.EntityFrameworkCore; - using Microsoft.EntityFrameworkCore.Design; - using Microsoft.EntityFrameworkCore.Infrastructure; - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - using Microsoft.EntityFrameworkCore.Migrations.Operations; - using Microsoft.EntityFrameworkCore.Storage; - using Microsoft.Extensions.DependencyInjection; - {{(assembly is null ? "" : "\n" + reference + "\n")}} - namespace {{ns}}; - + else + { + // EF reads the reference only from the startup and migrations assemblies, so the one + // generated here is read only when this project holds the migrations. When the migrations + // are PROVEN to be elsewhere without the line, the next scaffold of a start-only change is a + // RESTART that hands out ids live rows hold: that is an error, not a warning. A run that + // cannot prove it either way (no snapshot on disk yet) warns with the line to add. + var (message, missing) = DesignTimeServicesReferences.Check(ctx.Config, Name, contextName, $"{ns}.{className}", line, consequence); + if (message is not null && missing && restartRisk) + throw new InvalidOperationException($"{ErrDesignTimeReferenceMissing}: {message}"); + if (message is not null) ctx.Warn(message); + } + var w = NewWriter(); + w.GeneratedFileHeader("db-context"); + foreach (var used in new[] + { + "System", "System.Collections.Generic", "System.Linq", "Microsoft.EntityFrameworkCore", + "Microsoft.EntityFrameworkCore.Design", "Microsoft.EntityFrameworkCore.Infrastructure", + "Microsoft.EntityFrameworkCore.Metadata", "Microsoft.EntityFrameworkCore.Migrations", + "Microsoft.EntityFrameworkCore.Migrations.Operations", "Microsoft.EntityFrameworkCore.Storage", + "Microsoft.Extensions.DependencyInjection", + }) + w.Using(used); + if (assembly is not null) w.Line(reference); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Text($$""" /// Design-time only: a start-only identity change scaffolds as SQL that records the /// start and moves the counter forward to it, never back, instead of Npgsql's RESTART; and a /// JSON column's comment, which EF 8 cannot carry, scaffolds as COMMENT ON COLUMN. EF runs @@ -1254,7 +1272,8 @@ public static class {{contextName}}IdentityStartMigrations public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) where TContext : DbContext => options; } - """ + "\n"; + """); + return w.ToString(); } /// @@ -1267,7 +1286,7 @@ private void EmitCommentConfig(string owner, MetaObject entity, IEnumerable 0 } table) - modelLines.Add($" modelBuilder.Entity<{owner}>().Metadata.SetComment(\"{CSharpNaming.CSharpStringLiteral(table)}\");"); + modelLines.Add($"modelBuilder.Entity<{owner}>().Metadata.SetComment(\"{CSharpNaming.CSharpStringLiteral(table)}\");"); foreach (var f in fields) { var vo = f.SubType == FIELD_SUBTYPE_OBJECT ? ValueObjectNames.ResolveFieldRef(f, ctx.Root) as MetaObject : null; @@ -1292,7 +1311,7 @@ private void EmitCommentConfig(string owner, MetaObject entity, IEnumerable().Metadata.GetProperty(\"{PropertyName(f)}\").SetComment(\"{literal}\");"); + modelLines.Add($"modelBuilder.Entity<{owner}>().Metadata.GetProperty(\"{PropertyName(f)}\").SetComment(\"{literal}\");"); continue; } if (mapping == ObjectFieldMapping.Unknown) @@ -1307,13 +1326,13 @@ private void EmitCommentConfig(string owner, MetaObject entity, IEnumerable().Metadata.FindNavigation(\"{PropertyName(f)}\")!.TargetEntityType" + + modelLines.Add($"modelBuilder.Entity<{owner}>().Metadata.FindNavigation(\"{PropertyName(f)}\")!.TargetEntityType" + $".SetAnnotation(\"{JsonColumnCommentAnnotation}\", \"{literal}\");"); continue; } } // GetProperty, not FindProperty?.: a property this generator configures and cannot find is a bug, said loudly. - modelLines.Add($" modelBuilder.Entity<{owner}>().Metadata.GetProperty(\"{PropertyName(f)}\").SetComment(\"{literal}\");"); + modelLines.Add($"modelBuilder.Entity<{owner}>().Metadata.GetProperty(\"{PropertyName(f)}\").SetComment(\"{literal}\");"); } } @@ -1366,7 +1385,7 @@ private void EmitIndexConfig(string owner, MetaObject entity, GenContext ctx, Li // ADR-0039: resolving — @unique may be inherited via extends. if (f.Attr(FIELD_ATTR_UNIQUE) is not true || f.ResolvedIsArray()) continue; var column = CSharpNaming.Column(f, ctx.Config.ColumnNamingStrategy); - modelLines.Add($" modelBuilder.Entity<{owner}>().HasIndex(x => x.{PropertyName(f)}).IsUnique()" + + modelLines.Add($"modelBuilder.Entity<{owner}>().HasIndex(x => x.{PropertyName(f)}).IsUnique()" + $".HasDatabaseName(\"{CSharpNaming.CSharpStringLiteral(ForeignKeyIndexes.StoredName($"{table}_{column}_unique", ctx.Config.Dialect))}\");"); } var nodes = entity.SecondaryIdentities().Select(i => ((MetaData)i, i.Fields, true)) @@ -1392,7 +1411,7 @@ private void EmitIndexConfig(string owner, MetaObject entity, GenContext ctx, Li var selector = props.Count == 1 ? $"x => x.{props[0]}" : $"x => new {{ {string.Join(", ", props.Select(p => "x." + p))} }}"; // The NAMED overload: two indexes over one column list (a partial one beside a plain // one) are two EF indexes only when each carries its own name. - var line = new StringBuilder($" modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})"); + var line = new StringBuilder($"modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})"); if (unique) line.Append(".IsUnique()"); if (node.Attr(DbConstants.IDENTITY_ATTR_WHERE) is string where && where.Trim().Length > 0) line.Append($".HasFilter(\"{CSharpNaming.CSharpStringLiteral(where.Trim())}\")"); @@ -1408,7 +1427,7 @@ private void EmitIndexConfig(string owner, MetaObject entity, GenContext ctx, Li if (node.Attr(DbConstants.IDENTITY_ATTR_USING) is string method && method.Trim().Length > 0 && method.Trim() != "btree") { // One entry per statement (the modelLines invariant): the guard and its statement are one line. - modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})" + + modelLines.Add($"if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().HasIndex({selector}, {indexName})" + $".HasAnnotation(\"Npgsql:IndexMethod\", \"{CSharpNaming.CSharpStringLiteral(method.Trim())}\");"); } } @@ -1426,7 +1445,7 @@ private void EmitForeignKeyIndexConfig(MetaObject entity, TphPlan? tph, GenConte var name = $"\"{CSharpNaming.CSharpStringLiteral(index.Name)}\""; var props = index.Fields.Select(PropertyName).ToList(); var selector = props.Count == 1 ? $"x => x.{props[0]}" : $"x => new {{ {string.Join(", ", props.Select(p => "x." + p))} }}"; - modelLines.Add($" modelBuilder.Entity<{ValueObjectNames.Ref(index.Owner, ctx.Config)}>().HasIndex({selector}, {name}).HasDatabaseName({name});"); + modelLines.Add($"modelBuilder.Entity<{ValueObjectNames.Ref(index.Owner, ctx.Config)}>().HasIndex({selector}, {name}).HasDatabaseName({name});"); } } @@ -1538,7 +1557,7 @@ protected virtual IEnumerable TphSubtypeFieldConfig(MetaObject root, Met foreach (var f in own.Where(f => !f.ResolvedIsArray() && f.Mutability != MUTABILITY_READ_WRITE)) { lines.Add( - $" modelBuilder.Entity<{cls}>().Property(x => x.{PropertyName(f)}).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);"); + $"modelBuilder.Entity<{cls}>().Property(x => x.{PropertyName(f)}).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);"); } // The shared table's comment is the root's; a subtype's own columns carry theirs. EmitCommentConfig(cls, subtype, own, lines, ctx, tableComment: false); @@ -1563,7 +1582,7 @@ private void EmitShapeInheritedFacets( || TphPlanBuilder.IsTphMember(parent, ctx.Root)) return; var shapeDeclared = new HashSet(parent.Fields().Select(f => f.Name), StringComparer.Ordinal); - var lhs = $" modelBuilder.Entity<{className}>()"; + var lhs = $"modelBuilder.Entity<{className}>()"; if (entity.PrimaryIdentity()?.Fields is [var keyName] && shapeDeclared.Contains(keyName) && entity.FindField(keyName) is { } keyField) @@ -1661,7 +1680,7 @@ protected virtual IEnumerable ReferenceConfig( } var actions = ReferentialActions.Resolve(entity, reference); - return [$" modelBuilder.Entity<{owner}>().HasOne<{ValueObjectNames.Ref(target, ctx.Config)}>()" + return [$"modelBuilder.Entity<{owner}>().HasOne<{ValueObjectNames.Ref(target, ctx.Config)}>()" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) + $"{OnDeleteCall(entity, fkFields, actions.OnDelete, ctx)}" @@ -1720,7 +1739,7 @@ private IEnumerable FlattenedMemberReferenceConfig( var navigation = siblings > 0 ? $"{byFk}?.Name" : $"({linq}.Count({toTarget}) == 0 ? null : {linq}.Count({toTarget}) == 1 ? {linq}.First({toTarget}) : ({byFk} ?? throw {ambiguous}))?.Name"; - return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + return [$"modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) + $"{OnDeleteCall(entity, fkFields, actions.OnDelete, ctx)}" @@ -1888,7 +1907,7 @@ private string UsingEntityConfig(M2MNavigation nav, GenContext ctx) // property instead of the type. The inner parameter cannot reuse the outer `l`/`r` (CS0136), // hence `j` — it is the junction being configured on both sides. return - $" modelBuilder.Entity<{source}>().HasMany(x => x.{navProp}).WithMany().UsingEntity<{through}>(" + + $"modelBuilder.Entity<{source}>().HasMany(x => x.{navProp}).WithMany().UsingEntity<{through}>(" + $"l => l.HasOne<{target}>().WithMany().HasForeignKey({ForeignKeyExpression("j", [targetFkProp])}){targetOnDelete}, " + $"r => r.HasOne<{source}>().WithMany().HasForeignKey({ForeignKeyExpression("j", [sourceFkProp])}){sourceOnDelete});"; } @@ -1921,26 +1940,28 @@ private string UsingEntityConfig(M2MNavigation nav, GenContext ctx) /// rc.21 — the fail-fast helpers a @stringValueMap enum's converters end in, emitted only /// when a converter references them (so a model with none is byte-identical). /// - private static void EmitUnmappedStoredEnumHelper(StringBuilder sb) + private static void EmitUnmappedStoredEnumHelper(CsWriter w) { - sb.AppendLine(); - sb.AppendLine(" /// "); - sb.AppendLine(" /// A field.enum column with @stringValueMap held a string that maps to no member: the"); - sb.AppendLine(" /// database holds data the model says is impossible."); - sb.AppendLine(" /// "); - sb.AppendLine($" private static T {UnmappedEnumStoredValueHelperName}(string stored, string field) =>"); - sb.AppendLine(" throw new System.InvalidOperationException("); - sb.AppendLine(" $\"field.enum '{field}' read stored value '{stored}' with no member in \" +"); - sb.AppendLine(" \"@stringValueMap — the database holds a value the model does not describe.\");"); - sb.AppendLine(); - sb.AppendLine(" /// "); - sb.AppendLine(" /// A field.enum property with @stringValueMap held a value outside @values: it has no"); - sb.AppendLine(" /// declared stored string, and writing another member's would corrupt the row silently."); - sb.AppendLine(" /// "); - sb.AppendLine($" private static string {UnmappedEnumStoredMemberHelperName}(object? value, string field) =>"); - sb.AppendLine(" throw new System.InvalidOperationException("); - sb.AppendLine(" $\"field.enum '{field}' cannot write {value}: it has no stored string in \" +"); - sb.AppendLine(" \"@stringValueMap — the value is not one of the members the model declares.\");"); + w.Blank(); + w.Text($$""" + /// + /// A field.enum column with @stringValueMap held a string that maps to no member: the + /// database holds data the model says is impossible. + /// + private static T {{UnmappedEnumStoredValueHelperName}}(string stored, string field) => + throw new System.InvalidOperationException( + $"field.enum '{field}' read stored value '{stored}' with no member in " + + "@stringValueMap — the database holds a value the model does not describe."); + + /// + /// A field.enum property with @stringValueMap held a value outside @values: it has no + /// declared stored string, and writing another member's would corrupt the row silently. + /// + private static string {{UnmappedEnumStoredMemberHelperName}}(object? value, string field) => + throw new System.InvalidOperationException( + $"field.enum '{field}' cannot write {value}: it has no stored string in " + + "@stringValueMap — the value is not one of the members the model declares."); + """); } /// @@ -1948,31 +1969,33 @@ private static void EmitUnmappedStoredEnumHelper(StringBuilder sb) /// in. Emitted only when at least one such converter was generated, so a model with /// no @intValueMap produces byte-identical output. /// - private static void EmitUnmappedEnumHelper(StringBuilder sb) + private static void EmitUnmappedEnumHelper(CsWriter w) { - sb.AppendLine(); - sb.AppendLine(" /// "); - sb.AppendLine(" /// An int-backed field.enum column held a value that maps to no member: the"); - sb.AppendLine(" /// database holds data the model says is impossible (a hand-written INSERT, or a"); - sb.AppendLine(" /// member removed without a migration). Materializing the last member instead"); - sb.AppendLine(" /// would hand the caller a wrong-but-valid value, silently."); - sb.AppendLine(" /// "); - sb.AppendLine($" private static T {UnmappedEnumHelperName}(int stored, string field) =>"); + w.Blank(); // Fully qualified: the generated file's usings are a fixed set (EmitUsings), and // adding `using System;` there would change byte-identical output for every model. - sb.AppendLine(" throw new System.InvalidOperationException("); - sb.AppendLine(" $\"field.enum '{field}' read stored value {stored} with no member in \" +"); - sb.AppendLine(" \"@intValueMap — the database holds a value the model does not describe.\");"); - sb.AppendLine(); - sb.AppendLine(" /// "); - sb.AppendLine(" /// An int-backed field.enum property held a value outside @values (a cast integer, or"); - sb.AppendLine(" /// a member the C# enum declares that the metadata does not): it has no declared"); - sb.AppendLine(" /// integer, and writing some other member's instead would corrupt the row silently."); - sb.AppendLine(" /// "); - sb.AppendLine($" private static int {UnmappedEnumMemberHelperName}(object? value, string field) =>"); - sb.AppendLine(" throw new System.InvalidOperationException("); - sb.AppendLine(" $\"field.enum '{field}' cannot write {value}: it has no integer in \" +"); - sb.AppendLine(" \"@intValueMap — the value is not one of the members the model declares.\");"); + w.Text($$""" + /// + /// An int-backed field.enum column held a value that maps to no member: the + /// database holds data the model says is impossible (a hand-written INSERT, or a + /// member removed without a migration). Materializing the last member instead + /// would hand the caller a wrong-but-valid value, silently. + /// + private static T {{UnmappedEnumHelperName}}(int stored, string field) => + throw new System.InvalidOperationException( + $"field.enum '{field}' read stored value {stored} with no member in " + + "@intValueMap — the database holds a value the model does not describe."); + + /// + /// An int-backed field.enum property held a value outside @values (a cast integer, or + /// a member the C# enum declares that the metadata does not): it has no declared + /// integer, and writing some other member's instead would corrupt the row silently. + /// + private static int {{UnmappedEnumMemberHelperName}}(object? value, string field) => + throw new System.InvalidOperationException( + $"field.enum '{field}' cannot write {value}: it has no integer in " + + "@intValueMap — the value is not one of the members the model declares."); + """); } /// @@ -1982,7 +2005,7 @@ private static void EmitUnmappedEnumHelper(StringBuilder sb) /// a Dictionary<string, V> property and so both need the mapping. /// private string MapJsonbConfig(string className, MetaObject owner, MetaField f, GenContext ctx) => - $" modelBuilder.Entity<{className}>().Property(x => x.{PropertyName(f)})" + $"modelBuilder.Entity<{className}>().Property(x => x.{PropertyName(f)})" + MapJsonbSuffix(owner, f, ctx) + ";"; /// @@ -2070,100 +2093,102 @@ private static string MapValueTypeRef(MetaField f, GenContext ctx) /// untranslated and never invokes the expressions on it, so the lambdas' bodies are /// unchanged. /// - private static void EmitMapJsonbHelper(StringBuilder sb) + private static void EmitMapJsonbHelper(CsWriter w) { - sb.AppendLine(); - sb.AppendLine(" /// "); - sb.AppendLine(" /// Shared jsonb (de)serialization for field.map columns. The comparer is required:"); - sb.AppendLine(" /// EF snapshots a value-converted property by reference, so without it an in-place"); - sb.AppendLine(" /// edit to the dictionary is never detected and the row is never updated."); - sb.AppendLine(" /// "); - sb.AppendLine($" private static class {MapJsonbHelperName}"); - sb.AppendLine(" {"); - sb.AppendLine(" private static readonly System.Text.Json.JsonSerializerOptions Options = new()"); - sb.AppendLine(" {"); - sb.AppendLine(" Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }"); - sb.AppendLine(" };"); - sb.AppendLine(); - sb.AppendLine(" internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<"); - sb.AppendLine(" System.Collections.Generic.Dictionary, string> RequiredConverter() => new("); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Serialize(v, Options),"); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Deserialize<"); - sb.AppendLine(" System.Collections.Generic.Dictionary>(v, Options)!);"); - sb.AppendLine(); - sb.AppendLine(" /// Same conversion as RequiredConverter, over the NULLABLE dictionary a"); - sb.AppendLine(" /// non-required map's property carries — keep the two bodies identical. EF Core's"); - sb.AppendLine(" /// nullability-aware HasConversion checks the converter's model type against the"); - sb.AppendLine(" /// property's own annotation, so one factory cannot serve both arms."); - sb.AppendLine(" internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<"); - sb.AppendLine(" System.Collections.Generic.Dictionary?, string> Converter() => new("); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Serialize(v, Options),"); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Deserialize<"); - sb.AppendLine(" System.Collections.Generic.Dictionary>(v, Options)!);"); - sb.AppendLine(); + w.Blank(); // A value object that holds a map is stored as ONE document converted whole: EF Core 8 cannot // map a Dictionary member inside an owned-JSON type. The same Options serve it, so // a decimal member keeps its canonical-string wire form (DecimalWire.Declared on the member). - sb.AppendLine(" /// A whole value-object document (or collection of them) as one jsonb value,"); - sb.AppendLine(" /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON)."); - sb.AppendLine(" internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new("); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Serialize(v, Options),"); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Deserialize(v, Options)!);"); - sb.AppendLine(); - sb.AppendLine(" internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new("); - sb.AppendLine(" (a, b) => System.Text.Json.JsonSerializer.Serialize(a, Options) == System.Text.Json.JsonSerializer.Serialize(b, Options),"); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(),"); - sb.AppendLine(" v => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!);"); - sb.AppendLine(); - sb.AppendLine(" internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer<"); - sb.AppendLine(" System.Collections.Generic.Dictionary?> Comparer() => new("); - sb.AppendLine(" (a, b) => Eq(a, b), v => Hash(v), v => Snap(v));"); - sb.AppendLine(); - sb.AppendLine(" /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key"); - sb.AppendLine(" /// order holds the same value, and comparing serialized JSON would call it changed"); - sb.AppendLine(" /// and issue an UPDATE for a row nothing touched. Scalars settle on the default"); - sb.AppendLine(" /// comparer (no serialization at all); a value-object value falls through to a JSON"); - sb.AppendLine(" /// compare, since the generated POCO is a class and compares by reference."); - sb.AppendLine(" private static bool Eq("); - sb.AppendLine(" System.Collections.Generic.Dictionary? a,"); - sb.AppendLine(" System.Collections.Generic.Dictionary? b)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (a is null || b is null) return ReferenceEquals(a, b);"); - sb.AppendLine(" if (a.Count != b.Count) return false;"); - sb.AppendLine(" foreach (var kv in a)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!b.TryGetValue(kv.Key, out var other)) return false;"); - sb.AppendLine(" if (System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue;"); - sb.AppendLine(" if (System.Text.Json.JsonSerializer.Serialize(kv.Value, Options)"); - sb.AppendLine(" != System.Text.Json.JsonSerializer.Serialize(other, Options)) return false;"); - sb.AppendLine(" }"); - sb.AppendLine(" return true;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" /// Keys and count only — order-independent (XOR), allocation-free, and"); - sb.AppendLine(" /// stable for a value-object value whose GetHashCode is reference-based. Equal"); - sb.AppendLine(" /// dictionaries always hash equal, which is all EF requires."); - sb.AppendLine(" private static int Hash(System.Collections.Generic.Dictionary? v)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (v is null) return 0;"); - sb.AppendLine(" var h = v.Count;"); - sb.AppendLine(" foreach (var k in v.Keys) h ^= k.GetHashCode();"); - sb.AppendLine(" return h;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" /// The change-tracking snapshot. A value-object value needs a DEEP copy or"); - sb.AppendLine(" /// an in-place edit to a nested object mutates the snapshot too and goes undetected;"); - sb.AppendLine(" /// an immutable scalar only needs the dictionary copied."); - sb.AppendLine(" private static System.Collections.Generic.Dictionary? Snap("); - sb.AppendLine(" System.Collections.Generic.Dictionary? v) =>"); - sb.AppendLine(" v is null"); - sb.AppendLine(" ? null"); - sb.AppendLine(" : typeof(TValue).IsValueType || typeof(TValue) == typeof(string)"); - sb.AppendLine(" ? new System.Collections.Generic.Dictionary(v)"); - sb.AppendLine(" : System.Text.Json.JsonSerializer.Deserialize<"); - sb.AppendLine(" System.Collections.Generic.Dictionary>("); - sb.AppendLine(" System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!;"); - sb.AppendLine(" }"); + w.Text($$""" + /// + /// Shared jsonb (de)serialization for field.map columns. The comparer is required: + /// EF snapshots a value-converted property by reference, so without it an in-place + /// edit to the dictionary is never detected and the row is never updated. + /// + private static class {{MapJsonbHelperName}} + { + private static readonly System.Text.Json.JsonSerializerOptions Options = new() + { + Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } + }; + + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + System.Collections.Generic.Dictionary, string> RequiredConverter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>(v, Options)!); + + /// Same conversion as RequiredConverter, over the NULLABLE dictionary a + /// non-required map's property carries — keep the two bodies identical. EF Core's + /// nullability-aware HasConversion checks the converter's model type against the + /// property's own annotation, so one factory cannot serve both arms. + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + System.Collections.Generic.Dictionary?, string> Converter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>(v, Options)!); + + /// A whole value-object document (or collection of them) as one jsonb value, + /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON). + internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( + v => System.Text.Json.JsonSerializer.Serialize(v, Options), + v => System.Text.Json.JsonSerializer.Deserialize(v, Options)!); + + internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( + (a, b) => System.Text.Json.JsonSerializer.Serialize(a, Options) == System.Text.Json.JsonSerializer.Serialize(b, Options), + v => System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), + v => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); + + internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< + System.Collections.Generic.Dictionary?> Comparer() => new( + (a, b) => Eq(a, b), v => Hash(v), v => Snap(v)); + + /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key + /// order holds the same value, and comparing serialized JSON would call it changed + /// and issue an UPDATE for a row nothing touched. Scalars settle on the default + /// comparer (no serialization at all); a value-object value falls through to a JSON + /// compare, since the generated POCO is a class and compares by reference. + private static bool Eq( + System.Collections.Generic.Dictionary? a, + System.Collections.Generic.Dictionary? b) + { + if (a is null || b is null) return ReferenceEquals(a, b); + if (a.Count != b.Count) return false; + foreach (var kv in a) + { + if (!b.TryGetValue(kv.Key, out var other)) return false; + if (System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; + if (System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) + != System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; + } + return true; + } + + /// Keys and count only — order-independent (XOR), allocation-free, and + /// stable for a value-object value whose GetHashCode is reference-based. Equal + /// dictionaries always hash equal, which is all EF requires. + private static int Hash(System.Collections.Generic.Dictionary? v) + { + if (v is null) return 0; + var h = v.Count; + foreach (var k in v.Keys) h ^= k.GetHashCode(); + return h; + } + + /// The change-tracking snapshot. A value-object value needs a DEEP copy or + /// an in-place edit to a nested object mutates the snapshot too and goes undetected; + /// an immutable scalar only needs the dictionary copied. + private static System.Collections.Generic.Dictionary? Snap( + System.Collections.Generic.Dictionary? v) => + v is null + ? null + : typeof(TValue).IsValueType || typeof(TValue) == typeof(string) + ? new System.Collections.Generic.Dictionary(v) + : System.Text.Json.JsonSerializer.Deserialize< + System.Collections.Generic.Dictionary>( + System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; + } + """); } /// @@ -2387,11 +2412,11 @@ private void EmitFieldTypeConfig( // symbols (["DRAFT"]) — or as their declared ints — not as int ordinals ([0]). if (f.ResolvedIsArray()) { - modelLines.Add($" modelBuilder.Entity<{className}>().PrimitiveCollection(x => x.{prop}).ElementType().{conversion};"); + modelLines.Add($"modelBuilder.Entity<{className}>().PrimitiveCollection(x => x.{prop}).ElementType().{conversion};"); } else { - modelLines.Add($" modelBuilder.Entity<{className}>().Property(x => x.{prop}).{conversion};"); + modelLines.Add($"modelBuilder.Entity<{className}>().Property(x => x.{prop}).{conversion};"); } } } @@ -2503,14 +2528,14 @@ protected virtual IEnumerable FieldTypeConfig(string owner, MetaObject e if (array && CSharpNaming.ScalarFor(f.SubType) is not null) { - lines.Add($" modelBuilder.Entity<{owner}>().PrimitiveCollection(x => x.{prop});"); + lines.Add($"modelBuilder.Entity<{owner}>().PrimitiveCollection(x => x.{prop});"); } if (!array && f.SubType == FIELD_SUBTYPE_DECIMAL && f.Precision is not null) { lines.Add(f.Scale is long sc - ? $" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasPrecision({f.Precision}, {sc});" - : $" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasPrecision({f.Precision});"); + ? $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasPrecision({f.Precision}, {sc});" + : $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasPrecision({f.Precision});"); } if (!array && f.SubType == FIELD_SUBTYPE_TIMESTAMP) @@ -2518,7 +2543,7 @@ protected virtual IEnumerable FieldTypeConfig(string owner, MetaObject e var colType = CSharpNaming.IsLocalTime(f) ? "timestamp without time zone" : "timestamp with time zone"; - lines.Add($" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"{colType}\");"); + lines.Add($"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"{colType}\");"); } // #234: a @lenient field.uri / field.inet is a plain string mapped to a plain `text` @@ -2530,13 +2555,13 @@ protected virtual IEnumerable FieldTypeConfig(string owner, MetaObject e // to compile except under a host's ImplicitUsings — the generated context must be // self-contained (this is also on the #214 write-through read-model path now). lines.Add( - $" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"text\").HasConversion(v => v!.ToString(), v => new System.Uri(v));"); + $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"text\").HasConversion(v => v!.ToString(), v => new System.Uri(v));"); } if (!array && f.SubType == FIELD_SUBTYPE_INET && !CSharpNaming.IsLenientNet(f)) { lines.Add( - $" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"inet\");"); + $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"inet\");"); } // field.duration — a System.TimeSpan. Npgsql maps it to the native `interval` (and an array @@ -2572,8 +2597,17 @@ private void AddDurationConfig( string className, MetaObject entity, IEnumerable fields, GenContext ctx, List modelLines) { foreach (var f in fields.Where(f => f.SubType == FIELD_SUBTYPE_DURATION && f.DbColumnType is null)) - modelLines.Add(string.Join("\n", - DurationColumnLines($"modelBuilder.Entity<{className}>()", "x", PropertyName(f), f.ResolvedIsArray(), entity, ctx, " "))); + modelLines.Add(Entry(w => WriteDurationColumn( + w, $"modelBuilder.Entity<{className}>()", "x", PropertyName(f), f.ResolvedIsArray(), entity, ctx))); + } + + // One model entry written on its own writer, so an entry of several lines carries only the indentation + // its lines have relative to its first. OnModelCreating writes each entry at its place. + private static string Entry(Action write) + { + var entry = new CsWriter(); + write(entry); + return entry.ToString().Trim(); } // The provider-dependent mapping of one duration column (a top-level property, or a member of a @@ -2585,18 +2619,20 @@ private void AddDurationConfig( // - any other provider (SQLite, MySQL): a 64-bit count of microseconds in an integer column // (sub-microsecond ticks truncated toward zero; a count past a TimeSpan refused, not // wrapped), which orders and compares as the span does. An array holds the counts. - private static IEnumerable DurationColumnLines( - string target, string v, string prop, bool isArray, MetaObject owner, GenContext ctx, string indent) + private static void WriteDurationColumn( + CsWriter w, string target, string v, string prop, bool isArray, MetaObject owner, GenContext ctx) { var micros = DurationMicrosConverter(owner, ctx); - yield return $"{indent}if (Database.ProviderName == \"{NpgsqlProviderName}\")"; - yield return isArray - ? $"{indent} {target}.PrimitiveCollection({v} => {v}.{prop}).Metadata.SetTypeMapping({DurationIntervalHelperName}.ArrayMapping);" - : $"{indent} {target}.Property({v} => {v}.{prop}).HasColumnType(\"interval\").Metadata.SetTypeMapping({DurationIntervalHelperName}.Mapping);"; - yield return $"{indent}else"; - yield return isArray - ? $"{indent} {target}.PrimitiveCollection({v} => {v}.{prop}).ElementType().HasConversion({micros});" - : $"{indent} {target}.Property({v} => {v}.{prop}).HasConversion({micros});"; + w.Line($"if (Database.ProviderName == \"{NpgsqlProviderName}\")"); + using (w.Hanging()) + w.Line(isArray + ? $"{target}.PrimitiveCollection({v} => {v}.{prop}).Metadata.SetTypeMapping({DurationIntervalHelperName}.ArrayMapping);" + : $"{target}.Property({v} => {v}.{prop}).HasColumnType(\"interval\").Metadata.SetTypeMapping({DurationIntervalHelperName}.Mapping);"); + w.Line("else"); + using (w.Hanging()) + w.Line(isArray + ? $"{target}.PrimitiveCollection({v} => {v}.{prop}).ElementType().HasConversion({micros});" + : $"{target}.Property({v} => {v}.{prop}).HasConversion({micros});"); } // The namespace OWNER's DurationWire is emitted into (owner has a duration field, so it has one). @@ -2632,136 +2668,137 @@ private static string DurationMicrosConverter(MetaObject owner, GenContext ctx) // optimize`), which re-creates a property's mapping as `.Default.Clone(...)` and // refuses a nested or non-public one. DurationIntervalEfCoreTests (integration) gates LINQ, // interval arithmetic and a compiled model against a live Postgres. - private static void EmitDurationIntervalHelper(StringBuilder sb) => sb.AppendLine(DurationIntervalHelperSource); - - private const string DurationIntervalHelperSource = """ - -/// -/// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month -/// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. -/// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. -/// -internal static class DurationInterval -{ - // The Npgsql shape this mapping reads, resolved and checked when the model is built (the - // first touch is SetTypeMapping in OnModelCreating, or the first query on a compiled model), - // so a missing or changed type fails there, naming what is missing, rather than on a row. - internal static readonly global::System.Type IntervalType = Resolve(); - private static readonly global::System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; - private static readonly global::System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; - private static readonly global::System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; - internal static readonly global::System.Reflection.MethodInfo GetFieldValue = - typeof(global::System.Data.Common.DbDataReader).GetMethod(nameof(global::System.Data.Common.DbDataReader.GetFieldValue))!; - - internal static readonly global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = DurationIntervalMapping.Default; - internal static readonly global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = DurationIntervalArrayMapping.Default; - - private static global::System.Type Resolve() + private static void EmitDurationIntervalHelper(CsWriter w) { - var type = global::System.Type.GetType(IntervalShape.TypeName, throwOnError: false); - if (IntervalShape.Problem(type) is { } problem) throw new global::System.InvalidOperationException(problem); - return type!; - } + w.Blank(); + w.Text(""" + /// + /// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month + /// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. + /// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. + /// + internal static class DurationInterval + { + // The Npgsql shape this mapping reads, resolved and checked when the model is built (the + // first touch is SetTypeMapping in OnModelCreating, or the first query on a compiled model), + // so a missing or changed type fails there, naming what is missing, rather than on a row. + internal static readonly global::System.Type IntervalType = Resolve(); + private static readonly global::System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; + private static readonly global::System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; + private static readonly global::System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; + internal static readonly global::System.Reflection.MethodInfo GetFieldValue = + typeof(global::System.Data.Common.DbDataReader).GetMethod(nameof(global::System.Data.Common.DbDataReader.GetFieldValue))!; + + internal static readonly global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = DurationIntervalMapping.Default; + internal static readonly global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = DurationIntervalArrayMapping.Default; + + private static global::System.Type Resolve() + { + var type = global::System.Type.GetType(IntervalShape.TypeName, throwOnError: false); + if (IntervalShape.Problem(type) is { } problem) throw new global::System.InvalidOperationException(problem); + return type!; + } - /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. - internal static class IntervalShape - { - internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; + /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. + internal static class IntervalShape + { + internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; - /// Null when has the shape the mapping reads, else a message naming what is missing. - internal static string? Problem(global::System.Type? type) - { - const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + - "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + - "tested with Npgsql 8.0.5), but "; - if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; - var missing = new global::System.Collections.Generic.List(); - foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) - { - var property = type.GetProperty(name); - if (property is null || property.PropertyType != want) - missing.Add(want.Name + " " + name); - } - return missing.Count == 0 - ? null - : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; - } - } + /// Null when has the shape the mapping reads, else a message naming what is missing. + internal static string? Problem(global::System.Type? type) + { + const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + + "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + + "tested with Npgsql 8.0.5), but "; + if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; + var missing = new global::System.Collections.Generic.List(); + foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) + { + var property = type.GetProperty(name); + if (property is null || property.PropertyType != want) + missing.Add(want.Name + " " + name); + } + return missing.Count == 0 + ? null + : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; + } + } - /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. - public static global::System.TimeSpan FromInterval(object interval) - { - if ((int)Months.GetValue(interval)! != 0) - throw new global::System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); - var days = (int)Days.GetValue(interval)!; - var micros = (long)Time.GetValue(interval)!; - return global::System.TimeSpan.FromTicks(checked(days * global::System.TimeSpan.TicksPerDay + micros * 10)); - } + /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. + public static global::System.TimeSpan FromInterval(object interval) + { + if ((int)Months.GetValue(interval)! != 0) + throw new global::System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); + var days = (int)Days.GetValue(interval)!; + var micros = (long)Time.GetValue(interval)!; + return global::System.TimeSpan.FromTicks(checked(days * global::System.TimeSpan.TicksPerDay + micros * 10)); + } - /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. - public static global::System.Collections.Generic.IList FromIntervals(object intervals) - { - var list = new global::System.Collections.Generic.List(); - foreach (var interval in (global::System.Array)intervals) list.Add(FromInterval(interval!)); - return list; - } + /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. + public static global::System.Collections.Generic.IList FromIntervals(object intervals) + { + var list = new global::System.Collections.Generic.List(); + foreach (var interval in (global::System.Array)intervals) list.Add(FromInterval(interval!)); + return list; + } - // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. The column - // holds microseconds, so sub-microsecond ticks are truncated toward zero. - internal static string Literal(global::System.TimeSpan value) - { - long micros = value.Ticks / 10; - bool negative = micros < 0; - ulong rest = negative ? (ulong)(-(micros + 1)) + 1UL : (ulong)micros; - ulong frac = rest % 1_000_000UL, s = rest / 1_000_000UL % 60, m = rest / 60_000_000UL % 60, h = rest / 3_600_000_000UL; - var text = h.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture) - + ":" + s.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture); - if (frac > 0) text += "." + frac.ToString("D6", global::System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); - return "INTERVAL '" + (negative ? "-" : "") + text + "'"; - } -} + // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. The column + // holds microseconds, so sub-microsecond ticks are truncated toward zero. + internal static string Literal(global::System.TimeSpan value) + { + long micros = value.Ticks / 10; + bool negative = micros < 0; + ulong rest = negative ? (ulong)(-(micros + 1)) + 1UL : (ulong)micros; + ulong frac = rest % 1_000_000UL, s = rest / 1_000_000UL % 60, m = rest / 60_000_000UL % 60, h = rest / 3_600_000_000UL; + var text = h.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture) + + ":" + s.ToString("00", global::System.Globalization.CultureInfo.InvariantCulture); + if (frac > 0) text += "." + frac.ToString("D6", global::System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); + return "INTERVAL '" + (negative ? "-" : "") + text + "'"; + } + } -/// The type mapping of a field.duration column on Npgsql (an interval, read through ). -public sealed class DurationIntervalMapping : global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping -{ - public static DurationIntervalMapping Default { get; } = new(); - - public DurationIntervalMapping() : base("interval", typeof(global::System.TimeSpan)) { } - private DurationIntervalMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } - protected override global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalMapping(parameters); - public override global::System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType); - public override global::System.Linq.Expressions.Expression CustomizeDataReaderExpression(global::System.Linq.Expressions.Expression expression) => - global::System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromInterval))!, - global::System.Linq.Expressions.Expression.Convert(expression, typeof(object))); - protected override string GenerateNonNullSqlLiteral(object value) => DurationInterval.Literal((global::System.TimeSpan)value); -} + /// The type mapping of a field.duration column on Npgsql (an interval, read through ). + public sealed class DurationIntervalMapping : global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + public static DurationIntervalMapping Default { get; } = new(); + + public DurationIntervalMapping() : base("interval", typeof(global::System.TimeSpan)) { } + private DurationIntervalMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalMapping(parameters); + public override global::System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType); + public override global::System.Linq.Expressions.Expression CustomizeDataReaderExpression(global::System.Linq.Expressions.Expression expression) => + global::System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromInterval))!, + global::System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => DurationInterval.Literal((global::System.TimeSpan)value); + } -/// The type mapping of an @isArray field.duration column on Npgsql (an interval[]). -public sealed class DurationIntervalArrayMapping : global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping -{ - private static readonly global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( - (a, b) => a == null ? b == null : b != null && global::System.Linq.Enumerable.SequenceEqual(a, b), - v => global::System.Linq.Enumerable.Aggregate(v, 0, (h, e) => global::System.HashCode.Combine(h, e)), - v => global::System.Linq.Enumerable.ToList(v)); - - // After ListComparer: static initializers run in declaration order. The element mapping is the - // scalar one, which is what lets EF query the column as a primitive collection (Contains, Count, - // Any): a compiled model carries only what the mapping itself names. - public static DurationIntervalArrayMapping Default { get; } = new(); - - public DurationIntervalArrayMapping() : base(new RelationalTypeMappingParameters( - new CoreTypeMappingParameters(typeof(global::System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer, - elementMapping: DurationIntervalMapping.Default), "interval[]")) { } - private DurationIntervalArrayMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } - protected override global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalArrayMapping(parameters); - public override global::System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType.MakeArrayType()); - public override global::System.Linq.Expressions.Expression CustomizeDataReaderExpression(global::System.Linq.Expressions.Expression expression) => - global::System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromIntervals))!, - global::System.Linq.Expressions.Expression.Convert(expression, typeof(object))); - protected override string GenerateNonNullSqlLiteral(object value) => - "ARRAY[" + string.Join(",", global::System.Linq.Enumerable.Select((global::System.Collections.Generic.IEnumerable)value, DurationInterval.Literal)) + "]::interval[]"; -} -"""; + /// The type mapping of an @isArray field.duration column on Npgsql (an interval[]). + public sealed class DurationIntervalArrayMapping : global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + private static readonly global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( + (a, b) => a == null ? b == null : b != null && global::System.Linq.Enumerable.SequenceEqual(a, b), + v => global::System.Linq.Enumerable.Aggregate(v, 0, (h, e) => global::System.HashCode.Combine(h, e)), + v => global::System.Linq.Enumerable.ToList(v)); + + // After ListComparer: static initializers run in declaration order. The element mapping is the + // scalar one, which is what lets EF query the column as a primitive collection (Contains, Count, + // Any): a compiled model carries only what the mapping itself names. + public static DurationIntervalArrayMapping Default { get; } = new(); + + public DurationIntervalArrayMapping() : base(new RelationalTypeMappingParameters( + new CoreTypeMappingParameters(typeof(global::System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer, + elementMapping: DurationIntervalMapping.Default), "interval[]")) { } + private DurationIntervalArrayMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override global::Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalArrayMapping(parameters); + public override global::System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType.MakeArrayType()); + public override global::System.Linq.Expressions.Expression CustomizeDataReaderExpression(global::System.Linq.Expressions.Expression expression) => + global::System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromIntervals))!, + global::System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => + "ARRAY[" + string.Join(",", global::System.Linq.Enumerable.Select((global::System.Collections.Generic.IEnumerable)value, DurationInterval.Literal)) + "]::interval[]"; + } + """); + } // The EF Core provider name Npgsql registers (DbContext.Database.ProviderName). private const string NpgsqlProviderName = "Npgsql.EntityFrameworkCore.PostgreSQL"; @@ -2830,18 +2867,18 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var clr = field.ResolvedIsArray() ? $"System.Collections.Generic.ICollection<{voType}>{modelType}" : voType + modelType; - return $" modelBuilder.Entity<{owner}>().Property(x => x.{nav}).HasColumnName({parentColRef})" + return $"modelBuilder.Entity<{owner}>().Property(x => x.{nav}).HasColumnName({parentColRef})" + $".HasColumnType(\"jsonb\").HasConversion({MapJsonbHelperName}.ObjectConverter<{clr}>(), {MapJsonbHelperName}.ObjectComparer<{clr}>());"; } var jsonEnums = JsonEnumConversions(vo, ctx); if (field.ResolvedIsArray()) return jsonEnums.Count == 0 - ? $" modelBuilder.Entity<{owner}>().OwnsMany(x => x.{nav}, b => b.ToJson({parentColRef}));" + ? $"modelBuilder.Entity<{owner}>().OwnsMany(x => x.{nav}, b => b.ToJson({parentColRef}));" : OwnedJsonBlock("OwnsMany", owner, nav, parentColRef, jsonEnums); if (field.Storage != STORAGE_FLATTENED) return jsonEnums.Count == 0 - ? $" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.ToJson({parentColRef}));" + ? $"modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.ToJson({parentColRef}));" : OwnedJsonBlock("OwnsOne", owner, nav, parentColRef, jsonEnums); // Each nested member's column is core naming's, whole @@ -2853,9 +2890,9 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s // rule, so verify's probe of an alternate rule names these columns the way it names // every other. - var sb = new StringBuilder(); - sb.AppendLine($" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b =>"); - sb.AppendLine(" {"); + var s = new CsWriter(); + s.Line($"modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b =>"); + s.Open("{"); // A6 -- NOT converted, on two independent grounds. `vo` (object.value) never // carries a source (FR-024 value purity), so it has no Names artifact at // all — CSharpNaming.ColumnRef would miss on every nf, always. And even with @@ -2896,7 +2933,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s // An override returning null leaves the member unconverted: no line for it. if (EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx) is { } elementConversion) { - sb.AppendLine($" b.PrimitiveCollection(p => p.{PropertyName(nf)})" + s.Line($"b.PrimitiveCollection(p => p.{PropertyName(nf)})" + $".HasColumnName(\"{nestedColAny}\").ElementType()" + $".{elementConversion};"); } @@ -2920,7 +2957,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var clr = nf.ResolvedIsArray() ? $"System.Collections.Generic.ICollection<{nestedType}>{nullable}" : nestedType + nullable; - sb.AppendLine($" b.Property(p => p.{PropertyName(nf)}).HasColumnName(\"{nestedColAny}\")" + s.Line($"b.Property(p => p.{PropertyName(nf)}).HasColumnName(\"{nestedColAny}\")" + $".HasColumnType(\"jsonb\").HasConversion({MapJsonbHelperName}.ObjectConverter<{clr}>(), {MapJsonbHelperName}.ObjectComparer<{clr}>());"); continue; } @@ -2933,23 +2970,22 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s // default: a column the migration never creates (42703 at the engine). if (nf.SubType == FIELD_SUBTYPE_MAP) { - sb.AppendLine($" b.Property(p => p.{PropertyName(nf)})" + s.Line($"b.Property(p => p.{PropertyName(nf)})" + $".HasColumnName(\"{nestedColAny}\")" + MapJsonbSuffix(vo, nf, ctx) + ";"); continue; } // A `field.duration` member: the migration flattens it to an `interval` column on // Postgres and an integer microsecond count elsewhere — the same provider-dependent - // mapping a top-level duration takes (DurationColumnLines). Without it EF would write + // mapping a top-level duration takes (WriteDurationColumn). Without it EF would write // its own "01:30:00" text there and fail to read another port's count. if (nf.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(nf) is null) { var dprop = PropertyName(nf); - sb.AppendLine(nf.ResolvedIsArray() - ? $" b.PrimitiveCollection(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");" - : $" b.Property(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); - foreach (var line in DurationColumnLines("b", "p", dprop, nf.ResolvedIsArray(), vo, ctx, " ")) - sb.AppendLine(line); + s.Line(nf.ResolvedIsArray() + ? $"b.PrimitiveCollection(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");" + : $"b.Property(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); + WriteDurationColumn(s, "b", "p", dprop, nf.ResolvedIsArray(), vo, ctx); continue; } @@ -2970,10 +3006,10 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var conversion = isEnum && EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx) is { } call ? $".{call}" : ""; - sb.AppendLine($" b.Property(p => p.{PropertyName(nf)}).HasColumnName(\"{nestedCol}\"){conversion};"); + s.Line($"b.Property(p => p.{PropertyName(nf)}).HasColumnName(\"{nestedCol}\"){conversion};"); } - sb.Append(" });"); - return sb.ToString(); + s.Close("});"); + return s.ToString().Trim(); } /// @@ -3009,8 +3045,8 @@ private List JsonEnumConversions(MetaObject vo, GenContext ctx, string b && CSharpNaming.DbColumnTypeClrOverride(nf) is null) { lines.Add(CSharpNaming.IsRequired(vo, nf) - ? $" {builder}.Property(p => p.{prop}).HasConversion(v => v.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));" - : $" {builder}.Property(p => p.{prop}).HasConversion(v => v == null ? null : v.Value.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => s == null ? (decimal?)null : decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));"); + ? $"{builder}.Property(p => p.{prop}).HasConversion(v => v.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));" + : $"{builder}.Property(p => p.{prop}).HasConversion(v => v == null ? null : v.Value.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => s == null ? (decimal?)null : decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));"); continue; } // A duration member of a JSON document is stored as its canonical ISO-8601 string (the @@ -3019,15 +3055,15 @@ private List JsonEnumConversions(MetaObject vo, GenContext ctx, string b { var converter = DurationConverter(vo, ctx); lines.Add(nf.ResolvedIsArray() - ? $" {builder}.PrimitiveCollection(p => p.{prop}).ElementType().HasConversion({converter});" - : $" {builder}.Property(p => p.{prop}).HasConversion({converter});"); + ? $"{builder}.PrimitiveCollection(p => p.{prop}).ElementType().HasConversion({converter});" + : $"{builder}.Property(p => p.{prop}).HasConversion({converter});"); continue; } if (nf.SubType != FIELD_SUBTYPE_ENUM) continue; // ADR-0039: resolving — array-ness is inheritable via extends. lines.Add(nf.ResolvedIsArray() - ? $" {builder}.PrimitiveCollection(p => p.{prop}).ElementType().HasConversion();" - : $" {builder}.Property(p => p.{prop}).HasConversion();"); + ? $"{builder}.PrimitiveCollection(p => p.{prop}).ElementType().HasConversion();" + : $"{builder}.Property(p => p.{prop}).HasConversion();"); } return lines; } @@ -3039,12 +3075,12 @@ private List JsonEnumConversions(MetaObject vo, GenContext ctx, string b private static string OwnedJsonBlock( string ownsCall, string owner, string nav, string parentColRef, List memberLines) { - var sb = new StringBuilder(); - sb.AppendLine($" modelBuilder.Entity<{owner}>().{ownsCall}(x => x.{nav}, b =>"); - sb.AppendLine(" {"); - sb.AppendLine($" b.ToJson({parentColRef});"); - foreach (var line in memberLines) sb.AppendLine(line); - sb.Append(" });"); - return sb.ToString(); + var s = new CsWriter(); + s.Line($"modelBuilder.Entity<{owner}>().{ownsCall}(x => x.{nav}, b =>"); + s.Open("{"); + s.Line($"b.ToJson({parentColRef});"); + foreach (var line in memberLines) s.Line(line); + s.Close("});"); + return s.ToString().Trim(); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 00826f27ad..8fe19675d7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -14,7 +14,7 @@ // The PropertyName hook is obsolete for adopters (set GenConfig.PropertyNaming); this generator still calls it. #pragma warning disable CS0618 -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Codegen.Docs; using MetaObjects.Meta; using MetaObjects.Persistence.Origin; @@ -339,128 +339,115 @@ private EmittedFile EmitMappedClassImpl( var pkFields = pk?.Fields ?? []; var isProjection = isView; - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using System.ComponentModel.DataAnnotations;"); - sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;"); + var w = NewWriter(); + w.GeneratedFileHeader("entity-generator"); + w.Using("System"); + w.Using("System.Collections.Generic"); + w.Using("System.ComponentModel.DataAnnotations"); + w.Using("System.ComponentModel.DataAnnotations.Schema"); // A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98). if (CSharpNaming.RequiresSystemTextJson(entity)) - sb.AppendLine("using System.Text.Json;"); + w.Using("System.Text.Json"); // ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress. if (CSharpNaming.RequiresSystemNet(entity)) - sb.AppendLine("using System.Net;"); + w.Using("System.Net"); // #234 — a strict field.uri / field.inet property carries [JsonConverter(typeof(…))]. if (HasStrictNetField(entity)) - sb.AppendLine("using System.Text.Json.Serialization;"); + w.Using("System.Text.Json.Serialization"); // A composite PK emits a class-level [PrimaryKey(...)] which lives in the // Microsoft.EntityFrameworkCore namespace (not a DataAnnotations attribute) — // import it so the emitted class compiles standalone, without relying on the // host project's ImplicitUsings. if (pkFields.Count > 1) - sb.AppendLine("using Microsoft.EntityFrameworkCore;"); + w.Using("Microsoft.EntityFrameworkCore"); // FR-021 — usings for OTHER packages this entity references (object navs + TPH base). foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(entity, ctx.Root, ctx.Config)) - sb.AppendLine($"using {ns};"); - EmitFileUsings(sb, entity, ctx); - sb.AppendLine(); - sb.AppendLine($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); - sb.AppendLine(); + w.Using(ns); + EmitFileUsings(w, entity, ctx); + w.Blank(); + w.Line($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); + w.Blank(); - EmitClassHeader(sb, entity, className, isProjection, pkFields, ctx); // Cross-field validators run on the full create record only (never a read-only view). // A non-TPH entity never has a validating base: its only possible base is an abstract // shape, which declares no Validate, and every property it carries is present on this // class (own or inherited through the base chain), so every effective rule is emitted here. - var validateMethod = isProjection ? null : CrossFieldValidateMethod(entity, validatingBase: null); - if (validateMethod is not null) AppendValidatableInterface(sb); - sb.AppendLine("{"); - - // Nested enum declarations (before the class properties, as C# enum members - // must be declared before they are referenced by property types). - var enumDecls = CollectEnumDecls(entity); - - // Members in declared order: scalar columns + enum-typed props + (entities only) owned-type navs. - // When this entity extends an emitted abstract shape (DirectMappedParent), the shape carries - // the inherited fields — emit ONLY this entity's own fields and let C# inheritance supply - // the rest. A concrete parent is never a C# base (two mapped entities in one hierarchy would - // be an EF TPH/TPT mapping, not the one-table-per-entity model), so its fields are declared here. - var inheritedNames = DirectMappedParent(entity, ctx.Config) is { } mp - ? new HashSet(mp.Fields().Select(f => f.Name), StringComparer.Ordinal) - : new HashSet(StringComparer.Ordinal); - var members = new List(); - var strategy = ctx.Config.ColumnNamingStrategy; - foreach (var field in entity.Fields()) - { - if (inheritedNames.Contains(field.Name)) continue; // inherited via the C# base chain - // #214 — the write half of a write-through entity omits derived (origin.*) fields: - // they are view-computed, so they live only on the read model, never the write table. - if (excludeDerived && field.IsDerived()) continue; - string? member = null; - if (CSharpNaming.ScalarFor(field.SubType) is not null) + var validate = isProjection ? null : PlanCrossFieldValidate(entity, validatingBase: null); + EmitClassHeader(w, entity, className, isProjection, pkFields, ctx); + if (validate is not null) w.AddBaseType("IValidatableObject"); + using (w.Block("{")) + { + // Nested enum declarations (before the class properties, as C# enum members + // must be declared before they are referenced by property types). + foreach (var decl in CollectEnumDecls(entity)) + w.Line(decl); + + // Members in declared order: scalar columns + enum-typed props + (entities only) owned-type navs. + // When this entity extends an emitted abstract shape (DirectMappedParent), the shape carries + // the inherited fields — emit ONLY this entity's own fields and let C# inheritance supply + // the rest. A concrete parent is never a C# base (two mapped entities in one hierarchy would + // be an EF TPH/TPT mapping, not the one-table-per-entity model), so its fields are declared here. + var inheritedNames = DirectMappedParent(entity, ctx.Config) is { } mp + ? new HashSet(mp.Fields().Select(f => f.Name), StringComparer.Ordinal) + : new HashSet(StringComparer.Ordinal); + var strategy = ctx.Config.ColumnNamingStrategy; + foreach (var field in entity.Fields()) { - member = ScalarProperty(entity, field, pkFields, withAttributes: true, strategy, - includeNames: ctx.Config.IncludeNames, baseTypeOverride: AggregateResultScalar(field, ctx)); - } - else if (field.SubType == FIELD_SUBTYPE_ENUM) - { - member = EnumProperty(entity, field, ctx.Config, strategy); - } - else if (field.SubType == FIELD_SUBTYPE_OBJECT) - { - // Owned-type navigation only on entities; projection collection - // origins are materialized elsewhere. - if (isProjection) + if (inheritedNames.Contains(field.Name)) continue; // inherited via the C# base chain + // #214 — the write half of a write-through entity omits derived (origin.*) fields: + // they are view-computed, so they live only on the read model, never the write table. + if (excludeDerived && field.IsDerived()) continue; + if (CSharpNaming.ScalarFor(field.SubType) is not null) { - // #214 [1] — a write-through entity's read model (includeJsonbObjects) - // DOES carry its non-derived single-jsonb-column value-object columns: - // reads route to the view, so the column must be present to be readable. - // The DbContext registers the matching owned-VO config (OwnsOne/OwnsMany - // .ToJson). A FLATTENED VO (multi-column spread) is out of scope on the - // view. A plain projection keeps the original warn-and-skip. - if (!includeJsonbObjects || field.Storage == STORAGE_FLATTENED) + WriteScalarProperty(w, entity, field, pkFields, withAttributes: true, strategy, + includeNames: ctx.Config.IncludeNames, baseTypeOverride: AggregateResultScalar(field, ctx)); + } + else if (field.SubType == FIELD_SUBTYPE_ENUM) + { + WriteEnumProperty(w, entity, field, ctx.Config, strategy); + } + else if (field.SubType == FIELD_SUBTYPE_OBJECT) + { + // Owned-type navigation only on entities; projection collection + // origins are materialized elsewhere. + if (isProjection) { - ctx.Warn($"{Name}: skipping object-typed field \"{entity.Name}.{field.Name}\" on projection (collection materialization not emitted here)."); - continue; + // #214 [1] — a write-through entity's read model (includeJsonbObjects) + // DOES carry its non-derived single-jsonb-column value-object columns: + // reads route to the view, so the column must be present to be readable. + // The DbContext registers the matching owned-VO config (OwnsOne/OwnsMany + // .ToJson). A FLATTENED VO (multi-column spread) is out of scope on the + // view. A plain projection keeps the original warn-and-skip. + if (!includeJsonbObjects || field.Storage == STORAGE_FLATTENED) + { + ctx.Warn($"{Name}: skipping object-typed field \"{entity.Name}.{field.Name}\" on projection (collection materialization not emitted here)."); + continue; + } } + WriteObjectNavProperty(w, entity, field, ctx); + } + else if (field.SubType == FIELD_SUBTYPE_MAP) + { + WriteMapProperty(w, entity, field, ctx); } - member = ObjectNavProperty(entity, field, ctx); - } - else if (field.SubType == FIELD_SUBTYPE_MAP) - { - member = MapProperty(entity, field, ctx); } - if (member is null) continue; - member = ApplyPropertyAttributes(member, entity, field, ctx); - members.Add(XmlDocBuilder.Prepend(member, field, " ")); - } - // FR-018 M:N navigation collections (entities only; the EF UsingEntity - // wiring + the REST traversal route are emitted by the DbContext + routes - // generators). One ICollection per @cardinality:"many" + @through - // relationship — for a self-join the member is named after the relationship. - if (!isProjection) - foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) - members.Add(M2mNavProperty(nav, ctx.Config)); + // FR-018 M:N navigation collections (entities only; the EF UsingEntity + // wiring + the REST traversal route are emitted by the DbContext + routes + // generators). One ICollection per @cardinality:"many" + @through + // relationship — for a self-join the member is named after the relationship. + if (!isProjection) + foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) + WriteM2mNavProperty(w, nav, ctx.Config); - if (enumDecls.Count > 0) - { - sb.Append(string.Join("\n", enumDecls)); - sb.AppendLine(); - } - sb.Append(string.Join("\n", members)); - sb.AppendLine(); - if (validateMethod is not null) - { - sb.AppendLine(); - sb.Append(validateMethod); + if (validate is not null) + { + w.Blank(); + WriteCrossFieldValidate(w, validate); + } + EmitClassBodyTrailer(w, entity, ctx); } - EmitClassBodyTrailer(sb, entity, ctx); - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); } // Extension hook — owns the per-class header for a mapped entity/projection: the @@ -472,19 +459,19 @@ private EmittedFile EmitMappedClassImpl( // attributes, etc. (ADR-0002, open-closed). Implementations MUST NOT emit the // trailing `{` — the caller does. protected virtual void EmitClassHeader( - StringBuilder sb, MetaObject entity, string className, bool isProjection, + CsWriter w, MetaObject entity, string className, bool isProjection, IReadOnlyList pkFields, GenContext ctx) { // XML doc + [Obsolete] FIRST — XML doc-extraction tools (docfx, // Sandcastle, IDE hover-doc) require the doc comment to immediately // precede the declaration, before any attributes. - XmlDocBuilder.AppendTo(sb, entity); + XmlDocBuilder.WriteTo(w, entity); // Composite primary key -> class-level [PrimaryKey(...)] (EF Core 7+). if (pkFields.Count > 1) { var names = string.Join(", ", pkFields.Select(f => $"nameof({(entity.FindField(f) is { } pkField ? PropertyName(pkField) : CSharpNaming.Pascal(f))})")); - sb.AppendLine($"[PrimaryKey({names})]"); + w.Line($"[PrimaryKey({names})]"); } // A6 -- CSharpNaming.NameRef gates this on TWO independent things, neither of // which is the divergence check (that already threw, once, inside @@ -496,7 +483,7 @@ protected virtual void EmitClassHeader( // which generators ran). Falls back to the bare literal table name otherwise -- // exactly what this line emitted before Program A added the constant. if (!isProjection) - sb.AppendLine($"[Table({CSharpNaming.NameRef(entity, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, CSharpNaming.Table(entity))}" + w.Line($"[Table({CSharpNaming.NameRef(entity, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, CSharpNaming.Table(entity))}" + $"{CSharpNaming.TableSchemaArg(entity, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames)})]"); // FR-017 TPH — declare the concrete subtypes so System.Text.Json serializes each row // by its RUNTIME type. @@ -518,16 +505,16 @@ protected virtual void EmitClassHeader( { foreach (var line in TphDerivedTypeAttributes(entity, ctx)) { - sb.AppendLine(line); + w.Line(line); } } - EmitClassAttributes(sb, entity, className, ClassDeclarationKind.MappedEntity, ctx); + EmitClassAttributes(w, entity, className, ClassDeclarationKind.MappedEntity, ctx); // The `public [abstract] class [ : Base]` declaration line itself is routed // through the single overridable seam shared by all four emitted class kinds, so an // adopter's `partial`/marker-interface override applies uniformly. The EF mapping // attrs ([Table]/[PrimaryKey]) above stay here — they are mapped-entity-only. - EmitClassDeclarationLine(sb, entity, className, ClassDeclarationKind.MappedEntity, ctx); + EmitClassDeclarationLine(w, entity, className, ClassDeclarationKind.MappedEntity, ctx); } /// @@ -552,7 +539,7 @@ protected virtual IEnumerable TphDerivedTypeAttributes(MetaObject root, // Override it to add an attribute without re-implementing EmitClassHeader; each line written // should be a complete attribute line with no indent. protected virtual void EmitClassAttributes( - StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) + CsWriter w, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) { // No-op by default. } @@ -575,7 +562,7 @@ protected enum ClassDeclarationKind // body reproduces exactly the inline emission per kind, so default output is byte-identical. // Implementations MUST NOT emit the trailing `{` — the caller does. (ADR-0002, open-closed.) protected virtual void EmitClassDeclarationLine( - StringBuilder sb, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) + CsWriter w, MetaObject entity, string className, ClassDeclarationKind kind, GenContext ctx) { switch (kind) { @@ -586,7 +573,7 @@ protected virtual void EmitClassDeclarationLine( // HasValue(...) fails model validation ("has a discriminator property, // but does not have a discriminator value configured"). var classKeyword = TphPlanBuilder.IsTphDiscriminatorBase(entity, ctx.Root) ? "abstract class" : "class"; - sb.AppendLine($"public {classKeyword} {className}{MappedBaseClause(entity, ctx)}"); + w.Line($"public {classKeyword} {className}{MappedBaseClause(entity, ctx)}"); break; case ClassDeclarationKind.TphSubtype: // Extend the nearest ancestor that actually GETS EMITTED as a class — the @@ -605,13 +592,13 @@ protected virtual void EmitClassDeclarationLine( // drop them instead of merely failing to compile). var baseClass = ValueObjectNames.Ref(EmittedTphAncestor(entity, ctx), ctx.Config); var tphKeyword = InstanceArtifacts.IsAbstract(entity) ? "abstract class" : "class"; - sb.AppendLine($"public {tphKeyword} {className} : {baseClass}"); + w.Line($"public {tphKeyword} {className} : {baseClass}"); break; case ClassDeclarationKind.AbstractShape: - sb.AppendLine($"public abstract class {className}{MappedBaseClause(entity, ctx)}"); + w.Line($"public abstract class {className}{MappedBaseClause(entity, ctx)}"); break; case ClassDeclarationKind.ValueObject: - sb.AppendLine($"public class {className}"); + w.Line($"public class {className}"); break; } } @@ -645,12 +632,12 @@ private static string SetterFor(MetaField field) => // // Eject (ADR-0034 Amendment 3): public so an owned copy of another generator can // emit the SAME M:N nav-property shape this one does, rather than re-deriving it. - public static string M2mNavProperty(M2MNavigation nav, GenConfig? config = null) + public static void WriteM2mNavProperty(CsWriter w, M2MNavigation nav, GenConfig? config = null) { var target = config is null ? CSharpNaming.Pascal(nav.Target.Name) : ValueObjectNames.Ref(nav.Target, config); var prop = CSharpNaming.Pascal(nav.Name); - var notMapped = nav.IsSelfJoin ? " [NotMapped]\n" : ""; - return $"{notMapped} public ICollection<{target}> {prop} {{ get; set; }} = new List<{target}>();"; + if (nav.IsSelfJoin) w.Line("[NotMapped]"); + w.Line($"public ICollection<{target}> {prop} {{ get; set; }} = new List<{target}>();"); } // FR-017 TPH subtype class: `public class : ` carrying ONLY its @@ -675,80 +662,65 @@ protected virtual EmittedFile EmitTphSubtypeClass(MetaObject entity, GenContext var baseFieldNames = new HashSet( EmittedTphAncestor(entity, ctx).Fields().Select(f => f.Name), StringComparer.Ordinal); var strategy = ctx.Config.ColumnNamingStrategy; - - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator (TPH subtype). Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using System.ComponentModel.DataAnnotations;"); - sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;"); + var w = NewWriter(); + w.GeneratedFileHeader("entity-generator (TPH subtype)"); + w.Using("System"); + w.Using("System.Collections.Generic"); + w.Using("System.ComponentModel.DataAnnotations"); + w.Using("System.ComponentModel.DataAnnotations.Schema"); // FR-021 — usings for OTHER packages this entity references (object navs + TPH base). foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(entity, ctx.Root, ctx.Config)) - sb.AppendLine($"using {ns};"); - EmitFileUsings(sb, entity, ctx); - sb.AppendLine(); - sb.AppendLine($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); - sb.AppendLine(); - - XmlDocBuilder.AppendTo(sb, entity); - EmitClassAttributes(sb, entity, className, ClassDeclarationKind.TphSubtype, ctx); - EmitClassDeclarationLine(sb, entity, className, ClassDeclarationKind.TphSubtype, ctx); + w.Using(ns); + EmitFileUsings(w, entity, ctx); + w.Blank(); + w.Line($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); + w.Blank(); + var tphAncestor = EmittedTphAncestor(entity, ctx); var validatingBase = HasEffectiveCrossField(tphAncestor) ? tphAncestor : null; - var validateMethod = CrossFieldValidateMethod(entity, validatingBase); - if (validateMethod is not null && validatingBase is null) AppendValidatableInterface(sb); - sb.AppendLine("{"); + var validate = PlanCrossFieldValidate(entity, validatingBase); - // Subtype-only enum declarations (an enum field declared on the subtype, not the base). - var ownEnumDecls = new List(); - var seenEnum = new HashSet(StringComparer.Ordinal); - foreach (var field in entity.Fields()) + XmlDocBuilder.WriteTo(w, entity); + EmitClassAttributes(w, entity, className, ClassDeclarationKind.TphSubtype, ctx); + EmitClassDeclarationLine(w, entity, className, ClassDeclarationKind.TphSubtype, ctx); + if (validate is not null && validatingBase is null) w.AddBaseType("IValidatableObject"); + using (w.Block("{")) { - if (baseFieldNames.Contains(field.Name)) continue; - if (field.SubType != FIELD_SUBTYPE_ENUM) continue; - if (Fr019SharedEnum.SharedEnumForField(field) is not null) continue; // FR-019 shared/provided → referenced - var values = field.EffectiveEnumValues; - if (values is null || values.Count == 0) continue; - var typeName = CSharpNaming.EnumTypeName(entity, field); - if (!seenEnum.Add(typeName)) continue; - ownEnumDecls.Add($" public enum {typeName} {{ {string.Join(", ", values)} }}"); - } + // Subtype-only enum declarations (an enum field declared on the subtype, not the base). + var seenEnum = new HashSet(StringComparer.Ordinal); + foreach (var field in entity.Fields()) + { + if (baseFieldNames.Contains(field.Name)) continue; + if (field.SubType != FIELD_SUBTYPE_ENUM) continue; + if (Fr019SharedEnum.SharedEnumForField(field) is not null) continue; // FR-019 shared/provided → referenced + var values = field.EffectiveEnumValues; + if (values is null || values.Count == 0) continue; + var typeName = CSharpNaming.EnumTypeName(entity, field); + if (!seenEnum.Add(typeName)) continue; + w.Line($"public enum {typeName} {{ {string.Join(", ", values)} }}"); + } - var members = new List(); - foreach (var field in entity.Fields()) - { - if (baseFieldNames.Contains(field.Name)) continue; // inherited from the base - string? member = null; - if (CSharpNaming.ScalarFor(field.SubType) is not null) - member = TphSubtypeScalarProperty(entity, field, strategy, ctx.Config.IncludeNames); - else if (field.SubType == FIELD_SUBTYPE_ENUM) - member = TphSubtypeEnumProperty(entity, field, ctx.Config, strategy); - else if (field.SubType == FIELD_SUBTYPE_OBJECT) - member = ObjectNavProperty(entity, field, ctx); - else if (field.SubType == FIELD_SUBTYPE_MAP) - member = MapProperty(entity, field, ctx); - if (member is null) continue; - member = ApplyPropertyAttributes(member, entity, field, ctx); - members.Add(XmlDocBuilder.Prepend(member, field, " ")); - } + foreach (var field in entity.Fields()) + { + if (baseFieldNames.Contains(field.Name)) continue; // inherited from the base + if (CSharpNaming.ScalarFor(field.SubType) is not null) + WriteTphSubtypeScalarProperty(w, entity, field, strategy, ctx.Config.IncludeNames); + else if (field.SubType == FIELD_SUBTYPE_ENUM) + WriteTphSubtypeEnumProperty(w, entity, field, ctx.Config, strategy); + else if (field.SubType == FIELD_SUBTYPE_OBJECT) + WriteObjectNavProperty(w, entity, field, ctx); + else if (field.SubType == FIELD_SUBTYPE_MAP) + WriteMapProperty(w, entity, field, ctx); + } - if (ownEnumDecls.Count > 0) - { - sb.Append(string.Join("\n", ownEnumDecls)); - sb.AppendLine(); - } - sb.Append(string.Join("\n", members)); - sb.AppendLine(); - if (validateMethod is not null) - { - sb.AppendLine(); - sb.Append(validateMethod); + if (validate is not null) + { + w.Blank(); + WriteCrossFieldValidate(w, validate); + } + EmitClassBodyTrailer(w, entity, ctx); } - EmitClassBodyTrailer(sb, entity, ctx); - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); } // A subtype-only scalar property: [Column]-mapped, with the field's validator @@ -758,61 +730,60 @@ protected virtual EmittedFile EmitTphSubtypeClass(MetaObject entity, GenContext // of CLR nullability (a row of another subtype stores NULL there), so a non-null CLR // type maps to a nullable column correctly — and matches adopters whose marker // interfaces declare these members non-null. Arrays keep the List shape. - protected virtual string TphSubtypeScalarProperty( - MetaObject entity, MetaField field, ColumnNamingStrategy strategy, bool includeNames) + protected virtual void WriteTphSubtypeScalarProperty( + CsWriter w, MetaObject entity, MetaField field, ColumnNamingStrategy strategy, bool includeNames) { _site = new PropertySite(ValueObject: false, TphSubtype: true, null); // ScalarForField resolves the ADR-0036 Wave 2 conditional field.timestamp binding. var baseType = CSharpNaming.ScalarForField(field)!; var propName = PropertyName(field); + BeginMember(w, entity, field); if (field.ResolvedIsArray()) // ADR-0039: resolving — array-ness inheritable via extends { - var arr = new StringBuilder(); - if (ColumnAttributeLine(entity, field, strategy, includeNames) is { } arrColumn) + if (ColumnAttribute(entity, field, strategy, includeNames) is { } arrColumn) { - arr.AppendLine(arrColumn); + w.Line(arrColumn); } - AppendArrayValidatorAttributes(arr, field); - AppendDecimalConverterAttribute(arr, field, nullable: false, _wire); - AppendDurationConverterAttribute(arr, field, _wire); + WriteArrayValidatorAttributes(w, field); + WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection. - arr.Append(PropertyDeclaration(entity, field, propName, SetterFor(field))); - return arr.ToString(); + WritePropertyDeclaration(w, entity, field, propName, SetterFor(field)); + return; } - var sb = new StringBuilder(); - if (ColumnAttributeLine(entity, field, strategy, includeNames) is { } column) + if (ColumnAttribute(entity, field, strategy, includeNames) is { } column) { - sb.AppendLine(column); + w.Line(column); } if (baseType == "string") - AppendStringValidatorAttributes(sb, field); + WriteStringValidatorAttributes(w, field); else - AppendNumericValidatorAttributes(sb, field); + WriteNumericValidatorAttributes(w, field); var required = CSharpNaming.IsRequired(entity, field); - AppendDecimalConverterAttribute(sb, field, nullable: !required, _wire); - AppendDurationConverterAttribute(sb, field, _wire); - // Mirrors ScalarProperty's own initializer handling (its non-TPH sibling): a + WriteDecimalConverterAttribute(w, field, nullable: !required, _wire); + WriteDurationConverterAttribute(w, field, _wire); + // Mirrors WriteScalarProperty's own initializer handling (its non-TPH sibling): a // literal-safe @default (bool/int/long/double/float/decimal/string) wins over the // `= default!;` filler a required REFERENCE-type property would otherwise need. // Before this, a @required + @default TPH subtype-only field silently started // life at the CLR default (false/0/null) on `new Sub()` instead of the declared // @default value — every OTHER scalar-property path in this generator already // applies DefaultInitializer; this one was the one gap. - sb.Append(PropertyDeclaration(entity, field, propName, SetterFor(field))); - return sb.ToString(); + WritePropertyDeclaration(w, entity, field, propName, SetterFor(field)); } // A subtype-only enum property: [Column]-mapped (no [Required]). CLR nullability // follows @required (see TphSubtypeScalarProperty); the column is auto-nullable. - protected virtual string TphSubtypeEnumProperty(MetaObject entity, MetaField field, GenConfig config, ColumnNamingStrategy strategy) + protected virtual void WriteTphSubtypeEnumProperty(CsWriter w, MetaObject entity, MetaField field, GenConfig config, ColumnNamingStrategy strategy) { _site = new PropertySite(ValueObject: false, TphSubtype: true, null); var propName = PropertyName(field); - var colAttr = ColumnAttributeLine(entity, field, strategy, config.IncludeNames) is { } column ? column + "\n" : ""; - return colAttr + PropertyDeclaration(entity, field, propName, SetterFor(field)); + BeginMember(w, entity, field); + if (ColumnAttribute(entity, field, strategy, config.IncludeNames) is { } column) w.Line(column); + WritePropertyDeclaration(w, entity, field, propName, SetterFor(field)); } // An enum ARRAY property is IList with an empty-list initializer, except a @@ -905,66 +876,52 @@ protected virtual EmittedFile EmitAbstractShapeClass(MetaObject entity, GenConte { var className = CSharpNaming.Pascal(entity.Name); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator (abstract shape). Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); + var w = NewWriter(); + w.GeneratedFileHeader("entity-generator (abstract shape)"); + w.Using("System"); + w.Using("System.Collections.Generic"); // A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98). if (CSharpNaming.RequiresSystemTextJson(entity)) - sb.AppendLine("using System.Text.Json;"); + w.Using("System.Text.Json"); // ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress. if (CSharpNaming.RequiresSystemNet(entity)) - sb.AppendLine("using System.Net;"); + w.Using("System.Net"); // FR-021 — usings for OTHER packages this entity references (object navs + TPH base). foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(entity, ctx.Root, ctx.Config)) - sb.AppendLine($"using {ns};"); - EmitFileUsings(sb, entity, ctx); - sb.AppendLine(); - sb.AppendLine($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); - sb.AppendLine(); - - XmlDocBuilder.AppendTo(sb, entity); - EmitClassAttributes(sb, entity, className, ClassDeclarationKind.AbstractShape, ctx); - EmitClassDeclarationLine(sb, entity, className, ClassDeclarationKind.AbstractShape, ctx); - sb.AppendLine("{"); - - var enumDecls = CollectEnumDecls(entity); - - // Body: scalar + enum + object-nav members, all WITHOUT EF mapping attributes - // (a shape, not a table). When this abstract base extends another emitted base - // (e.g. BaseAuditableEntity : BaseEntity), emit only its OWN fields — the rest come - // through the C# base chain (mirrors the metadata `extends` chain). - var inheritedNames = DirectMappedParent(entity, ctx.Config) is { } amp - ? new HashSet(amp.Fields().Select(f => f.Name), StringComparer.Ordinal) - : new HashSet(StringComparer.Ordinal); - var members = new List(); - foreach (var field in entity.Fields()) - { - if (inheritedNames.Contains(field.Name)) continue; // inherited via the C# base chain - string? member = null; - if (CSharpNaming.ScalarFor(field.SubType) is not null) - member = ScalarProperty(entity, field, [], withAttributes: false); - else if (field.SubType == FIELD_SUBTYPE_ENUM) - member = EnumProperty(entity, field, ctx.Config, ColumnNamingStrategy.Literal, withAttributes: false); - else if (field.SubType == FIELD_SUBTYPE_OBJECT && ObjectNavProperty(entity, field, ctx) is { } nav) - member = nav; - if (member is null) continue; - member = ApplyPropertyAttributes(member, entity, field, ctx); - members.Add(XmlDocBuilder.Prepend(member, field, " ")); - } - - if (enumDecls.Count > 0) - { - sb.Append(string.Join("\n", enumDecls)); - sb.AppendLine(); + w.Using(ns); + EmitFileUsings(w, entity, ctx); + w.Blank(); + w.Line($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name)};"); + w.Blank(); + + XmlDocBuilder.WriteTo(w, entity); + EmitClassAttributes(w, entity, className, ClassDeclarationKind.AbstractShape, ctx); + EmitClassDeclarationLine(w, entity, className, ClassDeclarationKind.AbstractShape, ctx); + using (w.Block("{")) + { + foreach (var decl in CollectEnumDecls(entity)) + w.Line(decl); + + // Body: scalar + enum + object-nav members, all WITHOUT EF mapping attributes + // (a shape, not a table). When this abstract base extends another emitted base + // (e.g. BaseAuditableEntity : BaseEntity), emit only its OWN fields — the rest come + // through the C# base chain (mirrors the metadata `extends` chain). + var inheritedNames = DirectMappedParent(entity, ctx.Config) is { } amp + ? new HashSet(amp.Fields().Select(f => f.Name), StringComparer.Ordinal) + : new HashSet(StringComparer.Ordinal); + foreach (var field in entity.Fields()) + { + if (inheritedNames.Contains(field.Name)) continue; // inherited via the C# base chain + if (CSharpNaming.ScalarFor(field.SubType) is not null) + WriteScalarProperty(w, entity, field, [], withAttributes: false); + else if (field.SubType == FIELD_SUBTYPE_ENUM) + WriteEnumProperty(w, entity, field, ctx.Config, ColumnNamingStrategy.Literal, withAttributes: false); + else if (field.SubType == FIELD_SUBTYPE_OBJECT) + WriteObjectNavProperty(w, entity, field, ctx); + } + EmitClassBodyTrailer(w, entity, ctx); } - sb.Append(string.Join("\n", members)); - sb.AppendLine(); - EmitClassBodyTrailer(sb, entity, ctx); - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); } // Plain POCO for a value object nested by an owned-type navigation. No [Table] / @@ -976,102 +933,88 @@ protected virtual EmittedFile EmitAbstractShapeClass(MetaObject entity, GenConte // ADR-0056: the ONE name every generator uses for this type (collision-qualified when // two value objects share a short name). var className = ValueObjectNames.TypeName(vo, ctx.Root); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator (owned value object). Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); + var w = NewWriter(); + w.GeneratedFileHeader("entity-generator (owned value object)"); + w.Using("System"); + w.Using("System.Collections.Generic"); // A VO's own members carry validation DataAnnotations ([Required]/[MaxLength]/etc.) // so a nested value-object is validated in FULL on POST/PATCH (Program D). - sb.AppendLine("using System.ComponentModel.DataAnnotations;"); + w.Using("System.ComponentModel.DataAnnotations"); // A value-object field with an explicit @column emits [Column(...)] — same as the entity // paths, so it needs the Schema namespace too (was omitted here → CS0246 on Column). - sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;"); + w.Using("System.ComponentModel.DataAnnotations.Schema"); // [JsonPropertyName] pins each VO member's jsonb element name (+ wire name) to the // metadata field name (camelCase). EF Core 8 owned-JSON (.ToJson) honors it, so the // stored jsonb keys match the shared seed + the wire contract cross-port (Program D). - sb.AppendLine("using System.Text.Json.Serialization;"); + w.Using("System.Text.Json.Serialization"); // A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98). if (CSharpNaming.RequiresSystemTextJson(vo)) - sb.AppendLine("using System.Text.Json;"); + w.Using("System.Text.Json"); // ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress. if (CSharpNaming.RequiresSystemNet(vo)) - sb.AppendLine("using System.Net;"); + w.Using("System.Net"); // FR-021 — usings for OTHER packages this value-object references (object navs + super). foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(vo, ctx.Root, ctx.Config)) - sb.AppendLine($"using {ns};"); - EmitFileUsings(sb, vo, ctx); - sb.AppendLine(); - sb.AppendLine($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(vo), vo.Name, fallbackContext: vo.Name)};"); - sb.AppendLine(); - XmlDocBuilder.AppendTo(sb, vo); - EmitClassAttributes(sb, vo, className, ClassDeclarationKind.ValueObject, ctx); - EmitClassDeclarationLine(sb, vo, className, ClassDeclarationKind.ValueObject, ctx); - sb.AppendLine("{"); - - var enumDeclsVo = CollectEnumDecls(vo); - - var members = new List(); - foreach (var field in vo.Fields()) - { - string? member = null; - if (CSharpNaming.ScalarFor(field.SubType) is not null) - // VO POCO members carry NO EF-mapping attrs but DO carry validation - // DataAnnotations (the VO is validated in full on POST/PATCH; Program D). - member = ScalarProperty(vo, field, [], withAttributes: false, withValidationAttributes: true, - valueObject: true); - else if (field.SubType == FIELD_SUBTYPE_ENUM) - // Same rule as the scalar arm: no [Column(...)]. A VO's column mapping is decided - // by each OWNER (fluent, in the DbContext — .ToJson or the flattened per-member - // HasColumnName), never by the shared POCO. Left at its default of true this - // emitted a bare [Column("")] which EF IGNORES on a jsonb owner - // but HONOURS on a flattened one — binding an unprefixed column the migration - // never creates. - member = EnumProperty(vo, field, ctx.Config, ctx.Config.ColumnNamingStrategy, withAttributes: false); - else if (field.SubType == FIELD_SUBTYPE_OBJECT && ObjectNavProperty(vo, field, ctx, valueObject: true) is { } nav) - member = nav; - else if (field.SubType == FIELD_SUBTYPE_MAP) - member = MapProperty(vo, field, ctx, withAttributes: false); - if (member is null) continue; - // Pin the jsonb element name (+ wire name) to the metadata field name so the - // stored owned-JSON keys match the shared seed + the cross-port wire contract. - // Under `wire.nullMembers: omit` (ADR-0019 Amendment 2) a null member is left out of - // the wire; the default writes it as System.Text.Json does, `null` with the key - // present. Only a NULLABLE member can be null, and System.Text.Json throws - // InvalidOperationException when WhenWritingNull sits on a non-nullable value type - // (double, DateTimeOffset, ...), so the condition is emitted for the nullable members alone. - var nullableMember = _wire.NullMembers == NullMemberForm.Omit - && System.Text.RegularExpressions.Regex.IsMatch(member, @"^\s*public\s+[^=;{(]*\?\s+\w+", System.Text.RegularExpressions.RegexOptions.Multiline); - member = string.Concat(ValueObjectMemberAttributes(vo, field, ctx).Select(l => l + "\n")) - + (nullableMember ? " [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]\n" : "") - + member; - member = ApplyPropertyAttributes(member, vo, field, ctx); - members.Add(XmlDocBuilder.Prepend(member, field, " ")); - } - - if (enumDeclsVo.Count > 0) - { - sb.Append(string.Join("\n", enumDeclsVo)); - sb.AppendLine(); - } - sb.Append(string.Join("\n", members)); - sb.AppendLine(); - EmitClassBodyTrailer(sb, vo, ctx); - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(vo, ctx, $"{className}.g.cs"), sb.ToString()); + w.Using(ns); + EmitFileUsings(w, vo, ctx); + w.Blank(); + w.Line($"namespace {PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(vo), vo.Name, fallbackContext: vo.Name)};"); + w.Blank(); + XmlDocBuilder.WriteTo(w, vo); + EmitClassAttributes(w, vo, className, ClassDeclarationKind.ValueObject, ctx); + EmitClassDeclarationLine(w, vo, className, ClassDeclarationKind.ValueObject, ctx); + using (w.Block("{")) + { + foreach (var decl in CollectEnumDecls(vo)) + w.Line(decl); + + foreach (var field in vo.Fields()) + { + // Each member opens with its lead (BeginMember): the doc, the jsonb element name, and + // under `wire.nullMembers: omit` the [JsonIgnore] a nullable member needs. System.Text.Json + // throws InvalidOperationException when WhenWritingNull sits on a non-nullable value type + // (double, DateTimeOffset, ...), so the condition is written for the nullable members alone. + _voLead = (vo, ctx); + try + { + if (CSharpNaming.ScalarFor(field.SubType) is not null) + // VO POCO members carry NO EF-mapping attrs but DO carry validation + // DataAnnotations (the VO is validated in full on POST/PATCH; Program D). + WriteScalarProperty(w, vo, field, [], withAttributes: false, withValidationAttributes: true, + valueObject: true); + else if (field.SubType == FIELD_SUBTYPE_ENUM) + // Same rule as the scalar arm: no [Column(...)]. A VO's column mapping is decided + // by each OWNER (fluent, in the DbContext — .ToJson or the flattened per-member + // HasColumnName), never by the shared POCO. Left at its default of true this + // emitted a bare [Column("")] which EF IGNORES on a jsonb owner + // but HONOURS on a flattened one — binding an unprefixed column the migration + // never creates. + WriteEnumProperty(w, vo, field, ctx.Config, ctx.Config.ColumnNamingStrategy, withAttributes: false); + else if (field.SubType == FIELD_SUBTYPE_OBJECT) + WriteObjectNavProperty(w, vo, field, ctx, valueObject: true); + else if (field.SubType == FIELD_SUBTYPE_MAP) + WriteMapProperty(w, vo, field, ctx, withAttributes: false); + } + finally + { + _voLead = null; + } + } + EmitClassBodyTrailer(w, vo, ctx); + } + return new EmittedFile(OutputPaths.Of(vo, ctx, $"{className}.g.cs"), w.ToString()); } /// /// Hook — the attribute lines writes before one value-object /// member, ahead of the [JsonIgnore] a wire.nullMembers: omit run adds and of the - /// member's own attributes: complete lines, 4-space indent included. Called once per emitted - /// member. Default: [JsonPropertyName("<field>")], which pins the member's jsonb + /// member's own attributes: complete lines, no indent (the writer indents them). Called once per + /// emitted member. Default: [JsonPropertyName("<field>")], which pins the member's jsonb /// element and wire name to the metadata field name. Return none to let the serializer's naming /// policy (or a document already keyed by the CLR name) decide instead. /// protected virtual IEnumerable ValueObjectMemberAttributes(MetaObject vo, MetaField f, GenContext ctx) => - [$" [JsonPropertyName(\"{f.Name}\")]"]; + [$"[JsonPropertyName(\"{f.Name}\")]"]; // Collects nested C# enum declarations for all enum-subtype fields on an object, // deduplicating by type name so two fields that extend the same abstract enum emit @@ -1094,7 +1037,7 @@ protected static List CollectEnumDecls(MetaObject owner) var typeName = CSharpNaming.EnumTypeName(owner, field); if (!seen.Add(typeName)) continue; // skip duplicate type names var members = string.Join(", ", values); - decls.Add($" public enum {typeName} {{ {members} }}"); + decls.Add($"public enum {typeName} {{ {members} }}"); } return decls; } @@ -1158,44 +1101,42 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I if (ctx.Config.OutputLayout == OutputLayout.Package) return declared.Select(e => { - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator (FR-019 shared enum). Do not edit by hand."); - sb.AppendLine("// A reused package-level field.enum; consuming entities reference it."); - sb.AppendLine("#nullable enable"); - sb.AppendLine(); - sb.AppendLine($"namespace {Fr019SharedEnum.MaterializedNamespace(e, ctx.Config)};"); - sb.AppendLine(); - sb.Append(SharedEnumDeclaration(e)); + var w = NewWriter(); + w.Header("// ", + "// Generated by MetaObjects entity-generator (FR-019 shared enum). Do not edit by hand.", + "// A reused package-level field.enum; consuming entities reference it.", + "#nullable enable"); + w.Line($"namespace {Fr019SharedEnum.MaterializedNamespace(e, ctx.Config)};"); + w.Blank(); + WriteSharedEnumDeclaration(w, e); var fileName = $"{e.Name}.g.cs"; - return new EmittedFile(e.Declaration is { } decl ? OutputPaths.Of(decl, ctx, fileName) : fileName, sb.ToString()) { WholeModel = true }; + return new EmittedFile(e.Declaration is { } decl ? OutputPaths.Of(decl, ctx, fileName) : fileName, w.ToString()) { WholeModel = true }; }).ToList(); - var flat = new StringBuilder(); - flat.AppendLine("// "); - flat.AppendLine("// Generated by MetaObjects entity-generator (FR-019 shared enums). Do not edit by hand."); - flat.AppendLine("// One declaration per reused package-level field.enum; consuming entities reference these."); - flat.AppendLine("#nullable enable"); - flat.AppendLine(); + var flat = NewWriter(); + flat.Header("// ", + "// Generated by MetaObjects entity-generator (FR-019 shared enums). Do not edit by hand.", + "// One declaration per reused package-level field.enum; consuming entities reference these.", + "#nullable enable"); var groups = declared.GroupBy(e => Fr019SharedEnum.MaterializedNamespace(e, ctx.Config), StringComparer.Ordinal).ToList(); if (groups.Count == 1) { // One namespace (the default: GenConfig.Namespace), as ever. - flat.AppendLine($"namespace {groups[0].Key};"); - flat.AppendLine(); + flat.Line($"namespace {groups[0].Key};"); + flat.Blank(); foreach (var e in groups[0]) - flat.AppendLine($"public enum {e.Name} {{ {string.Join(", ", e.Values)} }}"); + flat.Line($"public enum {e.Name} {{ {string.Join(", ", e.Values)} }}"); } else { foreach (var g in groups.OrderBy(g => g.Key, StringComparer.Ordinal)) { - flat.AppendLine($"namespace {g.Key}"); - flat.AppendLine("{"); - foreach (var e in g) - flat.AppendLine($" public enum {e.Name} {{ {string.Join(", ", e.Values)} }}"); - flat.AppendLine("}"); - flat.AppendLine(); + using (flat.Braced($"namespace {g.Key}")) + { + foreach (var e in g) + flat.Line($"public enum {e.Name} {{ {string.Join(", ", e.Values)} }}"); + } + flat.Blank(); } } return [new EmittedFile("Enums.g.cs", flat.ToString()) { WholeModel = true }]; @@ -1225,7 +1166,7 @@ private bool AnotherEntryEmits(GenContext ctx, MetaObject home) => /// member's @intValueMap integer as its value, and each member's @enumDoc text as /// its <summary>. A member with no doc keeps the one-line form. /// - private static string SharedEnumDeclaration(SharedEnum e) + private static void WriteSharedEnumDeclaration(CsWriter w, SharedEnum e) { var decl = e.Declaration; var ints = decl?.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; @@ -1236,27 +1177,21 @@ string Member(string m) => : m; string? DocOf(string m) => docs is not null && docs.TryGetValue(m, out var d) && d?.ToString() is { Length: > 0 } text ? text : null; - var sb = new StringBuilder(); if (decl is not null) - { - var (xmlDoc, obsolete) = XmlDocBuilder.Render(decl); - if (xmlDoc.Length > 0) sb.AppendLine(xmlDoc); - if (obsolete is not null) sb.AppendLine(obsolete); - } + XmlDocBuilder.WriteTo(w, decl); if (e.Values.All(m => DocOf(m) is null)) { - sb.AppendLine($"public enum {e.Name} {{ {string.Join(", ", e.Values.Select(Member))} }}"); - return sb.ToString(); + w.Line($"public enum {e.Name} {{ {string.Join(", ", e.Values.Select(Member))} }}"); + return; } - sb.AppendLine($"public enum {e.Name}"); - sb.AppendLine("{"); - foreach (var m in e.Values) + using (w.Braced($"public enum {e.Name}")) { - if (DocOf(m) is { } doc) sb.AppendLine($" /// {XmlDocBuilder.EscapeXml(doc)}"); - sb.AppendLine($" {Member(m)},"); + foreach (var m in e.Values) + { + if (DocOf(m) is { } doc) w.Line($"/// {XmlDocBuilder.EscapeXml(doc)}"); + w.Line($"{Member(m)},"); + } } - sb.AppendLine("}"); - return sb.ToString(); } // ------------------------------------------------------------------------- @@ -1344,21 +1279,50 @@ private static List CrossFieldValidatorsFor(MetaObject entity, Me private static bool HasEffectiveCrossField(MetaObject entity) => entity.Validators().Any(IsCrossFieldValidator); - // Appends `, IValidatableObject` (or ` : IValidatableObject`) to the just-written class - // declaration line. Works on the builder so an overridden declaration seam still applies. - private static void AppendValidatableInterface(StringBuilder sb) + // The cross-field rules a class declares, ready to write: each is the guard of its optional + // @condition, the `if (...)` line, and the statement that follows it. + private sealed record ValidateRule(string? Guard, string Head, string Statement); + + private sealed record ValidatePlan(bool BaseHasValidate, IReadOnlyList Rules); + + // The Validate method: its doc, its declaration, an inherited loop when a base has one, then each + // rule. A rule with an @condition is checked only inside that condition's block. + private static void WriteCrossFieldValidate(CsWriter w, ValidatePlan plan) { - var len = sb.Length; - while (len > 0 && (sb[len - 1] == '\n' || sb[len - 1] == '\r')) len--; - var lineStart = len; - while (lineStart > 0 && sb[lineStart - 1] != '\n') lineStart--; - var line = sb.ToString(lineStart, len - lineStart); - sb.Length = len; - sb.AppendLine(line.Contains(" : ", StringComparison.Ordinal) ? ", IValidatableObject" : " : IValidatableObject"); + w.Line("/// Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne / exactlyOne, each with its optional @condition). Create-time only; the database CHECK is the enforcement on partial updates."); + using (w.Braced(plan.BaseHasValidate + ? "public override IEnumerable Validate(ValidationContext validationContext)" + : "public virtual IEnumerable Validate(ValidationContext validationContext)")) + { + if (plan.BaseHasValidate) + { + w.Line("foreach (var __inherited in base.Validate(validationContext))"); + using (w.Hanging()) w.Line("yield return __inherited;"); + } + if (plan.Rules.Count == 0) w.Line("yield break;"); + foreach (var rule in plan.Rules) + { + if (rule.Guard is null) + { + WriteRule(w, rule); + continue; + } + using (w.Braced($"if (({rule.Guard}) == true)")) + { + WriteRule(w, rule); + } + } + } + + static void WriteRule(CsWriter w, ValidateRule rule) + { + w.Line(rule.Head); + using (w.Hanging()) w.Line(rule.Statement); + } } - // Returns the emitted Validate method (4-space class-body indent), or null when nothing to emit. - private string? CrossFieldValidateMethod(MetaObject entity, MetaObject? validatingBase) + // The Validate method this class declares, or null when there is nothing to emit. + private ValidatePlan? PlanCrossFieldValidate(MetaObject entity, MetaObject? validatingBase) { var validators = CrossFieldValidatorsFor(entity, validatingBase); if (validators.Count == 0) return null; @@ -1606,12 +1570,12 @@ string Unwrap((string Expr, bool MayBeNull) x) } } - var body = new StringBuilder(); + var rules = new List(); var i = 0; foreach (var v in validators) { i++; - var rule = new StringBuilder(); + (string Head, string Statement)? rule = null; switch (v.SubType) { case VALIDATOR_SUBTYPE_COMPARISON: @@ -1639,8 +1603,7 @@ string Unwrap((string Expr, bool MayBeNull) x) else cond = op == "eq" ? $"Equals({a}, {b})" : $"!Equals({a}, {b})"; var lp = PropertyName(l); var rp = PropertyName(r); - rule.AppendLine($" if ({lp} is {{ }} {a} && {rp} is {{ }} {b} && !({cond}))"); - rule.AppendLine($" yield return new ValidationResult({CsLiteral($"{lp} must be {op} {rp}.")}, new[] {{ nameof({lp}), nameof({rp}) }});"); + rule = ($"if ({lp} is {{ }} {a} && {rp} is {{ }} {b} && !({cond}))", $"yield return new ValidationResult({CsLiteral($"{lp} must be {op} {rp}.")}, new[] {{ nameof({lp}), nameof({rp}) }});"); break; } case VALIDATOR_SUBTYPE_REQUIRED_WHEN: @@ -1654,13 +1617,11 @@ string Unwrap((string Expr, bool MayBeNull) x) var tp = PropertyName(target); var wp = PropertyName(when); if (v.SubType == VALIDATOR_SUBTYPE_REQUIRED_WHEN) { - rule.AppendLine($" if ({gate} && {tp} is null)"); - rule.AppendLine($" yield return new ValidationResult({CsLiteral($"{tp} is required when {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); + rule = ($"if ({gate} && {tp} is null)", $"yield return new ValidationResult({CsLiteral($"{tp} is required when {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); } else { - rule.AppendLine($" if (({tp} is not null) != {gate})"); - rule.AppendLine($" yield return new ValidationResult({CsLiteral($"{tp} must be present if and only if {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); + rule = ($"if (({tp} is not null) != {gate})", $"yield return new ValidationResult({CsLiteral($"{tp} must be present if and only if {wp} is {raw}.")}, new[] {{ nameof({tp}) }});"); } break; } @@ -1676,8 +1637,7 @@ string Unwrap((string Expr, bool MayBeNull) x) var fs = names.Select(Scalar).ToList(); if (fs.Count == 0 || fs.Any(f => f is null)) break; var props = fs.Select(f => PropertyName(f!)).ToList(); - rule.AppendLine($" if ({string.Join(" && ", props.Select(p => $"{p} is null"))})"); - rule.AppendLine($" yield return new ValidationResult({CsLiteral($"At least one of {string.Join(", ", props)} is required.")}, new[] {{ {string.Join(", ", props.Select(p => $"nameof({p})"))} }});"); + rule = ($"if ({string.Join(" && ", props.Select(p => $"{p} is null"))})", $"yield return new ValidationResult({CsLiteral($"At least one of {string.Join(", ", props)} is required.")}, new[] {{ {string.Join(", ", props.Select(p => $"nameof({p})"))} }});"); break; } case VALIDATOR_SUBTYPE_EXACTLY_ONE: @@ -1694,57 +1654,34 @@ string Unwrap((string Expr, bool MayBeNull) x) var props = fs.Select(f => PropertyName(f!)).ToList(); // Exactly one non-null: absent is null, "" is not null. (object?) keeps the test valid for any property type. var count = string.Join(" + ", props.Select(p => $"(((object?){p}) is null ? 0 : 1)")); - rule.AppendLine($" if ({count} != 1)"); - rule.AppendLine($" yield return new ValidationResult({CsLiteral($"Exactly one of {string.Join(", ", props)} is required.")}, new[] {{ {string.Join(", ", props.Select(p => $"nameof({p})"))} }});"); + rule = ($"if ({count} != 1)", $"yield return new ValidationResult({CsLiteral($"Exactly one of {string.Join(", ", props)} is required.")}, new[] {{ {string.Join(", ", props.Select(p => $"nameof({p})"))} }});"); break; } } - if (rule.Length == 0) continue; + if (rule is not { } built) continue; // A rule with an @condition is checked only when the condition is TRUE (the CHECK is // NOT (condition) OR (rule)); false or NULL lets the record through. A condition that // names a field outside the create model leaves the whole rule to the database. + string? guard = null; if (v.Attr(VALIDATOR_ATTR_CONDITION) is { } condition) { - var guard = CondCs(condition); + guard = CondCs(condition); if (guard is null) continue; - body.AppendLine($" if (({guard}) == true)"); - body.AppendLine(" {"); - foreach (var line in rule.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries)) - body.AppendLine(" " + line.TrimEnd('\r')); - body.AppendLine(" }"); } - else body.Append(rule); - } - if (body.Length == 0) - { - if (baseHasValidate) return null; - body.AppendLine(" yield break;"); + rules.Add(new ValidateRule(guard, built.Head, built.Statement)); } - - var sb = new StringBuilder(); - sb.AppendLine(" /// Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne / exactlyOne, each with its optional @condition). Create-time only; the database CHECK is the enforcement on partial updates."); - sb.AppendLine(baseHasValidate - ? " public override IEnumerable Validate(ValidationContext validationContext)" - : " public virtual IEnumerable Validate(ValidationContext validationContext)"); - sb.AppendLine(" {"); - if (baseHasValidate) - { - sb.AppendLine(" foreach (var __inherited in base.Validate(validationContext))"); - sb.AppendLine(" yield return __inherited;"); - } - sb.Append(body); - sb.AppendLine(" }"); - return sb.ToString(); + if (rules.Count == 0 && baseHasValidate) return null; + return new ValidatePlan(baseHasValidate, rules); } // Extension hook — invoked once per emitted property, AFTER the framework // attributes ([Key]/[Column]/[Required]/[MaxLength]/validators) and immediately // BEFORE the `public { get; ... }` line. The default body is empty - // (no-op), so default output is byte-identical. Override to append per-property C# + // (no-op), so default output is byte-identical. Override to write per-property C# // attributes (e.g. `[ContainsPhi]`, `[ReportingField(...)]`) keyed off the field's - // metadata. Each line written should carry the 4-space property indent. + // metadata, one `w.Line` each: the writer indents them. protected virtual void EmitPropertyAttributes( - StringBuilder sb, MetaObject owner, MetaField field, GenContext ctx) + CsWriter w, MetaObject owner, MetaField field, GenContext ctx) { // No-op by default. } @@ -1753,39 +1690,46 @@ protected virtual void EmitPropertyAttributes( // directives and BEFORE the blank line + `namespace`. The default body is empty // (no-op), so default output is byte-identical. Override to add adopter `using` // directives the emitted properties/attributes depend on (e.g. a namespace housing - // a custom marker interface or per-property attribute). Each line written should be - // a complete `using ...;` directive. - protected virtual void EmitFileUsings(StringBuilder sb, MetaObject entity, GenContext ctx) + // a custom marker interface or per-property attribute): `w.Using("Acme.Markers")`. + protected virtual void EmitFileUsings(CsWriter w, MetaObject entity, GenContext ctx) { // No-op by default. } // Extension hook — invoked once per emitted file at the END of the class body, // immediately before the closing `}`. The default body is empty (no-op), so default - // output is byte-identical. Override to append adopter members (extra methods, - // partial-method hooks, computed properties) inside the generated class. Each line - // written should carry the 4-space class-body indent. - protected virtual void EmitClassBodyTrailer(StringBuilder sb, MetaObject entity, GenContext ctx) + // output is byte-identical. Override to write adopter members (extra methods, + // partial-method hooks, computed properties) inside the generated class; the + // writer is already inside the class body, so its lines are indented for you. + protected virtual void EmitClassBodyTrailer(CsWriter w, MetaObject entity, GenContext ctx) { // No-op by default. } - // Splices the EmitPropertyAttributes hook output into an already-built member - // string, immediately before its ` public ` declaration line (after the - // framework attributes). When the hook is the default no-op the member is returned - // unchanged, keeping default output byte-identical. - private string ApplyPropertyAttributes(string member, MetaObject owner, MetaField field, GenContext ctx) - { - var hook = new StringBuilder(); - EmitPropertyAttributes(hook, owner, field, ctx); - if (hook.Length == 0) return member; + // The pieces of the file, one overridable method each (ADR-0063 item 7). Not a stability contract. + + /// The writer a file is written on. + protected virtual CsWriter NewWriter() => new(); - const string decl = " public "; - var idx = member.LastIndexOf(decl, StringComparison.Ordinal); - if (idx < 0) return member; // no recognizable property line — leave untouched - return member[..idx] + hook + member[idx..]; + // Writes the lead of the member about to be written: its XML doc and, when the value-object + // emitter asked for one (_voLead), the jsonb element name and the [JsonIgnore] a nullable member + // needs under `wire.nullMembers: omit`. Called once per member, after the member's site is set + // and before its first attribute. + private void BeginMember(CsWriter w, MetaObject owner, MetaField field) + { + XmlDocBuilder.WriteTo(w, field); + if (_voLead is not { } lead) return; + _voLead = null; + foreach (var line in ValueObjectMemberAttributes(lead.Vo, field, lead.Ctx)) + w.Line(line); + if (_wire.NullMembers == NullMemberForm.Omit + && PropertyClrType(owner, field, lead.Ctx).EndsWith('?')) + w.Line("[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]"); } + // The value-object emitter's request for the next member's lead (see BeginMember). + private (MetaObject Vo, GenContext Ctx)? _voLead; + // #234 — true iff FIELD is a (single, non-array) STRICT field.uri / field.inet — the fields // carrying the generated [JsonConverter] + backing MetaNetValidation. A @lenient uri/inet is a // plain string with no converter, so it does not count. Single SSOT predicate for both the @@ -1799,24 +1743,28 @@ private static bool IsStrictNetField(MetaField field) => // #234 — true iff the entity has any strict field.uri / field.inet (needs MetaNetValidation). private static bool HasStrictNetField(MetaObject entity) => entity.Fields().Any(IsStrictNetField); - // #234 — append the [JsonConverter(typeof(…))] binding a strict field.uri / field.inet property - // to the same-namespace generated MetaNetValidation converter. No-op for a @lenient uri/inet + // #234 — write the [JsonConverter(typeof(…))] binding a strict field.uri / field.inet property + // to the same-namespace generated MetaNetValidation converter. Nothing for a @lenient uri/inet // (a plain string) or any other field. An @isArray uri/inet (element-wise converter) is a // follow-up (no validation-conformance case). - private static void AppendNetConverterAttribute(StringBuilder sb, MetaField field) + private static void WriteNetConverterAttribute(CsWriter w, MetaField field) { if (!IsStrictNetField(field)) return; // strict predicate guarantees a non-array uri/inet if (field.SubType == FIELD_SUBTYPE_URI) - sb.AppendLine(" [JsonConverter(typeof(MetaNetValidation.AbsoluteUriJsonConverter))]"); + w.Line("[JsonConverter(typeof(MetaNetValidation.AbsoluteUriJsonConverter))]"); else if (field.SubType == FIELD_SUBTYPE_INET) - sb.AppendLine(" [JsonConverter(typeof(MetaNetValidation.IPAddressJsonConverter))]"); + w.Line("[JsonConverter(typeof(MetaNetValidation.IPAddressJsonConverter))]"); } // ADR-0019 Amendment 1 — the decimal wire form. This text is the Runtime/DecimalWire.cs - // source with its namespace as __NS__; DecimalWireTests gates the two byte-for-byte after - // the namespace swap. It lives HERE (not read from the HelperRuntime resource) so an - // ejected EntityGenerator stays self-contained, the way the MetaNetValidation text is. - private const string DecimalWireSourceTemplate = """ + // source with its namespace swapped in; DecimalWireTests gates the two byte-for-byte. + // It lives HERE (not read from the HelperRuntime resource) so an ejected EntityGenerator stays + // self-contained, the way the MetaNetValidation text is. The text is fixed code, so it goes in + // as snippets around the one line that varies. + private static EmittedFile EmitDecimalWireFile(string ns, string fileName) + { + var w = new CsWriter(); + w.Text(""" // // DecimalWire — the wire form of a field.decimal (ADR-0019 Amendments 1 and 2, W1-W4). // @@ -1845,9 +1793,11 @@ private static void AppendNetConverterAttribute(StringBuilder sb, MetaField fiel using System.Text; using System.Text.Json; using System.Text.Json.Serialization; - -namespace __NS__; - +"""); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Text(""" /// The canonical wire form of a decimal: format, parse, and the System.Text.Json converters. public static class DecimalWire { @@ -2142,16 +2092,19 @@ public override void Write(Utf8JsonWriter writer, IList value, JsonSeri } } } -"""; - - private static EmittedFile EmitDecimalWireFile(string ns, string fileName) => - new(fileName, DecimalWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n") { WholeModel = true }; +"""); + return new EmittedFile(fileName, w.ToString()) { WholeModel = true }; + } // field.duration — the duration wire form (fixtures/duration-wire/). This text is the // Runtime/DurationWire.cs source with its namespace as __NS__; DurationWireTests gates the two // byte-for-byte after the namespace swap. It lives HERE (not read from the HelperRuntime // resource) so an ejected EntityGenerator stays self-contained, the way DecimalWire's is. - private const string DurationWireSourceTemplate = """ + + private static EmittedFile EmitDurationWireFile(string ns, string fileName) + { + var w = new CsWriter(); + w.Text(""" // // DurationWire — the wire form of a field.duration: a fixed-length span of time, a TimeSpan in C#. // @@ -2183,9 +2136,11 @@ private static EmittedFile EmitDecimalWireFile(string ns, string fileName) => using System.Text; using System.Text.Json; using System.Text.Json.Serialization; - -namespace __NS__; - +"""); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Text(""" /// The canonical wire form of a duration: format, parse, and the System.Text.Json converters. public static class DurationWire { @@ -2410,10 +2365,9 @@ public override void Write(Utf8JsonWriter writer, IList value, JsonSer } } } -"""; - - private static EmittedFile EmitDurationWireFile(string ns, string fileName) => - new(fileName, DurationWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n") { WholeModel = true }; +"""); + return new EmittedFile(fileName, w.ToString()) { WholeModel = true }; + } // true iff FIELD is a field.duration (single or @isArray): a System.TimeSpan property carrying // the per-property ISO-8601 converter. @@ -2426,9 +2380,9 @@ private static bool IsDurationField(MetaField field) => // options cannot drop a property attribute). One attribute serves TimeSpan, TimeSpan? and // IList. Under the default `native` there is no attribute: System.Text.Json's own // TimeSpan form ("01:30:00") is the wire form, both ways. - private static void AppendDurationConverterAttribute(StringBuilder sb, MetaField field, WireFormat wire) + private static void WriteDurationConverterAttribute(CsWriter w, MetaField field, WireFormat wire) { - if (wire.Durations == DurationWireForm.Iso && IsDurationField(field)) sb.AppendLine(" [DurationWire.Iso]"); + if (wire.Durations == DurationWireForm.Iso && IsDurationField(field)) w.Line("[DurationWire.Iso]"); } // true iff FIELD surfaces as a CLR decimal (single or @isArray) and so carries the @@ -2442,25 +2396,25 @@ private static bool IsDecimalWireField(MetaField field) => // closed type the property has (decimal, decimal?, IList). Under the default // `wire.decimals: native` (ADR-0019 Amendment 2) it writes what System.Text.Json writes, a // JSON number, and keeps only the input rules; `string` writes the canonical string. - private static void AppendDecimalConverterAttribute(StringBuilder sb, MetaField field, bool nullable, WireFormat wire) + private static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, bool nullable, WireFormat wire) { if (!IsDecimalWireField(field)) return; if (wire.Decimals == DecimalWireForm.Native) { - sb.AppendLine(field.Precision is long p - ? $" [DecimalWire.Number({p}, {field.Scale ?? 0})]" - : " [DecimalWire.Number]"); + w.Line(field.Precision is long p + ? $"[DecimalWire.Number({p}, {field.Scale ?? 0})]" + : "[DecimalWire.Number]"); return; } // W3: a declared @precision and @scale bound the input; the attribute carries both. if (field.Precision is long precision) { - sb.AppendLine($" [DecimalWire.Declared({precision}, {field.Scale ?? 0})]"); + w.Line($"[DecimalWire.Declared({precision}, {field.Scale ?? 0})]"); return; } var converter = field.ResolvedIsArray() ? "DecimalListJsonConverter" : nullable ? "NullableDecimalJsonConverter" : "DecimalJsonConverter"; - sb.AppendLine($" [System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); + w.Line($"[System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); } // #234 — emit the codegen-owned MetaNetValidation.cs into `ns`: two strict System.Text.Json @@ -2469,109 +2423,114 @@ private static void AppendDecimalConverterAttribute(StringBuilder sb, MetaField // code runs without any MetaObjects runtime. The body is fixed; only the namespace varies. private static EmittedFile EmitNetValidationFile(string ns, string fileName) { - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Net;"); - sb.AppendLine("using System.Text.Json;"); - sb.AppendLine("using System.Text.Json.Serialization;"); - sb.AppendLine("using System.Text.RegularExpressions;"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine("/// GENERATED (#234) — strict System.Text.Json converters for field.uri /"); - sb.AppendLine("/// field.inet. Dependency-free; runs without any MetaObjects runtime."); - sb.AppendLine("public static class MetaNetValidation"); - sb.AppendLine("{"); - sb.AppendLine(" /// field.uri — an ABSOLUTE URI carrying an explicit scheme (leading/trailing"); - sb.AppendLine(" /// whitespace trimmed, WHATWG). A relative reference (example.com, /path) or malformed"); - sb.AppendLine(" /// value is rejected."); - sb.AppendLine(" public sealed class AbsoluteUriJsonConverter : JsonConverter"); - sb.AppendLine(" {"); - sb.AppendLine(" public override Uri? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)"); - sb.AppendLine(" {"); - sb.AppendLine(" // #234 review N2: a non-string JSON token (number/object/array) rejects as a"); - sb.AppendLine(" // JsonException (a clean 400), not an InvalidOperationException from GetString()."); - sb.AppendLine(" if (reader.TokenType != JsonTokenType.String && reader.TokenType != JsonTokenType.Null)"); - sb.AppendLine(" throw new JsonException(\"expected a JSON string\");"); - sb.AppendLine(" string? raw = reader.GetString();"); - sb.AppendLine(" if (raw is null) return null;"); - sb.AppendLine(" string s = raw.Trim();"); - sb.AppendLine(" // Require an explicit scheme so a bare path (\"/x\") is not inferred as a file: URI"); - sb.AppendLine(" // on .NET, AND that it parses as an absolute URI."); - sb.AppendLine(" if (!Regex.IsMatch(s, \"^[a-zA-Z][a-zA-Z0-9+.-]*:\")"); - sb.AppendLine(" || !Uri.TryCreate(s, UriKind.Absolute, out Uri? uri))"); - sb.AppendLine(" throw new JsonException(\"field.uri: must be an absolute URI carrying a scheme: \" + raw);"); - sb.AppendLine(" return uri;"); - sb.AppendLine(" }"); - sb.AppendLine(" public override void Write(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options)"); - sb.AppendLine(" => writer.WriteStringValue(value.OriginalString);"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" /// field.inet — an IPv4 or IPv6 LITERAL only. Never a DNS lookup: a value"); - sb.AppendLine(" /// containing ':' can only be an IPv6 literal, otherwise a strict dotted-quad IPv4."); - sb.AppendLine(" /// Hostnames, CIDR, padding, out-of-range octets are rejected."); - sb.AppendLine(" public sealed class IPAddressJsonConverter : JsonConverter"); - sb.AppendLine(" {"); - sb.AppendLine(" public override IPAddress? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)"); - sb.AppendLine(" {"); - sb.AppendLine(" // #234 review N2: a non-string JSON token (number/object/array) rejects as a"); - sb.AppendLine(" // JsonException (a clean 400), not an InvalidOperationException from GetString()."); - sb.AppendLine(" if (reader.TokenType != JsonTokenType.String && reader.TokenType != JsonTokenType.Null)"); - sb.AppendLine(" throw new JsonException(\"expected a JSON string\");"); - sb.AppendLine(" string? raw = reader.GetString();"); - sb.AppendLine(" if (raw is null) return null;"); - sb.AppendLine(" // No trim: IP-literal grammar has no whitespace, so padding is rejected."); - sb.AppendLine(" if (raw.IndexOf(':') >= 0)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (IPAddress.TryParse(raw, out IPAddress? v6)) return v6; // ':' => IPv6 literal, no DNS"); - sb.AppendLine(" throw new JsonException(\"field.inet: not a valid IPv6 literal: \" + raw);"); - sb.AppendLine(" }"); - sb.AppendLine(" return ParseIpv4(raw);"); - sb.AppendLine(" }"); - sb.AppendLine(" public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options)"); - sb.AppendLine(" => writer.WriteStringValue(value.ToString());"); - sb.AppendLine(); - sb.AppendLine(" private static IPAddress ParseIpv4(string s)"); - sb.AppendLine(" {"); - sb.AppendLine(" string[] parts = s.Split('.');"); - sb.AppendLine(" if (parts.Length != 4)"); - sb.AppendLine(" throw new JsonException(\"field.inet: not a valid IPv4 literal: \" + s);"); - sb.AppendLine(" var octets = new byte[4];"); - sb.AppendLine(" for (int i = 0; i < 4; i++)"); - sb.AppendLine(" {"); - sb.AppendLine(" string part = parts[i];"); - sb.AppendLine(" // #234 review H1: reject a leading-zero octet (010 / 01) — the"); - sb.AppendLine(" // octal/decimal-parse ambiguity — matching Python ipaddress + the TS regex."); - sb.AppendLine(" if (part.Length == 0 || part.Length > 3 || (part.Length > 1 && part[0] == '0'))"); - sb.AppendLine(" throw new JsonException(\"field.inet: not a valid IPv4 literal: \" + s);"); - sb.AppendLine(" foreach (char ch in part)"); - sb.AppendLine(" if (!char.IsDigit(ch))"); - sb.AppendLine(" throw new JsonException(\"field.inet: not a valid IPv4 literal: \" + s);"); - sb.AppendLine(" int v = int.Parse(part);"); - sb.AppendLine(" if (v > 255)"); - sb.AppendLine(" throw new JsonException(\"field.inet: IPv4 octet out of range: \" + s);"); - sb.AppendLine(" octets[i] = (byte)v;"); - sb.AppendLine(" }"); - sb.AppendLine(" return new IPAddress(octets);"); - sb.AppendLine(" }"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - return new EmittedFile(fileName, sb.ToString()) { WholeModel = true }; - } - - // One property's declaration line, from the two hooks: `public { }` - // plus ` = ;` when PropertyInitializer gives one. The attributes above it are the - // caller's. - private string PropertyDeclaration( - MetaObject owner, MetaField field, string propName, string setter, GenContext? ctx = null) + var w = new CsWriter(); + w.Text(""" +// +// Generated by MetaObjects entity-generator. Do not edit by hand. +#nullable enable +using System; +using System.Net; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +"""); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Text(""" +/// GENERATED (#234) — strict System.Text.Json converters for field.uri / +/// field.inet. Dependency-free; runs without any MetaObjects runtime. +public static class MetaNetValidation +{ + /// field.uri — an ABSOLUTE URI carrying an explicit scheme (leading/trailing + /// whitespace trimmed, WHATWG). A relative reference (example.com, /path) or malformed + /// value is rejected. + public sealed class AbsoluteUriJsonConverter : JsonConverter + { + public override Uri? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + // #234 review N2: a non-string JSON token (number/object/array) rejects as a + // JsonException (a clean 400), not an InvalidOperationException from GetString(). + if (reader.TokenType != JsonTokenType.String && reader.TokenType != JsonTokenType.Null) + throw new JsonException("expected a JSON string"); + string? raw = reader.GetString(); + if (raw is null) return null; + string s = raw.Trim(); + // Require an explicit scheme so a bare path ("/x") is not inferred as a file: URI + // on .NET, AND that it parses as an absolute URI. + if (!Regex.IsMatch(s, "^[a-zA-Z][a-zA-Z0-9+.-]*:") + || !Uri.TryCreate(s, UriKind.Absolute, out Uri? uri)) + throw new JsonException("field.uri: must be an absolute URI carrying a scheme: " + raw); + return uri; + } + public override void Write(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options) + => writer.WriteStringValue(value.OriginalString); + } + + /// field.inet — an IPv4 or IPv6 LITERAL only. Never a DNS lookup: a value + /// containing ':' can only be an IPv6 literal, otherwise a strict dotted-quad IPv4. + /// Hostnames, CIDR, padding, out-of-range octets are rejected. + public sealed class IPAddressJsonConverter : JsonConverter + { + public override IPAddress? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + // #234 review N2: a non-string JSON token (number/object/array) rejects as a + // JsonException (a clean 400), not an InvalidOperationException from GetString(). + if (reader.TokenType != JsonTokenType.String && reader.TokenType != JsonTokenType.Null) + throw new JsonException("expected a JSON string"); + string? raw = reader.GetString(); + if (raw is null) return null; + // No trim: IP-literal grammar has no whitespace, so padding is rejected. + if (raw.IndexOf(':') >= 0) + { + if (IPAddress.TryParse(raw, out IPAddress? v6)) return v6; // ':' => IPv6 literal, no DNS + throw new JsonException("field.inet: not a valid IPv6 literal: " + raw); + } + return ParseIpv4(raw); + } + public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString()); + + private static IPAddress ParseIpv4(string s) + { + string[] parts = s.Split('.'); + if (parts.Length != 4) + throw new JsonException("field.inet: not a valid IPv4 literal: " + s); + var octets = new byte[4]; + for (int i = 0; i < 4; i++) + { + string part = parts[i]; + // #234 review H1: reject a leading-zero octet (010 / 01) — the + // octal/decimal-parse ambiguity — matching Python ipaddress + the TS regex. + if (part.Length == 0 || part.Length > 3 || (part.Length > 1 && part[0] == '0')) + throw new JsonException("field.inet: not a valid IPv4 literal: " + s); + foreach (char ch in part) + if (!char.IsDigit(ch)) + throw new JsonException("field.inet: not a valid IPv4 literal: " + s); + int v = int.Parse(part); + if (v > 255) + throw new JsonException("field.inet: IPv4 octet out of range: " + s); + octets[i] = (byte)v; + } + return new IPAddress(octets); + } + } +} +"""); + return new EmittedFile(fileName, w.ToString()) { WholeModel = true }; + } + + // One property's declaration, from the two hooks: `public { }` plus + // ` = ;` when PropertyInitializer gives one. The attributes above it are the caller's; the + // EmitPropertyAttributes hook writes its own just before it. + private void WritePropertyDeclaration( + CsWriter w, MetaObject owner, MetaField field, string propName, string setter, GenContext? ctx = null) { ctx ??= HookContext(); var init = PropertyInitializer(owner, field, ctx); - return $" public {PropertyClrType(owner, field, ctx)} {propName} {{ {setter} }}" - + (init is null ? string.Empty : $" = {init};"); + var type = PropertyClrType(owner, field, ctx); + EmitPropertyAttributes(w, owner, field, ctx); + w.Line($"public {type} {propName} {{ {setter} }}" + (init is null ? string.Empty : $" = {init};")); } /// @@ -2733,15 +2692,15 @@ protected virtual IEnumerable ColumnAttributeArguments(MetaObject owner, // default so it reproduces that emitter's own [Column] exactly. private (ColumnNamingStrategy Strategy, bool IncludeNames)? _columnSite; - // The ` [Column(...)]` line (no newline), or null when ColumnAttributeArguments returns none. - private string? ColumnAttributeLine( + // The `[Column(...)]` attribute (no indent), or null when ColumnAttributeArguments returns none. + private string? ColumnAttribute( MetaObject owner, MetaField field, ColumnNamingStrategy strategy, bool includeNames, GenContext? ctx = null) { _columnSite = (strategy, includeNames); try { var args = ColumnAttributeArguments(owner, field, ctx ?? HookContext()).ToList(); - return args.Count == 0 ? null : $" [Column({string.Join(", ", args)})]"; + return args.Count == 0 ? null : $"[Column({string.Join(", ", args)})]"; } finally { @@ -2753,18 +2712,18 @@ protected virtual IEnumerable ColumnAttributeArguments(MetaObject owner, // When the field is an array, see EnumArrayProperty. // withAttributes adds the EF [Column] mapping; abstract shape classes pass false // (shapes carry no EF mapping). - protected virtual string EnumProperty( - MetaObject entity, MetaField field, GenConfig config, ColumnNamingStrategy strategy, bool withAttributes = true) + protected virtual void WriteEnumProperty( + CsWriter w, MetaObject entity, MetaField field, GenConfig config, ColumnNamingStrategy strategy, bool withAttributes = true) { // FR-019 — a shared/provided enum is referenced (materialized once / external); // an inline enum keeps the per-object nested type name. (The type and // the array initializer are the PropertyClrType / PropertyInitializer defaults.) _site = new PropertySite(ValueObject: false, TphSubtype: false, null); var propName = PropertyName(field); - var colAttr = withAttributes && ColumnAttributeLine(entity, field, strategy, config.IncludeNames) is { } column - ? column + "\n" - : ""; - return colAttr + PropertyDeclaration(entity, field, propName, SetterFor(field)); + BeginMember(w, entity, field); + if (withAttributes && ColumnAttribute(entity, field, strategy, config.IncludeNames) is { } column) + w.Line(column); + WritePropertyDeclaration(w, entity, field, propName, SetterFor(field)); } // A scalar property. withAttributes adds the EF-mapping annotations ([Key] for a @@ -2786,8 +2745,8 @@ protected virtual string EnumProperty( // ctx.Config.IncludeNames run-level presence gate CSharpNaming.ColumnRef needs; // defaults to false because a withAttributes:false caller (abstract shapes, VO // POCOs) never reaches ColumnRef at all, so the default is inert there. - protected virtual string ScalarProperty( - MetaObject owner, MetaField field, IReadOnlyList pkFields, + protected virtual void WriteScalarProperty( + CsWriter w, MetaObject owner, MetaField field, IReadOnlyList pkFields, bool withAttributes, ColumnNamingStrategy? strategy = null, bool includeNames = false, string? baseTypeOverride = null, bool? withValidationAttributes = null, @@ -2802,30 +2761,30 @@ protected virtual string ScalarProperty( // resolves the ADR-0036 Wave 2 conditional field.timestamp binding (default // DateTimeOffset / @localTime:true DateTime). var propName = PropertyName(field); + BeginMember(w, owner, field); // Array fields: emit List with an empty-list initializer and only a [Column] // attribute — [Key]/[MaxLength]/[Required] are not meaningful for a List jsonb // column (arrays are never PKs, and the list itself is never null in C#). if (field.ResolvedIsArray()) // ADR-0039: resolving — array-ness inheritable via extends { - var arr = new StringBuilder(); - if (withAttributes && ColumnAttributeLine(owner, field, strategy, includeNames) is { } arrColumn) + if (withAttributes && ColumnAttribute(owner, field, strategy, includeNames) is { } arrColumn) { - arr.AppendLine(arrColumn); + w.Line(arrColumn); } // validator.array @min/@max → element-count bounds on the collection. if (emitValidation) - AppendArrayValidatorAttributes(arr, field); + WriteArrayValidatorAttributes(w, field); // EF Core 8 on SQLite materializes a primitive collection only through IList (an // ICollection property throws at query compile time), so a scalar array is an IList. - AppendDecimalConverterAttribute(arr, field, nullable: false, _wire); - AppendDurationConverterAttribute(arr, field, _wire); + WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection; a // NON-required value-object array is nullable so a null member is omitted on the wire. // (That rule is the default of the PropertyClrType / PropertyInitializer hooks.) - arr.Append(PropertyDeclaration(owner, field, propName, SetterFor(field))); - return arr.ToString(); + WritePropertyDeclaration(w, owner, field, propName, SetterFor(field)); + return; } var baseType = ScalarBaseType(field); @@ -2837,16 +2796,15 @@ protected virtual string ScalarProperty( // [Required] validation attr stays keyed on `required` (author intent), while // the nullability `?` + `= default!;` init follow `nonNull` — mirroring TS // column-mapper, where notNull = isRequired || originGuaranteedNonNull. - var sb = new StringBuilder(); // EF-mapping attributes ([Key]/[Column]) — mapped entities only; a VO POCO's // JSON member mapping is fluent (.ToJson), so it carries none of these. if (withAttributes) { if (pkFields.Count == 1 && pkFields[0] == field.Name) - sb.AppendLine(" [Key]"); - if (ColumnAttributeLine(owner, field, strategy, includeNames) is { } column) + w.Line("[Key]"); + if (ColumnAttribute(owner, field, strategy, includeNames) is { } column) { - sb.AppendLine(column); + w.Line(column); } } // Validation DataAnnotations — mapped entities AND value-object POCOs (a VO's @@ -2862,14 +2820,14 @@ protected virtual string ScalarProperty( // floor of 1, folded into the length validator (see AppendStringValidatorAttributes) // so a validator.length @min is not double-emitted. if (required) - sb.AppendLine(" [Required(AllowEmptyStrings = true)]"); - AppendStringValidatorAttributes(sb, field, requiredMinFloor: required ? 1 : 0); + w.Line("[Required(AllowEmptyStrings = true)]"); + WriteStringValidatorAttributes(w, field, requiredMinFloor: required ? 1 : 0); } else { - AppendNumericValidatorAttributes(sb, field); + WriteNumericValidatorAttributes(w, field); if (required && !isValue) - sb.AppendLine(" [Required]"); + w.Line("[Required]"); } } @@ -2877,13 +2835,13 @@ protected virtual string ScalarProperty( // JsonConverter (absolute-scheme URI / IPv4-or-IPv6 literal, no DNS) so a malformed value // is rejected at the wire tier — aligning the C# entity with the TS/Python strict contract. if (emitValidation) - AppendNetConverterAttribute(sb, field); + WriteNetConverterAttribute(w, field); // ADR-0019 Amendment 1: a decimal crosses JSON as a canonical string. Attached per // property (not through host JsonSerializerOptions) so no host configuration drops it. - AppendDecimalConverterAttribute(sb, field, nullable: !ScalarIsNonNull(owner, field), _wire); + WriteDecimalConverterAttribute(w, field, nullable: !ScalarIsNonNull(owner, field), _wire); // field.duration: a TimeSpan crosses JSON as its canonical ISO-8601 string, never as // System.Text.Json's own "01:30:00". - AppendDurationConverterAttribute(sb, field, _wire); + WriteDurationConverterAttribute(w, field, _wire); // The type and initializer are the hooks' defaults: nullable unless required (or // origin-guaranteed non-null), a literal-safe @default as the initializer (e.g. `= false;`) @@ -2894,8 +2852,7 @@ protected virtual string ScalarProperty( // must be able to supply it on insert; freezing it afterwards is the DbContext's // SetAfterSaveBehavior(Ignore), not the property's job. var setter = SetterFor(field); - sb.Append(PropertyDeclaration(owner, field, propName, setter)); - return sb.ToString(); + WritePropertyDeclaration(w, owner, field, propName, setter); } // String length + pattern DataAnnotations for a string scalar, combining the field @@ -2916,8 +2873,8 @@ protected virtual string ScalarProperty( // opts back to presence-only, emitting no minimum constraint whatsoever. When the floor // does apply (no @min authored), it becomes a standalone [MinLength] alongside the // [MaxLength] (so the max attribute is undisturbed). - protected static void AppendStringValidatorAttributes( - StringBuilder sb, MetaField field, long requiredMinFloor = 0) + protected static void WriteStringValidatorAttributes( + CsWriter w, MetaField field, long requiredMinFloor = 0) { // ADR-0036 Wave 3 — @stringFormat narrows a plain string to a closed validated // format. The canonical matcher per format lives HERE (codegen), never author @@ -2927,10 +2884,10 @@ protected static void AppendStringValidatorAttributes( switch (field.Attr(FIELD_ATTR_STRING_FORMAT) as string) { case STRING_FORMAT_EMAIL: - sb.AppendLine(" [EmailAddress]"); + w.Line("[EmailAddress]"); break; case STRING_FORMAT_HOSTNAME: - sb.AppendLine($" [RegularExpression(@\"{CSharpNaming.HostnameRegex}\")]"); + w.Line($"[RegularExpression(@\"{CSharpNaming.HostnameRegex}\")]"); break; } @@ -2957,7 +2914,7 @@ protected static void AppendStringValidatorAttributes( // the anchored TS/Python (^(?:…)$) and Java/Kotlin (Matcher.matches) ports // ACCEPT. Wrapping forces the engine to backtrack to a full match. Redundant // on an already-anchored authored pattern (^(?:^…$)$ matches identically). - sb.AppendLine($" [RegularExpression(\"^(?:{EscapeAttrString(pattern)})$\")]"); + w.Line($"[RegularExpression(\"^(?:{EscapeAttrString(pattern)})$\")]"); } } @@ -2986,23 +2943,23 @@ protected static void AppendStringValidatorAttributes( // A pure required-floor min (no validator @min) keeps [MaxLength] and adds a // standalone [MinLength], leaving the max attribute unchanged. if (validatorMin is not null) - sb.AppendLine($" [StringLength({mx}, MinimumLength = {mn})]"); + w.Line($"[StringLength({mx}, MinimumLength = {mn})]"); else { - sb.AppendLine($" [MaxLength({mx})]"); - sb.AppendLine($" [MinLength({mn})]"); + w.Line($"[MaxLength({mx})]"); + w.Line($"[MinLength({mn})]"); } } else if (min is long mn2) - sb.AppendLine($" [MinLength({mn2})]"); + w.Line($"[MinLength({mn2})]"); else if (max is long mx2) - sb.AppendLine($" [MaxLength({mx2})]"); + w.Line($"[MaxLength({mx2})]"); } // Numeric value bounds for a non-string scalar: validator.numeric (@min/@max) → // [Range(min, max)]. Both bounds present in the canonical corpus; when only one is // declared the other defaults to the type's extreme so the single bound still gates. - protected static void AppendNumericValidatorAttributes(StringBuilder sb, MetaField field) + protected static void WriteNumericValidatorAttributes(CsWriter w, MetaField field) { foreach (var v in field.Validators()) { @@ -3010,20 +2967,20 @@ protected static void AppendNumericValidatorAttributes(StringBuilder sb, MetaFie if (v.Min is null && v.Max is null) continue; long lo = v.Min ?? long.MinValue; long hi = v.Max ?? long.MaxValue; - sb.AppendLine($" [Range({lo}, {hi})]"); + w.Line($"[Range({lo}, {hi})]"); return; } } // Element-count bounds for an array field: validator.array (@min/@max) → // [MinLength(min)] + [MaxLength(max)] on the List property. - protected static void AppendArrayValidatorAttributes(StringBuilder sb, MetaField field) + protected static void WriteArrayValidatorAttributes(CsWriter w, MetaField field) { foreach (var v in field.Validators()) { if (v.SubType != VALIDATOR_SUBTYPE_ARRAY) continue; - if (v.Min is long amin) sb.AppendLine($" [MinLength({amin})]"); - if (v.Max is long amax) sb.AppendLine($" [MaxLength({amax})]"); + if (v.Min is long amin) w.Line($"[MinLength({amin})]"); + if (v.Max is long amax) w.Line($"[MaxLength({amax})]"); return; } } @@ -3123,8 +3080,8 @@ protected static string EscapeAttrString(string s) { case '\\': sb.Append("\\\\"); break; case '"': sb.Append("\\\""); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; + case (char)10: sb.Append("\\n"); break; // the escape for a line feed, not a line break + case (char)13: sb.Append("\\r"); break; // the escape for a carriage return case '\t': sb.Append("\\t"); break; default: if (char.IsControl(c) || c is '\u2028' or '\u2029') @@ -3145,15 +3102,16 @@ protected static string EscapeAttrString(string s) // deserializes with it present instead of null behind a non-nullable type. An abstract // target cannot be constructed and keeps the filler; an entity's owned navigation keeps it // too (EF materializes it from the row). - protected string? ObjectNavProperty(MetaObject owner, MetaField field, GenContext ctx, bool valueObject = false) + protected bool WriteObjectNavProperty(CsWriter w, MetaObject owner, MetaField field, GenContext ctx, bool valueObject = false) { if (ValueObjectNames.ResolveFieldRef(field, ctx.Root) is not { } target) { ctx.Warn($"{Name}: object-typed field \"{owner.Name}.{field.Name}\" has an unresolved @objectRef \"{field.ObjectRef}\" — skipped."); - return null; + return false; } _site = new PropertySite(valueObject, TphSubtype: false, null); var propName = PropertyName(field); + BeginMember(w, owner, field); // An object-typed field with @isArray:true is a COLLECTION of the value object // (EF maps it via .OwnsMany(...).ToJson(...)), not a single nullable ref. A REQUIRED // array is a non-null collection with an empty-list initializer (never null). A @@ -3162,7 +3120,8 @@ protected static string EscapeAttrString(string s) // single-VO nullability below. A non-null empty-list default would erase that // null-vs-empty distinction (EF re-serializes the empty list to `[]` on write). // (The type and initializer are the PropertyClrType / PropertyInitializer defaults.) - return PropertyDeclaration(owner, field, propName, SetterFor(field), ctx); + WritePropertyDeclaration(w, owner, field, propName, SetterFor(field), ctx); + return true; } // A property for a field.map (an open-keyed map). Emits a single @@ -3184,15 +3143,15 @@ protected static string EscapeAttrString(string s) // When @objectRef names a value object, the resolved VO becomes a referenced POCO // via the normal ReferencedValueObjects walk. withAttributes adds the EF [Column] // mapping; value-object POCOs (no EF mapping) pass false. - protected string MapProperty(MetaObject owner, MetaField field, GenContext ctx, bool withAttributes = true) + protected void WriteMapProperty(CsWriter w, MetaObject owner, MetaField field, GenContext ctx, bool withAttributes = true) { _site = new PropertySite(ValueObject: false, TphSubtype: false, null); var propName = PropertyName(field); - var colAttr = withAttributes - && ColumnAttributeLine(owner, field, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, ctx) is { } column - ? column + "\n" - : ""; - return colAttr + PropertyDeclaration(owner, field, propName, SetterFor(field), ctx); + BeginMember(w, owner, field); + if (withAttributes + && ColumnAttribute(owner, field, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, ctx) is { } column) + w.Line(column); + WritePropertyDeclaration(w, owner, field, propName, SetterFor(field), ctx); } // The CLR scalar type for a projection field whose value is a MIN/MAX aggregate: diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs index 5c47fa9b86..b03ada4a77 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs @@ -10,6 +10,7 @@ // the file re-applies. using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Persistence.Db.DbConstants; using static MetaObjects.Persistence.Source.SourceConstants; @@ -65,11 +66,19 @@ MetaIndex mi when mi.IsLookup() => false, } if (statements.Count == 0) yield break; - var file = new StringBuilder() - .Append("-- MetaObjects expression-indexes. Do not edit by hand.\n") - .Append("-- The expression indexes (@expr) the EF model cannot carry; apply after the schema EF builds.\n\n"); - foreach (var statement in statements.Values) file.Append(statement).Append('\n'); - yield return new EmittedFile(FileName, file.ToString()); + // A SQL file, so the comments are `--`, but the writer still owns the line breaks and the + // blank line between the header and the statements. An expression written over several + // lines stays on several lines, each handed to the writer on its own. + var w = new CsWriter(); + w.Line("-- MetaObjects expression-indexes. Do not edit by hand."); + w.Line("-- The expression indexes (@expr) the EF model cannot carry; apply after the schema EF builds."); + w.Blank(); + foreach (var statement in statements.Values) + { + using var lines = new StringReader(statement); + while (lines.ReadLine() is { } line) w.Line(line); + } + yield return new EmittedFile(FileName, w.ToString()); } private static IEnumerable IndexNodes(MetaObject o) => diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs index 73b0a3aace..cf42eeeebb 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs @@ -23,7 +23,7 @@ using System.Collections.Generic; using System.Linq; -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Shared.BaseTypes; using static MetaObjects.Shared.Structural; @@ -157,20 +157,18 @@ public static EmittedFile MirrorFile(MetaData vo, MetaData root, GenConfig confi { var ns = ValueObjectNames.Namespace(vo, config); var name = MirrorName(vo, root); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects output-parser-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine($"/// Best-effort extracted twin of {ValueObjectNames.TypeName(vo, root)} — every component nullable (null where lost/malformed)."); - sb.AppendLine($"public sealed record {name}"); - sb.AppendLine("{"); - foreach (var f in Fr010FieldMapping.Fields(vo)) - sb.AppendLine($" public {NestedMirrorType(f, root, config, ns)} {f.Name} {{ get; init; }}"); - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(vo, config, $"{name}.g.cs"), sb.ToString()); + var w = new CsWriter(); + w.GeneratedFileHeader("output-parser-generator"); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Line($"/// Best-effort extracted twin of {ValueObjectNames.TypeName(vo, root)} — every component nullable (null where lost/malformed)."); + using (w.Braced($"public sealed record {name}")) + { + foreach (var f in Fr010FieldMapping.Fields(vo)) + w.Line($"public {NestedMirrorType(f, root, config, ns)} {f.Name} {{ get; init; }}"); + } + return new EmittedFile(OutputPaths.Of(vo, config, $"{name}.g.cs"), w.ToString()); } // ========================================================================= @@ -184,7 +182,7 @@ public static EmittedFile MirrorFile(MetaData vo, MetaData root, GenConfig confi /// mappers (payload + nested, deduped), and the shared ReadProp / MapObjectList /// / Dlg* helpers. /// - public static string DelegatingMembers(MetaData vo, MetaData root, GenConfig config, + public static void WriteDelegatingMembers(CsWriter w, MetaData vo, MetaData root, GenConfig config, string fromNamespace, string formatEnum) { string rootMirror = MirrorRef(vo, root, config, fromNamespace); @@ -209,70 +207,73 @@ public static string DelegatingMembers(MetaData vo, MetaData root, GenConfig con bool payloadNameAmbiguous = root.Children().Count(c => c.Type == TYPE_OBJECT && c.Name == vo.Name) > 1; string bakedPayloadFqn = payloadNameAmbiguous ? vo.ResolutionKey() : vo.Name; - var sb = new StringBuilder(); - sb.AppendLine(); - sb.AppendLine(" // FR-010 — runtime-delegating extraction (the single metadata-driven extract path)."); - sb.AppendLine(" // Delegates to the runtime MetaObjects.Codegen.Runtime.ExtractObject, which assembles the"); - sb.AppendLine(" // FULL object graph (nested objects + arrays-of-objects) reflection-free by reading the live"); - sb.AppendLine(" // metadata, then maps it into the typed nullable mirror via From*Extracted."); - sb.AppendLine(); + w.Blank(); + w.Line("// FR-010 — runtime-delegating extraction (the single metadata-driven extract path)."); + w.Line("// Delegates to the runtime MetaObjects.Codegen.Runtime.ExtractObject, which assembles the"); + w.Line("// FULL object graph (nested objects + arrays-of-objects) reflection-free by reading the live"); + w.Line("// metadata, then maps it into the typed nullable mirror via From*Extracted."); + w.Blank(); var ambiguousNote = payloadNameAmbiguous ? " ADR-0042 FQN (this payload's bare name collides with a same-short-name object elsewhere in the run)." : ""; - sb.AppendLine($" /// The payload's metadata name — resolve it against a loaded MetaRoot to obtain the runtime MetaObject.{ambiguousNote}"); - sb.AppendLine($" public const string PAYLOAD_FQN = \"{CSharpNaming.CSharpStringLiteral(bakedPayloadFqn)}\";"); - sb.AppendLine(); - sb.AppendLine($" /// Tolerant best-effort extraction delegating to the runtime; fully populates nested-object and"); - sb.AppendLine($" /// array-of-object components by reading the live metadata. Never throws."); - sb.AppendLine($" public static global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}> ExtractLenient("); - sb.AppendLine($" global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions? opts = null)"); - sb.AppendLine(" {"); - sb.AppendLine($" var raw = global::MetaObjects.Codegen.Runtime.ExtractObject.Extract(mo, text, {formatEnum}, opts);"); - sb.AppendLine(" // The assembled graph is a ValueObject (nested ValueObjects / lists of them) — map it into"); - sb.AppendLine(" // the typed mirror graph. ReadProp mirrors the MetaField GetValue SPI (reflection-free)."); - sb.AppendLine($" var data = {MapperName(vo, root)}(raw.Data);"); - sb.AppendLine($" return new global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}>(data, raw.Report);"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine($" /// Convenience overload — resolves from a loaded MetaRoot, then delegates."); - sb.AppendLine($" public static global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}> ExtractLenient("); - sb.AppendLine($" global::MetaObjects.Meta.MetaRoot root, string text, ExtractOptions? opts = null)"); - sb.AppendLine(" {"); - // NamingRefs.LookupCanonical returns MetaData?; ExtractLenient(MetaObject, ...) needs a - // MetaObject — the "as" narrows (never a hard cast throw) matching root.FindObject's own - // MetaObject? return type on the unique path. - sb.AppendLine(payloadNameAmbiguous - ? " var mo = global::MetaObjects.NamingRefs.LookupCanonical(root, PAYLOAD_FQN) as global::MetaObjects.Meta.MetaObject" - : " var mo = root.FindObject(PAYLOAD_FQN)"); - sb.AppendLine(" ?? throw new global::System.InvalidOperationException("); - sb.AppendLine(" $\"payload object \\\"{PAYLOAD_FQN}\\\" not found in the loaded metadata\");"); - sb.AppendLine(" return ExtractLenient(mo, text, opts);"); - sb.AppendLine(" }"); + w.Line($"/// The payload's metadata name — resolve it against a loaded MetaRoot to obtain the runtime MetaObject.{ambiguousNote}"); + w.Line($"public const string PAYLOAD_FQN = \"{CSharpNaming.CSharpStringLiteral(bakedPayloadFqn)}\";"); + w.Blank(); + w.Line("/// Tolerant best-effort extraction delegating to the runtime; fully populates nested-object and"); + w.Line("/// array-of-object components by reading the live metadata. Never throws."); + w.Line($"public static global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}> ExtractLenient("); + using (w.Hanging()) w.Line("global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions? opts = null)"); + using (w.Block("{")) + { + w.Line($"var raw = global::MetaObjects.Codegen.Runtime.ExtractObject.Extract(mo, text, {formatEnum}, opts);"); + w.Line("// The assembled graph is a ValueObject (nested ValueObjects / lists of them) — map it into"); + w.Line("// the typed mirror graph. ReadProp mirrors the MetaField GetValue SPI (reflection-free)."); + w.Line($"var data = {MapperName(vo, root)}(raw.Data);"); + w.Line($"return new global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}>(data, raw.Report);"); + } + w.Blank(); + w.Line("/// Convenience overload — resolves from a loaded MetaRoot, then delegates."); + w.Line($"public static global::MetaObjects.Render.Extract.ExtractionResult<{rootMirror}> ExtractLenient("); + using (w.Hanging()) w.Line("global::MetaObjects.Meta.MetaRoot root, string text, ExtractOptions? opts = null)"); + using (w.Block("{")) + { + // NamingRefs.LookupCanonical returns MetaData?; ExtractLenient(MetaObject, ...) needs a + // MetaObject — the "as" narrows (never a hard cast throw) matching root.FindObject's own + // MetaObject? return type on the unique path. + w.Line(payloadNameAmbiguous + ? "var mo = global::MetaObjects.NamingRefs.LookupCanonical(root, PAYLOAD_FQN) as global::MetaObjects.Meta.MetaObject" + : "var mo = root.FindObject(PAYLOAD_FQN)"); + using (w.Hanging()) + { + w.Line("?? throw new global::System.InvalidOperationException("); + using (w.Hanging()) w.Line("$\"payload object \\\"{PAYLOAD_FQN}\\\" not found in the loaded metadata\");"); + } + w.Line("return ExtractLenient(mo, text, opts);"); + } // ---- mappers: one FromExtracted per value object the mirror reaches (the // root included), deduped by FQN — so a nested reference back to the root resolves. foreach (var v in MirrorClosure(vo, root)) - EmitMapper(sb, v, root, config, fromNamespace); + WriteMapper(w, v, root, config, fromNamespace); // ---- shared helpers - AppendHelpers(sb); - return sb.ToString(); + WriteHelpers(w); } - private static void EmitMapper(StringBuilder sb, MetaData vo, MetaData root, GenConfig config, string fromNamespace) + private static void WriteMapper(CsWriter w, MetaData vo, MetaData root, GenConfig config, string fromNamespace) { string mirror = MirrorRef(vo, root, config, fromNamespace); - sb.AppendLine(); - sb.AppendLine($" /// Map an assembled ValueObject graph into a typed {MirrorName(vo, root)}. Generated; null-tolerant."); - sb.AppendLine($" private static {mirror}? {MapperName(vo, root)}(object? o)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (o is null) return null;"); - sb.AppendLine($" return new {mirror}"); - sb.AppendLine(" {"); - foreach (var f in Fr010FieldMapping.Fields(vo)) - sb.AppendLine($" {f.Name} = {MapperArg(f, root)},"); - sb.AppendLine(" };"); - sb.AppendLine(" }"); + w.Blank(); + w.Line($"/// Map an assembled ValueObject graph into a typed {MirrorName(vo, root)}. Generated; null-tolerant."); + using (w.Braced($"private static {mirror}? {MapperName(vo, root)}(object? o)")) + { + w.Line("if (o is null) return null;"); + using (w.Braced($"return new {mirror}", "};")) + { + foreach (var f in Fr010FieldMapping.Fields(vo)) + w.Line($"{f.Name} = {MapperArg(f, root)},"); + } + } } /// The mirror-field initializer expression that reads from the assembled object. @@ -332,59 +333,61 @@ private static string MapperArg(MetaData field, MetaData root) }; /// - /// Append the shared runtime-delegating helpers the mappers rely on. ReadProp mirrors + /// Write the shared runtime-delegating helpers the mappers rely on. ReadProp mirrors /// the MetaField GetValue SPI (ValueObject.Get(name)) so the mappers stay reflection-free /// + backing-agnostic; MapObjectList maps an assembled list element-wise; the Dlg* /// readers light-coerce to the mirror's nullable scalar shapes. (The Dlg prefix avoids /// shadowing the render ExtractMap.As*(d, key) two-arg readers the self-contained path uses.) /// - private static void AppendHelpers(StringBuilder sb) + private static void WriteHelpers(CsWriter w) { - sb.AppendLine(); - sb.AppendLine(" // ---- runtime-delegating extract helpers (generated) ----"); - sb.AppendLine(); - sb.AppendLine(" /// Read a property from an assembled backing object, mirroring the MetaField GetValue SPI."); - sb.AppendLine(" private static object? ReadProp(object? o, string name) =>"); - sb.AppendLine(" o is global::MetaObjects.Meta.ValueObject vo ? vo.Get(name) : null;"); - sb.AppendLine(); - sb.AppendLine(" /// Map each element of an assembled list via ; null/absent -> null."); - sb.AppendLine(" private static global::System.Collections.Generic.IReadOnlyList? MapObjectList("); - sb.AppendLine(" object? v, global::System.Func fn) where T : class"); - sb.AppendLine(" {"); - sb.AppendLine(" if (v is not global::System.Collections.IEnumerable e || v is string) return null;"); - sb.AppendLine(" var outList = new global::System.Collections.Generic.List();"); - sb.AppendLine(" foreach (var elem in e) outList.Add(fn(elem));"); - sb.AppendLine(" return outList;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" private static string? DlgString(object? v) => v?.ToString();"); - sb.AppendLine(); - sb.AppendLine(" private static int? DlgInt(object? v) => v switch"); - sb.AppendLine(" {"); - sb.AppendLine(" null => null,"); - sb.AppendLine(" int i => i,"); - sb.AppendLine(" long l => unchecked((int)l),"); - sb.AppendLine(" global::System.IConvertible => global::System.Convert.ToInt32(v, global::System.Globalization.CultureInfo.InvariantCulture),"); - sb.AppendLine(" _ => int.TryParse(v.ToString(), out var n) ? n : (int?)null,"); - sb.AppendLine(" };"); - sb.AppendLine(); - sb.AppendLine(" private static long? DlgLong(object? v) => v switch"); - sb.AppendLine(" {"); - sb.AppendLine(" null => null,"); - sb.AppendLine(" long l => l,"); - sb.AppendLine(" int i => i,"); - sb.AppendLine(" global::System.IConvertible => global::System.Convert.ToInt64(v, global::System.Globalization.CultureInfo.InvariantCulture),"); - sb.AppendLine(" _ => long.TryParse(v.ToString(), out var n) ? n : (long?)null,"); - sb.AppendLine(" };"); - sb.AppendLine(); - sb.AppendLine(" private static double? DlgDouble(object? v) => v switch"); - sb.AppendLine(" {"); - sb.AppendLine(" null => null,"); - sb.AppendLine(" double d => d,"); - sb.AppendLine(" global::System.IConvertible => global::System.Convert.ToDouble(v, global::System.Globalization.CultureInfo.InvariantCulture),"); - sb.AppendLine(" _ => double.TryParse(v.ToString(), global::System.Globalization.NumberStyles.Any, global::System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : (double?)null,"); - sb.AppendLine(" };"); - sb.AppendLine(); + w.Blank(); + w.Text(""" + // ---- runtime-delegating extract helpers (generated) ---- + + /// Read a property from an assembled backing object, mirroring the MetaField GetValue SPI. + private static object? ReadProp(object? o, string name) => + o is global::MetaObjects.Meta.ValueObject vo ? vo.Get(name) : null; + + /// Map each element of an assembled list via ; null/absent -> null. + private static global::System.Collections.Generic.IReadOnlyList? MapObjectList( + object? v, global::System.Func fn) where T : class + { + if (v is not global::System.Collections.IEnumerable e || v is string) return null; + var outList = new global::System.Collections.Generic.List(); + foreach (var elem in e) outList.Add(fn(elem)); + return outList; + } + + private static string? DlgString(object? v) => v?.ToString(); + + private static int? DlgInt(object? v) => v switch + { + null => null, + int i => i, + long l => unchecked((int)l), + global::System.IConvertible => global::System.Convert.ToInt32(v, global::System.Globalization.CultureInfo.InvariantCulture), + _ => int.TryParse(v.ToString(), out var n) ? n : (int?)null, + }; + + private static long? DlgLong(object? v) => v switch + { + null => null, + long l => l, + int i => i, + global::System.IConvertible => global::System.Convert.ToInt64(v, global::System.Globalization.CultureInfo.InvariantCulture), + _ => long.TryParse(v.ToString(), out var n) ? n : (long?)null, + }; + + private static double? DlgDouble(object? v) => v switch + { + null => null, + double d => d, + global::System.IConvertible => global::System.Convert.ToDouble(v, global::System.Globalization.CultureInfo.InvariantCulture), + _ => double.TryParse(v.ToString(), global::System.Globalization.NumberStyles.Any, global::System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : (double?)null, + }; + """); + w.Blank(); // Mirrors ExtractMap.AsDecimal's never-throws contract (the self-contained path's reader): // integer kinds widen losslessly, a boxed double/float converts (lossy by nature of the // source), anything non-numeric is null. The explicit range guard is what keeps the cast @@ -393,44 +396,46 @@ private static void AppendHelpers(StringBuilder sb) // conservative literal below decimal.MaxValue (7.9228e28) because (double)decimal.MaxValue // rounds UP, so comparing against it would admit values that still overflow the cast. // NaN / +-Infinity fail the range test and fall to null for free. - sb.AppendLine(" private static decimal? DlgDecimal(object? v) => v switch"); - sb.AppendLine(" {"); - sb.AppendLine(" null => null,"); - sb.AppendLine(" decimal m => m,"); - sb.AppendLine(" long l => l,"); - sb.AppendLine(" int i => i,"); - sb.AppendLine(" short s => s,"); - sb.AppendLine(" byte b => b,"); - sb.AppendLine(" double db => db is >= -7.9e28 and <= 7.9e28 ? (decimal)db : (decimal?)null,"); - sb.AppendLine(" float f => f is >= -7.9e28f and <= 7.9e28f ? (decimal)f : (decimal?)null,"); - sb.AppendLine(" _ => decimal.TryParse(v.ToString(), global::System.Globalization.NumberStyles.Float | global::System.Globalization.NumberStyles.AllowThousands, global::System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : (decimal?)null,"); - sb.AppendLine(" };"); - sb.AppendLine(); - sb.AppendLine(" private static bool? DlgBool(object? v) => v switch"); - sb.AppendLine(" {"); - sb.AppendLine(" null => null,"); - sb.AppendLine(" bool b => b,"); - sb.AppendLine(" _ => string.Equals(v.ToString(), \"true\", global::System.StringComparison.OrdinalIgnoreCase),"); - sb.AppendLine(" };"); - sb.AppendLine(); - sb.AppendLine(" /// Map an assembled scalar list element-wise via into a kind-typed nullable-element list."); - sb.AppendLine(" /// Two overloads (value-type struct element vs reference-type string element) keep the element nullable for both."); - sb.AppendLine(" private static global::System.Collections.Generic.IReadOnlyList? DlgList("); - sb.AppendLine(" object? v, global::System.Func fn) where T : struct"); - sb.AppendLine(" {"); - sb.AppendLine(" if (v is not global::System.Collections.IEnumerable e || v is string) return null;"); - sb.AppendLine(" var outList = new global::System.Collections.Generic.List();"); - sb.AppendLine(" foreach (var elem in e) outList.Add(fn(elem));"); - sb.AppendLine(" return outList;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" private static global::System.Collections.Generic.IReadOnlyList? DlgList("); - sb.AppendLine(" object? v, global::System.Func fn) where T : class"); - sb.AppendLine(" {"); - sb.AppendLine(" if (v is not global::System.Collections.IEnumerable e || v is string) return null;"); - sb.AppendLine(" var outList = new global::System.Collections.Generic.List();"); - sb.AppendLine(" foreach (var elem in e) outList.Add(fn(elem));"); - sb.AppendLine(" return outList;"); - sb.AppendLine(" }"); + w.Text(""" + private static decimal? DlgDecimal(object? v) => v switch + { + null => null, + decimal m => m, + long l => l, + int i => i, + short s => s, + byte b => b, + double db => db is >= -7.9e28 and <= 7.9e28 ? (decimal)db : (decimal?)null, + float f => f is >= -7.9e28f and <= 7.9e28f ? (decimal)f : (decimal?)null, + _ => decimal.TryParse(v.ToString(), global::System.Globalization.NumberStyles.Float | global::System.Globalization.NumberStyles.AllowThousands, global::System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : (decimal?)null, + }; + + private static bool? DlgBool(object? v) => v switch + { + null => null, + bool b => b, + _ => string.Equals(v.ToString(), "true", global::System.StringComparison.OrdinalIgnoreCase), + }; + + /// Map an assembled scalar list element-wise via into a kind-typed nullable-element list. + /// Two overloads (value-type struct element vs reference-type string element) keep the element nullable for both. + private static global::System.Collections.Generic.IReadOnlyList? DlgList( + object? v, global::System.Func fn) where T : struct + { + if (v is not global::System.Collections.IEnumerable e || v is string) return null; + var outList = new global::System.Collections.Generic.List(); + foreach (var elem in e) outList.Add(fn(elem)); + return outList; + } + + private static global::System.Collections.Generic.IReadOnlyList? DlgList( + object? v, global::System.Func fn) where T : class + { + if (v is not global::System.Collections.IEnumerable e || v is string) return null; + var outList = new global::System.Collections.Generic.List(); + foreach (var elem in e) outList.Add(fn(elem)); + return outList; + } + """); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index 54495d13ba..be4640ec41 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -24,7 +24,7 @@ using System.Collections.Generic; using System.Linq; -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Shared.BaseTypes; using static MetaObjects.Shared.Structural; @@ -79,80 +79,112 @@ protected virtual EmittedFile EmitExtractor(MetaData tmpl, MetaData vo, string p ctx.Claim($"the C# namespace {ns}", extractorClass, tmpl.ResolutionKey(), "rename one (an extractor is declared in the configured namespace, GenConfig.Namespace, whatever its package, " + "so the two packages do not keep them apart)"); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects extractor-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Linq;"); - sb.AppendLine("using MetaObjects.Render.Extract;"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine($"/// The extract tier for the {templateName} template.prompt — turns dirty LLM"); - sb.AppendLine($"/// text into a fully-typed graph (nested objects + arrays-of-objects"); - sb.AppendLine($"/// populated) in one call, by delegating to the nested-capable extract and mapping the all-nullable"); - sb.AppendLine($"/// {ExtractDelegateEmitter.MirrorName(vo, ctx.Root)} mirror onto the value object. No registry / binding / factory."); - sb.AppendLine($"public static class {extractorClass}"); - sb.AppendLine("{"); - - sb.AppendLine($" /// Extract a fully-typed from dirty using"); - sb.AppendLine($" /// the runtime (the loaded value object). Runs the tolerant extract, then maps"); - sb.AppendLine($" /// the extracted mirror onto the value object."); - sb.AppendLine($" /// iff a @required field was lost or malformed (the strict opt-in gate)."); - sb.AppendLine($" public static {strictType} Extract(global::MetaObjects.Meta.MetaObject mo, string text)"); - sb.AppendLine(" {"); - sb.AppendLine($" var r = {parserClass}.ExtractLenient(mo, text);"); - sb.AppendLine(" if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired())"); - sb.AppendLine(" throw new ExtractException(r.Report);"); - sb.AppendLine($" return {rootMapper}(r.Data!);"); - sb.AppendLine(" }"); - sb.AppendLine(); - - sb.AppendLine($" /// Extract with explicit ."); - sb.AppendLine($" /// iff a @required field was lost or malformed."); - sb.AppendLine($" public static {strictType} Extract(global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions opts)"); - sb.AppendLine(" {"); - sb.AppendLine($" var r = {parserClass}.ExtractLenient(mo, text, opts);"); - sb.AppendLine(" if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired())"); - sb.AppendLine(" throw new ExtractException(r.Report);"); - sb.AppendLine($" return {rootMapper}(r.Data!);"); - sb.AppendLine(" }"); - sb.AppendLine(); - - sb.AppendLine($" /// Re-exposes the nested-capable tolerant extract; never throws. Inspect Report for"); - sb.AppendLine($" /// lost/defaulted fields. Returns the all-nullable mirror (not the value object)."); - sb.AppendLine($" public static ExtractionResult<{rootMirror}> ExtractLenient(global::MetaObjects.Meta.MetaObject mo, string text) =>"); - sb.AppendLine($" {parserClass}.ExtractLenient(mo, text);"); - - // One mapper per value object the mirror reaches (the root included), deduped by FQN. - foreach (var v in ExtractDelegateEmitter.MirrorClosure(vo, ctx.Root)) - EmitMapper(sb, v, ctx); - - sb.AppendLine("}"); - - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{extractorClass}.cs"), sb.ToString()); + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + WriteTypeDoc(w, templateName, strictType, ExtractDelegateEmitter.MirrorName(vo, ctx.Root)); + using (w.Braced($"public static class {extractorClass}")) + { + WriteExtract(w, strictType, parserClass, rootMapper); + w.Blank(); + WriteExtractWithOptions(w, strictType, parserClass, rootMapper); + w.Blank(); + WriteExtractLenient(w, rootMirror, parserClass); + + // One mapper per value object the mirror reaches (the root included), deduped by FQN. + foreach (var v in ExtractDelegateEmitter.MirrorClosure(vo, ctx.Root)) + WriteMapper(w, v, ctx); + } + + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{extractorClass}.cs"), w.ToString()); } - private static string MapperName(MetaData vo, MetaData root) => $"ToStrict_{ValueObjectNames.MemberKey(vo, root)}"; + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); - private static void EmitMapper(StringBuilder sb, MetaData vo, GenContext ctx) + /// The generated-file marker, the nullable context and the usings. + protected virtual void WriteFileHeader(CsWriter w) + { + w.GeneratedFileHeader("extractor-generator"); + w.Using("System.Linq"); + w.Using("MetaObjects.Render.Extract"); + } + + /// The XML doc on the extractor class. + protected virtual void WriteTypeDoc(CsWriter w, string templateName, string strictType, string mirrorName) + { + w.Line($"/// The extract tier for the {templateName} template.prompt — turns dirty LLM"); + w.Line($"/// text into a fully-typed graph (nested objects + arrays-of-objects"); + w.Line("/// populated) in one call, by delegating to the nested-capable extract and mapping the all-nullable"); + w.Line($"/// {mirrorName} mirror onto the value object. No registry / binding / factory."); + } + + /// Extract(mo, text): the tolerant extract, then the strict gate and the mapping. + protected virtual void WriteExtract(CsWriter w, string strictType, string parserClass, string rootMapper) + { + w.Line($"/// Extract a fully-typed from dirty using"); + w.Line("/// the runtime (the loaded value object). Runs the tolerant extract, then maps"); + w.Line("/// the extracted mirror onto the value object."); + w.Line("/// iff a @required field was lost or malformed (the strict opt-in gate)."); + using (w.Braced($"public static {strictType} Extract(global::MetaObjects.Meta.MetaObject mo, string text)")) + { + w.Line($"var r = {parserClass}.ExtractLenient(mo, text);"); + w.Line("if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired())"); + using (w.Hanging()) w.Line("throw new ExtractException(r.Report);"); + w.Line($"return {rootMapper}(r.Data!);"); + } + } + + /// Extract(mo, text, opts): the same, with explicit extract options. + protected virtual void WriteExtractWithOptions(CsWriter w, string strictType, string parserClass, string rootMapper) + { + w.Line("/// Extract with explicit ."); + w.Line("/// iff a @required field was lost or malformed."); + using (w.Braced($"public static {strictType} Extract(global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions opts)")) + { + w.Line($"var r = {parserClass}.ExtractLenient(mo, text, opts);"); + w.Line("if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired())"); + using (w.Hanging()) w.Line("throw new ExtractException(r.Report);"); + w.Line($"return {rootMapper}(r.Data!);"); + } + } + + /// ExtractLenient: the nested-capable tolerant extract, re-exposed. + protected virtual void WriteExtractLenient(CsWriter w, string rootMirror, string parserClass) + { + w.Line("/// Re-exposes the nested-capable tolerant extract; never throws. Inspect Report for"); + w.Line("/// lost/defaulted fields. Returns the all-nullable mirror (not the value object)."); + w.Line($"public static ExtractionResult<{rootMirror}> ExtractLenient(global::MetaObjects.Meta.MetaObject mo, string text) =>"); + using (w.Hanging()) w.Line($"{parserClass}.ExtractLenient(mo, text);"); + } + + /// The mapper from one value object's all-nullable mirror onto the value object. + protected virtual void WriteMapper(CsWriter w, MetaData vo, GenContext ctx) { string ns = ctx.Config.Namespace; string type = ValueObjectNames.TypeRef(vo, ctx.Root, ctx.Config, ns); string mirror = ExtractDelegateEmitter.MirrorRef(vo, ctx.Root, ctx.Config, ns); - sb.AppendLine(); - sb.AppendLine($" /// Map the all-nullable {ExtractDelegateEmitter.MirrorName(vo, ctx.Root)} mirror onto {ValueObjectNames.TypeName(vo, ctx.Root)}. Generated."); - sb.AppendLine($" private static {type} {MapperName(vo, ctx.Root)}({mirror} m) => new {type}"); - sb.AppendLine(" {"); - foreach (var f in Fr010FieldMapping.Fields(vo).OfType()) + w.Blank(); + w.Line($"/// Map the all-nullable {ExtractDelegateEmitter.MirrorName(vo, ctx.Root)} mirror onto {ValueObjectNames.TypeName(vo, ctx.Root)}. Generated."); + w.Line($"private static {type} {MapperName(vo, ctx.Root)}({mirror} m) => new {type}"); + using (w.Block("{", "};")) { - // A readOnly member has a private setter on the POCO: an initializer cannot set it. - if (f.IsReadOnlyMutability) continue; - sb.AppendLine($" {CSharpNaming.PropertyName(f, ctx.Config)} = {StrictArg((MetaObject)vo, f, ctx)},"); + foreach (var f in Fr010FieldMapping.Fields(vo).OfType()) + { + // A readOnly member has a private setter on the POCO: an initializer cannot set it. + if (f.IsReadOnlyMutability) continue; + w.Line($"{CSharpNaming.PropertyName(f, ctx.Config)} = {StrictArg((MetaObject)vo, f, ctx)},"); + } } - sb.AppendLine(" };"); } + private static string MapperName(MetaData vo, MetaData root) => $"ToStrict_{ValueObjectNames.MemberKey(vo, root)}"; + /// The initializer expression mapping one mirror member onto the POCO member. private static string StrictArg(MetaObject owner, MetaField field, GenContext ctx) { diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 9d6f079767..46effc4e29 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -17,7 +17,7 @@ // A view-backed `object.report` (FR-044) gets one too, from its row model: every derived // field with a filter band is filterable (ReportRows). A report with no view source gets none. -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Core.Field.FieldConstants; @@ -81,62 +81,77 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) ctx.Claim($"the C# namespace {ns}", filterClass, entity.ResolutionKey(), "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one"); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine("/// "); - sb.AppendLine($"/// GENERATED — per-entity FR-009 filter allowlist for {cls}."); - sb.AppendLine("/// lists the filterable field names; "); - sb.AppendLine("/// constrains the operator vocabulary for each field by its subtype."); - sb.AppendLine("/// "); - sb.AppendLine($"public static class {filterClass}"); - sb.AppendLine("{"); - - // Fields — the field-name set. Use System.StringComparer.Ordinal for - // case-sensitive matching (the URL grammar is case-exact). - sb.AppendLine(" public static readonly HashSet Fields = new(System.StringComparer.Ordinal)"); - sb.AppendLine(" {"); - foreach (var f in opsByField.Keys) sb.AppendLine($" \"{f}\","); - sb.AppendLine(" };"); - sb.AppendLine(); - - // OpsByField — Dictionary>. - sb.AppendLine(" public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal)"); - sb.AppendLine(" {"); - foreach (var kvp in opsByField) + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + WriteTypeDoc(w, cls); + using (w.Braced($"public static class {filterClass}")) { - sb.Append($" [\"{kvp.Key}\"] = new(System.StringComparer.Ordinal) {{ "); - bool first = true; - foreach (var op in kvp.Value) + WriteFields(w, opsByField); + w.Blank(); + WriteOpsByField(w, opsByField); + // The field -> CLR property map, only when a property-naming resolver renamed a property + // beyond case (the runtime matches a field to its property case-insensitively, which + // covers every other spelling). Nothing is emitted otherwise, so default output is unchanged. + var renamed = CSharpNaming.RenamedProperties(entity, ctx.Config); + if (renamed.Count > 0) { - if (!first) sb.Append(", "); - first = false; - sb.Append('"').Append(op).Append('"'); + w.Blank(); + WritePropertyByField(w, renamed); } - sb.AppendLine(" },"); } - sb.AppendLine(" };"); - // The field -> CLR property map, only when a property-naming resolver renamed a property - // beyond case (the runtime matches a field to its property case-insensitively, which - // covers every other spelling). Nothing is emitted otherwise, so default output is unchanged. - var renamed = CSharpNaming.RenamedProperties(entity, ctx.Config); - if (renamed.Count > 0) + + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}FilterAllowlist.g.cs"), w.ToString()); + } + + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker, the generator's name, the nullable context and the usings. + protected virtual void WriteFileHeader(CsWriter w) + { + w.GeneratedFileHeader("filter-allowlist-generator"); + w.Using("System.Collections.Generic"); + } + + /// The XML doc on the allowlist class. + protected virtual void WriteTypeDoc(CsWriter w, string cls) => w.DocSummary( + $"GENERATED — per-entity FR-009 filter allowlist for {cls}.", + " lists the filterable field names; ", + "constrains the operator vocabulary for each field by its subtype."); + + /// The Fields set: the filterable field names. Ordinal comparison, because the URL grammar is case-exact. + protected virtual void WriteFields(CsWriter w, IReadOnlyDictionary> opsByField) + { + using (w.Braced("public static readonly HashSet Fields = new(System.StringComparer.Ordinal)", "};")) { - sb.AppendLine(); - sb.AppendLine(" /// The CLR property of each field whose property name is not the field name in another case."); - sb.AppendLine(" public static readonly IReadOnlyDictionary PropertyByField = new Dictionary(System.StringComparer.Ordinal)"); - sb.AppendLine(" {"); - foreach (var kvp in renamed) sb.AppendLine($" [\"{kvp.Key}\"] = \"{kvp.Value}\","); - sb.AppendLine(" };"); + foreach (var f in opsByField.Keys) w.Line($"\"{f}\","); } - sb.AppendLine("}"); + } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}FilterAllowlist.g.cs"), sb.ToString()); + /// The OpsByField dictionary: each field's operator set. + protected virtual void WriteOpsByField(CsWriter w, IReadOnlyDictionary> opsByField) + { + using (w.Braced("public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal)", "};")) + { + foreach (var (field, ops) in opsByField) + w.Line($"[\"{field}\"] = new(System.StringComparer.Ordinal) {{ {string.Join(", ", ops.Select(op => $"\"{op}\""))} }},"); + } + } + + /// The PropertyByField map, for a field whose CLR property is named beyond case. + protected virtual void WritePropertyByField(CsWriter w, IReadOnlyDictionary renamed) + { + w.Line("/// The CLR property of each field whose property name is not the field name in another case."); + using (w.Braced("public static readonly IReadOnlyDictionary PropertyByField = new Dictionary(System.StringComparer.Ordinal)", "};")) + { + foreach (var (field, property) in renamed) w.Line($"[\"{field}\"] = \"{property}\","); + } } /// diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index 25c5ecdbb1..1b54c6b156 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -22,7 +22,7 @@ // `static readonly` because a Dictionary cannot be const — it serves iteration, not // the attributes. -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Persistence.Source.SourceConstants; @@ -92,9 +92,10 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) => Render(entity, ctx, fragment: false) ?? throw new InvalidOperationException($"{entity.Name}: Render returned no names artifact."); - /// One emitted constant: its member name, its declaration body, and the metadata - /// node it came from (named in the collision refusal, so a failure points at the model). - private readonly record struct Member(string Name, string Decl, string NodePath, string? Attribute = null); + /// One emitted constant: its member name, its declaration body, the metadata + /// node it came from (named in the collision refusal, so a failure points at the model), and an + /// optional attribute line above it. + protected readonly record struct Member(string Name, string Decl, string NodePath, string? Attribute = null); // A @storage: flattened field's own column constant names no column of the table: its members // are the columns. It is still emitted (owned copies and existing code that read it must keep @@ -126,7 +127,7 @@ private static Member Str(string name, string value, string nodePath) => /// base's SourcePrimaryTable down. The structural fact and the emission rule are /// the same fact, read once. /// - private static List> MemberGroups(ObjectNames n, bool ownOnly) + protected static List> MemberGroups(ObjectNames n, bool ownOnly) { var skipped = CollidingFlattenedMembers(n); var groups = new List>(); @@ -352,75 +353,103 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra var ns = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name); ctx.Claim($"the C# namespace {ns}", cls, entity.ResolutionKey(), "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one"); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects names-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); // The base artifact is emitted in the BASE's namespace (the same resolution, below, applied // to it), which is not this one when the two bind to different packages. Without the // `using` the `: Names` clause does not resolve (CS0246). + string? superNs = null; if (superCls is not null && CSharpNaming.NamesArtifactSuperOf(entity) is { } sup) { - var superNs = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(sup), sup.Name, fallbackContext: sup.Name); - if (!string.IsNullOrEmpty(superNs) && superNs != ns) - sb.AppendLine($"using {superNs};"); + var resolved = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(sup), sup.Name, fallbackContext: sup.Name); + if (!string.IsNullOrEmpty(resolved) && resolved != ns) superNs = resolved; } - sb.AppendLine(); + + var w = NewWriter(); + WriteFileHeader(w, superNs); + w.Blank(); // Task 4 (§A6) — the same per-package resolution EntityGenerator uses for the // entity itself, so a package carrying a PackageNamespaces override still lands // its Names companion in the SAME namespace as the entity it describes // (the promise the consumption sites rely on: no new `using` is required). // Bare ctx.Config.Namespace would silently break that promise whenever a // per-package override is configured. - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine("/// "); - sb.AppendLine($"/// GENERATED — per-object physical database names for {CSharpNaming.Pascal(entity.Name)} (spec A1/A2/A6)."); - sb.AppendLine("/// "); + w.Line($"namespace {ns};"); + w.Blank(); + WriteTypeDoc(w, entity); // `abstract class`, not `static class`: a static class can neither inherit nor be // inherited, and this artifact now extends its parent's rather than restating it. // Abstract keeps the "never instantiate this" guarantee a static class gave, and a // `const` is inherited — `CouponAuthNames.IdColumn` resolves through the base — so // every consumption site is unchanged. var extends = superCls is null ? "" : $" : {superCls}"; - sb.AppendLine($"public abstract class {cls}{extends}"); - sb.AppendLine("{"); - foreach (var group in groups.Where(g => g.Count > 0)) + using (w.Braced($"public abstract class {cls}{extends}")) + { + WriteMembers(w, groups.Where(g => g.Count > 0), inherited); + WriteColumnsByField(w, names, hasBase: superCls is not null); + } + + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()); + } + + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker, the nullable context and the usings, with the base artifact's + /// namespace when it is not this one. + protected virtual void WriteFileHeader(CsWriter w, string? baseNamespace) + { + w.GeneratedFileHeader("names-generator"); + w.Using("System.Collections.Generic"); + if (baseNamespace is not null) w.Using(baseNamespace); + } + + /// The XML doc on the artifact's class. + protected virtual void WriteTypeDoc(CsWriter w, MetaObject entity) => w.DocSummary( + $"GENERATED — per-object physical database names for {CSharpNaming.Pascal(entity.Name)} (spec A1/A2/A6)."); + + /// The constants, one group after another, a blank line after each. + protected virtual void WriteMembers(CsWriter w, IEnumerable> groups, IReadOnlySet inherited) + { + foreach (var group in groups) { foreach (var m in group) { - if (m.Attribute is { } attribute) sb.AppendLine($" {attribute}"); - sb.AppendLine($" public {(inherited.Contains(m.Name) ? "new " : "")}{m.Decl}"); + if (m.Attribute is { } attribute) w.Line(attribute); + w.Line($"public {(inherited.Contains(m.Name) ? "new " : "")}{m.Decl}"); } - sb.AppendLine(); + w.Blank(); } - // ColumnsByField stays COMPLETE — every field, inherited included — because it is - // the lookup surface, and a miss on an inherited field is exactly the fallback-to- - // literal this artifact removes. It repeats no LITERAL: an inherited entry's value - // is the base's own const, reached through the base class. `new` because a derived - // class hides the base's field rather than overriding it (a static field cannot be - // virtual), which is what makes `Names.ColumnsByField` the complete one. - var hides = superCls is null ? "" : "new "; - sb.AppendLine($" public static {hides}readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal)"); - sb.AppendLine(" {"); - var skippedMembers = CollidingFlattenedMembers(names); - foreach (var f in names.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) + } + + /// + /// ColumnsByField, COMPLETE — every field, inherited included — because it is + /// the lookup surface, and a miss on an inherited field is exactly the fallback-to- + /// literal this artifact removes. It repeats no LITERAL: an inherited entry's value + /// is the base's own const, reached through the base class. new because a derived + /// class hides the base's field rather than overriding it (a static field cannot be + /// virtual), which is what makes <Sub>Names.ColumnsByField the complete one. + /// + protected virtual void WriteColumnsByField(CsWriter w, ObjectNames names, bool hasBase) + { + var hides = hasBase ? "new " : ""; + using (w.Braced($"public static {hides}readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal)", "};")) { - // A flattened field has no entry of its own: only its member keys. - if (f.Column is not null) - sb.AppendLine($" [\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); - // A flattened member is keyed `.`, the path the naming corpus uses. - foreach (var m in FlattenedMembers(f)) + var skippedMembers = CollidingFlattenedMembers(names); + foreach (var f in names.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) { - var memberName = CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name); - if (!skippedMembers.Contains(memberName)) - sb.AppendLine($" [\"{f.Name}.{m.Name}\"] = {memberName},"); + // A flattened field has no entry of its own: only its member keys. + if (f.Column is not null) + w.Line($"[\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); + // A flattened member is keyed `.`, the path the naming corpus uses. + foreach (var m in FlattenedMembers(f)) + { + var memberName = CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name); + if (!skippedMembers.Contains(memberName)) + w.Line($"[\"{f.Name}.{m.Name}\"] = {memberName},"); + } } } - sb.AppendLine(" };"); - sb.AppendLine("}"); - - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), sb.ToString()); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs index b1cf4efe1f..32ed579aca 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs @@ -46,7 +46,7 @@ // extract API must carry MetaObjects.Codegen on its classpath (it transitively // brings core + Render). -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Shared.BaseTypes; using static MetaObjects.Template.TemplateConstants; @@ -137,102 +137,149 @@ protected virtual EmittedFile EmitParser(MetaData tmpl, string responseRef, GenC // `Extracted` — a nullable mirror, the honest type for a best-effort parse. bool emitStrict = !FindInbound.IsXml(format); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects output-parser-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); - if (emitStrict) sb.AppendLine("using System.Diagnostics.CodeAnalysis;"); - if (emitStrict) sb.AppendLine("using System.Text.Json;"); - if (emitStrict) sb.AppendLine("using System.Text.Json.Serialization;"); var required = emitStrict && vo is not null ? RequiredFields(vo, ctx) : []; - if (required.Count > 0) sb.AppendLine("using System.Text.Json.Serialization.Metadata;"); - if (emitExtract) sb.AppendLine("using MetaObjects.Render.Extract;"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine($"/// Parser for LLM responses matching the {templateName} template.prompt."); - sb.AppendLine($"public static class {parserClass}"); - sb.AppendLine("{"); - if (emitStrict) + + var w = NewWriter(); + WriteFileHeader(w, emitStrict, requiredFields: required.Count > 0, emitExtract); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.Line($"/// Parser for LLM responses matching the {templateName} template.prompt."); + using (w.Braced($"public static class {parserClass}")) + { + if (emitStrict) + { + WriteOptions(w, required); + w.Blank(); + if (required.Count > 0) + { + WriteRequireDeclaredFields(w, required); + w.Blank(); + } + WriteParse(w, payloadType); + w.Blank(); + WriteTryParse(w, payloadType); + } + + // FR-010: emit the single metadata-driven extract path — the runtime-DELEGATING + // ExtractLenient(MetaObject/MetaRoot, text) overloads (delegating to + // MetaObjects.Codegen.Runtime.ExtractObject, which assembles the full object graph + // reflection-free by reading the live metadata directly) and the mappers into the + // value objects' mirrors. The mirror records themselves are emitted once per run + // (see Generate). No baked ExtractSchema snapshot. + string formatEnum = FindInbound.IsXml(format) ? "Format.Xml" : "Format.Json"; + + if (emitExtract) + WriteExtract(w, vo!, ctx, ns, formatEnum); + } + + // ADR-0052 D4: the artifact name follows the DIRECTION axis. A parser file named + // `.output.cs` generated from a prompt reproduces the confusion being removed. + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.response.cs"), w.ToString()); + } + + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker, the nullable context and the usings the file needs. + protected virtual void WriteFileHeader(CsWriter w, bool strict, bool requiredFields, bool extract) + { + w.GeneratedFileHeader("output-parser-generator"); + w.Using("System"); + w.Using("System.Collections.Generic"); + if (strict) + { + w.Using("System.Diagnostics.CodeAnalysis"); + w.Using("System.Text.Json"); + w.Using("System.Text.Json.Serialization"); + } + if (requiredFields) w.Using("System.Text.Json.Serialization.Metadata"); + if (extract) w.Using("MetaObjects.Render.Extract"); + } + + /// The strict tier's JsonSerializerOptions. + protected virtual void WriteOptions(CsWriter w, IReadOnlyList<(string Type, List Names)> required) + { + using (w.Braced("private static readonly JsonSerializerOptions Options = new()", "};")) { - sb.AppendLine(" private static readonly JsonSerializerOptions Options = new()"); - sb.AppendLine(" {"); // Case-sensitive (default) — every value-object POCO member carries its metadata // field name in [JsonPropertyName], which is the key the model is asked to produce. - sb.AppendLine(" PropertyNameCaseInsensitive = false,"); + w.Line("PropertyNameCaseInsensitive = false,"); // A field.enum travels as its member symbol, as the output-format prompt says. - sb.AppendLine(" Converters = { new JsonStringEnumConverter() },"); - if (required.Count > 0) - sb.AppendLine(" TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { RequireDeclaredFields } },"); - sb.AppendLine(" };"); - sb.AppendLine(); + w.Line("Converters = { new JsonStringEnumConverter() },"); if (required.Count > 0) + w.Line("TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { RequireDeclaredFields } },"); + } + } + + /// The type-info modifier that marks each @required field required. + protected virtual void WriteRequireDeclaredFields(CsWriter w, IReadOnlyList<(string Type, List Names)> required) + { + w.Line("/// A reply that omits a @required field fails to parse. The value-object POCOs"); + w.Line("/// cannot say so themselves: their members are shared with the REST tier, where presence is a"); + w.Line("/// validation concern."); + using (w.Braced("private static void RequireDeclaredFields(JsonTypeInfo info)")) + { + w.Line("string[]? required ="); + using (w.Hanging()) { - sb.AppendLine(" /// A reply that omits a @required field fails to parse. The value-object POCOs"); - sb.AppendLine(" /// cannot say so themselves: their members are shared with the REST tier, where presence is a"); - sb.AppendLine(" /// validation concern."); - sb.AppendLine(" private static void RequireDeclaredFields(JsonTypeInfo info)"); - sb.AppendLine(" {"); - sb.AppendLine(" string[]? required ="); foreach (var (type, names) in required) - sb.AppendLine($" info.Type == typeof({type}) ? new[] {{ {string.Join(", ", names.Select(n => $"\"{n}\""))} }} :"); - sb.AppendLine(" null;"); - sb.AppendLine(" if (required is null) return;"); - sb.AppendLine(" foreach (var p in info.Properties)"); - sb.AppendLine(" if (Array.IndexOf(required, p.Name) >= 0) p.IsRequired = true;"); - sb.AppendLine(" }"); - sb.AppendLine(); + w.Line($"info.Type == typeof({type}) ? new[] {{ {string.Join(", ", names.Select(n => $"\"{n}\""))} }} :"); + w.Line("null;"); } - sb.AppendLine($" /// Parse an LLM response into a typed ."); - sb.AppendLine($" /// The raw response text — expected to be JSON."); - sb.AppendLine(" /// The deserialized, validated response."); - sb.AppendLine(" /// JSON is malformed, missing a required property, or has a type mismatch."); - sb.AppendLine($" public static {payloadType} Parse(string text) =>"); - sb.AppendLine($" JsonSerializer.Deserialize<{payloadType}>(text, Options)"); - sb.AppendLine($" ?? throw new JsonException(\"deserialized to null\");"); - sb.AppendLine(); - sb.AppendLine($" /// Parse with explicit error handling — does not throw on validation failure."); - sb.AppendLine(" /// The raw response text — expected to be JSON."); - sb.AppendLine(" /// On success, the deserialized response; otherwise null."); - sb.AppendLine(" /// On failure, a human-readable error message; otherwise null."); - sb.AppendLine(" /// true on success; false on validation failure."); - sb.AppendLine($" public static bool TryParse(string text, [NotNullWhen(true)] out {payloadType}? value, [NotNullWhen(false)] out string? error)"); - sb.AppendLine(" {"); - sb.AppendLine(" try"); - sb.AppendLine(" {"); - sb.AppendLine(" value = Parse(text);"); - sb.AppendLine(" error = null;"); - sb.AppendLine(" return true;"); - sb.AppendLine(" }"); - sb.AppendLine(" catch (JsonException ex)"); - sb.AppendLine(" {"); - sb.AppendLine(" value = null;"); - sb.AppendLine(" error = ex.Message;"); - sb.AppendLine(" return false;"); - sb.AppendLine(" }"); - sb.AppendLine(" }"); + w.Line("if (required is null) return;"); + w.Line("foreach (var p in info.Properties)"); + using (w.Hanging()) w.Line("if (Array.IndexOf(required, p.Name) >= 0) p.IsRequired = true;"); } + } - // FR-010: emit the single metadata-driven extract path — the runtime-DELEGATING - // ExtractLenient(MetaObject/MetaRoot, text) overloads (delegating to - // MetaObjects.Codegen.Runtime.ExtractObject, which assembles the full object graph - // reflection-free by reading the live metadata directly) and the mappers into the - // value objects' mirrors. The mirror records themselves are emitted once per run - // (see Generate). No baked ExtractSchema snapshot. - string formatEnum = FindInbound.IsXml(format) ? "Format.Xml" : "Format.Json"; - - if (emitExtract) - sb.Append(ExtractDelegateEmitter.DelegatingMembers(vo!, ctx.Root, ctx.Config, ns, formatEnum)); - - sb.AppendLine("}"); + /// The throwing Parse. + protected virtual void WriteParse(CsWriter w, string payloadType) + { + w.Line($"/// Parse an LLM response into a typed ."); + w.Line($"/// The raw response text — expected to be JSON."); + w.Line("/// The deserialized, validated response."); + w.Line("/// JSON is malformed, missing a required property, or has a type mismatch."); + w.Line($"public static {payloadType} Parse(string text) =>"); + using (w.Hanging()) + { + w.Line($"JsonSerializer.Deserialize<{payloadType}>(text, Options)"); + using (w.Hanging()) w.Line($"?? throw new JsonException(\"deserialized to null\");"); + } + } - // ADR-0052 D4: the artifact name follows the DIRECTION axis. A parser file named - // `.output.cs` generated from a prompt reproduces the confusion being removed. - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.response.cs"), sb.ToString()); + /// The non-throwing TryParse. + protected virtual void WriteTryParse(CsWriter w, string payloadType) + { + w.Line($"/// Parse with explicit error handling — does not throw on validation failure."); + w.Line("/// The raw response text — expected to be JSON."); + w.Line("/// On success, the deserialized response; otherwise null."); + w.Line("/// On failure, a human-readable error message; otherwise null."); + w.Line("/// true on success; false on validation failure."); + using (w.Braced($"public static bool TryParse(string text, [NotNullWhen(true)] out {payloadType}? value, [NotNullWhen(false)] out string? error)")) + { + using (w.Braced("try")) + { + w.Line("value = Parse(text);"); + w.Line("error = null;"); + w.Line("return true;"); + } + using (w.Braced("catch (JsonException ex)")) + { + w.Line("value = null;"); + w.Line("error = ex.Message;"); + w.Line("return false;"); + } + } } + /// The runtime-delegating ExtractLenient members and their mappers. + protected virtual void WriteExtract(CsWriter w, MetaData vo, GenContext ctx, string ns, string formatEnum) => + ExtractDelegateEmitter.WriteDelegatingMembers(w, vo, ctx.Root, ctx.Config, ns, formatEnum); + /// /// The @required fields of every value object the strict parse decodes — the response /// value object and each one nested under it — as (type reference, JSON names) pairs. Value diff --git a/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs index 84eb8bea4a..8ab38ab874 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs @@ -13,7 +13,7 @@ // extract() codegen agree on the root element/object name. Mirrors the Java // SpringOutputPromptGenerator. Skips: template.output, and a missing/unresolved `@responseRef`. -using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Shared.BaseTypes; using static MetaObjects.Template.TemplateConstants; @@ -59,29 +59,49 @@ protected virtual EmittedFile EmitPrompt(MetaData tmpl, MetaData vo, string payl // agree — never the raw @responseRef, which may be an FQN (`acme::app::Answer`). var specLiteral = OutputFormatSpecEmitter.SpecLiteral(vo, tmpl, vo.Name); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects output-prompt-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using MetaObjects.Render.Prompt;"); - sb.AppendLine("using MetaObjects.Render.Extract;"); - sb.AppendLine(); - sb.AppendLine($"namespace {ctx.Config.Namespace};"); - sb.AppendLine(); - sb.AppendLine($"/// Response-format prompt fragment for the {templateName} template.prompt."); - sb.AppendLine($"public static class {promptClass}"); - sb.AppendLine("{"); - sb.AppendLine($" private static readonly OutputFormatSpec Spec = {specLiteral};"); - sb.AppendLine(); - sb.AppendLine(" /// The response-format instruction fragment (\"produce your answer like this\")."); - sb.AppendLine(" public static string RenderFormat() => OutputFormatRenderer.Render(Spec, PromptOverrides.None());"); - sb.AppendLine(); - sb.AppendLine(" /// The fragment with render-time overrides (style / per-field example / instruction)."); - sb.AppendLine(" public static string RenderFormat(PromptOverrides overrides) => OutputFormatRenderer.Render(Spec, overrides);"); - sb.AppendLine("}"); + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ctx.Config.Namespace};"); + w.Blank(); + w.Line($"/// Response-format prompt fragment for the {templateName} template.prompt."); + using (w.Braced($"public static class {promptClass}")) + { + WriteSpec(w, specLiteral); + w.Blank(); + WriteRenderFormat(w); + } // ADR-0052 D4: the artifact name follows the DIRECTION axis. A file named // `.prompt.cs` generated from a prompt reproduces the confusion being removed. - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.responseFormat.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.responseFormat.cs"), w.ToString()); + } + + // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the + // piece it wants and keeps the rest. Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker, the nullable context and the usings. + protected virtual void WriteFileHeader(CsWriter w) + { + w.GeneratedFileHeader("output-prompt-generator"); + w.Using("System.Collections.Generic"); + w.Using("MetaObjects.Render.Prompt"); + w.Using("MetaObjects.Render.Extract"); + } + + /// The baked OutputFormatSpec field. + protected virtual void WriteSpec(CsWriter w, string specLiteral) => + w.Line($"private static readonly OutputFormatSpec Spec = {specLiteral};"); + + /// The two RenderFormat entry points. + protected virtual void WriteRenderFormat(CsWriter w) + { + w.Line("/// The response-format instruction fragment (\"produce your answer like this\")."); + w.Line("public static string RenderFormat() => OutputFormatRenderer.Render(Spec, PromptOverrides.None());"); + w.Blank(); + w.Line("/// The fragment with render-time overrides (style / per-field example / instruction)."); + w.Line("public static string RenderFormat(PromptOverrides overrides) => OutputFormatRenderer.Render(Spec, overrides);"); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs index de4e8b13a5..261be9a126 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs @@ -44,6 +44,7 @@ // render-helper drift: template "" ref "" — : {{}} not on payload VO using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using MetaObjects.Render; using static MetaObjects.Shared.BaseTypes; @@ -165,66 +166,71 @@ protected virtual EmittedFile EmitHelper(MetaData tmpl, MetaData vo, string payl // ADR-0039: resolving — @kind may be inherited via an abstract template base. var kind = (tmpl.Attr(TEMPLATE_ATTR_KIND) as string ?? TEMPLATE_KIND_DEFAULT).ToLowerInvariant(); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects render-helper-generator. Do not edit by hand."); - sb.AppendLine("// Typed render helper wrapping the render engine; the payload field tree is"); - sb.AppendLine("// baked into the RenderRequest so the runtime drift check matches the build-time gate."); - sb.AppendLine("#nullable enable"); - sb.AppendLine(); - sb.AppendLine($"namespace {ctx.Config.Namespace};"); - sb.AppendLine(); - sb.AppendLine($"/// Typed render helper for the {templateName} template.{tmpl.SubType}."); - sb.AppendLine($"public static class {helperClass}"); - sb.AppendLine("{"); - - if (kind == TEMPLATE_KIND_EMAIL) + var w = new CsWriter(); + // The header comments, then `#nullable enable`, sit above the namespace; this file has no usings. + w.Line("// "); + w.Line("// Generated by MetaObjects render-helper-generator. Do not edit by hand."); + w.Line("// Typed render helper wrapping the render engine; the payload field tree is"); + w.Line("// baked into the RenderRequest so the runtime drift check matches the build-time gate."); + w.Line("#nullable enable"); + w.Blank(); + w.Line($"namespace {ctx.Config.Namespace};"); + w.Blank(); + w.Line($"/// Typed render helper for the {templateName} template.{tmpl.SubType}."); + using (w.Braced($"public static class {helperClass}")) { - // ADR-0039: resolving — email part-refs may be inherited via an abstract template base. - var subjectRef = tmpl.Attr(TEMPLATE_ATTR_SUBJECT_REF) as string; - var htmlBodyRef = tmpl.Attr(TEMPLATE_ATTR_HTML_BODY_REF) as string; - var textBodyRef = tmpl.Attr(TEMPLATE_ATTR_TEXT_BODY_REF) as string; - if (subjectRef is null) - throw new InvalidOperationException($"template.output \"{templateName}\" (email) missing @subjectRef"); - if (htmlBodyRef is null) - throw new InvalidOperationException($"template.output \"{templateName}\" (email) missing @htmlBodyRef"); + if (kind == TEMPLATE_KIND_EMAIL) + { + // ADR-0039: resolving — email part-refs may be inherited via an abstract template base. + var subjectRef = tmpl.Attr(TEMPLATE_ATTR_SUBJECT_REF) as string; + var htmlBodyRef = tmpl.Attr(TEMPLATE_ATTR_HTML_BODY_REF) as string; + var textBodyRef = tmpl.Attr(TEMPLATE_ATTR_TEXT_BODY_REF) as string; + if (subjectRef is null) + throw new InvalidOperationException($"template.output \"{templateName}\" (email) missing @subjectRef"); + if (htmlBodyRef is null) + throw new InvalidOperationException($"template.output \"{templateName}\" (email) missing @htmlBodyRef"); - // BUILD-TIME drift gate — every email part-ref is resolved + verified. - GateRef(templateName, subjectRef, fields); - GateRef(templateName, htmlBodyRef, fields); - if (textBodyRef is not null) GateRef(templateName, textBodyRef, fields); + // BUILD-TIME drift gate — every email part-ref is resolved + verified. + GateRef(templateName, subjectRef, fields); + GateRef(templateName, htmlBodyRef, fields); + if (textBodyRef is not null) GateRef(templateName, textBodyRef, fields); - sb.AppendLine($" /// Render the {templateName} email (subject + html body{(textBodyRef is not null ? " + text body" : "")}) from a typed {payloadType} payload."); - sb.AppendLine($" public static global::MetaObjects.Render.EmailDocument Render({payloadType} payload, global::MetaObjects.Render.IProvider provider) =>"); - sb.AppendLine(" new global::MetaObjects.Render.EmailDocument("); - sb.AppendLine($" global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(subjectRef)}, Payload = payload, Provider = provider, Format = \"text\", Verify = {ft} }}),"); - sb.Append($" global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(htmlBodyRef)}, Payload = payload, Provider = provider, Format = \"html\", Verify = {ft} }})"); - sb.AppendLine(","); - if (textBodyRef is not null) - sb.AppendLine($" global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(textBodyRef)}, Payload = payload, Provider = provider, Format = \"text\", Verify = {ft} }}));"); + w.Line($"/// Render the {templateName} email (subject + html body{(textBodyRef is not null ? " + text body" : "")}) from a typed {payloadType} payload."); + w.Line($"public static global::MetaObjects.Render.EmailDocument Render({payloadType} payload, global::MetaObjects.Render.IProvider provider) =>"); + using (w.Hanging()) + { + w.Line("new global::MetaObjects.Render.EmailDocument("); + using (w.Hanging()) + { + w.Line($"global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(subjectRef)}, Payload = payload, Provider = provider, Format = \"text\", Verify = {ft} }}),"); + w.Line($"global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(htmlBodyRef)}, Payload = payload, Provider = provider, Format = \"html\", Verify = {ft} }}),"); + if (textBodyRef is not null) + w.Line($"global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(textBodyRef)}, Payload = payload, Provider = provider, Format = \"text\", Verify = {ft} }}));"); + else + w.Line("null);"); + } + } + } else - sb.AppendLine(" null);"); - } - else - { - // ADR-0039: resolving — @textRef/@format may be inherited via an abstract template base. - var textRef = tmpl.Attr(TEMPLATE_ATTR_TEXT_REF) as string; - if (textRef is null) - throw new InvalidOperationException($"template.output \"{templateName}\" (document) missing @textRef"); - var format = tmpl.Attr(TEMPLATE_ATTR_FORMAT) as string ?? TEMPLATE_FORMAT_DEFAULT; - var maxChars = MaxCharsOf(tmpl); + { + // ADR-0039: resolving — @textRef/@format may be inherited via an abstract template base. + var textRef = tmpl.Attr(TEMPLATE_ATTR_TEXT_REF) as string; + if (textRef is null) + throw new InvalidOperationException($"template.output \"{templateName}\" (document) missing @textRef"); + var format = tmpl.Attr(TEMPLATE_ATTR_FORMAT) as string ?? TEMPLATE_FORMAT_DEFAULT; + var maxChars = MaxCharsOf(tmpl); - // BUILD-TIME drift gate. - GateRef(templateName, textRef, fields); + // BUILD-TIME drift gate. + GateRef(templateName, textRef, fields); - var maxCharsArg = maxChars is not null ? $", MaxChars = {maxChars}" : ""; - sb.AppendLine($" /// Render the {templateName} document from a typed {payloadType} payload."); - sb.AppendLine($" public static string Render({payloadType} payload, global::MetaObjects.Render.IProvider provider) =>"); - sb.AppendLine($" global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(textRef)}, Payload = payload, Provider = provider, Format = {Quote(format)}, Verify = {ft}{maxCharsArg} }});"); + var maxCharsArg = maxChars is not null ? $", MaxChars = {maxChars}" : ""; + w.Line($"/// Render the {templateName} document from a typed {payloadType} payload."); + w.Line($"public static string Render({payloadType} payload, global::MetaObjects.Render.IProvider provider) =>"); + using (w.Hanging()) + w.Line($"global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(textRef)}, Payload = payload, Provider = provider, Format = {Quote(format)}, Verify = {ft}{maxCharsArg} }});"); + } } - - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.render.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.render.cs"), w.ToString()); } // ------------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index 17fab9d940..e15f88f71f 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -35,6 +35,7 @@ // file into your project and you own it. using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Core.Field.FieldConstants; @@ -92,107 +93,70 @@ private string ReportModule(MetaObject report, GenContext ctx) var cls = CSharpNaming.Pascal(report.Name); // A credential column (a derived field over a view.password field) is never exported. var fields = report.Fields().Where(f => !f.Views().Any(v => v.SubType == MetaObjects.Presentation.View.ViewConstants.VIEW_SUBTYPE_PASSWORD)).ToList(); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects report-export. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using System.IO;"); - sb.AppendLine("using System.Linq;"); // The module lives in its report's namespace when package namespaces are on (a per-object // class); the shared writer stays in GenConfig.Namespace and is then named global::-qualified. var pkgMode = ctx.Config.PackageNamespacesFromMetadata; var ns = ValueObjectNames.CompanionNamespace(report, ctx.Config); - if (!pkgMode) foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, [report])) sb.AppendLine(u); var writer = pkgMode ? ValueObjectNames.Global(ctx.Config.Namespace, "ReportExportWriter") : "ReportExportWriter"; var cell = pkgMode ? ValueObjectNames.Global(ctx.Config.Namespace, "ReportExportCell") : "ReportExportCell"; - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine($"/// The CSV and XML export of the {report.Name} report: its columns, in derived-field order, over the generated row."); + var w = new CsWriter(); + w.GeneratedFileHeader("report-export"); + w.Using("System.Collections.Generic"); + w.Using("System.IO"); + w.Using("System.Linq"); + if (!pkgMode) foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, [report])) w.Using(u["using ".Length..^1]); + w.Line($"namespace {ns};"); + w.Blank(); + w.Line($"/// The CSV and XML export of the {report.Name} report: its columns, in derived-field order, over the generated row."); ctx.Claim($"the C# namespace {ns}", $"{cls}Export", report.ResolutionKey(), "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one"); - sb.AppendLine($"public static class {cls}Export"); - sb.AppendLine("{"); - sb.AppendLine(" /// The XML root element."); - sb.AppendLine($" public const string Root = \"{report.Name}\";"); - sb.AppendLine(); - sb.AppendLine(" /// The derived field names, in derived-field order: the CSV header row and the XML element names."); - sb.AppendLine(" public static readonly IReadOnlyList Columns ="); - sb.AppendLine(" ["); - foreach (var f in fields) sb.AppendLine($" \"{f.Name}\","); - sb.AppendLine(" ];"); - sb.AppendLine(); - sb.AppendLine(" /// One row's cells in wire form, in order."); - sb.AppendLine($" public static {cell}[] Cells({cls} row) =>"); - sb.AppendLine(" ["); - foreach (var f in fields) - sb.AppendLine($" {writer}.Cell(row.{CSharpNaming.PropertyName(f, ctx.Config)}),"); - sb.AppendLine(" ];"); - sb.AppendLine(); - sb.AppendLine(" /// Writes the rows as RFC 4180 CSV."); - sb.AppendLine($" public static void WriteCsv(TextWriter writer, IEnumerable<{cls}> rows) =>"); - sb.AppendLine($" {writer}.WriteCsv(writer, Columns, rows.Select(Cells));"); - sb.AppendLine(); - sb.AppendLine(" /// Writes the rows as XML."); - sb.AppendLine($" public static void WriteXml(TextWriter writer, IEnumerable<{cls}> rows) =>"); - sb.AppendLine($" {writer}.WriteXml(writer, Root, Columns, rows.Select(Cells));"); - sb.AppendLine("}"); - return sb.ToString(); + using (w.Braced($"public static class {cls}Export")) + { + w.Line("/// The XML root element."); + w.Line($"public const string Root = \"{report.Name}\";"); + w.Blank(); + w.Line("/// The derived field names, in derived-field order: the CSV header row and the XML element names."); + w.Line("public static readonly IReadOnlyList Columns ="); + w.Open("["); + foreach (var f in fields) w.Line($"\"{f.Name}\","); + w.Close("];"); + w.Blank(); + w.Line("/// One row's cells in wire form, in order."); + w.Line($"public static {cell}[] Cells({cls} row) =>"); + w.Open("["); + foreach (var f in fields) + w.Line($"{writer}.Cell(row.{CSharpNaming.PropertyName(f, ctx.Config)}),"); + w.Close("];"); + w.Blank(); + w.Line("/// Writes the rows as RFC 4180 CSV."); + w.Line($"public static void WriteCsv(TextWriter writer, IEnumerable<{cls}> rows) =>"); + using (w.Hanging()) + w.Line($"{writer}.WriteCsv(writer, Columns, rows.Select(Cells));"); + w.Blank(); + w.Line("/// Writes the rows as XML."); + w.Line($"public static void WriteXml(TextWriter writer, IEnumerable<{cls}> rows) =>"); + using (w.Hanging()) + w.Line($"{writer}.WriteXml(writer, Root, Columns, rows.Select(Cells));"); + } + return w.ToString(); } // field.duration — the duration parts of the shared writer, emitted only when a served report has a // duration column, so the writer of a model without one is byte-identical to the one before // durations existed. The rule is the generated DurationWire.Format's. private const string DurationDoc = "a duration as its canonical ISO-8601 string, "; - private const string DurationCase = " case TimeSpan ts: return new(Duration(ts), false);\n"; - private const string DurationMethod = """ - // A field.duration as the wire writes it: the canonical ISO-8601 duration [-]PT[nH][nM][n[.f]S], - // hours never folded into days, up to seven fractional digits (a TimeSpan tick is 100 ns), - // zero as PT0S. The same rule as the generated DurationWire.Format. - private static string Duration(TimeSpan value) - { - long ticks = value.Ticks; - if (ticks == 0) return "PT0S"; - bool negative = ticks < 0; - ulong rest = negative ? (ulong)(-(ticks + 1)) + 1UL : (ulong)ticks; - ulong h = rest / 36_000_000_000UL, m = rest / 600_000_000UL % 60, s = rest / 10_000_000UL % 60, f = rest % 10_000_000UL; - var sb = new StringBuilder(negative ? "-PT" : "PT"); - if (h > 0) sb.Append(h.ToString(CultureInfo.InvariantCulture)).Append('H'); - if (m > 0) sb.Append(m.ToString(CultureInfo.InvariantCulture)).Append('M'); - if (s > 0 || f > 0) - { - sb.Append(s.ToString(CultureInfo.InvariantCulture)); - if (f > 0) sb.Append('.').Append(f.ToString("D7", CultureInfo.InvariantCulture).TrimEnd('0')); - sb.Append('S'); - } - return sb.ToString(); - } - - -"""; + private const string DurationCase = "case TimeSpan ts: return new(Duration(ts), false);"; // True when a served report has a field.duration column (a TimeSpan cell). private static bool HasDurationColumn(IEnumerable served) => served.Any(r => r.Fields().Any(f => f.SubType == FIELD_SUBTYPE_DURATION)); + // The shared writer: the C# it holds is full of braces, so it is written as raw interpolated + // text with `{{ }}` for the few values that vary; the optional duration parts are their own pieces. private string SharedWriter(GenContext ctx, bool durations) { - var text = SharedWriterTemplate - .Replace("@NAMESPACE@", ctx.Config.Namespace, StringComparison.Ordinal) - .Replace("@CSV_BOM@", Literal(CsvBom), StringComparison.Ordinal) - .Replace("@DECIMALS_AS_STRING@", Literal(ctx.Root.WireFormat.Decimals == DecimalWireForm.String), StringComparison.Ordinal) - .Replace("@XML_NIL@", Literal(XmlNulls == ReportExportXmlNulls.Nil), StringComparison.Ordinal) - .Replace("@DURATION_DOC@", durations ? DurationDoc : "", StringComparison.Ordinal) - .Replace("@DURATION_CASE@", durations ? DurationCase : "", StringComparison.Ordinal) - .Replace("@DURATION_METHOD@", durations ? DurationMethod : "", StringComparison.Ordinal); - return text; - } - - // The shared writer, verbatim but for its @TOKENS@ (the @DURATION_*@ ones are empty without a - // duration column). A plain string, not an interpolated - // one: the C# it holds is full of braces. - private const string SharedWriterTemplate = """ + var w = new CsWriter(); + w.Text($$""" // // Generated by MetaObjects report-export. Do not edit by hand. // @@ -207,30 +171,33 @@ private string SharedWriter(GenContext ctx, bool durations) using System.Text; using System.Xml; -namespace @NAMESPACE@; +namespace {{ctx.Config.Namespace}}; /// One exported cell: its wire-form text (null for a null) and whether the CSV formula-injection guard applies to it. public readonly record struct ReportExportCell(string? Value, bool IsText); /// CSV and XML writers for a report export, and the wire-form conversion of a cell. -public static class ReportExportWriter -{ +"""); + using (w.Braced("public static class ReportExportWriter")) + { + w.Text($$""" /// Start the CSV with a UTF-8 byte order mark. Flip it here, or regenerate with CsvBom = true. - public static readonly bool ExportCsvBom = @CSV_BOM@; + public static readonly bool ExportCsvBom = {{Literal(CsvBom)}}; /// The project's wire.decimals setting: write a decimal as its canonical string (12.5) rather than as System.Text.Json does (12.50). - public static readonly bool DecimalsAsString = @DECIMALS_AS_STRING@; + public static readonly bool DecimalsAsString = {{Literal(ctx.Root.WireFormat.Decimals == DecimalWireForm.String)}}; /// Write a null field as an empty element carrying xsi:nil="true" (and declare xmlns:xsi on the root) instead of as a bare empty element. - public static readonly bool XmlNil = @XML_NIL@; + public static readonly bool XmlNil = {{Literal(XmlNulls == ReportExportXmlNulls.Nil)}}; private const string XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"; - /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, @DURATION_DOC@a boolean as true/false, a null as null. - public static ReportExportCell Cell(object? value) - { - switch (value) - { + /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, {{(durations ? DurationDoc : "")}}a boolean as true/false, a null as null. +"""); + using (w.Braced("public static ReportExportCell Cell(object? value)")) + using (w.Braced("switch (value)")) + { + w.Text(""" case null: return new(null, false); case string s: return new(s, true); case bool b: return new(b ? "true" : "false", false); @@ -243,12 +210,16 @@ public static ReportExportCell Cell(object? value) case Enum e: return new(e.ToString(), true); case Uri u: return new(u.OriginalString, true); case IPAddress ip: return new(ip.ToString(), false); -@DURATION_CASE@ case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); +"""); + if (durations) w.Line(DurationCase); + w.Text(""" + case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); - } - } - +"""); + } + w.Blank(); + w.Text($$""" // A timestamp as the list route writes it (Iso8601TimestampConverter): UTC with Z, and // milliseconds only when the instant has a fraction. private static string Timestamp(DateTimeOffset value) @@ -260,7 +231,38 @@ private static string Timestamp(DateTimeOffset value) return utc.ToString(format, CultureInfo.InvariantCulture); } -@DURATION_METHOD@ // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". +"""); + if (durations) + { + // The duration parts of the shared writer exist only when a served report has a duration column. + w.Text(""" + // A field.duration as the wire writes it: the canonical ISO-8601 duration [-]PT[nH][nM][n[.f]S], + // hours never folded into days, up to seven fractional digits (a TimeSpan tick is 100 ns), + // zero as PT0S. The same rule as the generated DurationWire.Format. + private static string Duration(TimeSpan value) + { + long ticks = value.Ticks; + if (ticks == 0) return "PT0S"; + bool negative = ticks < 0; + ulong rest = negative ? (ulong)(-(ticks + 1)) + 1UL : (ulong)ticks; + ulong h = rest / 36_000_000_000UL, m = rest / 600_000_000UL % 60, s = rest / 10_000_000UL % 60, f = rest % 10_000_000UL; + var sb = new StringBuilder(negative ? "-PT" : "PT"); + if (h > 0) sb.Append(h.ToString(CultureInfo.InvariantCulture)).Append('H'); + if (m > 0) sb.Append(m.ToString(CultureInfo.InvariantCulture)).Append('M'); + if (s > 0 || f > 0) + { + sb.Append(s.ToString(CultureInfo.InvariantCulture)); + if (f > 0) sb.Append('.').Append(f.ToString("D7", CultureInfo.InvariantCulture).TrimEnd('0')); + sb.Append('S'); + } + return sb.ToString(); + } +"""); + w.Blank(); + } + w.Blank(); + w.Text($$""" + // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". private static string Canonical(decimal value) { var s = value.ToString(CultureInfo.InvariantCulture); @@ -361,6 +363,8 @@ private static string XmlSafe(string text) } return fixedUp?.ToString() ?? text; } -} -"""; +"""); + } + return w.ToString(); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs index 1102046f90..cdf718188a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs @@ -35,6 +35,7 @@ using System.Globalization; using System.Text; using System.Text.RegularExpressions; +using MetaObjects.Codegen.Writer; using MetaObjects.Core.Requirement; using MetaObjects.Meta; @@ -236,12 +237,13 @@ private static void RefuseCollisions(List planned) var pairs = RequirementTestIdentities.WitnessKeyCollisions(planned.Select(p => p.Identity)); if (pairs.Count == 0) return; var keyById = planned.ToDictionary(p => p.Identity.Id, p => p.Identity.WitnessKey, StringComparer.Ordinal); - var sb = new StringBuilder(ErrWitnessKeyCollision) - .Append(": two requirement tests map to one witness key, so one witness could not serve both. ") - .Append("Rename one so the names differ in more than punctuation:"); - foreach (var (first, second) in pairs) - sb.Append("\n '").Append(first).Append("' and '").Append(second).Append("' (witness key ").Append(keyById[first]).Append(')'); - throw new InvalidOperationException(sb.ToString()); + var w = new CsWriter(); + w.Line(ErrWitnessKeyCollision + ": two requirement tests map to one witness key, so one witness could not serve both. " + + "Rename one so the names differ in more than punctuation:"); + using (w.Hanging()) + foreach (var (first, second) in pairs) + w.Line($"'{first}' and '{second}' (witness key {keyById[first]})"); + throw new InvalidOperationException(w.ToString().TrimEnd()); } private static string UncoveredWarning(IReadOnlyList uncovered) @@ -258,9 +260,9 @@ private static string UncoveredWarning(IReadOnlyList uncovered) // rendering: the default rendering lives here, in this one file, so an eject takes it too // ------------------------------------------------------------------ - private const string GeneratedHeader = - "// \n" + - "// GENERATED by metaobjects (requirement-tests). DO NOT EDIT: this file is rewritten whole.\n"; + // The two header comment lines of both files of a pair. + private const string HeaderGenerated = "// "; + private const string HeaderRewritten = "// GENERATED by metaobjects (requirement-tests). DO NOT EDIT: this file is rewritten whole."; private static string WitnessInterface(DottedName testNamespace, string name, DottedName witnessClass, List tests) { @@ -268,73 +270,88 @@ private static string WitnessInterface(DottedName testNamespace, string name, Do var example = tests.FirstOrDefault(t => t.Identity.Skip is null)?.Identity.WitnessKey ?? "req_
__"; // The interface is named with its namespace: the witness class is in another one by default, // so the bare name would not resolve where this line is pasted. - var sb = new StringBuilder(GeneratedHeader) - .Append("// Witnesses are project-owned: implement this interface in ").Append(CommentText(witnessClass.Plain)) - .Append(", one EXPLICIT member per witness, e.g.\n") - .Append("// void ").Append(testNamespace.Code).Append('.').Append(name).Append('.').Append(example).Append("() { ... }\n") - .Append("// Explicit, so that a member whose requirement is retired or deleted stops compiling instead of going stale silently.\n") - .Append("namespace ").Append(testNamespace.Code).Append(";\n\n") - .Append("public interface ").Append(name).Append("\n{"); - foreach (var p in tests) + var w = new CsWriter(); + // No usings, so the comments are body lines: the namespace follows them directly. + w.Line(HeaderGenerated); + w.Line(HeaderRewritten); + w.Line($"// Witnesses are project-owned: implement this interface in {CommentText(witnessClass.Plain)}, one EXPLICIT member per witness, e.g."); + w.Line($"// void {testNamespace.Code}.{name}.{example}() {{ ... }}"); + w.Line("// Explicit, so that a member whose requirement is retired or deleted stops compiling instead of going stale silently."); + w.Line($"namespace {testNamespace.Code};"); + w.Blank(); + using (w.Braced($"public interface {name}")) { - var id = p.Identity; - if (id.Skip is not null) continue; // a skipped test claims nothing works yet: no member - sb.Append('\n').Append(Indent(TestComments(p.Args))).Append('\n') - .Append(" void ").Append(id.WitnessKey).Append("()\n {\n") - .Append(" throw new global::Xunit.Sdk.XunitException(\"") - .Append(StringLiteral( - "unimplemented requirement: " + id.Id + " - write " + witnessClass.Plain + "." + id.WitnessKey + - "() so that it fails when: " + p.Args.Counterexample)) - .Append("\");\n }\n"); + foreach (var p in tests) + { + var id = p.Identity; + if (id.Skip is not null) continue; // a skipped test claims nothing works yet: no member + w.Blank(); + WriteTestComments(w, p.Args); + using (w.Braced($"void {id.WitnessKey}()")) + w.Line($"throw new global::Xunit.Sdk.XunitException(\"{StringLiteral("unimplemented requirement: " + id.Id + " - write " + witnessClass.Plain + "." + id.WitnessKey + "() so that it fails when: " + p.Args.Counterexample)}\");"); + } } - return sb.Append("}\n").ToString(); + return w.ToString(); } private static string TestClass( DottedName testNamespace, string name, string witnesses, DottedName witnessClass, List tests, IRequirementTestRenderer? renderer) { + var w = new CsWriter(); + w.Header( + HeaderGenerated, + HeaderRewritten, + $"// The witnesses are project-owned, in {CommentText(witnessClass.Plain)}.", + "// Implement each member explicitly, as the witness interface shows, so that a stale one stops compiling."); + // Every test's source is rendered first: a renderer can ask for usings, which sit above the namespace. var usings = new SortedSet(StringComparer.Ordinal) { "Xunit" }; - var body = new StringBuilder(); + var sources = new List(); foreach (var p in tests) { var rendered = renderer?.Render(p.Args); - string source; if (rendered is not null) { foreach (var u in rendered.Usings) usings.Add(u); - source = rendered.Source; + sources.Add(rendered.Source); } else { - source = DefaultTest(p); + sources.Add(DefaultTest(p)); } - body.Append('\n').Append(Indent(source.TrimEnd())).Append('\n'); } - var sb = new StringBuilder(GeneratedHeader) - .Append("// The witnesses are project-owned, in ").Append(CommentText(witnessClass.Plain)).Append(".\n") - .Append("// Implement each member explicitly, as the witness interface shows, so that a stale one stops compiling.\n"); - foreach (var u in usings) sb.Append("using ").Append(u).Append(";\n"); - return sb.Append("\nnamespace ").Append(testNamespace.Code).Append(";\n\n") - .Append("public class ").Append(name).Append("\n{\n") - .Append(" private readonly ").Append(witnesses).Append(" witnesses = new global::").Append(witnessClass.Code).Append("();\n") - .Append(body).Append("}\n").ToString(); + foreach (var u in usings) w.Using(u); + w.Line($"namespace {testNamespace.Code};"); + w.Blank(); + using (w.Braced($"public class {name}")) + { + w.Line($"private readonly {witnesses} witnesses = new global::{witnessClass.Code}();"); + foreach (var source in sources) + { + w.Blank(); + w.Text(source.TrimEnd()); + } + } + return w.ToString(); } /// The default rendering of one test: its comments, then a [Fact] calling the witness. private static string DefaultTest(Planned p) { var id = p.Identity; - var sb = new StringBuilder(TestComments(p.Args)).Append('\n'); + var w = new CsWriter(); + WriteTestComments(w, p.Args); if (id.Skip is null) { - sb.Append("[Fact]\npublic void ").Append(id.WitnessKey).Append("()\n{\n witnesses.").Append(id.WitnessKey).Append("();\n}"); + w.Line("[Fact]"); + using (w.Braced($"public void {id.WitnessKey}()")) + w.Line($"witnesses.{id.WitnessKey}();"); } else { - sb.Append("[Fact(Skip = \"").Append(StringLiteral(SkipReason(id.Skip))).Append("\")]\n") - .Append("public void ").Append(id.WitnessKey).Append("()\n{\n}"); + w.Line($"[Fact(Skip = \"{StringLiteral(SkipReason(id.Skip))}\")]"); + using (w.Braced($"public void {id.WitnessKey}()")) { } } - return sb.ToString(); + return w.ToString(); } private static string SkipReason(string skip) => skip switch @@ -345,45 +362,36 @@ private static string DefaultTest(Planned p) }; /// The comment block above a test: id, statement, counterexample, status, claims, digest. - private static string TestComments(RequirementTestArgs a) + private static void WriteTestComments(CsWriter w, RequirementTestArgs a) { var id = a.Identity; var claims = a.Targets.Count == 0 ? "(none)" : string.Join(", ", a.Targets.Select(c => $"{c.Ref} ({c.Concern})")); - return CommentLines(id.Id) + "\n" - + CommentLines(a.Statement) + "\n" - + CommentLines("Counterexample: " + a.Counterexample) + "\n" - + CommentLines("Status: " + (id.Status ?? "(none)")) + "\n" - + CommentLines("Claims: " + claims) + "\n" - + CommentLines("Digest: " + id.Digest); + WriteComment(w, id.Id); + WriteComment(w, a.Statement); + WriteComment(w, "Counterexample: " + a.Counterexample); + WriteComment(w, "Status: " + (id.Status ?? "(none)")); + WriteComment(w, "Claims: " + claims); + WriteComment(w, "Digest: " + id.Digest); } // ------------------------------------------------------------------ // escaping: author prose lands in string literals and comments, and must not break either // ------------------------------------------------------------------ - private static string Indent(string block) - { - var sb = new StringBuilder(); - foreach (var line in block.Split('\n')) - { - if (sb.Length > 0) sb.Append('\n'); - if (line.Length > 0) sb.Append(" ").Append(line); - } - return sb.ToString(); - } - // A C# line ends at a line feed, a carriage return, a CR LF pair, or U+0085, U+2028 or U+2029. - private static readonly Regex LineTerminator = new("\r\n|[\r\n\u0085\u2028\u2029]", RegexOptions.CultureInvariant); + private static readonly Regex LineTerminator = new Regex("\r\n|[\r\n\u0085\u2028\u2029]", RegexOptions.CultureInvariant); /// /// One // marker per line: every line terminator of the language splits, so none can end the comment /// early and leave the rest of the prose as code. */ is broken as * / by contract. C# does /// not process a Unicode escape inside a comment, so \u000a stays as written. /// - private static string CommentLines(string text) => - string.Join("\n", LineTerminator.Split(text).Select(line => "// " + CommentText(line))); + private static void WriteComment(CsWriter w, string text) + { + foreach (var line in LineTerminator.Split(text)) w.Line("// " + CommentText(line)); + } private static string CommentText(string line) => line.Replace("*/", "* /", StringComparison.Ordinal); @@ -392,6 +400,10 @@ private static string CommentLines(string text) => /// \n and \r, is escaped, so no value can end the literal. A lone surrogate is escaped too: it has /// no UTF-8 spelling and would not survive being written to the file. ///
+ // The two line terminators a literal spells as escapes, named so the source types no line break. + private const char LineFeed = (char)0x0A; + private const char CarriageReturn = (char)0x0D; + private static string StringLiteral(string s) { var sb = new StringBuilder(); @@ -402,8 +414,8 @@ private static string StringLiteral(string s) { case '\\': sb.Append("\\\\"); break; case '"': sb.Append("\\\""); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; + case LineFeed: sb.Append("\\n"); break; + case CarriageReturn: sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: if (char.IsHighSurrogate(c) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs index 1f420a17c0..29133997a2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs @@ -19,6 +19,7 @@ // own query surface. M:N navigation (junction traversal) is a SEPARATE concern // (M2MNavigation) and is unaffected. +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Core.Identity.IdentityConstants; @@ -132,61 +133,55 @@ private static string FkValueType(MetaObject entity, ReverseFk fk, MetaRoot root var queriesCls = CSharpNaming.QueriesClassName(entity); var dbSet = readDbSetOverride ?? CSharpNaming.DbSetName(entity); // #214 write-through → Views - var sb = new System.Text.StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects entity-generator (reverse FK finders, ADR-0038). Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine("using System.Linq;"); - sb.AppendLine("using Microsoft.EntityFrameworkCore;"); - if (!ctx.Config.PackageNamespacesFromMetadata && entityNs != ns) sb.AppendLine($"using {entityNs};"); - sb.AppendLine(); - sb.AppendLine($"namespace {ns};"); - sb.AppendLine(); - sb.AppendLine("/// Reverse-relationship FK finders for " + cls + " (ADR-0038): explicit,"); - sb.AppendLine("/// single-query reads — no lazy navigation, no N+1."); - sb.AppendLine($"public static class {queriesCls}"); - sb.AppendLine("{"); - - // The finders are members of one class: two FKs whose segments fold to one name collide. - ctx.Claim($"the C# namespace {ns}", queriesCls, entity.ResolutionKey(), - "map the packages to distinct namespaces (GenConfig.PackageNamespaces), or rename one"); - foreach (var fk in fks) - { - ctx.Claim($"the reverse finders of {ns}.{queriesCls}", CSharpNaming.ReverseFinderName(entity, fk.FkField), - $"{entity.ResolutionKey()}.{fk.FkField}", "rename one of the foreign-key fields"); - ctx.Claim($"the reverse finders of {ns}.{queriesCls}", CSharpNaming.ReverseFinderInName(entity, fk.FkField), - $"{entity.ResolutionKey()}.{fk.FkField}", "rename one of the foreign-key fields"); - } - - var first = true; - foreach (var fk in fks) + var w = new CsWriter(); + w.GeneratedFileHeader("entity-generator (reverse FK finders, ADR-0038)"); + w.Using("System.Collections.Generic"); + w.Using("System.Linq"); + w.Using("Microsoft.EntityFrameworkCore"); + if (!ctx.Config.PackageNamespacesFromMetadata && entityNs != ns) w.Using(entityNs); + w.Line($"namespace {ns};"); + w.Blank(); + w.Line("/// Reverse-relationship FK finders for " + cls + " (ADR-0038): explicit,"); + w.Line("/// single-query reads — no lazy navigation, no N+1."); + using (w.Braced($"public static class {queriesCls}")) { - var valueType = FkValueType(entity, fk, ctx.Root); - var prop = entity.FindField(fk.FkField) is { } fkField ? propertyName(fkField) : CSharpNaming.Pascal(fk.FkField); - var arg = fk.FkField; - var single = CSharpNaming.ReverseFinderName(entity, fk.FkField); - var batched = CSharpNaming.ReverseFinderInName(entity, fk.FkField); - - if (!first) sb.AppendLine(); - first = false; - - // Single: one indexed WHERE = value → List. - sb.AppendLine($" /// The {cls} rows whose {prop} equals (one indexed query)."); - sb.AppendLine($" public static async {sys}System.Threading.Tasks.Task> {single}({contextType} db, {valueType} {arg}) =>"); - sb.AppendLine($" await db.{dbSet}.AsNoTracking().Where(e => e.{prop} == {arg}).ToListAsync();"); - sb.AppendLine(); - - // Batched: one WHERE IN (values) → List (anti-N+1 "selectin" shape). - sb.AppendLine($" /// The {cls} rows whose {prop} is in (one batched IN query; anti-N+1)."); - sb.AppendLine($" public static async {sys}System.Threading.Tasks.Task> {batched}({contextType} db, IReadOnlyCollection<{valueType}> {arg}s)"); - sb.AppendLine(" {"); - sb.AppendLine($" if ({arg}s.Count == 0) return new List<{rowType}>();"); - sb.AppendLine($" return await db.{dbSet}.AsNoTracking().Where(e => {arg}s.Contains(e.{prop})).ToListAsync();"); - sb.AppendLine(" }"); + // The finders are members of one class: two FKs whose segments fold to one name collide. + ctx.Claim($"the C# namespace {ns}", queriesCls, entity.ResolutionKey(), + "map the packages to distinct namespaces (GenConfig.PackageNamespaces), or rename one"); + foreach (var fk in fks) + { + ctx.Claim($"the reverse finders of {ns}.{queriesCls}", CSharpNaming.ReverseFinderName(entity, fk.FkField), + $"{entity.ResolutionKey()}.{fk.FkField}", "rename one of the foreign-key fields"); + ctx.Claim($"the reverse finders of {ns}.{queriesCls}", CSharpNaming.ReverseFinderInName(entity, fk.FkField), + $"{entity.ResolutionKey()}.{fk.FkField}", "rename one of the foreign-key fields"); + } + + foreach (var fk in fks) + { + var valueType = FkValueType(entity, fk, ctx.Root); + var prop = entity.FindField(fk.FkField) is { } fkField ? propertyName(fkField) : CSharpNaming.Pascal(fk.FkField); + var arg = fk.FkField; + var single = CSharpNaming.ReverseFinderName(entity, fk.FkField); + var batched = CSharpNaming.ReverseFinderInName(entity, fk.FkField); + + w.Blank(); + + // Single: one indexed WHERE = value → List. + w.Line($"/// The {cls} rows whose {prop} equals (one indexed query)."); + w.Line($"public static async {sys}System.Threading.Tasks.Task> {single}({contextType} db, {valueType} {arg}) =>"); + using (w.Hanging()) + w.Line($"await db.{dbSet}.AsNoTracking().Where(e => e.{prop} == {arg}).ToListAsync();"); + w.Blank(); + + // Batched: one WHERE IN (values) → List (anti-N+1 "selectin" shape). + w.Line($"/// The {cls} rows whose {prop} is in (one batched IN query; anti-N+1)."); + using (w.Braced($"public static async {sys}System.Threading.Tasks.Task> {batched}({contextType} db, IReadOnlyCollection<{valueType}> {arg}s)")) + { + w.Line($"if ({arg}s.Count == 0) return new List<{rowType}>();"); + w.Line($"return await db.{dbSet}.AsNoTracking().Where(e => {arg}s.Contains(e.{prop})).ToListAsync();"); + } + } } - - sb.AppendLine("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{queriesCls}.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{queriesCls}.g.cs"), w.ToString()); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 419029b869..006789c712 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -38,6 +38,7 @@ // copied both — see MetaObjects.Codegen.HelperRuntime. using System.Text; +using MetaObjects.Codegen.Writer; using MetaObjects.Meta; using static MetaObjects.Core.Field.FieldConstants; using static MetaObjects.Core.Object.ObjectConstants; @@ -117,16 +118,16 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) // policy to a bare Map* call, and an adopter that doesn't notice ships it open. The XML // doc on the mount method is the one place a consumer reads before wiring it into their // host, so it says so and shows the fix rather than leaving it to a README nobody opens. - private static void AppendUnauthenticatedRoutesDoc(StringBuilder sb, string cls, bool readOnly) + private static void AppendUnauthenticatedRoutesDoc(CsWriter w, string cls, bool readOnly) { var verbs = readOnly ? "read endpoints" : "endpoints"; - sb.AppendLine($" /// Maps {cls} REST routes. Unauthenticated — see remarks."); - sb.AppendLine(" /// "); - sb.AppendLine($" /// These {verbs} are unauthenticated. Guard them by mapping on a group that requires"); - sb.AppendLine($" /// authorization, e.g. app.MapGroup(\"\").RequireAuthorization().Map{cls}Routes();"); - sb.AppendLine(" /// A row-ownership rule (\"only the owner may read this row\") cannot be expressed on a mount:"); - sb.AppendLine($" /// eject this generator with dotnet meta eject and hand-write those {verbs}."); - sb.AppendLine(" /// "); + w.Line($"/// Maps {cls} REST routes. Unauthenticated — see remarks."); + w.Line("/// "); + w.Line($"/// These {verbs} are unauthenticated. Guard them by mapping on a group that requires"); + w.Line($"/// authorization, e.g. app.MapGroup(\"\").RequireAuthorization().Map{cls}Routes();"); + w.Line("/// A row-ownership rule (\"only the owner may read this row\") cannot be expressed on a mount:"); + w.Line($"/// eject this generator with dotnet meta eject and hand-write those {verbs}."); + w.Line("/// "); } /// @@ -154,56 +155,56 @@ private static void AppendUnauthenticatedRoutesDoc(StringBuilder sb, string cls, // (that generator's MaxRows) governs instead and the refusal is export_too_large; // report_too_large never answers on an export. With no report-export generator wired the // emitted text is the same as before export existed. - private void AppendReportPaging(StringBuilder sb, int? exportMaxRows) + private void AppendReportPaging(CsWriter w, int? exportMaxRows) { var max = ReportMaxRows.ToString(System.Globalization.CultureInfo.InvariantCulture); var tooLarge = "Results.BadRequest(new { error = \"report_too_large\", maxRows })"; - sb.AppendLine(" // Pagination (report): every row up to the cap, refused above it."); + w.Line("// Pagination (report): every row up to the cap, refused above it."); if (exportMaxRows is not { } exportCap) { - sb.AppendLine($" const int maxRows = {max};"); + w.Line($"const int maxRows = {max};"); } else { var exportMax = exportCap.ToString(System.Globalization.CultureInfo.InvariantCulture); - sb.AppendLine($" const int listMaxRows = {max};"); - sb.AppendLine($" const int exportMaxRows = {exportMax};"); - sb.AppendLine(" // With ?format the export cap governs and report_too_large never answers."); - sb.AppendLine(" var maxRows = format is null ? listMaxRows : exportMaxRows;"); + w.Line($"const int listMaxRows = {max};"); + w.Line($"const int exportMaxRows = {exportMax};"); + w.Line("// With ?format the export cap governs and report_too_large never answers."); + w.Line("var maxRows = format is null ? listMaxRows : exportMaxRows;"); tooLarge = "format is null ? " + tooLarge + " : ReportExportHttp.TooLarge(maxRows)"; } - sb.AppendLine(" long? limit = null;"); - sb.AppendLine(" long offset = 0;"); - sb.AppendLine(" if (qs.TryGetValue(\"limit\", out var limitRaw))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1)"); - sb.AppendLine(" return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"limit\", value = limitRaw.ToString(), expected = $\"an integer from 1 to {maxRows}\" });"); - sb.AppendLine(" if (parsedLimit > maxRows)"); - sb.AppendLine($" return {tooLarge};"); - sb.AppendLine(" limit = parsedLimit;"); - sb.AppendLine(" }"); - sb.AppendLine(" if (qs.TryGetValue(\"offset\", out var offsetRaw)"); - sb.AppendLine(" && (!long.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0))"); - sb.AppendLine(" return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"offset\", value = offsetRaw.ToString(), expected = \"a non-negative integer (0 or more)\" });"); - sb.AppendLine(" if (offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue));"); - sb.AppendLine(" q = q.Take((int)(limit ?? maxRows + 1L));"); - sb.AppendLine(); - sb.AppendLine(" var rows = await q.ToListAsync();"); - sb.AppendLine(" if (limit is null && rows.Count > maxRows)"); - sb.AppendLine($" return {tooLarge};"); + w.Line("long? limit = null;"); + w.Line("long offset = 0;"); + w.Line("if (qs.TryGetValue(\"limit\", out var limitRaw))"); + w.Open("{"); + w.Line("if (!long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1)"); + using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"limit\", value = limitRaw.ToString(), expected = $\"an integer from 1 to {maxRows}\" });"); + w.Line("if (parsedLimit > maxRows)"); + using (w.Hanging()) w.Line($"return {tooLarge};"); + w.Line("limit = parsedLimit;"); + w.Close("}"); + w.Line("if (qs.TryGetValue(\"offset\", out var offsetRaw)"); + using (w.Hanging()) w.Line("&& (!long.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0))"); + using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"offset\", value = offsetRaw.ToString(), expected = \"a non-negative integer (0 or more)\" });"); + w.Line("if (offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue));"); + w.Line("q = q.Take((int)(limit ?? maxRows + 1L));"); + w.Blank(); + w.Line("var rows = await q.ToListAsync();"); + w.Line("if (limit is null && rows.Count > maxRows)"); + using (w.Hanging()) w.Line($"return {tooLarge};"); } // A report-export download: the rows are fetched exactly as the list route fetches them, then // written as CSV or XML by the module the report-export generator emitted for this report. A JSON // export is the list route's own body, written by the withCount tail below. - private static void AppendReportExportBranch(StringBuilder sb, string cls, string route) + private static void AppendReportExportBranch(CsWriter w, string cls, string route) { - sb.AppendLine(); - sb.AppendLine(" // Export (report-export): the same rows as a download. withCount with csv or xml was refused above."); - sb.AppendLine(" if (format == \"csv\")"); - sb.AppendLine($" return ReportExportHttp.Csv(http, \"{route}\", w => {cls}Export.WriteCsv(w, rows));"); - sb.AppendLine(" if (format == \"xml\")"); - sb.AppendLine($" return ReportExportHttp.Xml(http, \"{route}\", w => {cls}Export.WriteXml(w, rows));"); + w.Blank(); + w.Line("// Export (report-export): the same rows as a download. withCount with csv or xml was refused above."); + w.Line("if (format == \"csv\")"); + using (w.Hanging()) w.Line($"return ReportExportHttp.Csv(http, \"{route}\", w => {cls}Export.WriteCsv(w, rows));"); + w.Line("if (format == \"xml\")"); + using (w.Hanging()) w.Line($"return ReportExportHttp.Xml(http, \"{route}\", w => {cls}Export.WriteXml(w, rows));"); } // Every type the route file names bare — the entity itself, its value objects (owned and map @@ -319,110 +320,111 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte .ToHashSet(StringComparer.Ordinal); bool sqliteSort = sortFields.Any(decimalSortFields.Contains); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects routes-generator. Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Linq;"); - sb.AppendLine("using Microsoft.AspNetCore.Builder;"); - sb.AppendLine("using Microsoft.AspNetCore.Http;"); - sb.AppendLine("using Microsoft.AspNetCore.Routing;"); - sb.AppendLine("using Microsoft.EntityFrameworkCore;"); - sb.AppendLine($"using {HelperRuntimeNamespace};"); + var w = new CsWriter(); + w.Line("// "); + w.Line("// Generated by MetaObjects routes-generator. Do not edit by hand."); + w.Line("#nullable enable"); + w.Line("using System.Linq;"); + w.Line("using Microsoft.AspNetCore.Builder;"); + w.Line("using Microsoft.AspNetCore.Http;"); + w.Line("using Microsoft.AspNetCore.Routing;"); + w.Line("using Microsoft.EntityFrameworkCore;"); + w.Line($"using {HelperRuntimeNamespace};"); if (!ctx.Config.PackageNamespacesFromMetadata) - foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, ReferencedTypes([entity], ctx.Root))) sb.AppendLine(u); - sb.AppendLine(); - sb.AppendLine($"namespace {ValueObjectNames.CompanionNamespace(entity, ctx.Config)};"); - sb.AppendLine(); - sb.AppendLine($"public static class {cls}Routes"); - sb.AppendLine("{"); + foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, ReferencedTypes([entity], ctx.Root))) w.Line(u); + w.Blank(); + w.Line($"namespace {ValueObjectNames.CompanionNamespace(entity, ctx.Config)};"); + w.Blank(); + w.Line($"public static class {cls}Routes"); + w.Open("{"); // Static sort allowlist (case-insensitive) so the qs ?sort=field:dir // is gated against the entity's scalar fields. - AppendSortAllowlist(sb, "SortAllowlist", sortFieldNodes, ctx.Config); - AppendSortDefaultOrder(sb, entity, "SortDefaultDesc", ctx.Config); - if (writable) AppendKnownFields(sb, [entity], ctx.Root); - AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); - sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); - sb.AppendLine(" {"); + AppendSortAllowlist(w, "SortAllowlist", sortFieldNodes, ctx.Config); + AppendSortDefaultOrder(w, entity, "SortDefaultDesc", ctx.Config); + if (writable) AppendKnownFields(w, [entity], ctx.Root); + AppendUnauthenticatedRoutesDoc(w, cls, isProjection); + w.Line($"public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); + w.Open("{"); // Refuse to start when the host's serializer contract cannot be read to strip a credential. if (credentials.Count > 0) - sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); - AppendDecimalRangeGroup(sb); + w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); + AppendDecimalRangeGroup(w); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. - sb.AppendLine(" app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); - sb.AppendLine(" {"); - sb.AppendLine(" var qs = http.Request.Query;"); + w.Line("app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + w.Open("{"); + w.Line("var qs = http.Request.Query;"); if (export is not null) { - sb.AppendLine(" // Export (report-export): ?format=csv|json|xml. An unknown format, or withCount with csv or xml, is refused before any query runs."); - sb.AppendLine(" var format = ReportExportHttp.Requested(qs);"); - sb.AppendLine(" if (ReportExportHttp.Refuse(format, qs) is { } exportRefusal) return exportRefusal;"); + w.Line("// Export (report-export): ?format=csv|json|xml. An unknown format, or withCount with csv or xml, is refused before any query runs."); + w.Line("var format = ReportExportHttp.Requested(qs);"); + w.Line("if (ReportExportHttp.Refuse(format, qs) is { } exportRefusal) return exportRefusal;"); } - sb.AppendLine($" IQueryable<{readCls}> q = db." + readDbSet + ".AsNoTracking();"); - sb.AppendLine(); - sb.AppendLine(" // Filter: ?filter[][]= against the per-entity allowlist."); + w.Line($"IQueryable<{readCls}> q = db." + readDbSet + ".AsNoTracking();"); + w.Blank(); + w.Line("// Filter: ?filter[][]= against the per-entity allowlist."); var fm = FilterMapArg($"{cls}FilterAllowlist", entity, ctx.Config); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField){fm});"); - sb.AppendLine(" if (filter.ErrorEnvelope is not null)"); + w.Line($"var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField){fm});"); + w.Line("if (filter.ErrorEnvelope is not null)"); // `field` names the rejected filter field — required cross-port on every // filter envelope, so a caller with several filters knows which one failed. - sb.AppendLine(" return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fm});"); - sb.AppendLine(); - sb.AppendLine(" // Sort: ?sort=field:asc|desc against the static allowlist."); - sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - sb.AppendLine(" {"); - sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); - sb.AppendLine(" var field = parts[0];"); - sb.AppendLine(" if (!SortAllowlist.TryGetValue(field, out var resolved))"); - sb.AppendLine(" return Results.BadRequest(new { error = \"invalid_sort\", field });"); + using (w.Hanging()) w.Line("return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); + w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fm});"); + w.Blank(); + w.Line("// Sort: ?sort=field:asc|desc against the static allowlist."); + w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); + w.Open("{"); + w.Line("var parts = sortRaw.ToString().Split(':', 2);"); + w.Line("var field = parts[0];"); + w.Line("if (!SortAllowlist.TryGetValue(field, out var resolved))"); + using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"invalid_sort\", field });"); // `?sort=field` with no `:order` takes the field's DECLARED @sortableDefaultOrder. // Keyed on `resolved` — the allowlist's canonical Pascal spelling — so a // case-insensitive wire name still finds its declaration. Ascending stays the // fallback HERE, one place per port. - sb.AppendLine(" var desc = parts.Length > 1"); - sb.AppendLine(" ? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - sb.AppendLine(" : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - sb.AppendLine(sqliteSort - ? $" q = ApplySort{cls}(q, resolved, desc, db.Database.ProviderName?.Contains(\"Sqlite\", System.StringComparison.OrdinalIgnoreCase) == true);" - : $" q = ApplySort{cls}(q, resolved, desc);"); - sb.AppendLine(" }"); - sb.AppendLine(); + w.Line("var desc = parts.Length > 1"); + using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); + using (w.Hanging()) w.Line(": SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); + if (sqliteSort) + w.Line($"q = ApplySort{cls}(q, resolved, desc, db.Database.ProviderName?.Contains(\"Sqlite\", System.StringComparison.OrdinalIgnoreCase) == true);"); + else + w.Line($"q = ApplySort{cls}(q, resolved, desc);"); + w.Close("}"); + w.Blank(); if (isReport) { - AppendReportPaging(sb, export); - if (export is not null) AppendReportExportBranch(sb, cls, route); + AppendReportPaging(w, export); + if (export is not null) AppendReportExportBranch(w, cls, route); } else { - sb.AppendLine(" // Pagination: ?offset=N first (skip), then ?limit=N (take)."); - AppendOffsetLimit(sb, ctx.Root.Api.Pagination, " ", "offsetRaw", "offset", "limitRaw", "limit"); - sb.AppendLine(); - sb.AppendLine(" var rows = await q.ToListAsync();"); + w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); + AppendOffsetLimit(w, ctx.Root.Api.Pagination, "offsetRaw", "offset", "limitRaw", "limit"); + w.Blank(); + w.Line("var rows = await q.ToListAsync();"); } - sb.AppendLine(); - sb.AppendLine(" // withCount=1 → { rows, total } envelope; otherwise bare row array."); - sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Blank(); + w.Line("// withCount=1 → { rows, total } envelope; otherwise bare row array."); + w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); if (export is null) - sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); + w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); else - sb.AppendLine($" if (!withCount) return format is null ? {OkResult("rows", credentials)} : ReportExportHttp.Json(http, \"{route}\", rows{ExportOmit(credentials, false)});"); - sb.AppendLine($" var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates{fm});"); - sb.AppendLine(" var total = await totalQ.CountAsync();"); + w.Line($"if (!withCount) return format is null ? {OkResult("rows", credentials)} : ReportExportHttp.Json(http, \"{route}\", rows{ExportOmit(credentials, false)});"); + w.Line($"var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates{fm});"); + w.Line("var total = await totalQ.CountAsync();"); if (export is null) - sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); + w.Line($"return {OkResult("new { rows, total }", credentials, envelope: true)};"); else - sb.AppendLine($" return format is null ? {OkResult("new { rows, total }", credentials, envelope: true)} : ReportExportHttp.Json(http, \"{route}\", new {{ rows, total }}{ExportOmit(credentials, true)});"); - sb.AppendLine(" });"); + w.Line($"return format is null ? {OkResult("new { rows, total }", credentials, envelope: true)} : ReportExportHttp.Json(http, \"{route}\", new {{ rows, total }}{ExportOmit(credentials, true)});"); + w.Close("});"); if (hasItem) { - sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); - sb.AppendLine(" await db." + readDbSet + ".FindAsync(id) is { } found"); - sb.AppendLine(" ? " + OkResult("found", credentials)); - sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + using (w.Hanging()) w.Line("await db." + readDbSet + ".FindAsync(id) is { } found"); + using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", credentials)); + using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); } if (writable) @@ -432,11 +434,11 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // field.timestamp → non-nullable DateTimeOffset) binds to a CLR default when // omitted, invisible to [Required], so the create handler checks raw-JSON presence. var requiredKeys = RequiredCreateKeys(entity, f => pkFields.Contains(f.Name)); - sb.AppendLine(); + w.Blank(); // #214 — a write-through create binds the derived-FREE WRITE entity, persists to // the table, then RE-READS the row through the replica view by PK so the returned // body carries the derived (view-computed) fields (read-your-writes). - AppendCreateHandler(sb, "/" + route, cls, ValueObjectNames.ContextTypeRef(ctx.Config), dbSet, requiredKeys, + AppendCreateHandler(w, "/" + route, cls, ValueObjectNames.ContextTypeRef(ctx.Config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields, writeThrough ? (readDbSet, pkProp!, route) : null, deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), credentials, @@ -458,59 +460,59 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // CLEARS a nullable column; an explicit null on a NOT-NULL (@required) column // is a 400. The per-key merge (shared with the TPH per-subtype handler) is // emitted by AppendPartialMergeLoop. - sb.AppendLine(); - sb.AppendLine(" async System.Threading.Tasks.Task Update" + cls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db)"); - sb.AppendLine(" {"); - sb.AppendLine(" var existing = await db." + dbSet + ".FindAsync(id);"); - sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - sb.AppendLine(" System.Text.Json.JsonDocument body;"); - sb.AppendLine(" try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - sb.AppendLine(" catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); - sb.AppendLine(" using var bodyScope = body;"); - sb.AppendLine(" if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); - AppendUnknownFieldsCheck(sb, ctx.Root, "body"); - sb.AppendLine(" // Deserialize each value with the app's CONFIGURED JSON options, not defaults —"); - sb.AppendLine(" // a field.timestamp binds to DateTimeOffset via a custom converter registered on"); - sb.AppendLine(" // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500."); - sb.AppendLine(" var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); - sb.AppendLine(" .Value.SerializerOptions;"); - sb.AppendLine(" var entry = db.Entry(existing);"); - AppendUpdateAutoSet(sb, autoSetFields); - AppendPartialMergeLoop(sb, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), + w.Blank(); + w.Line("async System.Threading.Tasks.Task Update" + cls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db)"); + w.Open("{"); + w.Line("var existing = await db." + dbSet + ".FindAsync(id);"); + w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); + w.Line("System.Text.Json.JsonDocument body;"); + w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); + w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("using var bodyScope = body;"); + w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); + AppendUnknownFieldsCheck(w, ctx.Root, "body"); + w.Line("// Deserialize each value with the app's CONFIGURED JSON options, not defaults —"); + w.Line("// a field.timestamp binds to DateTimeOffset via a custom converter registered on"); + w.Line("// ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500."); + w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); + using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + using (w.Hanging()) w.Line(".Value.SerializerOptions;"); + w.Line("var entry = db.Entry(existing);"); + AppendUpdateAutoSet(w, autoSetFields); + AppendPartialMergeLoop(w, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), deniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), HasIsoDurationField(entity, ctx.Root)); - AppendSaveChanges(sb); - AppendArrayNullClears(sb, voFields, tableRef, pkColumnRef); + AppendSaveChanges(w); + AppendArrayNullClears(w, voFields, tableRef, pkColumnRef); // #214 — writes target the table; for a write-through entity re-read the row // through the replica view by PK so the returned body carries the derived fields. if (writeThrough) { - sb.AppendLine($" var __view = await db.{readDbSet}.FindAsync(id);"); + w.Line($"var __view = await db.{readDbSet}.FindAsync(id);"); // #214 [2] — a @kind:materializedView (unrefreshed) or filtered replica view may // not surface the just-written row; fall back to the write entity so the body is // never null (degraded — missing only the derived fields; matches the Python port). - sb.AppendLine($" return {OkResult("(object?)__view ?? existing", credentials)};"); + w.Line($"return {OkResult("(object?)__view ?? existing", credentials)};"); } else { - sb.AppendLine($" return {OkResult("existing", credentials)};"); + w.Line($"return {OkResult("existing", credentials)};"); } - sb.AppendLine(" }"); - sb.AppendLine(" app.MapPatch(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); - sb.AppendLine(" app.MapPut(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); - sb.AppendLine(); - sb.AppendLine(" app.MapDelete(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); - sb.AppendLine(" {"); - sb.AppendLine(" var existing = await db." + dbSet + ".FindAsync(id);"); - sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - sb.AppendLine(" db." + dbSet + ".Remove(existing);"); - AppendSaveChanges(sb); - sb.AppendLine(" return Results.NoContent();"); - sb.AppendLine(" });"); + w.Close("}"); + w.Line("app.MapPatch(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); + w.Line("app.MapPut(prefix + \"/" + route + "/{id}\", Update" + cls + ");"); + w.Blank(); + w.Line("app.MapDelete(prefix + \"/" + route + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + w.Open("{"); + w.Line("var existing = await db." + dbSet + ".FindAsync(id);"); + w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); + w.Line("db." + dbSet + ".Remove(existing);"); + AppendSaveChanges(w); + w.Line("return Results.NoContent();"); + w.Close("});"); } else if (isProjection) { - AppendProjectionRejects(sb, route, pkType, hasItem, isReport ? "report" : "projection"); + AppendProjectionRejects(w, route, pkType, hasItem, isReport ? "report" : "projection"); } // FR-018 M:N traversal — GET //{id}/ through the @@ -519,37 +521,38 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // segment = relationship name. if (hasItem) foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) - AppendM2mRoute(sb, nav, route, pkType!, ctx.Root, ctx.Config); + AppendM2mRoute(w, nav, route, pkType!, ctx.Root, ctx.Config); - sb.AppendLine(); - sb.AppendLine(" return mount;"); - sb.AppendLine(" }"); - sb.AppendLine(); + w.Blank(); + w.Line("return mount;"); + w.Close("}"); + w.Blank(); // Allowlisted property name → IOrderedQueryable dispatch via EF.Property. // Reflection-free at runtime; EF Core translates EF.Property(x, "") // into the column reference at SQL generation. - sb.AppendLine($" private static IOrderedQueryable<{readCls}> ApplySort{cls}(IQueryable<{readCls}> q, string field, bool desc{(sqliteSort ? ", bool sqlite" : "")})"); - sb.AppendLine(" {"); - sb.AppendLine(" return field switch"); - sb.AppendLine(" {"); + w.Line($"private static IOrderedQueryable<{readCls}> ApplySort{cls}(IQueryable<{readCls}> q, string field, bool desc{(sqliteSort ? ", bool sqlite" : "")})"); + w.Open("{"); + w.Line("return field switch"); + w.Open("{"); foreach (var name in sortFields) { var exact = NullsLargestSort("q", $"EF.Property(x!, \"{name}\")"); - sb.AppendLine(decimalSortFields.Contains(name) - ? $" \"{name}\" => sqlite ? ({NullsLargestSort("q", $"(double?)EF.Property(x!, \"{name}\")")}) : ({exact})," - : $" \"{name}\" => {exact},"); + if (decimalSortFields.Contains(name)) + w.Line($"\"{name}\" => sqlite ? ({NullsLargestSort("q", $"(double?)EF.Property(x!, \"{name}\")")}) : ({exact}),"); + else + w.Line($"\"{name}\" => {exact},"); } - sb.AppendLine(" _ => (IOrderedQueryable<" + readCls + ">)q.OrderBy(x => 0),"); - sb.AppendLine(" };"); - sb.AppendLine(" }"); + w.Line("_ => (IOrderedQueryable<" + readCls + ">)q.OrderBy(x => 0),"); + w.Close("};"); + w.Close("}"); // Issue #203 — the verbatim-insert escape hatch, only for an entity with @autoSet // fields (writable entities only; a read-only projection has no insert path). if (writable && autoSetFields.Count > 0) - AppendInsertPreserving(sb, cls, dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); - AppendOmitResultClass(sb); - sb.AppendLine("}"); + AppendInsertPreserving(w, cls, dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); + AppendOmitResultClass(w, credentials.Count > 0 || (hasItem && M2mTargetHasCredentials([entity], ctx.Root, ctx.Config))); + w.Close("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}Routes.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}Routes.g.cs"), w.ToString()); } // F22 — the write verbs on a read-only projection, each answering the cross-port @@ -569,24 +572,24 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // // A view-backed report (FR-044) takes the keyless arm: POST only. `noun` is what the // free-prose message calls the resource ("projection" or "report"). - private static void AppendProjectionRejects(StringBuilder sb, string route, string? pkType, bool hasItem, string noun) + private static void AppendProjectionRejects(CsWriter w, string route, string? pkType, bool hasItem, string noun) { - sb.AppendLine(); - AppendReject(sb, "MapPost", "/" + route, "POST", null, noun); + w.Blank(); + AppendReject(w, "MapPost", "/" + route, "POST", null, noun); if (!hasItem) return; - AppendReject(sb, "MapPatch", "/" + route + "/{id}", "PATCH", pkType, noun); - AppendReject(sb, "MapPut", "/" + route + "/{id}", "PUT", pkType, noun); - AppendReject(sb, "MapDelete", "/" + route + "/{id}", "DELETE", pkType, noun); + AppendReject(w, "MapPatch", "/" + route + "/{id}", "PATCH", pkType, noun); + AppendReject(w, "MapPut", "/" + route + "/{id}", "PUT", pkType, noun); + AppendReject(w, "MapDelete", "/" + route + "/{id}", "DELETE", pkType, noun); } // The item handlers take the route's `id` even though they ignore it: a typed // parameter makes an unparsable id a 404 from routing rather than a 405 claiming // the write was refused on a row that could never have been addressed. - private static void AppendReject(StringBuilder sb, string map, string path, string verb, string? pkType, string noun) + private static void AppendReject(CsWriter w, string map, string path, string verb, string? pkType, string noun) { var parms = pkType is null ? "()" : "(" + pkType + " id)"; - sb.AppendLine(" app." + map + "(prefix + \"" + path + "\", " + parms + " =>"); - sb.AppendLine(" Results.Json(new { error = \"method_not_allowed\", message = \"" + verb + w.Line("app." + map + "(prefix + \"" + path + "\", " + parms + " =>"); + using (w.Hanging()) w.Line("Results.Json(new { error = \"method_not_allowed\", message = \"" + verb + " is not supported on a " + noun + " (read-only).\" }, statusCode: 405));"); } @@ -633,29 +636,29 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t .ToList(); var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); - var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Generated by MetaObjects routes-generator (TPH). Do not edit by hand."); - sb.AppendLine("#nullable enable"); - sb.AppendLine("using System.Linq;"); - sb.AppendLine("using Microsoft.AspNetCore.Builder;"); - sb.AppendLine("using Microsoft.AspNetCore.Http;"); - sb.AppendLine("using Microsoft.AspNetCore.Routing;"); - sb.AppendLine("using Microsoft.EntityFrameworkCore;"); - sb.AppendLine($"using {HelperRuntimeNamespace};"); + var w = new CsWriter(); + w.Line("// "); + w.Line("// Generated by MetaObjects routes-generator (TPH). Do not edit by hand."); + w.Line("#nullable enable"); + w.Line("using System.Linq;"); + w.Line("using Microsoft.AspNetCore.Builder;"); + w.Line("using Microsoft.AspNetCore.Http;"); + w.Line("using Microsoft.AspNetCore.Routing;"); + w.Line("using Microsoft.EntityFrameworkCore;"); + w.Line($"using {HelperRuntimeNamespace};"); if (!ctx.Config.PackageNamespacesFromMetadata) - foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, ReferencedTypes(tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root))) sb.AppendLine(u); - sb.AppendLine(); - sb.AppendLine($"namespace {ValueObjectNames.CompanionNamespace(baseEntity, ctx.Config)};"); - sb.AppendLine(); - sb.AppendLine($"public static class {baseCls}Routes"); - sb.AppendLine("{"); + foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, ReferencedTypes(tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root))) w.Line(u); + w.Blank(); + w.Line($"namespace {ValueObjectNames.CompanionNamespace(baseEntity, ctx.Config)};"); + w.Blank(); + w.Line($"public static class {baseCls}Routes"); + w.Open("{"); // Polymorphic sort allowlist over the base scalar columns. - AppendSortAllowlist(sb, "SortAllowlist", sortFieldNodes, ctx.Config); - AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc", ctx.Config); + AppendSortAllowlist(w, "SortAllowlist", sortFieldNodes, ctx.Config); + AppendSortDefaultOrder(w, baseEntity, "SortDefaultDesc", ctx.Config); // One known set for the whole hierarchy: a sibling subtype's column is declared, so it is not unknown. - AppendKnownFields(sb, tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root); + AppendKnownFields(w, tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root); // Per-subtype sort allowlists (case-insensitive) over each subtype's EFFECTIVE // scalar fields (inherited base + own). The per-subtype list resolves the qs @@ -668,54 +671,54 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var subSortFields = st.Entity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !hierarchyCredentials.Contains(f.Name)) .ToList(); - AppendSortAllowlist(sb, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); - AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); + AppendSortAllowlist(w, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); + AppendSortDefaultOrder(w, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); } - AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); - sb.AppendLine($" public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); - sb.AppendLine(" {"); + AppendUnauthenticatedRoutesDoc(w, baseCls, readOnly: false); + w.Line($"public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); + w.Open("{"); if (baseCredentials.Count > 0) { var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); - sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); + w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); } - AppendDecimalRangeGroup(sb); + AppendDecimalRangeGroup(w); // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- - sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); - sb.AppendLine(" {"); - sb.AppendLine(" var qs = http.Request.Query;"); - sb.AppendLine($" IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); + w.Line("app.MapGet(prefix + \"/" + baseRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + w.Open("{"); + w.Line("var qs = http.Request.Query;"); + w.Line($"IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); var fmB = FilterMapArg($"{baseCls}FilterAllowlist", baseEntity, ctx.Config); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField){fmB});"); - sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmB});"); - sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - sb.AppendLine(" {"); - sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); - sb.AppendLine(" if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = \"invalid_sort\", field = parts[0] });"); - sb.AppendLine(" var desc = parts.Length > 1"); - sb.AppendLine(" ? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - sb.AppendLine(" : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - sb.AppendLine(" q = ApplySort(q, resolved, desc);"); - sb.AppendLine(" }"); - AppendOffsetLimit(sb, ctx.Root.Api.Pagination, " ", "offRaw", "off", "limRaw", "lim"); - sb.AppendLine(" var rows = await q.ToListAsync();"); - sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); - sb.AppendLine($" if (!withCount) return {OkResult("rows", baseCredentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); - sb.AppendLine($" return {OkResult("new { rows, total }", baseCredentials, envelope: true)};"); - sb.AppendLine(" });"); + w.Line($"var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField){fmB});"); + w.Line("if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); + w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmB});"); + w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); + w.Open("{"); + w.Line("var parts = sortRaw.ToString().Split(':', 2);"); + w.Line("if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = \"invalid_sort\", field = parts[0] });"); + w.Line("var desc = parts.Length > 1"); + using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); + using (w.Hanging()) w.Line(": SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); + w.Line("q = ApplySort(q, resolved, desc);"); + w.Close("}"); + AppendOffsetLimit(w, ctx.Root.Api.Pagination, "offRaw", "off", "limRaw", "lim"); + w.Line("var rows = await q.ToListAsync();"); + w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Line($"if (!withCount) return {OkResult("rows", baseCredentials)};"); + w.Line($"var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); + w.Line($"return {OkResult("new { rows, total }", baseCredentials, envelope: true)};"); + w.Close("});"); if (hasItem) { // --- Polymorphic get: GET //{id} (one row of whatever subtype) --- - sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + baseRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); - sb.AppendLine($" await db.{dbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); - sb.AppendLine(" ? " + OkResult("found", baseCredentials)); - sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + baseRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + using (w.Hanging()) w.Line($"await db.{dbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); + using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", baseCredentials)); + using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); // FW-8 — M:N traversal declared on the BASE: every row of the shared table // is a legitimate source (rule a in the cross-port contract — the independent @@ -724,40 +727,40 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // a vanilla entity's traversal at the base route. Mirrors TS // renderTphRoutesFile's baseM2mMounts. foreach (var nav in M2MNavigationBuilder.For(baseEntity, ctx.Root, ctx.Warn)) - AppendM2mRoute(sb, nav, baseRoute, pkType!, ctx.Root, ctx.Config); + AppendM2mRoute(w, nav, baseRoute, pkType!, ctx.Root, ctx.Config); // --- Per-subtype CRUD sets --- var hierarchy = tph.Subtypes.Select(s => s.Entity).Prepend(baseEntity).ToList(); foreach (var st in tph.Subtypes) - AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, ctx.Config, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn); + AppendTphSubtypeRoutes(w, st, hierarchy, ctx.Root, ctx.Config, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn); } - sb.AppendLine(); - sb.AppendLine(" return mount;"); - sb.AppendLine(" }"); - sb.AppendLine(); + w.Blank(); + w.Line("return mount;"); + w.Close("}"); + w.Blank(); // Polymorphic sort dispatch over base scalar columns (reflection-free via EF.Property). - sb.AppendLine($" private static IOrderedQueryable<{baseCls}> ApplySort(IQueryable<{baseCls}> q, string field, bool desc)"); - sb.AppendLine(" {"); - sb.AppendLine(" return field switch"); - sb.AppendLine(" {"); + w.Line($"private static IOrderedQueryable<{baseCls}> ApplySort(IQueryable<{baseCls}> q, string field, bool desc)"); + w.Open("{"); + w.Line("return field switch"); + w.Open("{"); foreach (var name in sortFields) - sb.AppendLine($" \"{name}\" => {NullsLargestSort("q", $"EF.Property(x!, \"{name}\")")},"); - sb.AppendLine(" _ => (IOrderedQueryable<" + baseCls + ">)q.OrderBy(x => 0),"); - sb.AppendLine(" };"); - sb.AppendLine(" }"); + w.Line($"\"{name}\" => {NullsLargestSort("q", $"EF.Property(x!, \"{name}\")")},"); + w.Line("_ => (IOrderedQueryable<" + baseCls + ">)q.OrderBy(x => 0),"); + w.Close("};"); + w.Close("}"); // Issue #203 — a verbatim-insert escape hatch per subtype that declares @autoSet // fields (overloaded by the subtype parameter type; the discriminator is injected by // EF via the subtype CLR type on Add). Only when the subtype has @autoSet columns. if (hasItem) foreach (var st in tph.Subtypes) if (AutoSetFields(st.Entity, ctx.Config).Count > 0) - AppendInsertPreserving(sb, ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)), dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); - AppendOmitResultClass(sb); - sb.AppendLine("}"); + AppendInsertPreserving(w, ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)), dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); + AppendOmitResultClass(w, baseCredentials.Count > 0 || (hasItem && M2mTargetHasCredentials(tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root, ctx.Config))); + w.Close("}"); - return new EmittedFile(OutputPaths.Of(baseEntity, ctx, $"{baseCls}Routes.g.cs"), sb.ToString()); + return new EmittedFile(OutputPaths.Of(baseEntity, ctx, $"{baseCls}Routes.g.cs"), w.ToString()); } // FR-036 #4 — the wire keys of the @required fields whose keys must be PRESENT (and @@ -888,28 +891,26 @@ private static string KeyMatch(IEnumerable keys) => // ignoring case), as ever. When a resolver renamed a property beyond case it is a map that accepts the // field name too, so `?sort=` takes the same key as `?filter[...]` (which keys on the field name) // and the property name a client may have read from a response. - private static void AppendSortAllowlist(StringBuilder sb, string name, IReadOnlyList fields, GenConfig config) + private static void AppendSortAllowlist(CsWriter w, string name, IReadOnlyList fields, GenConfig config) { var pairs = fields.Select(f => (Field: f.Name, Prop: CSharpNaming.PropertyName(f, config))).ToList(); if (pairs.All(p => string.Equals(p.Field, p.Prop, StringComparison.OrdinalIgnoreCase))) { - sb.Append($" private static readonly System.Collections.Generic.HashSet {name} ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); - foreach (var p in pairs) sb.AppendLine($" \"{p.Prop}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + w.Line($"private static readonly System.Collections.Generic.HashSet {name} = new(System.StringComparer.OrdinalIgnoreCase)"); + w.Open("{"); + foreach (var p in pairs) w.Line($"\"{p.Prop}\","); + w.Close("};"); + w.Blank(); return; } - sb.Append($" private static readonly System.Collections.Generic.Dictionary {name} ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); + w.Line($"private static readonly System.Collections.Generic.Dictionary {name} = new(System.StringComparer.OrdinalIgnoreCase)"); + w.Open("{"); // Property names first, so a field name that spells another field's property never shadows it. var keys = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var p in pairs) if (keys.Add(p.Prop)) sb.AppendLine($" [\"{p.Prop}\"] = \"{p.Prop}\","); - foreach (var p in pairs) if (keys.Add(p.Field)) sb.AppendLine($" [\"{p.Field}\"] = \"{p.Prop}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + foreach (var p in pairs) if (keys.Add(p.Prop)) w.Line($"[\"{p.Prop}\"] = \"{p.Prop}\","); + foreach (var p in pairs) if (keys.Add(p.Field)) w.Line($"[\"{p.Field}\"] = \"{p.Prop}\","); + w.Close("};"); + w.Blank(); } // The extra argument that hands the filter dispatch the allowlist's field-to-property map: only @@ -937,35 +938,39 @@ private static string CreatedResult(string location, string value, IReadOnlyList ? $"Results.Created({location}, {value})" : $"(IResult)new CredentialOmittingResult({value}, {NamesLiteral(credentials)}, status: 201, location: {location})"; + // True when any M:N traversal mounted for these sources returns rows of a target that carries a credential. + private static bool M2mTargetHasCredentials(IEnumerable sources, MetaRoot root, GenConfig config) => + sources.Any(src => M2MNavigationBuilder.For(src, root).Any(nav => TphUnionCredentialNames(nav.Target, root, config).Count > 0)); + // Emitted only into a routes class that uses it (never for a model without a credential). - private static void AppendOmitResultClass(StringBuilder sb) + private static void AppendOmitResultClass(CsWriter w, bool used) { - if (!sb.ToString().Contains("new CredentialOmittingResult(")) return; - sb.AppendLine(); - sb.AppendLine(" // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled."); - sb.AppendLine(" // Serializes with the app's configured JSON options, then removes the named keys from each row."); - sb.AppendLine(" private sealed class CredentialOmittingResult : IResult"); - sb.AppendLine(" {"); - sb.AppendLine(" private readonly object _value;"); - sb.AppendLine(" private readonly string[] _names;"); - sb.AppendLine(" private readonly bool _envelope;"); - sb.AppendLine(" private readonly int _status;"); - sb.AppendLine(" private readonly string? _location;"); - sb.AppendLine(" public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null)"); - sb.AppendLine(" { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; }"); - sb.AppendLine(" public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http)"); - sb.AppendLine(" {"); - sb.AppendLine(" var opts = ((Microsoft.Extensions.Options.IOptions)"); - sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); - sb.AppendLine(" .Value.SerializerOptions;"); - sb.AppendLine(" var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); - sb.AppendLine(" // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names."); - sb.AppendLine(" SerializerKeys.StripBody(node, _value, _envelope, opts, _names);"); - sb.AppendLine(" http.Response.StatusCode = _status;"); - sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); - sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); - sb.AppendLine(" }"); - sb.AppendLine(" }"); + if (!used) return; + w.Blank(); + w.Line("// #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled."); + w.Line("// Serializes with the app's configured JSON options, then removes the named keys from each row."); + w.Line("private sealed class CredentialOmittingResult : IResult"); + w.Open("{"); + w.Line("private readonly object _value;"); + w.Line("private readonly string[] _names;"); + w.Line("private readonly bool _envelope;"); + w.Line("private readonly int _status;"); + w.Line("private readonly string? _location;"); + w.Line("public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null)"); + w.Line("{ _value = value; _names = names; _envelope = envelope; _status = status; _location = location; }"); + w.Line("public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http)"); + w.Open("{"); + w.Line("var opts = ((Microsoft.Extensions.Options.IOptions)"); + using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + using (w.Hanging()) w.Line(".Value.SerializerOptions;"); + w.Line("var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); + w.Line("// The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names."); + w.Line("SerializerKeys.StripBody(node, _value, _envelope, opts, _names);"); + w.Line("http.Response.StatusCode = _status;"); + w.Line("if (_location is not null) http.Response.Headers.Location = _location;"); + w.Line("await http.Response.WriteAsJsonAsync(node, opts);"); + w.Close("}"); + w.Close("}"); } private static List AutoSetFields(MetaObject entity, GenConfig config) @@ -1073,62 +1078,62 @@ private static List ValueObjectFields(MetaObject entity, MetaRoot root, // routes class. Null under `drop` (nothing is emitted and no handler checks): the constant's name otherwise. private const string KnownFieldsConst = "KnownFields"; - private static void AppendKnownFields(StringBuilder sb, IEnumerable objects, MetaRoot root) + private static void AppendKnownFields(CsWriter w, IEnumerable objects, MetaRoot root) { if (root.Api.UnknownFields != UnknownFieldsMode.Reject) return; var names = objects.SelectMany(o => o.Fields()).Select(f => f.Name) .Distinct(StringComparer.Ordinal).OrderBy(n => n, StringComparer.Ordinal).ToList(); - sb.AppendLine(" // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400."); - sb.AppendLine(" private static readonly System.Collections.Generic.HashSet " + KnownFieldsConst + " = new(System.StringComparer.Ordinal)"); - sb.AppendLine(" {"); - foreach (var n in names) sb.AppendLine($" \"{n}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + w.Line("// api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400."); + w.Line("private static readonly System.Collections.Generic.HashSet " + KnownFieldsConst + " = new(System.StringComparer.Ordinal)"); + w.Open("{"); + foreach (var n in names) w.Line($"\"{n}\","); + w.Close("};"); + w.Blank(); } // The unknown-field refusal, before any validation of the body. `bodyVar` is the parsed JsonDocument. - private static void AppendUnknownFieldsCheck(StringBuilder sb, MetaRoot root, string bodyVar) + private static void AppendUnknownFieldsCheck(CsWriter w, MetaRoot root, string bodyVar) { if (root.Api.UnknownFields != UnknownFieldsMode.Reject) return; // `http` carries the app's JSON options: a key the binder matches case-insensitively is declared. - sb.AppendLine($" if (UnknownFieldCheck.Reject({bodyVar}.RootElement, {KnownFieldsConst}, http) is {{ }} __unknown) return __unknown;"); + w.Line($"if (UnknownFieldCheck.Reject({bodyVar}.RootElement, {KnownFieldsConst}, http) is {{ }} __unknown) return __unknown;"); } // The offset + limit lines of a list route. Without `api.pagination` they are exactly what they always // were; with it, no limit takes defaultLimit and one above maxLimit is 400 limit_too_large. - private static void AppendOffsetLimit(StringBuilder sb, ApiPagination? page, string indent, string offRaw, string off, string limRaw, string lim) + private static void AppendOffsetLimit(CsWriter w, ApiPagination? page, string offRaw, string off, string limRaw, string lim) { if (page is not null) { // An offset that is present but not a non-negative int is refused, as the TypeScript routes answer, // never read as "absent" and answered with a page the client did not ask for. - sb.AppendLine($"{indent}if (qs.TryGetValue(\"offset\", out var {offRaw}Bad) && !(int.TryParse({offRaw}Bad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}Bad) && {off}Bad >= 0))"); - sb.AppendLine($"{indent} return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"offset\", value = {offRaw}Bad.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); + w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}Bad) && !(int.TryParse({offRaw}Bad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}Bad) && {off}Bad >= 0))"); + using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"offset\", value = {offRaw}Bad.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); } - sb.AppendLine($"{indent}if (qs.TryGetValue(\"offset\", out var {offRaw}) && int.TryParse({offRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}) && {off} > 0)"); - sb.AppendLine($"{indent} q = q.Skip({off});"); + w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}) && int.TryParse({offRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}) && {off} > 0)"); + using (w.Hanging()) w.Line($"q = q.Skip({off});"); if (page is null) { - sb.AppendLine($"{indent}if (qs.TryGetValue(\"limit\", out var {limRaw}) && int.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} > 0)"); - sb.AppendLine($"{indent} q = q.Take({lim});"); + w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}) && int.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} > 0)"); + using (w.Hanging()) w.Line($"q = q.Take({lim});"); return; } - sb.AppendLine($"{indent}// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); + w.Line($"// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); // A negative or non-numeric limit is refused with the malformed-bound envelope, as the TypeScript routes answer. - sb.AppendLine($"{indent}if (qs.TryGetValue(\"limit\", out var {limRaw}Neg) && !(long.TryParse({limRaw}Neg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}Neg) && {lim}Neg >= 0))"); - sb.AppendLine($"{indent} return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"limit\", value = {limRaw}Neg.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); - sb.AppendLine($"{indent}var __take = {page.DefaultLimit};"); + w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}Neg) && !(long.TryParse({limRaw}Neg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}Neg) && {lim}Neg >= 0))"); + using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"limit\", value = {limRaw}Neg.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); + w.Line($"var __take = {page.DefaultLimit};"); // `limit=0` is a page of zero rows, as every other port serves it, not "no limit". - sb.AppendLine($"{indent}if (qs.TryGetValue(\"limit\", out var {limRaw}) && long.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} >= 0)"); - sb.AppendLine($"{indent}{{"); - sb.AppendLine($"{indent} if ({lim} > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); - sb.AppendLine($"{indent} __take = (int){lim};"); - sb.AppendLine($"{indent}}}"); - sb.AppendLine($"{indent}q = q.Take(__take);"); + w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}) && long.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} >= 0)"); + w.Open("{"); + w.Line($"if ({lim} > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); + w.Line($"__take = (int){lim};"); + w.Close($"}}"); + w.Line($"q = q.Take(__take);"); } private static void AppendCreateHandler( - StringBuilder sb, string mapPath, string cls, string ctxType, string dbSet, + CsWriter w, string mapPath, string cls, string ctxType, string dbSet, IReadOnlyList requiredKeys, string createdExpr, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetFields, @@ -1142,44 +1147,42 @@ private static void AppendCreateHandler( // The body is always read here, not model-bound: the framework answers a body it cannot bind with a // bare 400 and no body, while every validation failure must list its issues (the cross-port // {error:"validation", issues:[...]} envelope), so the handler reads the body itself and collects them. - sb.AppendLine($" app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, {ctxType} db) =>"); - sb.AppendLine(" {"); - AppendJsonOptsLocal(sb); - sb.AppendLine(" System.Text.Json.JsonDocument __body;"); - sb.AppendLine(" try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - sb.AppendLine(" catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); - sb.AppendLine(" using var __bodyScope = __body;"); - sb.AppendLine(" if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)"); - sb.AppendLine(" return ValidationIssues.Unreadable();"); - if (root is not null) AppendUnknownFieldsCheck(sb, root, "__body"); - sb.AppendLine(" var __issues = new ValidationIssues();"); + w.Line($"app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, {ctxType} db) =>"); + w.Open("{"); + AppendJsonOptsLocal(w); + w.Line("System.Text.Json.JsonDocument __body;"); + w.Line("try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); + w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("using var __bodyScope = __body;"); + w.Line("if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)"); + using (w.Hanging()) w.Line("return ValidationIssues.Unreadable();"); + if (root is not null) AppendUnknownFieldsCheck(w, root, "__body"); + w.Line("var __issues = new ValidationIssues();"); // FR-036 #4 — @required-key presence: an omitted key OR an explicit null on a @required // field → 400, matching the JVM/Python "missing @required → 400" contract. Case-insensitive // so a camelCase wire key ("createdAt") matches its PascalCase property ("CreatedAt"). if (requiredKeys.Count > 0) { - sb.AppendLine(" var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase);"); - sb.AppendLine(" foreach (var __p in __body.RootElement.EnumerateObject())"); - sb.AppendLine(" if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);"); - sb.Append(" foreach (var __req in new[] { "); - sb.Append(string.Join(", ", requiredKeys.Select(k => "\"" + k + "\""))); - sb.AppendLine(" })"); - sb.AppendLine(" if (!__present.Contains(__req)) __issues.AddRequired(__req);"); + w.Line("var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase);"); + w.Line("foreach (var __p in __body.RootElement.EnumerateObject())"); + using (w.Hanging()) w.Line("if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);"); + w.Line("foreach (var __req in new[] { " + string.Join(", ", requiredKeys.Select(k => "\"" + k + "\"")) + " })"); + using (w.Hanging()) w.Line("if (!__present.Contains(__req)) __issues.AddRequired(__req);"); } // A value that cannot be read (a wrong-shaped VO, a decimal out of range, a malformed date) throws // JsonException: it is listed at its path, and the body cannot be checked further. - sb.AppendLine($" {cls}? input = null;"); - sb.AppendLine(" try { input = System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }"); - sb.AppendLine(" catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(" + cls + ")); }"); - sb.AppendLine(" if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable();"); - AppendCreateServerOwned(sb, serverOwned); - AppendCreateIgnoreDenied(sb, deniedNavs); - AppendCreateValidation(sb, readOnlyRequired); - AppendCreateVoValidation(sb, voFields, mapVoFields); - sb.AppendLine(" if (__issues.Any) return __issues.ToResult();"); - AppendCreateAutoSet(sb, autoSetFields); - AppendCreatePersist(sb, dbSet, createdExpr, reRead, credentials ?? []); - sb.AppendLine(" });"); + w.Line($"{cls}? input = null;"); + w.Line("try { input = System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }"); + w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(" + cls + ")); }"); + w.Line("if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable();"); + AppendCreateServerOwned(w, serverOwned); + AppendCreateIgnoreDenied(w, deniedNavs); + AppendCreateValidation(w, readOnlyRequired); + AppendCreateVoValidation(w, voFields, mapVoFields); + w.Line("if (__issues.Any) return __issues.ToResult();"); + AppendCreateAutoSet(w, autoSetFields); + AppendCreatePersist(w, dbSet, createdExpr, reRead, credentials ?? []); + w.Close("});"); } // The persist tail of a generated POST handler: add the bound `input` to the WRITE @@ -1188,23 +1191,23 @@ private static void AppendCreateHandler( // is set: the row is read back THROUGH the replica view by PK so the returned body // carries the derived (view-computed) fields. Assumes `input` + `db` are in scope. private static void AppendCreatePersist( - StringBuilder sb, string dbSet, string createdExpr, + CsWriter w, string dbSet, string createdExpr, (string ReadDbSet, string PkProp, string Route)? reRead, IReadOnlyList credentials) { - sb.AppendLine($" db.{dbSet}.Add(input);"); - AppendSaveChanges(sb); + w.Line($"db.{dbSet}.Add(input);"); + AppendSaveChanges(w); if (reRead is { } rr) { - sb.AppendLine($" var __created = await db.{rr.ReadDbSet}.FindAsync(input.{rr.PkProp});"); + w.Line($"var __created = await db.{rr.ReadDbSet}.FindAsync(input.{rr.PkProp});"); // #214 [2] — a @kind:materializedView (unrefreshed) or filtered replica view may not // surface the just-inserted row; fall back to the bound write `input` so the 201 body // is never null (degraded — missing only the derived fields; matches the Python port). - sb.AppendLine($" return {CreatedResult($"prefix + \"/{rr.Route}/\" + input.{rr.PkProp}", "(object?)__created ?? input", credentials)};"); + w.Line($"return {CreatedResult($"prefix + \"/{rr.Route}/\" + input.{rr.PkProp}", "(object?)__created ?? input", credentials)};"); } else { - sb.AppendLine($" return {createdExpr};"); + w.Line($"return {createdExpr};"); } } @@ -1217,11 +1220,11 @@ private static void AppendCreatePersist( // - M:N navigation collections: emptied, else `Add` would insert a client-sent related graph. // A readOnly field needs no line here: the entity declares it with a private setter, which // System.Text.Json never binds (EntityGenerator.SetterFor). - private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList? statements) + private static void AppendCreateServerOwned(CsWriter w, IReadOnlyList? statements) { if (statements is null || statements.Count == 0) return; - sb.AppendLine(" // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored."); - foreach (var st in statements) sb.AppendLine(" " + st); + w.Line("// Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored."); + foreach (var st in statements) w.Line("" + st); } // The reset statements AppendCreateServerOwned emits for one entity (empty when it has none, so an @@ -1257,22 +1260,22 @@ or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID // #484 — a write-denied key (@formExclude or credential) on a create body is IGNORED, never // rejected: the bound value is reset to the CLR default (unset / null) before validation. - private static void AppendCreateIgnoreDenied(StringBuilder sb, IReadOnlyList? deniedNavs) + private static void AppendCreateIgnoreDenied(CsWriter w, IReadOnlyList? deniedNavs) { if (deniedNavs is null || deniedNavs.Count == 0) return; - sb.AppendLine(" // @formExclude / credential: not settable through the generated create; the value is ignored."); + w.Line("// @formExclude / credential: not settable through the generated create; the value is ignored."); foreach (var nav in deniedNavs) - sb.AppendLine($" input.{nav} = default!;"); + w.Line($"input.{nav} = default!;"); } // Issue #203 — stamp EVERY @autoSet column (onCreate AND onUpdate) with now() on // insert, overriding whatever the client sent (the model's value is ignored, so a // fresh row's updated-at equals its created-at). Emits nothing when the entity has no // @autoSet field. Assumes the bound local `input` is in scope. - private static void AppendCreateAutoSet(StringBuilder sb, IReadOnlyList autoSetFields) + private static void AppendCreateAutoSet(CsWriter w, IReadOnlyList autoSetFields) { foreach (var a in autoSetFields) - sb.AppendLine($" input.{a.Nav} = {a.NowExpr};"); + w.Line($"input.{a.Nav} = {a.NowExpr};"); } // Issue #203 — stamp each onUpdate @autoSet column with now() on update, BEFORE the @@ -1280,11 +1283,11 @@ private static void AppendCreateAutoSet(StringBuilder sb, IReadOnlyList autoSetFields) + private static void AppendUpdateAutoSet(CsWriter w, IReadOnlyList autoSetFields) { foreach (var a in autoSetFields) if (a.OnUpdate) - sb.AppendLine($" existing.{a.Nav} = {a.NowExpr};"); + w.Line($"existing.{a.Nav} = {a.NowExpr};"); } // Issue #203 — the InsertPreserving escape hatch for one entity: a public static helper @@ -1292,17 +1295,17 @@ private static void AppendUpdateAutoSet(StringBuilder sb, IReadOnlyListEscape hatch: insert without @autoSet stamping (created-at/updated-at"); - sb.AppendLine(" /// written verbatim from ) for import / restore / replication."); - sb.AppendLine($" public static async System.Threading.Tasks.Task<{cls}> InsertPreserving({ctxType} db, {cls} input)"); - sb.AppendLine(" {"); - sb.AppendLine($" db.{dbSet}.Add(input);"); - sb.AppendLine(" await db.SaveChangesAsync();"); - sb.AppendLine(" return input;"); - sb.AppendLine(" }"); + w.Blank(); + w.Line("/// Escape hatch: insert without @autoSet stamping (created-at/updated-at"); + w.Line("/// written verbatim from ) for import / restore / replication."); + w.Line($"public static async System.Threading.Tasks.Task<{cls}> InsertPreserving({ctxType} db, {cls} input)"); + w.Open("{"); + w.Line($"db.{dbSet}.Add(input);"); + w.Line("await db.SaveChangesAsync();"); + w.Line("return input;"); + w.Close("}"); } // Program D — post-save raw NULL for each nullable array-of-VO column a request cleared @@ -1316,14 +1319,13 @@ private static void AppendInsertPreserving(StringBuilder sb, string cls, string // the bare literals otherwise (ADR-0034's documented fallback, byte-identical to before). // Emits nothing when the entity has no nullable array-of-VO column. private static void AppendArrayNullClears( - StringBuilder sb, IReadOnlyList voFields, string tableRef, string pkColumnRef) + CsWriter w, IReadOnlyList voFields, string tableRef, string pkColumnRef) { for (int i = 0; i < voFields.Count; i++) { var vf = voFields[i]; if (!vf.IsArray || vf.Required) continue; - sb.AppendLine( - $" if (__clearVo{i}) await db.Database.ExecuteSqlRawAsync(" + + w.Line($"if (__clearVo{i}) await db.Database.ExecuteSqlRawAsync(" + $"\"UPDATE \\\"{SqlSplice(tableRef)}\\\" SET \\\"{SqlSplice(vf.JsonColumnRef)}\\\" = NULL WHERE \\\"{SqlSplice(pkColumnRef)}\\\" = {{0}}\", id);"); } } @@ -1343,18 +1345,16 @@ private static string SqlSplice(string nameExpr) => // into nested VO members; a null nav is vacuously valid (a missing required VO column is // already caught by the @required-key presence check). Assumes `input` is in scope. private static void AppendCreateVoValidation( - StringBuilder sb, IReadOnlyList voFields, IReadOnlyList mapVoFields) + CsWriter w, IReadOnlyList voFields, IReadOnlyList mapVoFields) { foreach (var vf in voFields) - sb.AppendLine( - $" ValueObjectValidator.Collect(input.{vf.Nav}, __issues, jsonOpts, \"{vf.WireName}\");"); + w.Line($"ValueObjectValidator.Collect(input.{vf.Nav}, __issues, jsonOpts, \"{vf.WireName}\");"); // #362 — a field.map @objectRef's values are value objects and get the same graph // validation. ValueObjectValidator unwraps an IDictionary to its Values; before that // arm existed a Dictionary hit the IEnumerable arm, yielded KeyValuePair structs, and // validated vacuously — so this line and that arm are one fix, not two. foreach (var mf in mapVoFields) - sb.AppendLine( - $" ValueObjectValidator.Collect(input.{mf.Nav}, __issues, jsonOpts, \"{mf.WireName}\");"); + w.Line($"ValueObjectValidator.Collect(input.{mf.Nav}, __issues, jsonOpts, \"{mf.WireName}\");"); } // The configured System.Text.Json options local (`jsonOpts`) — the app's @@ -1392,17 +1392,17 @@ private static bool HasDecimalField(MetaObject entity, HashSet? seen private static bool HasIsoDurationField(MetaObject entity, MetaRoot root) => WireFormat.Of(root).Durations == DurationWireForm.Iso && entity.Fields().Any(f => f.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(f) is null); - private static void AppendDecimalRangeGroup(StringBuilder sb) + private static void AppendDecimalRangeGroup(CsWriter w) { - sb.AppendLine(" IEndpointRouteBuilder mount = app;"); - sb.AppendLine(" app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter());"); + w.Line("IEndpointRouteBuilder mount = app;"); + w.Line("app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter());"); } - private static void AppendJsonOptsLocal(StringBuilder sb) + private static void AppendJsonOptsLocal(CsWriter w) { - sb.AppendLine(" var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); - sb.AppendLine(" .Value.SerializerOptions;"); + w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); + using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + using (w.Hanging()) w.Line(".Value.SerializerOptions;"); } // FR-036 A2 — the shared create-validation preamble for a generated POST handler @@ -1413,15 +1413,15 @@ private static void AppendJsonOptsLocal(StringBuilder sb) // DataAnnotations on its own). Assumes the bound local `input` is in scope. // A violation naming only a @required readOnly member () // is ignored: the client cannot set that member, so it cannot satisfy the rule. - private static void AppendCreateValidation(StringBuilder sb, IReadOnlyList? readOnlyRequired = null) + private static void AppendCreateValidation(CsWriter w, IReadOnlyList? readOnlyRequired = null) { if (readOnlyRequired is null || readOnlyRequired.Count == 0) { - sb.AppendLine(" __issues.ValidateObject(input, jsonOpts);"); + w.Line("__issues.ValidateObject(input, jsonOpts);"); return; } var names = string.Join(", ", readOnlyRequired.Select(n => "\"" + n + "\"")); - sb.AppendLine($" __issues.ValidateObjectExcept(input, jsonOpts, new[] {{ {names} }});"); + w.Line($"__issues.ValidateObjectExcept(input, jsonOpts, new[] {{ {names} }});"); } // FR-035 PATCH-2 — the shared present-key merge loop for the generated update @@ -1432,7 +1432,7 @@ private static void AppendCreateValidation(StringBuilder sb, IReadOnlyList voFields, + CsWriter w, string? discProp, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetNavs, IReadOnlyList frozenNavs, bool hasDecimal, IReadOnlyList deniedKeys, IReadOnlyList deniedClr, bool hasDuration = false) @@ -1443,23 +1443,23 @@ private static void AppendPartialMergeLoop( // (AppendArrayNullClears). Declared before the loop so the post-save clears see it. for (int i = 0; i < voFields.Count; i++) if (voFields[i].IsArray && !voFields[i].Required) - sb.AppendLine($" var __clearVo{i} = false;"); + w.Line($"var __clearVo{i} = false;"); // The body key -> CLR property map comes from the host serializer's own contract (a naming policy // such as SnakeCaseLower, a rename, an attribute), never from a guess at the name: the keys a // client echoes from a response are the keys this resolves. - sb.AppendLine($" var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts);"); + w.Line($"var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts);"); // Every violation is collected (never the first alone) and answered together after the loop. - sb.AppendLine(" var __issues = new ValidationIssues();"); - sb.AppendLine(" foreach (var prop in body.RootElement.EnumerateObject())"); - sb.AppendLine(" {"); - sb.AppendLine(" var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null;"); + w.Line("var __issues = new ValidationIssues();"); + w.Line("foreach (var prop in body.RootElement.EnumerateObject())"); + w.Open("{"); + w.Line("var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null;"); // #484 — @formExclude / credential keys are IGNORED (never a 400), ahead of every arm below // (a present null is a write too). Denied by the serializer-resolved property AND by the field-name spellings. if (deniedClr.Count > 0) - sb.AppendLine($" if (__clr is {string.Join(" or ", deniedClr.Select(n => "\"" + n + "\""))}) continue; // @formExclude / credential: not writable"); + w.Line($"if (__clr is {string.Join(" or ", deniedClr.Select(n => "\"" + n + "\""))}) continue; // @formExclude / credential: not writable"); foreach (var key in deniedKeys) - sb.AppendLine($" if (string.Equals(prop.Name, \"{key}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); + w.Line($"if (string.Equals(prop.Name, \"{key}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); // Program D — typed value-object arms FIRST (owned-nav columns are invisible to // EF's FindProperty below, so the generic scalar path would silently drop them). // Present value → deserialize + recursive VO validation + assign the CLR nav @@ -1470,33 +1470,33 @@ private static void AppendPartialMergeLoop( { var vf = voFields[i]; var v = "__vo" + i; - sb.AppendLine($" if ({KeyMatch(vf.WireKeys)} || __clr == \"{vf.Nav}\")"); - sb.AppendLine(" {"); - sb.AppendLine(" if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); - sb.AppendLine(" {"); + w.Line($"if ({KeyMatch(vf.WireKeys)} || __clr == \"{vf.Nav}\")"); + w.Open("{"); + w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Open("{"); if (vf.Required) { - sb.AppendLine($" __issues.AddRequired(\"{vf.WireName}\"); // @required VO column: present-null is a 400"); - sb.AppendLine(" continue;"); + w.Line($"__issues.AddRequired(\"{vf.WireName}\"); // @required VO column: present-null is a 400"); + w.Line("continue;"); } else { - sb.AppendLine($" existing.{vf.Nav} = null;"); + w.Line($"existing.{vf.Nav} = null;"); if (vf.IsArray) - sb.AppendLine($" __clearVo{i} = true; // NULL the jsonb column post-save (EF writes [] for a null OwnsMany nav)"); - sb.AppendLine(" continue;"); + w.Line($"__clearVo{i} = true; // NULL the jsonb column post-save (EF writes [] for a null OwnsMany nav)"); + w.Line("continue;"); } - sb.AppendLine(" }"); + w.Close("}"); // A wrong-shaped VO value (e.g. a JSON array for a single-VO column, an object for an // array column) throws JsonException — return the cross-port 400 rather than an // unhandled 500 (matches every other port + this port's own reference lane). - sb.AppendLine($" {vf.DeserType} {v};"); - sb.AppendLine($" try {{ {v} = System.Text.Json.JsonSerializer.Deserialize<{vf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); - sb.AppendLine($" catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{vf.WireName}\"); continue; }}"); - sb.AppendLine($" if (!ValueObjectValidator.Collect({v}, __issues, jsonOpts, \"{vf.WireName}\")) continue;"); - sb.AppendLine($" existing.{vf.Nav} = {v}{(vf.Required ? "!" : "")};"); - sb.AppendLine(" continue;"); - sb.AppendLine(" }"); + w.Line($"{vf.DeserType} {v};"); + w.Line($"try {{ {v} = System.Text.Json.JsonSerializer.Deserialize<{vf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); + w.Line($"catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{vf.WireName}\"); continue; }}"); + w.Line($"if (!ValueObjectValidator.Collect({v}, __issues, jsonOpts, \"{vf.WireName}\")) continue;"); + w.Line($"existing.{vf.Nav} = {v}{(vf.Required ? "!" : "")};"); + w.Line("continue;"); + w.Close("}"); } // #362 — a present field.map @objectRef key, handled BEFORE the generic property path. // The generic path deserializes and assigns without ever running the value-object graph @@ -1507,48 +1507,48 @@ private static void AppendPartialMergeLoop( { var mf = mapVoFields[i]; var mv = "__map" + i; - sb.AppendLine($" if ({KeyMatch(mf.WireKeys)} || __clr == \"{mf.Nav}\")"); - sb.AppendLine(" {"); - sb.AppendLine(" if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); - sb.AppendLine($" {{ existing.{mf.Nav} = null; continue; }}"); - sb.AppendLine($" {mf.DeserType}? {mv};"); - sb.AppendLine($" try {{ {mv} = System.Text.Json.JsonSerializer.Deserialize<{mf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); - sb.AppendLine($" catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{mf.WireName}\"); continue; }}"); - sb.AppendLine($" if (!ValueObjectValidator.Collect({mv}, __issues, jsonOpts, \"{mf.WireName}\")) continue;"); - sb.AppendLine($" existing.{mf.Nav} = {mv};"); - sb.AppendLine(" continue;"); - sb.AppendLine(" }"); + w.Line($"if ({KeyMatch(mf.WireKeys)} || __clr == \"{mf.Nav}\")"); + w.Open("{"); + w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Line($"{{ existing.{mf.Nav} = null; continue; }}"); + w.Line($"{mf.DeserType}? {mv};"); + w.Line($"try {{ {mv} = System.Text.Json.JsonSerializer.Deserialize<{mf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); + w.Line($"catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{mf.WireName}\"); continue; }}"); + w.Line($"if (!ValueObjectValidator.Collect({mv}, __issues, jsonOpts, \"{mf.WireName}\")) continue;"); + w.Line($"existing.{mf.Nav} = {mv};"); + w.Line("continue;"); + w.Close("}"); } - sb.AppendLine(" var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))"); - sb.AppendLine(" ?? entry.Metadata.FindProperty(prop.Name)"); - sb.AppendLine(" ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase));"); - sb.AppendLine(" if (target is null) continue;"); - sb.AppendLine(" var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);"); - sb.AppendLine(" if (target.IsPrimaryKey()) continue; // PK is route-authoritative"); + w.Line("var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))"); + using (w.Hanging()) w.Line("?? entry.Metadata.FindProperty(prop.Name)"); + using (w.Hanging()) w.Line("?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase));"); + w.Line("if (target is null) continue;"); + w.Line("var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);"); + w.Line("if (target.IsPrimaryKey()) continue; // PK is route-authoritative"); if (discProp is not null) { - sb.AppendLine($" if (string.Equals(target.Name, \"{discProp}\", System.StringComparison.Ordinal)) continue; // discriminator is immutable"); + w.Line($"if (string.Equals(target.Name, \"{discProp}\", System.StringComparison.Ordinal)) continue; // discriminator is immutable"); } // Issue #203 — @autoSet columns are server-owned: an onUpdate column is stamped to // now() (below), an onCreate column is never rewritten. Either way the caller can // never set them via the PATCH/PUT body, so skip any present key. foreach (var nav in autoSetNavs) - sb.AppendLine($" if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned"); + w.Line($"if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned"); // FR-037 R1 — @mutability readOnly / writeOnce are not PATCH-settable. STRIPPED, // never 400'd: the uniform behaviour of every excluded key on this path. Skipping // BEFORE the null branch also covers the FR-035 present-null arm, since clearing a // column is itself a write. foreach (var nav in frozenNavs) - sb.AppendLine($" if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable"); - sb.AppendLine(" if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); - sb.AppendLine(" {"); - sb.AppendLine(" // FR-035 PATCH-2: explicit null clears a nullable column; on a"); - sb.AppendLine(" // NOT-NULL (@required) column it is a 400 (matching the cross-port contract)."); - sb.AppendLine(" if (!target.IsNullable) { __issues.AddRequired(__wire); continue; }"); - sb.AppendLine(" entry.CurrentValues[target] = null;"); - sb.AppendLine(" continue;"); - sb.AppendLine(" }"); - sb.AppendLine(" var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;"); + w.Line($"if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable"); + w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Open("{"); + w.Line("// FR-035 PATCH-2: explicit null clears a nullable column; on a"); + w.Line("// NOT-NULL (@required) column it is a 400 (matching the cross-port contract)."); + w.Line("if (!target.IsNullable) { __issues.AddRequired(__wire); continue; }"); + w.Line("entry.CurrentValues[target] = null;"); + w.Line("continue;"); + w.Close("}"); + w.Line("var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;"); // ADR-0019 Amendment 1 (W2): a decimal is read from a JSON-number string or a JSON number, // exactly; anything else, or a value decimal cannot hold, is the 400 validation envelope. // `DecimalWire` resolves to the copy the entity generator emits into this namespace (the @@ -1556,30 +1556,30 @@ private static void AppendPartialMergeLoop( // ejected generator only in the helper-runtime `using`, as before. if (hasDecimal || hasDuration) { - sb.AppendLine(" object? __val;"); + w.Line("object? __val;"); var arm = "if"; if (hasDecimal) { - sb.AppendLine(" if (clr == typeof(decimal))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!DecimalWire.TryParseElement(prop.Value, out var __dec)) { __issues.Add(\"invalid_type\", __wire + \" is not a decimal\", __wire); continue; }"); - sb.AppendLine(" if (!DecimalWire.FitsDeclared(existing.GetType(), target.Name, __dec)) { __issues.Add(\"too_big\", __wire + \" exceeds its declared precision and scale\", __wire); continue; }"); - sb.AppendLine(" __val = __dec;"); - sb.AppendLine(" }"); - sb.AppendLine(" else if (clr == typeof(System.Collections.Generic.IList))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); - sb.AppendLine(" var __decs = new System.Collections.Generic.List();"); - sb.AppendLine(" var __decBad = false;"); - sb.AppendLine(" foreach (var __el in prop.Value.EnumerateArray())"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!DecimalWire.TryParseElement(__el, out var __d1)) { __issues.Add(\"invalid_type\", __wire + \" holds a value that is not a decimal\", __wire, __decs.Count); __decBad = true; break; }"); - sb.AppendLine(" if (!DecimalWire.FitsDeclared(existing.GetType(), target.Name, __d1)) { __issues.Add(\"too_big\", __wire + \" holds a value over its declared precision and scale\", __wire, __decs.Count); __decBad = true; break; }"); - sb.AppendLine(" __decs.Add(__d1);"); - sb.AppendLine(" }"); - sb.AppendLine(" if (__decBad) continue;"); - sb.AppendLine(" __val = __decs;"); - sb.AppendLine(" }"); + w.Line("if (clr == typeof(decimal))"); + w.Open("{"); + w.Line("if (!DecimalWire.TryParseElement(prop.Value, out var __dec)) { __issues.Add(\"invalid_type\", __wire + \" is not a decimal\", __wire); continue; }"); + w.Line("if (!DecimalWire.FitsDeclared(existing.GetType(), target.Name, __dec)) { __issues.Add(\"too_big\", __wire + \" exceeds its declared precision and scale\", __wire); continue; }"); + w.Line("__val = __dec;"); + w.Close("}"); + w.Line("else if (clr == typeof(System.Collections.Generic.IList))"); + w.Open("{"); + w.Line("if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); + w.Line("var __decs = new System.Collections.Generic.List();"); + w.Line("var __decBad = false;"); + w.Line("foreach (var __el in prop.Value.EnumerateArray())"); + w.Open("{"); + w.Line("if (!DecimalWire.TryParseElement(__el, out var __d1)) { __issues.Add(\"invalid_type\", __wire + \" holds a value that is not a decimal\", __wire, __decs.Count); __decBad = true; break; }"); + w.Line("if (!DecimalWire.FitsDeclared(existing.GetType(), target.Name, __d1)) { __issues.Add(\"too_big\", __wire + \" holds a value over its declared precision and scale\", __wire, __decs.Count); __decBad = true; break; }"); + w.Line("__decs.Add(__d1);"); + w.Close("}"); + w.Line("if (__decBad) continue;"); + w.Line("__val = __decs;"); + w.Close("}"); arm = "else if"; } // field.duration: a bare TimeSpan deserialized here would take System.Text.Json's own @@ -1588,44 +1588,44 @@ private static void AppendPartialMergeLoop( // namespace) and refuse anything else with the validation envelope. if (hasDuration) { - sb.AppendLine($" {arm} (clr == typeof(System.TimeSpan))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!DurationWire.TryParseElement(prop.Value, out var __dur)) { __issues.Add(\"invalid_type\", __wire + \" is not an ISO-8601 duration\", __wire); continue; }"); - sb.AppendLine(" __val = __dur;"); - sb.AppendLine(" }"); - sb.AppendLine(" else if (clr == typeof(System.Collections.Generic.IList))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); - sb.AppendLine(" var __durs = new System.Collections.Generic.List();"); - sb.AppendLine(" var __durBad = false;"); - sb.AppendLine(" foreach (var __el in prop.Value.EnumerateArray())"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!DurationWire.TryParseElement(__el, out var __u1)) { __issues.Add(\"invalid_type\", __wire + \" holds a value that is not an ISO-8601 duration\", __wire, __durs.Count); __durBad = true; break; }"); - sb.AppendLine(" __durs.Add(__u1);"); - sb.AppendLine(" }"); - sb.AppendLine(" if (__durBad) continue;"); - sb.AppendLine(" __val = __durs;"); - sb.AppendLine(" }"); + w.Line($"{arm} (clr == typeof(System.TimeSpan))"); + w.Open("{"); + w.Line("if (!DurationWire.TryParseElement(prop.Value, out var __dur)) { __issues.Add(\"invalid_type\", __wire + \" is not an ISO-8601 duration\", __wire); continue; }"); + w.Line("__val = __dur;"); + w.Close("}"); + w.Line("else if (clr == typeof(System.Collections.Generic.IList))"); + w.Open("{"); + w.Line("if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); + w.Line("var __durs = new System.Collections.Generic.List();"); + w.Line("var __durBad = false;"); + w.Line("foreach (var __el in prop.Value.EnumerateArray())"); + w.Open("{"); + w.Line("if (!DurationWire.TryParseElement(__el, out var __u1)) { __issues.Add(\"invalid_type\", __wire + \" holds a value that is not an ISO-8601 duration\", __wire, __durs.Count); __durBad = true; break; }"); + w.Line("__durs.Add(__u1);"); + w.Close("}"); + w.Line("if (__durBad) continue;"); + w.Line("__val = __durs;"); + w.Close("}"); } - sb.AppendLine(" else"); - sb.AppendLine(" {"); - sb.AppendLine(" try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); - sb.AppendLine(" catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); - sb.AppendLine(" }"); + w.Line("else"); + w.Open("{"); + w.Line("try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); + w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); + w.Close("}"); } else { - sb.AppendLine(" object? __val;"); - sb.AppendLine(" try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); - sb.AppendLine(" catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); + w.Line("object? __val;"); + w.Line("try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); + w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); } - sb.AppendLine(" // FR-036 A2 — validate the PRESENT, non-null value with the same per-field"); - sb.AppendLine(" // DataAnnotations as create. This validates ONLY the present value (never the"); - sb.AppendLine(" // whole row) so an ABSENT @required field is untouched, not a 400."); - sb.AppendLine(" if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue;"); - sb.AppendLine(" entry.CurrentValues[target] = __val;"); - sb.AppendLine(" }"); - sb.AppendLine(" if (__issues.Any) return __issues.ToResult();"); + w.Line("// FR-036 A2 — validate the PRESENT, non-null value with the same per-field"); + w.Line("// DataAnnotations as create. This validates ONLY the present value (never the"); + w.Line("// whole row) so an ABSENT @required field is untouched, not a 400."); + w.Line("if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue;"); + w.Line("entry.CurrentValues[target] = __val;"); + w.Close("}"); + w.Line("if (__issues.Any) return __issues.ToResult();"); } // Emit the per-subtype CRUD route set under //. Scoped to the subtype @@ -1633,7 +1633,7 @@ private static void AppendPartialMergeLoop( // subtype CLR type (discriminator injected by EF on Add); update is a partial merge // that never touches the PK or the discriminator. private static void AppendTphSubtypeRoutes( - StringBuilder sb, TphSubtypePlan st, IReadOnlyList hierarchy, MetaRoot root, GenConfig config, string baseRoute, string baseCls, string dbSet, + CsWriter w, TphSubtypePlan st, IReadOnlyList hierarchy, MetaRoot root, GenConfig config, string baseRoute, string baseCls, string dbSet, string pkType, string pkProp, string discProp, MetaField? discField, Action onWarn) { // #362 — field.object columns on a TPH subtype stay out of scope (Program D §6), but a @@ -1660,38 +1660,38 @@ private static void AppendTphSubtypeRoutes( var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); // Per-subtype list: GET // - sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); - sb.AppendLine(" {"); - sb.AppendLine(" var qs = http.Request.Query;"); - sb.AppendLine($" IQueryable<{subType}> q = db.{dbSet}.OfType<{subType}>().AsNoTracking();"); + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + subRoute + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Open("{"); + w.Line("var qs = http.Request.Query;"); + w.Line($"IQueryable<{subType}> q = db.{dbSet}.OfType<{subType}>().AsNoTracking();"); var fmS = FilterMapArg(subAllowlist, st.Entity, config); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField){fmS});"); - sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmS});"); - sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - sb.AppendLine(" {"); - sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); - sb.AppendLine($" if (!{subCls}SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new {{ error = \"invalid_sort\", field = parts[0] }});"); - sb.AppendLine(" var desc = parts.Length > 1"); - sb.AppendLine(" ? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - sb.AppendLine($" : {subCls}SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - sb.AppendLine(" q = " + NullsLargestSort("q", "EF.Property(x!, resolved)") + ";"); - sb.AppendLine(" }"); - AppendOffsetLimit(sb, root.Api.Pagination, " ", "offRaw", "off", "limRaw", "lim"); - sb.AppendLine(" var rows = await q.ToListAsync();"); - sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); - sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates{fmS}).CountAsync();"); - sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); - sb.AppendLine(" });"); + w.Line($"var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField){fmS});"); + w.Line("if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); + w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmS});"); + w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); + w.Open("{"); + w.Line("var parts = sortRaw.ToString().Split(':', 2);"); + w.Line($"if (!{subCls}SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new {{ error = \"invalid_sort\", field = parts[0] }});"); + w.Line("var desc = parts.Length > 1"); + using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); + using (w.Hanging()) w.Line($": {subCls}SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); + w.Line("q = " + NullsLargestSort("q", "EF.Property(x!, resolved)") + ";"); + w.Close("}"); + AppendOffsetLimit(w, root.Api.Pagination, "offRaw", "off", "limRaw", "lim"); + w.Line("var rows = await q.ToListAsync();"); + w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); + w.Line($"var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates{fmS}).CountAsync();"); + w.Line($"return {OkResult("new { rows, total }", credentials, envelope: true)};"); + w.Close("});"); // Per-subtype get: GET ///{id} — scoped (cross-subtype → 404). - sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); - sb.AppendLine($" await db.{dbSet}.OfType<{subType}>().AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); - sb.AppendLine(" ? " + OkResult("found", credentials)); - sb.AppendLine(" : Results.NotFound(new { error = \"not_found\" }));"); + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + using (w.Hanging()) w.Line($"await db.{dbSet}.OfType<{subType}>().AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); + using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", credentials)); + using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); // Per-subtype create: POST // — discriminator injected by EF via the // subtype CLR type; the POST body OMITS the discriminator. FR-036 #4: the @required-key @@ -1703,9 +1703,9 @@ private static void AppendTphSubtypeRoutes( return string.Equals(p, pkProp, System.StringComparison.Ordinal) || string.Equals(p, discProp, System.StringComparison.Ordinal); }); - sb.AppendLine(); + w.Blank(); // VO columns on a TPH subtype are out of scope (Program D §6) — no typed arms. - AppendCreateHandler(sb, "/" + subRoute, subType, ValueObjectNames.ContextTypeRef(config), dbSet, requiredKeys, + AppendCreateHandler(w, "/" + subRoute, subType, ValueObjectNames.ContextTypeRef(config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields, deniedNavs: deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), credentials: credentials, serverOwned: ServerOwnedCreateResets(st.Entity, root, config, discField, hierarchy[0]), root: root, @@ -1713,44 +1713,44 @@ private static void AppendTphSubtypeRoutes( // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. - sb.AppendLine(); - sb.AppendLine(" async System.Threading.Tasks.Task Update" + subCls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); - sb.AppendLine(" {"); - sb.AppendLine($" var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); - sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - sb.AppendLine(" System.Text.Json.JsonDocument body;"); - sb.AppendLine(" try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - sb.AppendLine(" catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); - sb.AppendLine(" using var bodyScope = body;"); - sb.AppendLine(" if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); - AppendUnknownFieldsCheck(sb, root, "body"); - sb.AppendLine(" // Configured JSON options (not defaults) so a custom converter — e.g. the"); - sb.AppendLine(" // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it."); - sb.AppendLine(" var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); - sb.AppendLine(" .Value.SerializerOptions;"); - sb.AppendLine(" var entry = db.Entry(existing);"); - AppendUpdateAutoSet(sb, autoSetFields); + w.Blank(); + w.Line("async System.Threading.Tasks.Task Update" + subCls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); + w.Open("{"); + w.Line($"var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); + w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); + w.Line("System.Text.Json.JsonDocument body;"); + w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); + w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("using var bodyScope = body;"); + w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); + AppendUnknownFieldsCheck(w, root, "body"); + w.Line("// Configured JSON options (not defaults) so a custom converter — e.g. the"); + w.Line("// field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it."); + w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); + using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + using (w.Hanging()) w.Line(".Value.SerializerOptions;"); + w.Line("var entry = db.Entry(existing);"); + AppendUpdateAutoSet(w, autoSetFields); // ADR-0045 + the 0.19.4 lesson: TPH is a SEPARATE code path per port, so the // per-subtype merge states the same exclusion rather than inheriting it. - AppendPartialMergeLoop(sb, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), + AppendPartialMergeLoop(w, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), deniedFields.SelectMany(f => WireKeys(f, config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), HasIsoDurationField(st.Entity, root)); - AppendSaveChanges(sb); - sb.AppendLine($" return {OkResult("existing", credentials)};"); - sb.AppendLine(" }"); - sb.AppendLine(" app.MapPatch(prefix + \"/" + subRoute + "/{id}\", Update" + subCls + ");"); - sb.AppendLine(" app.MapPut(prefix + \"/" + subRoute + "/{id}\", Update" + subCls + ");"); + AppendSaveChanges(w); + w.Line($"return {OkResult("existing", credentials)};"); + w.Close("}"); + w.Line("app.MapPatch(prefix + \"/" + subRoute + "/{id}\", Update" + subCls + ");"); + w.Line("app.MapPut(prefix + \"/" + subRoute + "/{id}\", Update" + subCls + ");"); // Per-subtype delete: DELETE ///{id} — scoped (cross-subtype → 404). - sb.AppendLine(); - sb.AppendLine(" app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); - sb.AppendLine(" {"); - sb.AppendLine($" var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); - sb.AppendLine(" if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - sb.AppendLine($" db.{dbSet}.Remove(existing);"); - AppendSaveChanges(sb); - sb.AppendLine(" return Results.NoContent();"); - sb.AppendLine(" });"); + w.Blank(); + w.Line("app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Open("{"); + w.Line($"var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); + w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); + w.Line($"db.{dbSet}.Remove(existing);"); + AppendSaveChanges(w); + w.Line("return Results.NoContent();"); + w.Close("});"); // FW-8 — M:N traversal this SUBTYPE resolves, own + INHERITED (rule b: use the // resolving Relationships(), not an own-only read — M2MNavigationBuilder.For @@ -1762,7 +1762,7 @@ private static void AppendTphSubtypeRoutes( // segment in the URL would be decorative (rule c). var sourceScope = new TphM2mSourceScope(dbSet, subType, pkProp); foreach (var nav in M2MNavigationBuilder.For(st.Entity, root, onWarn)) - AppendM2mRoute(sb, nav, subRoute, pkType, root, config, sourceScope); + AppendM2mRoute(w, nav, subRoute, pkType, root, config, sourceScope); } /// @@ -1783,17 +1783,17 @@ private static void AppendTphSubtypeRoutes( /// kind, identical on both ports. /// /// - private static void AppendSaveChanges(StringBuilder sb, string indent = " ") + private static void AppendSaveChanges(CsWriter w) { - sb.AppendLine(indent + "try { await db.SaveChangesAsync(); }"); - sb.AppendLine(indent + "catch (System.Exception __saveError)"); - sb.AppendLine(indent + "{"); - sb.AppendLine(indent + " if (ConstraintErrors.Classify(__saveError) is { } __constraint)"); - sb.AppendLine(indent + " return Results.Json("); - sb.AppendLine(indent + " new { error = __constraint.Error, constraint = __constraint.Constraint },"); - sb.AppendLine(indent + " statusCode: __constraint.Status);"); - sb.AppendLine(indent + " throw;"); - sb.AppendLine(indent + "}"); + w.Line("try { await db.SaveChangesAsync(); }"); + w.Line("catch (System.Exception __saveError)"); + w.Open("{"); + w.Line("if (ConstraintErrors.Classify(__saveError) is { } __constraint)"); + using (w.Hanging()) w.Line("return Results.Json("); + using (w.Hanging()) using (w.Hanging()) w.Line("new { error = __constraint.Error, constraint = __constraint.Constraint },"); + using (w.Hanging()) using (w.Hanging()) w.Line("statusCode: __constraint.Status);"); + w.Line("throw;"); + w.Close("}"); } // A junction/target column's CLR property, through the same resolver its entity class used. @@ -1821,7 +1821,7 @@ private static string JunctionProperty(MetaObject owner, string fieldName, GenCo // traverse it just as well and the segment would be decorative (rule c in the // cross-port contract; mirrors TS mount-m2m.ts's `sourceDiscriminator` Stage 0). private static void AppendM2mRoute( - System.Text.StringBuilder sb, M2MNavigation nav, string sourceRoute, string pkType, MetaRoot root, + CsWriter w, M2MNavigation nav, string sourceRoute, string pkType, MetaRoot root, GenConfig config, TphM2mSourceScope? sourceScope = null) { var relSeg = nav.Name; // relationship name segment @@ -1843,42 +1843,42 @@ private static void AppendM2mRoute( var targetPk = nav.Target.PrimaryIdentity()?.Fields is { Count: 1 } tf ? JunctionProperty(nav.Target, tf[0], config) : "Id"; - sb.AppendLine(); - sb.AppendLine(" app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); - sb.AppendLine(" {"); + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Open("{"); if (sourceScope is not null) { // Rule c — prove the id names a row of THIS subtype before touching the // junction. A well-formed id belonging to a SIBLING subtype is not an error // (it just has no relations under this segment): 200 with an empty list, // never 404 and never the sibling's rows. - sb.AppendLine($" if (!await db.{sourceScope.DbSet}.OfType<{sourceScope.SubtypeClass}>().AnyAsync(x => x.{sourceScope.PkProp} == id))"); - sb.AppendLine($" return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); + w.Line($"if (!await db.{sourceScope.DbSet}.OfType<{sourceScope.SubtypeClass}>().AnyAsync(x => x.{sourceScope.PkProp} == id))"); + using (w.Hanging()) w.Line($"return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); } if (nav.Symmetric) { // Union both junction columns; the related id is the column that is NOT the source id. - sb.AppendLine($" var pairs = await db.{junctionDbSet}.AsNoTracking()"); - sb.AppendLine($" .Where(j => EF.Property<{fkType}>(j, \"{srcFkProp}\").Equals(id) || EF.Property<{fkType}>(j, \"{tgtFkProp}\").Equals(id))"); - sb.AppendLine($" .Select(j => new {{ S = EF.Property<{fkType}>(j, \"{srcFkProp}\"), T = EF.Property<{fkType}>(j, \"{tgtFkProp}\") }})"); - sb.AppendLine(" .ToListAsync();"); - sb.AppendLine($" var relatedIds = new System.Collections.Generic.HashSet<{fkType}>();"); - sb.AppendLine(" foreach (var p in pairs)"); - sb.AppendLine(" relatedIds.Add(p.S.Equals(id) ? p.T : p.S);"); + w.Line($"var pairs = await db.{junctionDbSet}.AsNoTracking()"); + using (w.Hanging()) w.Line($".Where(j => EF.Property<{fkType}>(j, \"{srcFkProp}\").Equals(id) || EF.Property<{fkType}>(j, \"{tgtFkProp}\").Equals(id))"); + using (w.Hanging()) w.Line($".Select(j => new {{ S = EF.Property<{fkType}>(j, \"{srcFkProp}\"), T = EF.Property<{fkType}>(j, \"{tgtFkProp}\") }})"); + using (w.Hanging()) w.Line(".ToListAsync();"); + w.Line($"var relatedIds = new System.Collections.Generic.HashSet<{fkType}>();"); + w.Line("foreach (var p in pairs)"); + using (w.Hanging()) w.Line("relatedIds.Add(p.S.Equals(id) ? p.T : p.S);"); } else { - sb.AppendLine($" var relatedIds = (await db.{junctionDbSet}.AsNoTracking()"); - sb.AppendLine($" .Where(j => EF.Property<{fkType}>(j, \"{srcFkProp}\").Equals(id))"); - sb.AppendLine($" .Select(j => EF.Property<{fkType}>(j, \"{tgtFkProp}\"))"); - sb.AppendLine(" .ToListAsync()).ToHashSet();"); + w.Line($"var relatedIds = (await db.{junctionDbSet}.AsNoTracking()"); + using (w.Hanging()) w.Line($".Where(j => EF.Property<{fkType}>(j, \"{srcFkProp}\").Equals(id))"); + using (w.Hanging()) w.Line($".Select(j => EF.Property<{fkType}>(j, \"{tgtFkProp}\"))"); + using (w.Hanging()) w.Line(".ToListAsync()).ToHashSet();"); } - sb.AppendLine($" if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); - sb.AppendLine($" var rows = await {targetFrom}.AsNoTracking()"); - sb.AppendLine($" .Where(t => relatedIds.Contains(EF.Property<{fkType}>(t, \"{targetPk}\")))"); - sb.AppendLine(" .ToListAsync();"); - sb.AppendLine($" return {OkResult("rows", TphUnionCredentialNames(nav.Target, root, config))};"); - sb.AppendLine(" });"); + w.Line($"if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); + w.Line($"var rows = await {targetFrom}.AsNoTracking()"); + using (w.Hanging()) w.Line($".Where(t => relatedIds.Contains(EF.Property<{fkType}>(t, \"{targetPk}\")))"); + using (w.Hanging()) w.Line(".ToListAsync();"); + w.Line($"return {OkResult("rows", TphUnionCredentialNames(nav.Target, root, config))};"); + w.Close("});"); } /// @@ -1911,20 +1911,19 @@ private static string JunctionFkType(M2MNavigation nav) /// default into its map. Attr() is the RESOLVING accessor (ADR-0039), so an /// order inherited via extends is honoured. /// - private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, string constName, GenConfig config) + private static void AppendSortDefaultOrder(CsWriter w, MetaObject owner, string constName, GenConfig config) { - sb.Append($" private static readonly System.Collections.Generic.Dictionary {constName} ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); + w.Line($"private static readonly System.Collections.Generic.Dictionary {constName} = new(System.StringComparer.OrdinalIgnoreCase)"); + w.Open("{"); foreach (var f in owner.Fields()) { if (CSharpNaming.ScalarFor(f.SubType) is null || f.ResolvedIsArray()) continue; if (f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) is not string v) continue; if (v != "asc" && v != "desc") continue; - sb.AppendLine($" [\"{CSharpNaming.PropertyName(f, config)}\"] = {(v == "desc" ? "true" : "false")},"); + w.Line($"[\"{CSharpNaming.PropertyName(f, config)}\"] = {(v == "desc" ? "true" : "false")},"); } - sb.AppendLine(" };"); - sb.AppendLine(); + w.Close("};"); + w.Blank(); } diff --git a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs new file mode 100644 index 0000000000..9c7424456e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs @@ -0,0 +1,338 @@ +// 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 ever 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). The layout ratchet (MetaObjects.Codegen.Tests/LayoutRatchet) holds +// every other generator file to that. + +using System.Text; +using System.Text.RegularExpressions; + +namespace MetaObjects.Codegen.Writer; + +/// Error codes a writer throws. Shared by every port's writer (spec/code-writer.md). +public static class WriterErrors +{ + /// Close() with no block open. + public const string UnbalancedClose = "ERR_WRITER_UNBALANCED_CLOSE"; + /// The file was finished with a block still open; the message quotes the line that opened it. + public const string UnclosedBlock = "ERR_WRITER_UNCLOSED_BLOCK"; + /// Line() was handed text containing a line break. + public const string NewlineInLine = "ERR_WRITER_NEWLINE_IN_LINE"; + /// One local name imported from two different places. + public const string ImportConflict = "ERR_WRITER_IMPORT_CONFLICT"; +} + +/// A writer error: one of the codes and a message for people. +public sealed class WriterException : InvalidOperationException +{ + public string Code { get; } + + public WriterException(string code, string message) : base($"{code}: {message}") => Code = code; +} + +/// +/// An expression fragment: text, a breakable list, or a concatenation of fragments. A +/// converts to one implicitly, so a line is written +/// w.Line("var x = ", w.List("(", args, ")"), ";"). +/// +public abstract class Piece +{ + public static implicit operator Piece(string text) => new Text(text); + + /// A list with no padding inside its brackets: [a, b], f(a, b), <A, B>. + public static Piece List(string open, IEnumerable items, string close) => new Group(open, items, close); + + /// A list padded inside its brackets when it stays on one line: { a, b }. + public static Piece Padded(string open, IEnumerable items, string close) => new Group(open, items, close, pad: true); + + /// Several parts of one line, concatenated. + public static Piece Seq(params Piece[] parts) => new Sequence(parts); + + /// The piece printed on one line. + public string Flat() + { + var sb = new StringBuilder(); + FlatInto(sb); + return sb.ToString(); + } + + internal abstract void FlatInto(StringBuilder sb); + + internal sealed class Text(string value) : Piece + { + public string Value { get; } = value; + internal override void FlatInto(StringBuilder sb) => sb.Append(Value); + } + + internal sealed class Sequence(IReadOnlyList parts) : Piece + { + public IReadOnlyList Parts { get; } = parts; + internal override void FlatInto(StringBuilder sb) + { + foreach (var p in Parts) p.FlatInto(sb); + } + } +} + +/// +/// 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. +/// +public sealed class Group : Piece +{ + public string Open { get; } + public IReadOnlyList Items { get; } + public string Close { get; } + /// { a, b } (true) versus [a, b] or f(a, b) (false) when printed on one line. + public bool Pad { get; } + + public Group(string open, IEnumerable items, string close, bool pad = false) + { + Open = open; + Items = items.ToList(); + Close = close; + Pad = pad; + } + + internal override void FlatInto(StringBuilder sb) + { + sb.Append(Open); + if (Items.Count > 0) + { + if (Pad) sb.Append(' '); + for (var n = 0; n < Items.Count; n++) + { + if (n > 0) sb.Append(", "); + Items[n].FlatInto(sb); + } + if (Pad) sb.Append(' '); + } + sb.Append(Close); + } +} + +/// The three options of the core contract. A dialect sets the defaults for its language. +public sealed record CodeWriterOptions +{ + /// One level of indentation. + public string Indent { get; init; } = " "; + /// The column a line may reach before its last list breaks, in Unicode code points. + public int Width { get; init; } = 120; + /// Whether a broken list puts a comma after its last item too. + public bool TrailingComma { get; init; } = true; +} + +/// +/// The core writer. Built to be extended (ADR-0063): every method is public or protected, so a +/// dialect or an adopter's subclass overrides the one step it needs to change, such as where a line +/// breaks () or whether it fits (). These methods are not a +/// stability contract and may change between minor versions. +/// +public class CodeWriter +{ + private static readonly Regex AnyLineBreak = new("\r\n?|\n", RegexOptions.Compiled); + + public string Indent { get; } + public int Width { get; } + public bool TrailingComma { get; } + + protected readonly List Out = []; + /// The text of each line that opened a block still open, outermost first. + protected readonly List Openers = []; + private readonly List _prefixes = [""]; + protected bool WantBlank; + /// True at the start of the file and right after a block opens: no blank line goes here. + protected bool AtBlockStart = true; + + public CodeWriter() : this(new CodeWriterOptions()) { } + + public CodeWriter(CodeWriterOptions options) + { + Indent = options.Indent; + Width = options.Width; + TrailingComma = options.TrailingComma; + } + + /// + /// 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. + /// + public CodeWriter Line(params Piece[] parts) => Put(Piece.Seq(parts)); + + /// Ask for one blank line before whatever is written next. Requests never stack. + public CodeWriter Blank() + { + WantBlank = true; + return this; + } + + /// Write the line that opens a block, then indent. + public CodeWriter Open(params Piece[] parts) => OpenPiece(Piece.Seq(parts)); + + /// Dedent, then write the line that closes the block. + public CodeWriter Close(params Piece[] parts) => ClosePiece(Piece.Seq(parts)); + + /// + /// Open(head), then (on dispose) Close(tail): the indent cannot be left + /// unbalanced. Used as using (w.Block("if (x) {")); the head carries its own opening + /// brace, and tail is the closing line (} by default). A dialect adds the form + /// its language writes ( puts the brace on its own line). + /// + public IDisposable Block(Piece head, string tail = "}") + { + Open(head); + return new Scope(() => Close(tail)); + } + + /// + /// 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. + /// + public CodeWriter Text(string snippet) + { + var lines = AnyLineBreak.Split(snippet).ToList(); + if (lines.Count > 1 && lines[0].Trim().Length == 0) lines.RemoveAt(0); + if (lines.Count > 0 && lines[^1].Trim().Length == 0) lines.RemoveAt(lines.Count - 1); + var margin = int.MaxValue; + foreach (var l in lines) + { + if (l.Trim().Length != 0) margin = Math.Min(margin, l.Length - l.TrimStart().Length); + } + foreach (var l in lines) + { + if (l.Trim().Length == 0) Blank(); + else Put(l[margin..]); + } + return this; + } + + /// The body text: every line joined, with no final newline. Throws if a block is still open. + protected virtual string Body() + { + if (Openers.Count > 0) + throw new WriterException(WriterErrors.UnclosedBlock, $"unclosed block opened by: {Openers[^1]}"); + return string.Join('\n', Out); + } + + /// The finished file: \n line endings, no trailing whitespace, one final newline (none when empty). + public override string ToString() + { + var body = Body(); + return body.Length == 0 ? "" : body + '\n'; + } + + /// Whether fits on one line at the current indent. + protected virtual bool Fits(string text) => WidthOf(Prefix()) + WidthOf(text) <= Width; + + /// + /// Where a line that does not fit breaks: the text before, the list that breaks, and the text + /// after; or null to print the line as it is. The default is the line's LAST non-empty list. + /// + protected virtual (string Before, Group List, string After)? BreakAt(Piece piece) => LastGroup(piece); + + protected CodeWriter OpenPiece(Piece piece) + { + Put(piece); + Openers.Add(piece.Flat().Trim()); + AtBlockStart = true; + return this; + } + + protected CodeWriter ClosePiece(Piece piece) + { + if (Openers.Count == 0) + throw new WriterException(WriterErrors.UnbalancedClose, $"Close(\"{piece.Flat()}\") with no block open"); + Openers.RemoveAt(Openers.Count - 1); + WantBlank = false; + return Put(piece); + } + + protected string Prefix() + { + var depth = Openers.Count; + while (_prefixes.Count <= depth) _prefixes.Add(_prefixes[^1] + Indent); + return _prefixes[depth]; + } + + protected CodeWriter Put(Piece piece) + { + var raw = piece.Flat(); + if (AnyLineBreak.IsMatch(raw)) + throw new WriterException(WriterErrors.NewlineInLine, + $"line text contains a line break; write each line separately or use Text(): \"{raw.Replace("\r", "\\r").Replace("\n", "\\n")}\""); + var text = raw.TrimEnd(); + if (text.Length == 0) return Blank(); + if (WantBlank && !AtBlockStart) Out.Add(""); + WantBlank = false; + AtBlockStart = false; + var pre = Prefix(); + var split = Fits(text) ? null : BreakAt(piece); + if (split is null) + { + Out.Add(pre + text); + return this; + } + var (before, group, after) = split.Value; + OpenPiece(before + group.Open); + for (var n = 0; n < group.Items.Count; n++) + { + var comma = n < group.Items.Count - 1 || TrailingComma ? "," : ""; + Put(Piece.Seq(group.Items[n], comma)); + } + return ClosePiece(group.Close + after); + } + + /// Character width of , in Unicode code points. + protected static int WidthOf(string s) + { + var width = 0; + for (var i = 0; i < s.Length; i++) + { + if (char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) i++; + width++; + } + return width; + } + + /// Split a piece around its LAST non-empty list: text before, the list, text after. + protected static (string Before, Group List, string After)? LastGroup(Piece p) + { + switch (p) + { + case Group g: + return g.Items.Count == 0 ? null : ("", g, ""); + case Piece.Sequence seq: + for (var i = seq.Parts.Count - 1; i >= 0; i--) + { + if (LastGroup(seq.Parts[i]) is not { } hit) continue; + var head = new StringBuilder(); + for (var k = 0; k < i; k++) seq.Parts[k].FlatInto(head); + var tail = new StringBuilder(hit.After); + for (var k = i + 1; k < seq.Parts.Count; k++) seq.Parts[k].FlatInto(tail); + return (head.ToString() + hit.Before, hit.List, tail.ToString()); + } + return null; + default: + return null; + } + } + + private sealed class Scope(Action onDispose) : IDisposable + { + private bool _done; + + public void Dispose() + { + if (_done) return; + _done = true; + onDispose(); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs new file mode 100644 index 0000000000..560d8386a3 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs @@ -0,0 +1,162 @@ +// The C# dialect of the code writer (ADR-0063; contract: spec/code-writer.md). +// +// Adds what is specific to C#: the file header, `using` directives collected while the body is +// written and printed before it, XML doc comments, and the Allman brace block. The core it +// extends owns lines, blocks, blank lines and fit-or-break lists; a subclass overrides one step +// (OrderUsings, WriteHeader, WriteUsings) and keeps the rest. + +namespace MetaObjects.Codegen.Writer; + +/// How a orders the using directives it collected. +public enum UsingOrder +{ + /// The order the generator named them, each once. What the reference generators wrote before + /// the writer, so converting one changes no byte. + AsWritten, + /// System namespaces first, then the rest, each group in code-unit order. + Sorted, +} + +/// +/// The writer a C# generator writes through. Four-space indent, 120 columns, a trailing comma in +/// broken lists. Not final: every method is public or protected. +/// +public class CsWriter : CodeWriter +{ + private readonly List _header = []; + private readonly List _usings = []; + private readonly Dictionary _aliases = new(StringComparer.Ordinal); + + /// The order the using block prints in. + public UsingOrder UsingOrder { get; init; } = UsingOrder.AsWritten; + + public CsWriter() : base(new CodeWriterOptions { Indent = " ", Width = 120, TrailingComma = true }) { } + + public CsWriter(CodeWriterOptions options) : base(options) { } + + /// Lines that print first, before the using block: the generated-file marker, + /// #nullable enable. Each line is written as given. + public CsWriter Header(params string[] lines) + { + _header.AddRange(lines); + return this; + } + + /// The header every generated file starts with: the generated-file marker, the generator's + /// name, and (unless is false) #nullable enable. + public CsWriter GeneratedFileHeader(string generator, bool nullable = true) + { + Header("// ", $"// Generated by MetaObjects {generator}. Do not edit by hand."); + return nullable ? Header("#nullable enable") : this; + } + + /// + /// A statement that continues on the next lines, one level in: using (w.Hanging()) { w.Line(".Select(x)"); } + /// after a line that is not finished. Writes nothing itself; the indent returns when the scope ends. + /// + public IDisposable Hanging() + { + Openers.Add(Out.Count > 0 ? Out[^1].Trim() : ""); + var depth = Openers.Count; + return new HangingScope(() => + { + if (Openers.Count != depth) + throw new WriterException(WriterErrors.UnbalancedClose, "a hanging continuation ended while a block inside it is still open"); + Openers.RemoveAt(Openers.Count - 1); + }); + } + + private sealed class HangingScope(Action onDispose) : IDisposable + { + private bool _done; + public void Dispose() { if (_done) return; _done = true; onDispose(); } + } + + /// Add to the base list of the declaration line just written: + /// , type when it already has one, else : type. + public CsWriter AddBaseType(string type) + { + var last = Out.Count - 1; + if (last < 0) throw new InvalidOperationException("AddBaseType before any line was written"); + Out[last] += Out[last].Contains(" : ", StringComparison.Ordinal) ? ", " + type : " : " + type; + return this; + } + + /// Record using ns;. Naming the same namespace twice prints it once. + public CsWriter Using(string ns) => AddUsing($"using {ns};"); + + /// Record using static type;. + public CsWriter UsingStatic(string type) => AddUsing($"using static {type};"); + + /// Record using alias = target;. One alias naming two targets is + /// . + public CsWriter UsingAlias(string alias, string target) + { + if (_aliases.TryGetValue(alias, out var seen)) + { + if (seen != target) + throw new WriterException(WriterErrors.ImportConflict, $"the alias {alias} names both {seen} and {target}"); + return this; + } + _aliases[alias] = target; + return AddUsing($"using {alias} = {target};"); + } + + private CsWriter AddUsing(string directive) + { + if (!_usings.Contains(directive)) _usings.Add(directive); + return this; + } + + /// + /// A block whose braces are on their own lines, the way C# is written: + /// using (w.Braced("public class A")) { ... } writes public class A, {, the + /// body, then }. Pass a different for };. + /// + public IDisposable Braced(Piece head, string tail = "}") + { + Line(head); + return Block("{", tail); + } + + /// An XML doc <summary>: one /// line per entry (a bare /// for an empty one). + /// The text is written as given, so it carries any XML escaping it needs. + public CsWriter DocSummary(params string[] lines) + { + Line("/// "); + foreach (var l in lines) Line(l.Length == 0 ? "///" : "/// " + l); + Line("/// "); + return this; + } + + /// The using directives in print order. A subclass overrides this to order them its own way. + protected virtual IReadOnlyList OrderUsings(IReadOnlyList asWritten) => UsingOrder switch + { + UsingOrder.Sorted => asWritten + .OrderBy(u => IsSystem(Target(u)) ? 0 : 1) + .ThenBy(Target, StringComparer.Ordinal) + .ToList(), + _ => asWritten, + }; + + /// What a directive names: using A.B; is A.B. Sorting compares this, so + /// System comes before System.Linq although . sorts before ;. + private static string Target(string directive) => directive["using ".Length..^1]; + + private static bool IsSystem(string target) => + target == "System" || target.StartsWith("System.", StringComparison.Ordinal); + + /// The header lines, as printed. + protected virtual IEnumerable WriteHeader() => _header; + + /// The using block, as printed. + protected virtual IEnumerable WriteUsings() => OrderUsings(_usings); + + protected override string Body() + { + var body = base.Body(); + var top = WriteHeader().Concat(WriteUsings()).ToList(); + if (top.Count == 0) return body; + return body.Length == 0 ? string.Join('\n', top) : string.Join('\n', top) + "\n\n" + body; + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/DurationIntervalEfCoreTests.cs b/server/csharp/MetaObjects.IntegrationTests/DurationIntervalEfCoreTests.cs index 882d3828d5..4aa0799ebe 100644 --- a/server/csharp/MetaObjects.IntegrationTests/DurationIntervalEfCoreTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/DurationIntervalEfCoreTests.cs @@ -73,7 +73,7 @@ public class GuardedSpanContext(DbContextOptions options) : protected override void OnModelCreating(ModelBuilder modelBuilder) { SpanTable.Map(modelBuilder); - // DbContextGenerator.DurationColumnLines, verbatim but for the entity; the mapping objects + // DbContextGenerator.WriteDurationColumn, verbatim but for the entity; the mapping objects // are the generated AppDbContext's own. if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") { diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 62bf5ec23a..74fef9ba1b 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -243,10 +243,10 @@ public void A_reference_over_a_flattened_member_is_a_foreign_key_of_the_owned_ty // shadow `CountryId1`, and the declared delete behaviour on it. private sealed class AddressWithCountry : MetaObjects.Codegen.Generators.EntityGenerator { - protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + protected override void EmitClassBodyTrailer(MetaObjects.Codegen.Writer.CsWriter w, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) { if (entity.Name == "Address") - sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? Country {{ get; set; }}"); + w.Line($"public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? Country {{ get; set; }}"); } } @@ -266,10 +266,10 @@ public void A_reference_over_a_flattened_member_uses_the_owned_types_navigation( // rc.21 fix round (M6): the owned type's only navigation to the target is used whatever its name. private sealed class AddressWithHomeCountry : MetaObjects.Codegen.Generators.EntityGenerator { - protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + protected override void EmitClassBodyTrailer(MetaObjects.Codegen.Writer.CsWriter w, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) { if (entity.Name == "Address") - sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? HomeCountry {{ get; set; }}"); + w.Line($"public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? HomeCountry {{ get; set; }}"); } } @@ -311,10 +311,10 @@ public void A_reference_over_a_flattened_member_uses_the_owned_types_only_naviga private sealed class AddressWithBillingCountry : MetaObjects.Codegen.Generators.EntityGenerator { - protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + protected override void EmitClassBodyTrailer(MetaObjects.Codegen.Writer.CsWriter w, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) { if (entity.Name == "Address") - sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? BillingCountry {{ get; set; }}"); + w.Line($"public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? BillingCountry {{ get; set; }}"); } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java new file mode 100644 index 0000000000..fe77e5be81 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java @@ -0,0 +1,278 @@ +package com.metaobjects.generator.writer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +/** + * The language-neutral code writer (ADR-0063; contract: {@code 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 ever runs + * over the result. It never parses the text it is handed: it lays out the structure the + * generator gave it, which is lines, blocks, blank-line requests and breakable lists. + * + *

This package is the only generator source allowed to type layout (line breaks and + * indentation). The layout ratchet test holds every other generator file to that. + * + *

The class is built to be extended (ADR-0063, item 7): nothing is final or private, so a + * dialect or an adopter's subclass overrides the one step it needs to change, such as where a + * line breaks ({@link #breakAt}) or what a part becomes ({@link #piece}). These methods are not + * a stability contract and may change between minor versions. + */ +public class CodeWriter { + + private static final String NEWLINE = "\n"; + private static final Pattern ANY_LINE_BREAK = Pattern.compile("\r\n?|\n"); + + protected final WriterOptions options; + protected final List out = new ArrayList<>(); + /** The text of each line that opened a block still open, outermost first. */ + protected final List openers = new ArrayList<>(); + protected final List prefixes = new ArrayList<>(List.of("")); + protected boolean wantBlank = false; + /** True at the start of the file and right after a block opens: no blank line goes here. */ + protected boolean atBlockStart = true; + + public CodeWriter(WriterOptions options) { + this.options = options; + } + + public WriterOptions options() { + return options; + } + + /** + * 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. + */ + public CodeWriter line(Object... parts) { + return put(piece(Arrays.asList(parts))); + } + + /** Ask for one blank line before whatever is written next. Requests never stack. */ + public CodeWriter blank() { + wantBlank = true; + return this; + } + + /** Write the line that opens a block, then indent. */ + public CodeWriter open(Object... parts) { + return openPiece(piece(Arrays.asList(parts))); + } + + /** Dedent, then write the line that closes the block. */ + public CodeWriter close(Object... parts) { + return closePiece(piece(Arrays.asList(parts))); + } + + /** + * A block, scoped: {@code try (var b = w.block("class A {")) { ... }} writes the head, indents, + * and on leaving the {@code try} dedents and writes {@code "}"}. The indent cannot be left + * unbalanced. + */ + public Block block(Object head) { + return block(head, "}"); + } + + /** A block closed by {@code tail} instead of {@code "}"}, such as {@code "});"}. */ + public Block block(Object head, Object tail) { + open(head); + return new Block(tail); + } + + /** The scope {@link #block} returns; closing it writes the block's closing line. */ + public class Block implements AutoCloseable { + private final Object tail; + + protected Block(Object tail) { + this.tail = tail; + } + + @Override + public void close() { + CodeWriter.this.close(tail); + } + } + + /** + * A multi-line snippet written as it should read: a Java text block is the natural argument. + * 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. + */ + public CodeWriter text(String snippet) { + List lines = new ArrayList<>(List.of(ANY_LINE_BREAK.split(snippet, -1))); + if (lines.size() > 1 && lines.get(0).isBlank()) lines.remove(0); + if (!lines.isEmpty() && lines.get(lines.size() - 1).isBlank()) lines.remove(lines.size() - 1); + int margin = Integer.MAX_VALUE; + for (String l : lines) { + if (!l.isBlank()) margin = Math.min(margin, l.length() - l.stripLeading().length()); + } + for (String l : lines) { + if (l.isBlank()) blank(); + else put(l.substring(margin)); + } + return this; + } + + /** The body text: every line joined, with no final newline. Throws if a block is still open. */ + protected String body() { + if (!openers.isEmpty()) { + throw new WriterException( + WriterException.UNCLOSED_BLOCK, + "unclosed block opened by: " + openers.get(openers.size() - 1)); + } + return String.join(NEWLINE, out); + } + + /** The finished file: {@code \n} line endings, no trailing whitespace, one final newline (none when empty). */ + @Override + public String toString() { + String body = body(); + return body.isEmpty() ? "" : body + NEWLINE; + } + + /** + * Turn one argument of {@code line()} into a writer piece. A dialect overrides this to accept + * its own fragment types, and calls {@code super} for the rest. + */ + protected Object piece(Object p) { + if (p instanceof CharSequence cs) return cs.toString(); + if (p instanceof Group g) { + List items = new ArrayList<>(g.items().size()); + for (Object i : g.items()) items.add(piece(i)); + return new Group(g.open(), items, g.close(), g.pad()); + } + if (p instanceof List l) { + List parts = new ArrayList<>(l.size()); + for (Object x : l) parts.add(piece(x)); + return parts; + } + if (p instanceof Object[] a) return piece(Arrays.asList(a)); + throw new WriterException(WriterException.UNKNOWN_PIECE, "cannot write " + describe(p)); + } + + /** Whether {@code text} fits on one line at the current indent. */ + protected boolean fits(String text) { + return widthOf(prefix()) + widthOf(text) <= options.width(); + } + + /** + * Where a line that does not fit breaks: the text before, the list that breaks, the text + * after; or null to print the line as it is. The default is the line's LAST non-empty list. + */ + protected Split breakAt(Object piece) { + return lastGroup(piece); + } + + protected CodeWriter openPiece(Object piece) { + put(piece); + openers.add(flat(piece).strip()); + atBlockStart = true; + return this; + } + + protected CodeWriter closePiece(Object piece) { + if (openers.isEmpty()) { + throw new WriterException( + WriterException.UNBALANCED_CLOSE, "close(\"" + flat(piece) + "\") with no block open"); + } + openers.remove(openers.size() - 1); + wantBlank = false; + return put(piece); + } + + protected String prefix() { + int depth = openers.size(); + while (prefixes.size() <= depth) prefixes.add(prefixes.get(prefixes.size() - 1) + options.indent()); + return prefixes.get(depth); + } + + protected CodeWriter put(Object piece) { + String raw = flat(piece); + if (ANY_LINE_BREAK.matcher(raw).find()) { + throw new WriterException( + WriterException.NEWLINE_IN_LINE, + "line text contains a line break; write each line separately or use text(): \"" + raw + "\""); + } + String text = raw.stripTrailing(); + if (text.isEmpty()) return blank(); + if (wantBlank && !atBlockStart) out.add(""); + wantBlank = false; + atBlockStart = false; + String pre = prefix(); + Split split = fits(text) ? null : breakAt(piece); + if (split == null) { + out.add(pre + text); + return this; + } + openPiece(split.before() + split.group().open()); + List items = split.group().items(); + for (int n = 0; n < items.size(); n++) { + boolean comma = n < items.size() - 1 || options.trailingComma(); + put(List.of(items.get(n), comma ? "," : "")); + } + return closePiece(split.group().close() + split.after()); + } + + /** The text before a list that breaks, the list, and the text after it. */ + public record Split(String before, Group group, String after) {} + + /** A list with no padding inside its brackets: {@code [a, b]}, {@code f(a, b)}, {@code }. */ + public static Group list(String open, List items, String close) { + return new Group(open, items, close, false); + } + + /** A list with a space inside its brackets: {@code { a, b }}. */ + public static Group padded(String open, List items, String close) { + return new Group(open, items, close, true); + } + + /** A piece printed on one line. */ + public static String flat(Object p) { + if (p instanceof String s) return s; + if (p instanceof Group g) { + if (g.items().isEmpty()) return g.open() + g.close(); + StringBuilder inner = new StringBuilder(); + for (int i = 0; i < g.items().size(); i++) { + if (i > 0) inner.append(", "); + inner.append(flat(g.items().get(i))); + } + return g.pad() ? g.open() + " " + inner + " " + g.close() : g.open() + inner + g.close(); + } + if (p instanceof List l) { + StringBuilder s = new StringBuilder(); + for (Object x : l) s.append(flat(x)); + return s.toString(); + } + return String.valueOf(p); + } + + /** Split a piece around its LAST non-empty list: the text before, the list, the text after. */ + protected static Split lastGroup(Object p) { + if (p instanceof Group g) return g.items().isEmpty() ? null : new Split("", g, ""); + if (p instanceof List l) { + for (int i = l.size() - 1; i >= 0; i--) { + Split hit = lastGroup(l.get(i)); + if (hit != null) { + return new Split( + flat(l.subList(0, i)) + hit.before(), hit.group(), hit.after() + flat(l.subList(i + 1, l.size()))); + } + } + } + return null; + } + + /** Width in Unicode code points, so an emoji counts as one although it is two UTF-16 units. */ + protected static int widthOf(String s) { + return s.codePointCount(0, s.length()); + } + + private static String describe(Object p) { + if (p == null) return "null"; + return "an object (" + p.getClass().getName() + ")"; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java new file mode 100644 index 0000000000..ee20a4bf22 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java @@ -0,0 +1,48 @@ +package com.metaobjects.generator.writer; + +import java.util.List; + +/** + * 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. + * + *

The items are pieces: a {@code String}, another {@code Group}, or a {@code List} or array + * of pieces, which are concatenated. + */ +public class Group { + private final String open; + private final List items; + private final String close; + private final boolean pad; + + /** + * @param pad {@code { a, b }} (true) versus {@code [a, b]} or {@code f(a, b)} (false) when + * printed on one line + */ + public Group(String open, List items, String close, boolean pad) { + this.open = open; + this.items = List.copyOf(items); + this.close = close; + this.pad = pad; + } + + public Group(String open, List items, String close) { + this(open, items, close, false); + } + + public String open() { + return open; + } + + public List items() { + return items; + } + + public String close() { + return close; + } + + public boolean pad() { + return pad; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java new file mode 100644 index 0000000000..5d6707035e --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java @@ -0,0 +1,183 @@ +package com.metaobjects.generator.writer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * The Java dialect of the code writer (ADR-0063; contract: {@code spec/code-writer.md}). + * + *

Adds what is Java's own: the {@code package} line, imports collected while the body is + * written and printed first, string quoting and Javadoc comments. A generator names a type once + * with {@link #use} and writes what comes back, so the imports can never disagree with the body. + * + *

Like {@link CodeWriter} it is built to be extended: each section of the file + * ({@link #writeHeader}, {@link #writePackage}, {@link #writeImports}) is its own overridable + * method, and none of them is a stability contract. + */ +public class JavaWriter extends CodeWriter { + + private static final String JAVA_LANG = "java.lang"; + + /** Simple name to the fully qualified name that owns it, so one name cannot come from two types. */ + protected final Map locals = new TreeMap<>(); + /** Fully qualified names to import, in code-unit order. */ + protected final TreeSet imports = new TreeSet<>(Comparator.naturalOrder()); + /** Static members to import, as {@code pkg.Type.member}. */ + protected final TreeSet staticImports = new TreeSet<>(Comparator.naturalOrder()); + /** Member name to the type that owns it: one static name cannot come from two types. */ + protected final Map staticLocals = new TreeMap<>(); + protected final List headLines = new ArrayList<>(); + protected String packageName; + + public JavaWriter() { + this(WriterOptions.JAVA); + } + + public JavaWriter(WriterOptions options) { + super(options); + } + + /** A correctly quoted Java string literal. */ + public static String str(String value) { + StringBuilder sb = new StringBuilder(value.length() + 2).append('"'); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + case '\b' -> sb.append("\\b"); + case '\f' -> sb.append("\\f"); + default -> { + if (c < 0x20 || c == 0x7f) sb.append(String.format("\\u%04x", (int) c)); + else sb.append(c); + } + } + } + return sb.append('"').toString(); + } + + /** A call: {@code fn(a, b)}. */ + public static Group call(String fn, Object... args) { + return list(fn + "(", Arrays.asList(args), ")"); + } + + /** The {@code package} this file is in; types of that package need no import. */ + public JavaWriter packageName(String name) { + this.packageName = Objects.requireNonNull(name); + return this; + } + + /** + * Reference a type by its fully qualified name; returns the name to write (its simple name). + * A type in {@code java.lang} or in this file's package imports nothing. A nested type + * ({@code java.util.Map.Entry}) is imported as written and written by its last segment. + */ + public String use(String qualifiedName) { + String local = simpleName(qualifiedName); + String owner = locals.get(local); + if (owner != null && !owner.equals(qualifiedName)) { + throw new WriterException( + WriterException.IMPORT_CONFLICT, local + " is imported from both " + owner + " and " + qualifiedName); + } + locals.put(local, qualifiedName); + imports.add(qualifiedName); + return local; + } + + /** + * Reference a static member by {@code pkg.Type.member}; returns the name to write (the member). + */ + public String useStatic(String qualifiedMember) { + String member = simpleName(qualifiedMember); + String owner = staticLocals.get(member); + if (owner != null && !owner.equals(qualifiedMember)) { + throw new WriterException( + WriterException.IMPORT_CONFLICT, member + " is imported from both " + owner + " and " + qualifiedMember); + } + staticLocals.put(member, qualifiedMember); + staticImports.add(qualifiedMember); + return member; + } + + /** Lines printed at the very top, before the package line: a banner comment. */ + public JavaWriter header(String... lines) { + headLines.addAll(Arrays.asList(lines)); + return this; + } + + /** A Javadoc comment: one line when it fits, otherwise a block with one {@code * } line per entry. */ + public JavaWriter doc(String... lines) { + if (lines.length == 0) return this; + List safe = new ArrayList<>(lines.length); + for (String l : lines) safe.add(l.replace("*/", "*/")); + String one = "/** " + safe.get(0) + " */"; + if (safe.size() == 1 && fits(one)) { + line(one); + return this; + } + line("/**"); + for (String l : safe) line(l.isEmpty() ? " *" : " * " + l); + line(" */"); + return this; + } + + @Override + public String toString() { + CodeWriter head = sectionWriter(); + writeHeader(head); + head.blank(); + writePackage(head); + head.blank(); + writeImports(head); + String top = head.toString(); + String body = super.toString(); + if (top.isEmpty()) return body; + if (body.isEmpty()) return top; + return top + "\n" + body; + } + + /** The writer the header, package and import sections are laid out with: same options, no dialect. */ + protected CodeWriter sectionWriter() { + return new CodeWriter(options); + } + + /** The {@link #header} lines, as given. */ + protected void writeHeader(CodeWriter w) { + for (String l : headLines) w.line(l); + } + + /** The {@code package} line, when one was set. */ + protected void writePackage(CodeWriter w) { + if (packageName != null) w.line("package ", packageName, ";"); + } + + /** Static imports, a blank line, then the other imports: each group in code-unit order. */ + protected void writeImports(CodeWriter w) { + for (String s : staticImports) w.line("import static ", s, ";"); + w.blank(); + for (String t : imports) { + if (needsImport(t)) w.line("import ", t, ";"); + } + } + + /** False for a type that is in {@code java.lang} or in the file's own package. */ + protected boolean needsImport(String qualifiedName) { + int dot = qualifiedName.lastIndexOf('.'); + if (dot < 0) return false; + String pkg = qualifiedName.substring(0, dot); + return !pkg.equals(JAVA_LANG) && !pkg.equals(packageName); + } + + private static String simpleName(String qualified) { + return qualified.substring(qualified.lastIndexOf('.') + 1); + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java new file mode 100644 index 0000000000..672be302c9 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java @@ -0,0 +1,30 @@ +package com.metaobjects.generator.writer; + +/** + * An error the code writer throws (ADR-0063; contract: {@code spec/code-writer.md}). The + * {@link #code()} is one of the codes every port's writer shares, and the message starts with it. + */ +public class WriterException extends RuntimeException { + + /** {@code close()} with no block open. */ + public static final String UNBALANCED_CLOSE = "ERR_WRITER_UNBALANCED_CLOSE"; + /** The file was finished with a block still open; the message quotes the line that opened it. */ + public static final String UNCLOSED_BLOCK = "ERR_WRITER_UNCLOSED_BLOCK"; + /** {@code line()} was handed text containing a line break. */ + public static final String NEWLINE_IN_LINE = "ERR_WRITER_NEWLINE_IN_LINE"; + /** One local name imported from two different places. */ + public static final String IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT"; + /** A piece the writer does not know how to print. */ + public static final String UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE"; + + private final String code; + + public WriterException(String code, String message) { + super(code + ": " + message); + this.code = code; + } + + public String code() { + return code; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java new file mode 100644 index 0000000000..cc5e342254 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java @@ -0,0 +1,27 @@ +package com.metaobjects.generator.writer; + +/** + * What a writer is configured with (spec/code-writer.md, "Options"). A dialect supplies the + * defaults for its language; a shared {@code core} case states all three. + * + * @param indent one level of indentation + * @param width the last column a line may reach before its last list breaks + * @param trailingComma whether a broken list puts a comma after its last item too + */ +public record WriterOptions(String indent, int width, boolean trailingComma) { + + /** Four spaces, 120 columns, no trailing comma: what Java allows in an argument list. */ + public static final WriterOptions JAVA = new WriterOptions(" ", 120, false); + + public WriterOptions withIndent(String indent) { + return new WriterOptions(indent, width, trailingComma); + } + + public WriterOptions withWidth(int width) { + return new WriterOptions(indent, width, trailingComma); + } + + public WriterOptions withTrailingComma(boolean trailingComma) { + return new WriterOptions(indent, width, trailingComma); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java new file mode 100644 index 0000000000..dbdc04fd4c --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java @@ -0,0 +1,102 @@ +package com.metaobjects.generator.writer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; +import org.junit.Test; + +/** What the shared corpus cannot say: the Java-shaped API around the cases it pins. */ +public class JavaWriterTest { + + @Test + public void str_quotes_a_java_string_literal() { + assertEquals("\"a\\\"b\\\\c\"", JavaWriter.str("a\"b\\c")); + assertEquals("\"line\\nbreak\\ttab\\r\"", JavaWriter.str("line\nbreak\ttab\r")); + assertEquals("\"\\u0001\"", JavaWriter.str("\u0001")); + assertEquals("\"caf\u00e9\"", JavaWriter.str("caf\u00e9")); + } + + @Test + public void a_scoped_block_indents_and_closes_itself() { + JavaWriter w = new JavaWriter(); + try (var cls = w.block("class A {")) { + try (var m = w.block("void f() {")) { + w.line("g();"); + } + } + assertEquals("class A {\n void f() {\n g();\n }\n}\n", w.toString()); + } + + @Test + public void a_block_can_close_with_its_own_tail() { + JavaWriter w = new JavaWriter(); + try (var b = w.block("run(() -> {", "});")) { + w.line("g();"); + } + assertEquals("run(() -> {\n g();\n});\n", w.toString()); + } + + @Test + public void use_returns_the_name_to_write() { + JavaWriter w = new JavaWriter().packageName("com.acme"); + String list = w.use("java.util.List"); + String str = w.use("java.lang.String"); + w.line("private final ", list, "<", str, "> names;"); + assertEquals("package com.acme;\n\nimport java.util.List;\n\nprivate final List names;\n", w.toString()); + } + + @Test + public void a_call_group_breaks_at_the_last_list_without_a_trailing_comma() { + JavaWriter w = new JavaWriter(WriterOptions.JAVA.withWidth(30)); + w.line("return ", JavaWriter.call("build", "alpha", "beta", "gamma", "delta"), ";"); + assertEquals("return build(\n alpha,\n beta,\n gamma,\n delta\n);\n", w.toString()); + } + + @Test + public void a_piece_that_is_not_text_is_refused() { + try { + new JavaWriter().line("x = ", 5, ";"); + fail("expected ERR_WRITER_UNKNOWN_PIECE"); + } catch (WriterException e) { + assertEquals(WriterException.UNKNOWN_PIECE, e.code()); + assertTrue(e.getMessage(), e.getMessage().startsWith("ERR_WRITER_UNKNOWN_PIECE: ")); + } + } + + @Test + public void a_list_or_array_of_parts_is_concatenated() { + JavaWriter w = new JavaWriter(); + w.line(List.of("a", "b"), new Object[] {"c", List.of("d")}); + assertEquals("abcd\n", w.toString()); + } + + @Test + public void a_text_block_is_a_snippet() { + JavaWriter w = new JavaWriter(); + try (var b = w.block("class A {")) { + w.text( + """ + void f() { + g(); + } + """); + } + assertEquals("class A {\n void f() {\n g();\n }\n}\n", w.toString()); + } + + @Test + public void a_subclass_can_change_one_layout_step() { + JavaWriter w = + new JavaWriter() { + @Override + protected void writeImports(CodeWriter section) { + section.line("// imports are elsewhere"); + } + }; + w.use("java.util.List"); + w.line("class A {}"); + assertEquals("// imports are elsewhere\n\nclass A {}\n", w.toString()); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java new file mode 100644 index 0000000000..446b612dd3 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java @@ -0,0 +1,134 @@ +package com.metaobjects.generator.writer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +/** + * Runs {@code fixtures/writer-conformance/} against the Java writer (spec/code-writer.md). + * {@code core} cases run on {@link CodeWriter} with the options the case states; {@code java} + * cases run on {@link JavaWriter} with its own defaults unless the case overrides them. A case + * of another dialect belongs to that port's writer and is skipped here by name. + */ +@RunWith(Parameterized.class) +public class WriterConformanceTest { + + private static final String CORE = "core"; + private static final String JAVA = "java"; + + private static Path cases() { + return Path.of(System.getProperty("user.dir")) + .resolve("../../../fixtures/writer-conformance/cases") + .normalize(); + } + + @Parameterized.Parameters(name = "{0}") + public static List corpus() throws IOException { + List out = new ArrayList<>(); + try (Stream files = Files.list(cases())) { + for (Path f : files.filter(p -> p.toString().endsWith(".json")).sorted().toList()) { + JsonObject c = new Gson().fromJson(Files.readString(f), JsonObject.class); + String dialect = c.get("dialect").getAsString(); + if (dialect.equals(CORE) || dialect.equals(JAVA)) { + out.add(new Object[] {f.getFileName().toString().replaceFirst("\\.json$", ""), c}); + } + } + } + return out; + } + + private final JsonObject c; + + public WriterConformanceTest(String name, JsonObject c) { + this.c = c; + } + + @Test + public void case_matches_expected_output() { + boolean core = c.get("dialect").getAsString().equals(CORE); + if (core) assertNotNull("a core case states its options", c.get("options")); + if (c.has("error")) { + try { + run(core); + } catch (WriterException e) { + assertEquals(c.get("error").getAsString(), e.code()); + if (c.has("errorQuotes")) assertTrue(e.getMessage(), e.getMessage().contains(c.get("errorQuotes").getAsString())); + return; + } + fail("expected " + c.get("error").getAsString()); + } + List lines = new ArrayList<>(); + for (JsonElement l : c.getAsJsonArray("expected")) lines.add(l.getAsString()); + assertEquals(lines.isEmpty() ? "" : String.join("\n", lines) + "\n", run(core)); + } + + private String run(boolean core) { + CodeWriter base = core ? new CodeWriter(options()) : new JavaWriter(options()); + for (JsonElement e : c.getAsJsonArray("ops")) { + JsonArray op = e.getAsJsonArray(); + String name = op.get(0).getAsString(); + List args = new ArrayList<>(); + for (int i = 1; i < op.size(); i++) args.add(piece(op.get(i))); + switch (name) { + case "line" -> base.line(args.toArray()); + case "open" -> base.open(args.toArray()); + case "close" -> base.close(args.toArray()); + case "blank" -> base.blank(); + case "text" -> base.text((String) args.get(0)); + default -> { + if (!(base instanceof JavaWriter w)) throw new IllegalStateException("op " + name + " is not a core op"); + String[] s = args.stream().map(String.class::cast).toArray(String[]::new); + switch (name) { + case "use" -> w.use(s[0]); + case "useStatic" -> w.useStatic(s[0]); + case "package" -> w.packageName(s[0]); + case "header" -> w.header(s); + case "doc" -> w.doc(s); + default -> throw new IllegalStateException("unknown op " + name); + } + } + } + } + return base.toString(); + } + + /** The case's options laid over the dialect's defaults (core states all three). */ + private WriterOptions options() { + WriterOptions o = c.get("dialect").getAsString().equals(CORE) ? new WriterOptions(" ", 120, true) : WriterOptions.JAVA; + if (!c.has("options")) return o; + JsonObject given = c.getAsJsonObject("options"); + if (given.has("indent")) o = o.withIndent(given.get("indent").getAsString()); + if (given.has("width")) o = o.withWidth(given.get("width").getAsInt()); + if (given.has("trailingComma")) o = o.withTrailingComma(given.get("trailingComma").getAsBoolean()); + return o; + } + + private static Object piece(JsonElement p) { + if (p.isJsonPrimitive()) return p.getAsString(); + if (p.isJsonArray()) { + List parts = new ArrayList<>(); + for (JsonElement x : p.getAsJsonArray()) parts.add(piece(x)); + return parts; + } + JsonObject l = p.getAsJsonObject().getAsJsonObject("list"); + List items = new ArrayList<>(); + for (JsonElement x : l.getAsJsonArray("items")) items.add(piece(x)); + boolean pad = l.has("pad") && l.get("pad").getAsBoolean(); + return new Group(l.get("open").getAsString(), items, l.get("close").getAsString(), pad); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java new file mode 100644 index 0000000000..0f339ca7a1 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java @@ -0,0 +1,327 @@ +package com.metaobjects.generator.writer.layout; + +import com.sun.source.tree.BinaryTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.ConditionalExpressionTree; +import com.sun.source.tree.ConstantCaseLabelTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.LiteralTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.TypeCastTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.JavacTask; +import com.sun.source.util.SourcePositions; +import com.sun.source.util.TreePath; +import com.sun.source.util.TreePathScanner; +import com.sun.source.util.Trees; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +/** + * 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 file with javac's + * own parser (the Compiler Tree API, parse only) and walks the syntax tree. Working on the tree, + * not the text, is what makes the rules exact: a comment is never a node, a string's value is the + * parser's cooked value (so {@code "\n"}, {@code "\u000a"} and a text block are the same + * finding), and a {@code final} constant is followed to its declaration so + * {@code String NL = "\n"; xs.join(NL, ...)} is a finding at the join as well as at the + * declaration. + * + *

Four rules: + * + *

    + *
  • {@code newline-literal}: a string or char literal, text block, {@code %n} format + * directive or {@code lineSeparator()} call that writes a line break. + *
  • {@code indent-literal}: a string that starts a line of output (it is not the right-hand + * part of a {@code +}) and begins with an indentation run: two or more spaces, or a tab. + *
  • {@code newline-join}: {@code String.join(sep, ...)}, {@code Collectors.joining(sep)} or + * {@code new StringJoiner(sep)} whose separator contains a line break, resolved through + * same-file constants. + *
  • {@code indent-repeat}: {@code s.repeat(n)} where {@code s} resolves to whitespace. + *
+ * + *

Places a literal is not output, and so is not layout, are ruled out by position: a search or + * comparison (the first argument of split, indexOf, lastIndexOf, contains, startsWith, endsWith, + * replace, replaceAll, replaceFirst, matches, equals, equalsIgnoreCase, contentEquals, or an + * operand of {@code ==} or {@code !=}, or a {@code case} label), a log message (the first argument + * of trace, debug, info, warn or error), and a writer snippet (the + * argument of a {@code .text(...)} call, the writer's entry for fixed code written as it should + * read: it removes the margin and re-indents). + */ +public final class LayoutAnalyzer { + + public enum Kind { + NEWLINE_LITERAL("newline-literal"), + INDENT_LITERAL("indent-literal"), + NEWLINE_JOIN("newline-join"), + INDENT_REPEAT("indent-repeat"); + + private final String label; + + Kind(String label) { + this.label = label; + } + + @Override + public String toString() { + return label; + } + } + + /** One piece of hand-typed layout: its rule, 1-based position and shortened source text. */ + public record Finding(Kind kind, int line, int column, String excerpt) { + @Override + public String toString() { + return line + ":" + column + " " + kind + " " + excerpt; + } + } + + private static final Pattern LINE_BREAK = Pattern.compile("[\r\n]|%n"); + private static final Pattern INDENT_RUN = Pattern.compile("^(?: {2,}|\t)"); + private static final Pattern WHITESPACE = Pattern.compile("^[ \t\r\n]+$"); + private static final Set SEARCH_METHODS = + Set.of( + "split", "indexOf", "lastIndexOf", "contains", "startsWith", "endsWith", "replace", + "replaceAll", "replaceFirst", "matches", "equals", "equalsIgnoreCase", "contentEquals"); + /** A logger call's message is a diagnostic for the person running the build, not generated output. */ + private static final Set LOG_METHODS = Set.of("trace", "debug", "info", "warn", "error"); + private static final String SNIPPET_METHOD = "text"; + private static final Set JOIN_METHODS = Set.of("join", "joining"); + private static final String REPEAT_METHOD = "repeat"; + private static final String LINE_SEPARATOR = "lineSeparator"; + private static final String STRING_JOINER = "StringJoiner"; + private static final int MAX_RESOLVE_DEPTH = 8; + + private LayoutAnalyzer() {} + + /** What a string expression is known to contain. {@code complete} is false when part of it is unknown. */ + private record Resolved(String text, boolean complete) {} + + public static List analyze(String fileName, String source) { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + JavaFileObject file = + new SimpleJavaFileObject(URI.create("string:///" + fileName), JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return source; + } + }; + JavacTask task = (JavacTask) compiler.getTask(null, null, null, List.of("-proc:none"), null, List.of(file)); + Iterable units; + try { + units = task.parse(); + } catch (IOException e) { + throw new IllegalStateException("cannot parse " + fileName, e); + } + SourcePositions positions = Trees.instance(task).getSourcePositions(); + List findings = new ArrayList<>(); + for (CompilationUnitTree unit : units) { + Map consts = collectConsts(unit); + new Scan(unit, positions, consts, source, findings).scan(unit, null); + } + findings.sort( + java.util.Comparator.comparingInt(Finding::line).thenComparingInt(Finding::column).thenComparing(Finding::kind)); + return findings; + } + + private static final class Scan extends TreePathScanner { + private final CompilationUnitTree unit; + private final SourcePositions positions; + private final Map consts; + private final String source; + private final List findings; + + Scan( + CompilationUnitTree unit, + SourcePositions positions, + Map consts, + String source, + List findings) { + this.unit = unit; + this.positions = positions; + this.consts = consts; + this.source = source; + this.findings = findings; + } + + private void report(Kind kind, Tree node) { + long start = positions.getStartPosition(unit, node); + long end = positions.getEndPosition(unit, node); + long line = unit.getLineMap().getLineNumber(start); + long column = unit.getLineMap().getColumnNumber(start); + String raw = source.substring((int) start, (int) Math.max(start, Math.min(end, source.length()))).replaceAll("\\s+", " "); + findings.add(new Finding(kind, (int) line, (int) column, raw.length() > 60 ? raw.substring(0, 57) + "..." : raw)); + } + + @Override + public Void visitLiteral(LiteralTree node, Void unused) { + Object value = node.getValue(); + boolean string = value instanceof String; + boolean ch = value instanceof Character; + if ((string || ch) && !isSearchPattern(getCurrentPath()) && !isSnippet(getCurrentPath())) { + String v = String.valueOf(value); + if (LINE_BREAK.matcher(v).find()) report(Kind.NEWLINE_LITERAL, node); + else if (string && startsALine(getCurrentPath()) && INDENT_RUN.matcher(v).find()) report(Kind.INDENT_LITERAL, node); + } + return super.visitLiteral(node, unused); + } + + @Override + public Void visitMethodInvocation(MethodInvocationTree call, Void unused) { + String method = calledName(call.getMethodSelect()); + if (method != null) { + if (JOIN_METHODS.contains(method) && !call.getArguments().isEmpty()) { + Resolved sep = resolve(call.getArguments().get(0), 0); + if (sep != null && LINE_BREAK.matcher(sep.text()).find()) report(Kind.NEWLINE_JOIN, call); + } else if (method.equals(REPEAT_METHOD) && call.getMethodSelect() instanceof MemberSelectTree ms) { + Resolved unit = resolve(ms.getExpression(), 0); + if (unit != null && unit.complete() && WHITESPACE.matcher(unit.text()).find()) report(Kind.INDENT_REPEAT, call); + } else if (method.equals(LINE_SEPARATOR) && call.getArguments().isEmpty()) { + report(Kind.NEWLINE_LITERAL, call); + } + } + return super.visitMethodInvocation(call, unused); + } + + @Override + public Void visitNewClass(NewClassTree node, Void unused) { + if (node.getIdentifier() instanceof IdentifierTree id + && id.getName().contentEquals(STRING_JOINER) + && !node.getArguments().isEmpty()) { + Resolved sep = resolve(node.getArguments().get(0), 0); + if (sep != null && LINE_BREAK.matcher(sep.text()).find()) report(Kind.NEWLINE_JOIN, node); + } + return super.visitNewClass(node, unused); + } + + private Resolved resolve(ExpressionTree expr, int depth) { + if (depth > MAX_RESOLVE_DEPTH) return null; + if (expr instanceof LiteralTree lit && lit.getValue() instanceof String s) return new Resolved(s, true); + if (expr instanceof LiteralTree lit && lit.getValue() instanceof Character c) return new Resolved(String.valueOf(c), true); + if (expr instanceof ParenthesizedTree p) return resolve(p.getExpression(), depth + 1); + if (expr instanceof TypeCastTree c) return resolve(c.getExpression(), depth + 1); + if (expr instanceof BinaryTree b && b.getKind() == Tree.Kind.PLUS) { + Resolved l = resolve(b.getLeftOperand(), depth + 1); + Resolved r = resolve(b.getRightOperand(), depth + 1); + if (l == null && r == null) return null; + return new Resolved( + (l == null ? "" : l.text()) + (r == null ? "" : r.text()), + l != null && l.complete() && r != null && r.complete()); + } + if (expr instanceof ConditionalExpressionTree c) { + // Either branch may be written; for "does it contain a line break" both count. + Resolved a = resolve(c.getTrueExpression(), depth + 1); + Resolved b = resolve(c.getFalseExpression(), depth + 1); + if (a == null && b == null) return null; + return new Resolved((a == null ? "" : a.text()) + (b == null ? "" : b.text()), false); + } + if (expr instanceof IdentifierTree id) { + ExpressionTree init = consts.get(id.getName().toString()); + return init == null ? null : resolve(init, depth + 1); + } + if (expr instanceof MemberSelectTree ms) { + // `Type.NAME` or `this.NAME`: the member name is looked up among the file's constants. + ExpressionTree init = consts.get(ms.getIdentifier().toString()); + return init == null ? null : resolve(init, depth + 1); + } + return null; + } + } + + /** + * Every {@code final} variable with an initializer whose name is declared exactly once in the + * file. A name declared more than once is left out: it is shadowed somewhere. + */ + private static Map collectConsts(CompilationUnitTree unit) { + Map seen = new HashMap<>(); + Set shadowed = new java.util.HashSet<>(); + new TreePathScanner() { + @Override + public Void visitVariable(VariableTree v, Void unused) { + String name = v.getName().toString(); + boolean isFinal = v.getModifiers().getFlags().contains(javax.lang.model.element.Modifier.FINAL); + if (seen.containsKey(name) || shadowed.contains(name) || v.getInitializer() == null || !isFinal) { + shadowed.add(name); + seen.remove(name); + } else { + seen.put(name, v.getInitializer()); + } + return super.visitVariable(v, unused); + } + }.scan(unit, null); + return seen; + } + + /** The method name a call invokes: {@code x.join(...)} is "join", {@code join(...)} is "join". */ + private static String calledName(ExpressionTree select) { + if (select instanceof MemberSelectTree ms) return ms.getIdentifier().toString(); + if (select instanceof IdentifierTree id) return id.getName().toString(); + return null; + } + + /** A string that is the right-hand part of a {@code +} follows other text, so it does not start a line. */ + private static boolean startsALine(TreePath path) { + Tree parent = path.getParentPath().getLeaf(); + return !(parent instanceof BinaryTree b && b.getKind() == Tree.Kind.PLUS && b.getRightOperand() == path.getLeaf()); + } + + private static boolean isSearchPattern(TreePath path) { + Tree leaf = path.getLeaf(); + Tree parent = path.getParentPath().getLeaf(); + if (parent instanceof ParenthesizedTree) return isSearchPattern(path.getParentPath()); + if (parent instanceof BinaryTree b && (b.getKind() == Tree.Kind.EQUAL_TO || b.getKind() == Tree.Kind.NOT_EQUAL_TO)) { + return true; + } + if (parent instanceof ConstantCaseLabelTree) return true; + return isArgument(path, SEARCH_METHODS::contains, 0) || isArgument(path, LOG_METHODS::contains, 0); + } + + private static boolean isSnippet(TreePath path) { + return isArgument(path, SNIPPET_METHOD::equals, 0); + } + + private static boolean isArgument(TreePath path, java.util.function.Predicate method, int index) { + Tree leaf = path.getLeaf(); + Tree parent = path.getParentPath().getLeaf(); + if (!(parent instanceof MethodInvocationTree call) || !(call.getMethodSelect() instanceof MemberSelectTree ms)) return false; + return method.test(ms.getIdentifier().toString()) && call.getArguments().size() > index && call.getArguments().get(index) == leaf; + } + + // ── which files the ratchet reads ────────────────────────────────────────────────────── + + /** The modules whose {@code src/main/java} holds generator source, relative to {@code server/java/}. */ + public static final List SCANNED_MODULES = + List.of("codegen-base", "codegen-spring", "codegen-plantuml", "codegen-mustache"); + + /** The writer itself: the one package that lays text out, so the one allowed to type layout. */ + private static final String WRITER_DIR = "codegen-base/src/main/java/com/metaobjects/generator/writer/"; + + /** + * Whether a file (relative to {@code server/java/}) is generator source the ratchet reads. + * Excluded by rule, never by listing: anything outside a scanned module's {@code src/main/java}, + * tests, {@code package-info.java} and the writer. + */ + public static boolean isGeneratorSource(String rel) { + String path = rel.replace('\\', '/'); + if (SCANNED_MODULES.stream().noneMatch(m -> path.startsWith(m + "/src/main/java/"))) return false; + if (!path.endsWith(".java") || path.endsWith("/package-info.java")) return false; + return !path.startsWith(WRITER_DIR); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java new file mode 100644 index 0000000000..86d062bac5 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java @@ -0,0 +1,369 @@ +package com.metaobjects.generator.writer.layout; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.metaobjects.generator.writer.layout.LayoutAnalyzer.Finding; +import com.metaobjects.generator.writer.layout.LayoutAnalyzer.Kind; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.Test; + +/** + * The layout ratchet (ADR-0063): generator source never types layout; the writer does. + * + *

Three parts: the analyzer's own cases (layout it must catch, and writer-based code it must + * pass), the scope rule (which files are generator source, by rule and not by list) and the + * ratchet over the real modules: 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. + */ +public class LayoutRatchetTest { + + private static List kinds(String body) { + return LayoutAnalyzer.analyze("Fixture.java", "class Fixture { void f() { " + body + " } }").stream() + .map(Finding::kind) + .sorted() + .toList(); + } + + private static List sorted(Kind... k) { + return Stream.of(k).sorted().toList(); + } + + // ── 1. the analyzer ────────────────────────────────────────────────────────────────── + + @Test + public void catches_a_newline_escape() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"a\\nb\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"a\\r\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("sb.append('\\n');")); + } + + @Test + public void catches_a_text_block_a_percent_n_and_a_line_separator() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"\"\"\n a\n \"\"\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = String.format(\"%s%n\", x);")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = System.lineSeparator();")); + } + + @Test + public void catches_a_string_that_starts_with_an_indentation_run() { + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\" \" + name);")); + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\"\\tx\");")); + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\" name: String;\");")); + } + + @Test + public void catches_a_join_on_a_line_break() { + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("String.join(\"\\n\", rows);")); + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("rows.stream().collect(Collectors.joining(\",\\n\"));")); + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("var j = new StringJoiner(\"\\n\");")); + } + + @Test + public void catches_an_indentation_repeat() { + assertEquals(sorted(Kind.INDENT_REPEAT, Kind.INDENT_LITERAL), kinds("String pad = \" \".repeat(depth);")); + assertEquals(sorted(Kind.INDENT_REPEAT), kinds("String pad = \" \".repeat(depth * 2);")); + } + + @Test + public void a_newline_hidden_behind_a_constant_is_caught_where_it_is_used() { + String source = "class F { static final String NL = \"\\n\"; String f() { return String.join(NL, rows); } }"; + List found = LayoutAnalyzer.analyze("F.java", source); + assertEquals( + List.of(Kind.NEWLINE_LITERAL, Kind.NEWLINE_JOIN), found.stream().map(Finding::kind).toList()); + } + + @Test + public void a_constant_built_from_other_constants_is_followed() { + String source = + "class F { static final String NL = \"\\n\"; static final String SEP = \",\" + NL;" + + " String f() { return String.join(SEP, rows); } }"; + List found = LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList(); + assertEquals(List.of(Kind.NEWLINE_LITERAL, Kind.NEWLINE_JOIN), found); + } + + @Test + public void an_indentation_unit_hidden_behind_a_constant_is_caught_at_the_repeat() { + String source = "class F { static final String UNIT = \" \"; String f() { return UNIT.repeat(4); } }"; + assertEquals(List.of(Kind.INDENT_REPEAT), LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList()); + } + + @Test + public void either_branch_of_a_conditional_separator_counts() { + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("String.join(compact ? \", \" : \",\\n\", rows);")); + } + + @Test + public void findings_carry_the_line_and_column_of_the_node() { + Finding f = LayoutAnalyzer.analyze("F.java", "class F {\n String s = \"a\\nb\";\n}").get(0); + assertEquals(2, f.line()); + assertEquals(14, f.column()); + } + + @Test + public void passes_a_generator_written_on_the_writer() { + String source = + """ + import com.metaobjects.generator.writer.JavaWriter; + + class Gen { + // Comments may say anything, including "\\n" and + // indented text: a comment is never a node. + /* + * a block comment, indented + */ + String render(Entity entity) { + JavaWriter w = new JavaWriter(); + String list = w.use("java.util.List"); + try (var b = w.block("class " + entity.name() + " {")) { + w.line("private final ", list, " names;"); + w.blank(); + w.text(\"\"\" + void check() { + return; + } + \"\"\"); + } + return w.toString(); + } + } + """; + assertEquals(List.of(), LayoutAnalyzer.analyze("Gen.java", source)); + } + + @Test + public void a_line_break_used_as_a_search_pattern_or_comparison_is_not_output() { + assertEquals(List.of(), kinds("String[] p = description.split(\"\\n\");")); + assertEquals(List.of(), kinds("if (body.contains(\"\\n\")) flag();")); + assertEquals(List.of(), kinds("String s = body.replace(\"\\r\\n\", \" \").replaceAll(\"\\n\", \" \");")); + assertEquals(List.of(), kinds("int at = body.indexOf(\" \");")); + assertEquals(List.of(), kinds("if (c == '\\n') flag();")); + assertEquals(List.of(), kinds("switch (c) { case \"\\n\" -> flag(); default -> {} }")); + assertEquals(List.of(), kinds("switch (ch) { case '\\n': flag(); break; default: break; }")); + assertEquals(List.of(), kinds("log.debug(\" Template Path: {}\", path);")); + } + + @Test + public void a_replacement_that_writes_a_line_break_is_still_output() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = body.replace(\";\", \";\\n\");")); + } + + @Test + public void single_spaces_joins_on_a_space_and_text_after_a_concatenation_are_not_layout() { + assertEquals(List.of(), kinds("String a = String.join(\", \", names); String b = left + \" \" + right; String c = \" \" + x;")); + } + + @Test + public void a_variable_shadowing_a_layout_constant_is_not_resolved_to_it() { + String source = "class F { String f(String SEP) { return String.join(SEP, rows); } static final String SEP = \",\\n\"; }"; + // The declaration is a finding; the join, whose SEP is the parameter, is not. + assertEquals(List.of(Kind.NEWLINE_LITERAL), LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList()); + } + + // ── 2. the scope rule ──────────────────────────────────────────────────────────────── + + @Test + public void scope_is_decided_by_rule() { + String[][] cases = { + {"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java", "true"}, + {"codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaCodeWriter.java", "true"}, + {"codegen-plantuml/src/main/java/com/metaobjects/generator/direct/plantuml/PlantUMLWriter.java", "true"}, + {"codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java", "false"}, + {"codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java", "false"}, + {"codegen-spring/src/test/java/com/metaobjects/generator/spring/Foo.java", "false"}, + {"codegen-spring/src/main/java/com/metaobjects/generator/spring/package-info.java", "false"}, + {"codegen-spring/src/main/resources/templates/x.java", "false"}, + {"metadata/src/main/java/com/metaobjects/Foo.java", "false"}, + {"codegen-spring/README.md", "false"}, + }; + for (String[] c : cases) assertEquals(c[0], Boolean.parseBoolean(c[1]), LayoutAnalyzer.isGeneratorSource(c[0])); + } + + // ── 3. the ratchet over the real modules ───────────────────────────────────────────────── + + /** {@code server/java/}: the tests run with the module as the working directory. */ + private static final Path JAVA = Path.of(System.getProperty("user.dir")).resolve("..").normalize(); + + private static final Path ALLOWLIST = Path.of(System.getProperty("user.dir"), "src/test/resources/layout-ratchet/allowlist.json"); + + /** The allowlist: {@code unconverted} and {@code exempt}, each a map from file to its written reason. */ + record Allowlist(Map unconverted, Map exempt) { + Map entries() { + Map all = new TreeMap<>(unconverted); + all.putAll(exempt); + return all; + } + } + + private static Allowlist readAllowlist(String json) { + Map raw = new Gson().fromJson(json, new TypeToken>() {}.getType()); + return new Allowlist(strings(raw.get("unconverted")), strings(raw.get("exempt"))); + } + + @SuppressWarnings("unchecked") + private static Map strings(Object o) { + return o == null ? new TreeMap<>() : new TreeMap<>((Map) o); + } + + private static final Allowlist allowlist; + private static final Map> findings = new TreeMap<>(); + + static { + try { + allowlist = readAllowlist(Files.readString(ALLOWLIST, StandardCharsets.UTF_8)); + for (String module : LayoutAnalyzer.SCANNED_MODULES) { + Path src = JAVA.resolve(module).resolve("src/main/java"); + try (Stream files = Files.walk(src)) { + for (Path f : files.filter(Files::isRegularFile).toList()) { + String rel = JAVA.relativize(f).toString().replace('\\', '/'); + if (LayoutAnalyzer.isGeneratorSource(rel)) { + findings.put(rel, LayoutAnalyzer.analyze(rel, Files.readString(f, StandardCharsets.UTF_8))); + } + } + } + } + // `-Dlayout.dump=` lists every file that types layout, to write or prune allowlist entries. + String dump = System.getProperty("layout.dump"); + if (dump != null) { + List rows = new ArrayList<>(); + findings.forEach((f, found) -> { if (!found.isEmpty()) rows.add(f + "\t" + found.size() + "\t" + found.stream().map(x -> x.kind().toString()).distinct().sorted().collect(Collectors.joining(","))); }); + Files.write(Path.of(dump), rows); + } + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Test + public void it_reads_every_scanned_module() { + for (String m : LayoutAnalyzer.SCANNED_MODULES) { + assertTrue(m, findings.keySet().stream().anyMatch(f -> f.startsWith(m + "/"))); + } + } + + @Test + public void no_generator_source_types_layout_unless_its_file_is_allowlisted() { + Map entries = allowlist.entries(); + List offenders = new ArrayList<>(); + findings.forEach( + (file, found) -> { + if (!found.isEmpty() && !entries.containsKey(file)) { + offenders.add(file + "\n" + found.stream().map(f -> " " + f).collect(Collectors.joining("\n"))); + } + }); + assertEquals( + "Write these lines through JavaWriter (generator/writer/) instead of typing line breaks or" + + " indentation. A file is never added to the allowlist: it only shrinks.", + List.of(), + offenders); + } + + @Test + public void every_allowlisted_file_still_needs_its_entry() { + List stale = new ArrayList<>(); + for (String file : allowlist.entries().keySet()) { + if (findings.getOrDefault(file, List.of()).isEmpty()) stale.add(file); + } + assertEquals("these files no longer type layout (or no longer exist): remove their allowlist entries", List.of(), stale); + } + + @Test + public void every_allowlisted_path_is_generator_source_that_exists() { + for (String file : allowlist.entries().keySet()) { + assertTrue(file + " is not in the ratchet's scope", LayoutAnalyzer.isGeneratorSource(file)); + assertTrue(file + " does not exist", Files.exists(JAVA.resolve(file))); + } + } + + @Test + public void every_entry_carries_a_written_reason() { + allowlist.entries().forEach((file, reason) -> assertTrue(file + " needs a reason", reason.length() > 40)); + } + + @Test + public void a_file_is_either_unconverted_or_exempt_never_both_and_each_list_is_sorted() { + for (String f : allowlist.unconverted().keySet()) assertFalse(f, allowlist.exempt().containsKey(f)); + for (Map list : List.of(allowlist.unconverted(), allowlist.exempt())) { + assertEquals(new ArrayList<>(new TreeMap<>(list).keySet()), new ArrayList<>(list.keySet())); + } + } + + /** The allowlist may only shrink. Compared with the copy at the merge base of every integration branch this checkout knows. */ + @Test + public void the_allowlist_only_shrinks() throws Exception { + List bases = mergeBaseAllowlists(); + assumeTrue("git or the integration refs are unavailable (an export or a shallow clone)", bases != null); + for (Allowlist base : bases) { + assertEquals( + "the allowlist grew since the merge base; convert the file to the writer instead", + List.of(), + growth(base, allowlist)); + } + } + + @Test + public void growth_is_an_added_entry_or_an_unconverted_file_relabelled_exempt_and_removal_is_not() { + Allowlist before = + new Allowlist(new TreeMap<>(Map.of("A.java", "r", "B.java", "r")), new TreeMap<>(Map.of("C.java", "r"))); + assertEquals(List.of(), growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r")), new TreeMap<>()))); + assertEquals( + List.of("added D.java"), + growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r", "D.java", "r")), new TreeMap<>(Map.of("C.java", "r"))))); + assertEquals( + List.of("relabelled B.java as exempt"), + growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r")), new TreeMap<>(Map.of("B.java", "r", "C.java", "r"))))); + } + + /** How {@code now} grew relative to {@code before}: entries that are new, and unconverted files relabelled exempt. */ + private static List growth(Allowlist before, Allowlist now) { + List out = new ArrayList<>(); + Map had = before.entries(); + for (String f : now.entries().keySet()) if (!had.containsKey(f)) out.add("added " + f); + for (String f : now.exempt().keySet()) if (before.unconverted().containsKey(f)) out.add("relabelled " + f + " as exempt"); + return out; + } + + private static String git(String... args) { + try { + List cmd = new ArrayList<>(List.of("git", "-C", JAVA.toString())); + cmd.addAll(List.of(args)); + Process p = new ProcessBuilder(cmd).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + String out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + return p.waitFor() == 0 ? out : null; + } catch (IOException | InterruptedException e) { + return null; + } + } + + /** The allowlist as it stood at the merge base of HEAD with each integration branch; null when git or those refs are unavailable. */ + private static List mergeBaseAllowlists() { + String refs = git("for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/main", "refs/remotes/origin/release/"); + if (refs == null || refs.isEmpty()) return null; + String top = git("rev-parse", "--show-toplevel"); + if (top == null) return null; + String rel = Path.of(top).relativize(ALLOWLIST).toString().replace('\\', '/'); + List out = new ArrayList<>(); + boolean reachable = false; + for (String ref : refs.split("\\s+")) { + String base = git("merge-base", "HEAD", ref); + if (base == null) continue; + reachable = true; + String text = git("show", base + ":" + rel); + if (text != null) out.add(readAllowlist(text)); + } + return reachable ? out : null; + } +} diff --git a/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json b/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json new file mode 100644 index 0000000000..1ad86f3d8c --- /dev/null +++ b/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json @@ -0,0 +1,35 @@ +{ + "$comment": "The layout ratchet's allowlist for the Java generators (ADR-0063). `unconverted`: generator source that still types its own layout; each entry names what it emits and the writer PR that converts it, and is removed when that PR 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: LayoutRatchetTest compares it with the copy at the branch's merge base.", + "unconverted": { + "codegen-base/src/main/java/com/metaobjects/generator/direct/FileDirectWriter.java": "Builds the FileIndentor with a hand-typed two-space indentation unit, the older indentor pipeline under the object code generators. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java": "Emits the generated entity Extractor class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaCodeGenerator.java": "Configures the older object code writer with a hand-typed four-space indentation unit. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java": "Emits the plain Java object class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/apidocs/JavaApiModelBuilder.java": "Emits the Java code samples shown in the generated API docs by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java": "Emits the shared enum class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/JUnitRequirementTestsGenerator.java": "Emits the JUnit requirement test classes by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java": "Emits the LLM trace helper class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java": "Emits the Spring controller by string concatenation with hand-typed line breaks and indentation. Converts with the Java controller and support class writer PR (W-JV-3).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java": "Emits the DTO records by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java": "Emits the filter allowlist class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java": "Emits the validator methods and import lines shared by the Spring generators by string concatenation with hand-typed line breaks and indentation. Converts with the Java controller and support class writer PR (W-JV-3).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java": "Emits the names constants class by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNaming.java": "Writes the package line of a generated file with a typed line break. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4), when that package line comes from JavaWriter.packageName().", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java": "Emits the output parser class by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java": "Emits the output prompt class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRecordBuilder.java": "Emits the record builder source for a DTO by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java": "Emits the render helper class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java": "Emits the report export class by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java": "Emits the repository interface by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java": "Emits the enum class for a string-valued enum field by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java": "Emits the value object record by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5)." + }, + "exempt": { + "codegen-base/src/main/java/com/metaobjects/generator/GeneratorIOException.java": "Builds the text of an exception message with typed line breaks. It is a diagnostic for the person running the build, not code an adopter edits.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/ai/MetaDataAIDocumentationGenerator.java": "Builds the one-paragraph configuration summary used in log output with typed line breaks. It is a diagnostic, not generated code.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/MetaDataHtmlDocumentationGenerator.java": "Builds the one-paragraph configuration summary used in log output with typed line breaks. It is a diagnostic, not generated code.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/MetaDataHtmlDocumentationWriter.java": "Emits the HTML metadata documentation page with its stylesheet. Documentation output is exempt from the writer conversion (ADR-0063; the docs and markdown emitters), because it is not code an adopter edits.", + "codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java": "Reads and writes the hash manifest, a line-based data file the tool owns and no adopter edits. It is not generated code.", + "codegen-plantuml/src/main/java/com/metaobjects/generator/direct/plantuml/PlantUMLWriter.java": "Emits PlantUML diagram text. A diagram is documentation output, exempt from the writer conversion (ADR-0063), and not code an adopter edits." + } +} diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java new file mode 100644 index 0000000000..0aa10abd07 --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java @@ -0,0 +1,99 @@ +package com.metaobjects.generator.spring; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * The REST surface of the Spring generators, pinned byte for byte (W-JV-2). + * + *

{@code SpringControllerGenerator}, {@code SpringRepositoryGenerator}, + * {@code SpringNamesGenerator} and {@code SpringReportExportGenerator} run over + * {@code golden/spring-rest-surface/input/meta.json}: entities with an enum, a decimal, a date, a + * to-one reference and a many-to-many through entity, a read-only projection and a served report. + * Every emitted file must equal its counterpart under {@code golden/spring-rest-surface/expected/}. + * + *

Why it exists: moving these generators onto the code writer (ADR-0063) changes how they lay + * text out, and until now the Spring module had byte-exact files for DTOs only. The expected files + * are the generators' output as they stood before any conversion. A conversion PR changes them on + * purpose, and its description lists what moved and why; a change nobody meant shows up here as a + * diff against a named file. + * + *

To rewrite the expected files after an intended change, run this test with + * {@code -Dgolden.update=true} and review the diff. + */ +public class SpringRestSurfaceGoldenTest extends SharedRegistryTestBase { + + private static final Path GOLDEN = Path.of("src/test/resources/golden/spring-rest-surface"); + private static final String UPDATE = "golden.update"; + + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + + private static Map filesUnder(Path root) throws IOException { + Map files = new TreeMap<>(); + if (!Files.isDirectory(root)) return files; + try (Stream walk = Files.walk(root)) { + for (Path p : walk.filter(Files::isRegularFile).toList()) { + files.put(root.relativize(p).toString().replace('\\', '/'), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return files; + } + + @Test + public void theRestSurfaceRegeneratesByteIdentical() throws Exception { + MetaDataLoader loader = + SpringTestFixtures.loadFixture( + tmp.newFolder().toPath(), + "restSurface", + Files.readString(GOLDEN.resolve("input/meta.json"), StandardCharsets.UTF_8)); + Path out = tmp.newFolder().toPath(); + Map args = new HashMap<>(); + args.put("outputDir", out.toString()); + for (var generator : + List.of( + new SpringControllerGenerator(), + new SpringRepositoryGenerator(), + new SpringNamesGenerator(), + new SpringReportExportGenerator())) { + generator.setArgs(args); + generator.execute(loader); + } + + Map actual = filesUnder(out); + if (Boolean.getBoolean(UPDATE)) { + Path expectedDir = GOLDEN.resolve("expected"); + if (Files.isDirectory(expectedDir)) { + try (Stream walk = Files.walk(expectedDir)) { + for (Path p : walk.sorted(java.util.Comparator.reverseOrder()).filter(Files::isRegularFile).toList()) Files.delete(p); + } + } + for (Map.Entry e : actual.entrySet()) { + Path target = expectedDir.resolve(e.getKey()); + Files.createDirectories(target.getParent()); + Files.writeString(target, e.getValue(), StandardCharsets.UTF_8); + } + } + + Map expected = filesUnder(GOLDEN.resolve("expected")); + assertFalse("the golden tree must not be empty", expected.isEmpty()); + assertEquals("the generated file set must match the golden tree", expected.keySet(), actual.keySet()); + for (Map.Entry e : expected.entrySet()) { + assertEquals(e.getKey() + " must be byte-identical to the golden file", e.getValue(), actual.get(e.getKey())); + } + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java new file mode 100644 index 0000000000..3500ca4ff0 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java @@ -0,0 +1,201 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Customer entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/customers/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/customers") +public class CustomerController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "name", "status", "balance", "createdAt"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** Components the server owns on create (primary key, @autoSet): a + * @NotNull on one of these describes the RESPONSE shape and must not + * reject a create body that legitimately omits it. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "name", "status", "balance", "createdAt"); + + private final CustomerRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public CustomerController(CustomerRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @org.springframework.web.bind.annotation.ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) + public ResponseEntity onUnreadableBody(org.springframework.http.converter.HttpMessageNotReadableException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + CustomerRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), CustomerFilterAllowlist.FIELDS, CustomerFilterAllowlist.OPS_BY_FIELD, CustomerFilterAllowlist.DECIMAL_FIELDS, CustomerFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) { + return ResponseEntity.badRequest().body(new ValidationIssues() + .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), "request body must be a JSON object").body()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + CustomerDto dto; + try { + dto = objectMapper.treeToValue(filled, CustomerDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new CustomerDto(null, dto.name(), dto.status(), dto.balance(), dto.createdAt()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + CustomerDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + CustomerPatch __patch = null; + Map __assigned; + try { + __patch = CustomerPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(CustomerDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + private static CustomerRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new CustomerRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java new file mode 100644 index 0000000000..fc608750c4 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java @@ -0,0 +1,43 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Customer. + */ +public abstract class CustomerNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Customer"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "customers"; + + public static final String BALANCE_FIELD = "balance"; + public static final String BALANCE_COLUMN = "balance"; + public static final String CREATED_AT_FIELD = "createdAt"; + public static final String CREATED_AT_COLUMN = "created_at"; + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String NAME_FIELD = "name"; + public static final String NAME_COLUMN = "name"; + public static final String STATUS_FIELD = "status"; + public static final String STATUS_COLUMN = "status"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("balance", BALANCE_COLUMN), + Map.entry("createdAt", CREATED_AT_COLUMN), + Map.entry("id", ID_COLUMN), + Map.entry("name", NAME_COLUMN), + Map.entry("status", STATUS_COLUMN) + ); + + protected CustomerNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java new file mode 100644 index 0000000000..2025e52e9f --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java @@ -0,0 +1,23 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching CustomerController delegates to this interface. + */ +public interface CustomerRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + CustomerDto create(CustomerDto dto); + Optional update(Long id, CustomerDto dto); + Optional patch(Long id, CustomerPatch patch); + boolean delete(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java new file mode 100644 index 0000000000..c26d55624d --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java @@ -0,0 +1,125 @@ +package acme.shop; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — READ-ONLY REST controller for the CustomerStatusTotals report. + * Implements the cross-port API contract: GET list; POST answers + * 405 {"error": "method_not_allowed"}. A report has no identity, so no item + * route is mounted. + * + *

Auth: these read endpoints are unauthenticated. Require authentication for this path + * in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/customer_status_totals/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/customer_status_totals") +public class CustomerStatusTotalsController { + + private static final Set SORT_ALLOWLIST = Set.of("status", "customers", "activeCustomers"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + private final CustomerStatusTotalsRepository repository; + + public CustomerStatusTotalsController(CustomerStatusTotalsRepository repository) { + this.repository = repository; + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) String limit, + @RequestParam(required = false) String offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + final int maxRows = 10000; + Integer requestedLimit = null; + if (limit != null) { + Long parsed = parseBound(limit, 1); + if (parsed == null) { + return ResponseEntity.badRequest().body(Map.of("error", "pagination.invalid_value", "param", "limit", "value", limit, "expected", "an integer from 1 to " + maxRows)); + } + if (parsed > maxRows) { + return ResponseEntity.badRequest().body(Map.of("error", "report_too_large", "maxRows", maxRows)); + } + requestedLimit = parsed.intValue(); + } + int actualOffset = 0; + if (offset != null) { + Long parsed = parseBound(offset, 0); + if (parsed == null) { + return ResponseEntity.badRequest().body(Map.of("error", "pagination.invalid_value", "param", "offset", "value", offset, "expected", "a non-negative integer (0 or more)")); + } + actualOffset = (int) Math.min(parsed, Integer.MAX_VALUE); + } + CustomerStatusTotalsRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), CustomerStatusTotalsFilterAllowlist.FIELDS, CustomerStatusTotalsFilterAllowlist.OPS_BY_FIELD, CustomerStatusTotalsFilterAllowlist.DECIMAL_FIELDS, CustomerStatusTotalsFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(requestedLimit != null ? requestedLimit : maxRows + 1, actualOffset, sortClause, filters); + if (requestedLimit == null && rows.size() > maxRows) { + return ResponseEntity.badRequest().body(Map.of("error", "report_too_large", "maxRows", maxRows)); + } + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + /** A page bound as an integer of at least {@code min}, or null when it is not one. */ + private static Long parseBound(String raw, long min) { + try { + long n = Long.parseLong(raw); + return n >= min ? n : null; + } catch (NumberFormatException e) { + return null; + } + } + + @PostMapping + public ResponseEntity create() { + return methodNotAllowed("POST"); + } + + private static ResponseEntity methodNotAllowed(String verb) { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(Map.of("error", "method_not_allowed", + "message", verb + " is not supported on a report (read-only).")); + } + + private static CustomerStatusTotalsRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new CustomerStatusTotalsRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java new file mode 100644 index 0000000000..544cb0a84b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java @@ -0,0 +1,41 @@ +package acme.shop; + +import java.util.List; + +/** + * GENERATED — the export of the CustomerStatusTotals report: its columns in + * derived-field order, each cell's wire form, and the CSV and XML bodies. The + * route reads {@link #MAX_ROWS}; the shared {@link ReportExportWriter} writes the bytes. + */ +public final class CustomerStatusTotalsExport { + + private CustomerStatusTotalsExport() {} + + /** The most rows one export answers; one more is 400 export_too_large. */ + public static final int MAX_ROWS = 100000; + + /** The XML root element and the report's name. */ + public static final String ROOT = "CustomerStatusTotals"; + + /** The derived fields, in order: the CSV header row and the XML element names. */ + public static final List FIELDS = List.of("status", "customers", "activeCustomers"); + + /** One row's cells in wire form: currency as integer minor units, a date as YYYY-MM-DD, + * a decimal as the wire setting writes it, a boolean as true/false, null as null. */ + public static List cells(CustomerStatusTotalsDto row) { + return List.of( + ReportExportWriter.text(row.status()), + ReportExportWriter.raw(row.customers()), + ReportExportWriter.raw(row.activeCustomers())); + } + + /** The rows as RFC 4180 CSV bytes (UTF-8). */ + public static byte[] csv(List rows) { + return ReportExportWriter.csv(FIELDS, rows.stream().map(CustomerStatusTotalsExport::cells).toList()); + } + + /** The rows as XML bytes (UTF-8, no declaration). */ + public static byte[] xml(List rows) { + return ReportExportWriter.xml(ROOT, FIELDS, rows.stream().map(CustomerStatusTotalsExport::cells).toList()); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java new file mode 100644 index 0000000000..beaaf623ef --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java @@ -0,0 +1,20 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching CustomerStatusTotalsController delegates to this interface. + * + *

READ-ONLY: CustomerStatusTotals is a report over a database view, so there is no write method to + * implement. Its controller answers every write verb with 405.

+ */ +public interface CustomerStatusTotalsRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java new file mode 100644 index 0000000000..106052f947 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java @@ -0,0 +1,206 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Order entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/orders/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/orders") +public class OrderController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "customerId", "total", "placedOn", "rush"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** Components the server owns on create (primary key, @autoSet): a + * @NotNull on one of these describes the RESPONSE shape and must not + * reject a create body that legitimately omits it. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "customerId", "total", "placedOn", "rush"); + + private final OrderRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public OrderController(OrderRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @org.springframework.web.bind.annotation.ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) + public ResponseEntity onUnreadableBody(org.springframework.http.converter.HttpMessageNotReadableException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderFilterAllowlist.FIELDS, OrderFilterAllowlist.OPS_BY_FIELD, OrderFilterAllowlist.DECIMAL_FIELDS, OrderFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) { + return ResponseEntity.badRequest().body(new ValidationIssues() + .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), "request body must be a JSON object").body()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + OrderDto dto; + try { + dto = objectMapper.treeToValue(filled, OrderDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new OrderDto(null, dto.customerId(), dto.total(), dto.placedOn(), dto.rush()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + OrderDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + OrderPatch __patch = null; + Map __assigned; + try { + __patch = OrderPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(OrderDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @GetMapping("/{id}/tags") + public ResponseEntity> findTags(@PathVariable Long id) { + return ResponseEntity.ok(repository.findTags(id)); + } + + private static OrderRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new OrderRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java new file mode 100644 index 0000000000..31f2280b21 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java @@ -0,0 +1,46 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Order. + */ +public abstract class OrderNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Order"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "orders"; + + public static final String CUSTOMER_ID_FIELD = "customerId"; + public static final String CUSTOMER_ID_COLUMN = "customer_id"; + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String PLACED_ON_FIELD = "placedOn"; + public static final String PLACED_ON_COLUMN = "placed_on"; + public static final String RUSH_FIELD = "rush"; + public static final String RUSH_COLUMN = "rush"; + public static final String TOTAL_FIELD = "total"; + public static final String TOTAL_COLUMN = "total"; + + public static final String IDENTITY_FK_CUSTOMER_TYPE = "identity"; + public static final String IDENTITY_FK_CUSTOMER_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_CUSTOMER_NAME = "fkCustomer"; + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("customerId", CUSTOMER_ID_COLUMN), + Map.entry("id", ID_COLUMN), + Map.entry("placedOn", PLACED_ON_COLUMN), + Map.entry("rush", RUSH_COLUMN), + Map.entry("total", TOTAL_COLUMN) + ); + + protected OrderNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java new file mode 100644 index 0000000000..11d577eb94 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java @@ -0,0 +1,31 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderController delegates to this interface. + */ +public interface OrderRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + OrderDto create(OrderDto dto); + Optional update(Long id, OrderDto dto); + Optional patch(Long id, OrderPatch patch); + boolean delete(Long id); + + /** M:N traversal: the Tag rows related to this Order through OrderTag. */ + List findTags(Long sourceId); + + /** Reverse nav: the Order rows whose customerId FK points at the given Customer id (single indexed query). */ + List findByCustomer(Long customerId); + /** Reverse nav (batched, anti-N+1): the Order rows whose customerId FK is IN the given Customer ids. */ + List findByCustomerIn(List customerIds); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java new file mode 100644 index 0000000000..90befd6bd0 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java @@ -0,0 +1,107 @@ +package acme.shop; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — READ-ONLY REST controller for the OrderSummary 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. Require authentication for this path + * in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/order_summaries/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/order_summaries") +public class OrderSummaryController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "total", "placedOn"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + private final OrderSummaryRepository repository; + + public OrderSummaryController(OrderSummaryRepository repository) { + this.repository = repository; + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderSummaryRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderSummaryFilterAllowlist.FIELDS, OrderSummaryFilterAllowlist.OPS_BY_FIELD, OrderSummaryFilterAllowlist.DECIMAL_FIELDS, OrderSummaryFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create() { + return methodNotAllowed("POST"); + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE }) + public ResponseEntity rejectItemWrite(@PathVariable Long id, HttpServletRequest request) { + return methodNotAllowed(request.getMethod()); + } + + private static ResponseEntity methodNotAllowed(String verb) { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(Map.of("error", "method_not_allowed", + "message", verb + " is not supported on a projection (read-only).")); + } + + private static OrderSummaryRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new OrderSummaryRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java new file mode 100644 index 0000000000..55f20993c1 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java @@ -0,0 +1,37 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for OrderSummary. + */ +public abstract class OrderSummaryNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "projection"; + public static final String NAME = "OrderSummary"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "view"; + public static final String SOURCE_PRIMARY_VIEW = "v_order_summary"; + + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String PLACED_ON_FIELD = "placedOn"; + public static final String PLACED_ON_COLUMN = "placed_on"; + public static final String TOTAL_FIELD = "total"; + public static final String TOTAL_COLUMN = "total"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("id", ID_COLUMN), + Map.entry("placedOn", PLACED_ON_COLUMN), + Map.entry("total", TOTAL_COLUMN) + ); + + protected OrderSummaryNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java new file mode 100644 index 0000000000..9412e6f4f9 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java @@ -0,0 +1,22 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderSummaryController delegates to this interface. + * + *

READ-ONLY: OrderSummary is a projection over a database view, so there is no write method to + * implement. Its controller answers every write verb with 405.

+ */ +public interface OrderSummaryRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java new file mode 100644 index 0000000000..0e1524b837 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java @@ -0,0 +1,200 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for OrderTag entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/order_tags/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/order_tags") +public class OrderTagController { + + private static final Set SORT_ALLOWLIST = Set.of("orderId", "tagId"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** Components the server owns on create (primary key, @autoSet): a + * @NotNull on one of these describes the RESPONSE shape and must not + * reject a create body that legitimately omits it. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("orderId", "tagId"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("orderId", "tagId"); + + private final OrderTagRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public OrderTagController(OrderTagRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @org.springframework.web.bind.annotation.ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) + public ResponseEntity onUnreadableBody(org.springframework.http.converter.HttpMessageNotReadableException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderTagRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderTagFilterAllowlist.FIELDS, OrderTagFilterAllowlist.OPS_BY_FIELD, OrderTagFilterAllowlist.DECIMAL_FIELDS, OrderTagFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) { + return ResponseEntity.badRequest().body(new ValidationIssues() + .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), "request body must be a JSON object").body()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + OrderTagDto dto; + try { + dto = objectMapper.treeToValue(filled, OrderTagDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + OrderTagDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + OrderTagPatch __patch = null; + Map __assigned; + try { + __patch = OrderTagPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(OrderTagDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + private static OrderTagRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new OrderTagRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java new file mode 100644 index 0000000000..b9c03857dc --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java @@ -0,0 +1,40 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for OrderTag. + */ +public abstract class OrderTagNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "OrderTag"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "order_tags"; + + public static final String ORDER_ID_FIELD = "orderId"; + public static final String ORDER_ID_COLUMN = "order_id"; + public static final String TAG_ID_FIELD = "tagId"; + public static final String TAG_ID_COLUMN = "tag_id"; + + public static final String IDENTITY_FK_ORDER_TYPE = "identity"; + public static final String IDENTITY_FK_ORDER_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_ORDER_NAME = "fkOrder"; + public static final String IDENTITY_FK_TAG_TYPE = "identity"; + public static final String IDENTITY_FK_TAG_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_TAG_NAME = "fkTag"; + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("orderId", ORDER_ID_COLUMN), + Map.entry("tagId", TAG_ID_COLUMN) + ); + + protected OrderTagNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java new file mode 100644 index 0000000000..931670c68b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java @@ -0,0 +1,33 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderTagController delegates to this interface. + */ +public interface OrderTagRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + OrderTagDto create(OrderTagDto dto); + Optional update(Long id, OrderTagDto dto); + Optional patch(Long id, OrderTagPatch patch); + boolean delete(Long id); + + /** Reverse nav: the OrderTag rows whose orderId FK points at the given Order id (single indexed query). */ + List findByOrder(Long orderId); + /** Reverse nav (batched, anti-N+1): the OrderTag rows whose orderId FK is IN the given Order ids. */ + List findByOrderIn(List orderIds); + + /** Reverse nav: the OrderTag rows whose tagId FK points at the given Tag id (single indexed query). */ + List findByTag(Long tagId); + /** Reverse nav (batched, anti-N+1): the OrderTag rows whose tagId FK is IN the given Tag ids. */ + List findByTagIn(List tagIds); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java new file mode 100644 index 0000000000..40be71de5b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java @@ -0,0 +1,199 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * GENERATED — the one writer every report export shares: CSV quoting, CRLF, the byte order + * mark constant, the formula-injection guard, and XML over the JDK's StAX writer. + * + *

The guard applies to string-valued cells only (a string, an enum symbol, a uri): a value + * starting with {@code =}, {@code +}, {@code -}, {@code @}, TAB or CR gets a leading + * {@code '}, then the cell is quoted if it holds a quote, comma, CR or LF. A number, a + * decimal, a date or a boolean is never guarded, so a negative number stays a number. + */ +public final class ReportExportWriter { + + private ReportExportWriter() {} + + /** Write a UTF-8 byte order mark before the CSV (Excel on Windows wants one). */ + public static final boolean EXPORT_CSV_BOM = false; + + /** Write a null field as an empty element with xsi:nil="true" (true) or as an empty element (false). */ + public static final boolean EXPORT_XML_NIL = false; + + /** The project's wire.decimals: the canonical string (true, "string") or as Jackson writes a + * BigDecimal number (false, "native"), so a decimal cell matches the list route. */ + public static final boolean DECIMALS_AS_STRING = false; + + private static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; + + private static final ObjectMapper JSON = new ObjectMapper() + .findAndRegisterModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + /** One cell in wire form: its text, or null for a null; {@code guarded} marks a string-valued cell. */ + public static final class Cell { + private final String text; + private final boolean guarded; + + private Cell(String text, boolean guarded) { + this.text = text; + this.guarded = guarded; + } + + public String text() { + return text; + } + + public boolean guarded() { + return guarded; + } + } + + private static final Cell NULL = new Cell(null, false); + + /** A string-valued cell (string, enum symbol, uri): subject to the formula-injection guard. */ + public static Cell text(Object value) { + return value == null ? NULL : new Cell(String.valueOf(value), true); + } + + /** A cell that is never guarded (number, date, time, timestamp, uuid, boolean, currency). + * A time and a zone-less timestamp keep their seconds, as Jackson's JSR-310 serializers write them. */ + public static Cell raw(Object value) { + if (value == null) return NULL; + if (value instanceof LocalTime) { + return new Cell(((LocalTime) value).format(DateTimeFormatter.ISO_LOCAL_TIME), false); + } + if (value instanceof LocalDateTime) { + return new Cell(((LocalDateTime) value).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), false); + } + return new Cell(String.valueOf(value), false); + } + + /** A decimal as the wire setting writes it: under "string" canonical plain notation (no + * exponent, no trailing fraction zeros, zero as 0), under "native" as Jackson writes it. */ + public static Cell decimal(BigDecimal value) { + if (value == null) return NULL; + if (!DECIMALS_AS_STRING) return new Cell(value.toString(), false); + return new Cell(value.signum() == 0 ? "0" : value.stripTrailingZeros().toPlainString(), false); + } + + /** An array or a map, as compact JSON text. */ + public static Cell json(Object value) { + if (value == null) return NULL; + try { + return new Cell(JSON.writeValueAsString(value), false); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new IllegalStateException("cannot write a report cell as JSON: " + e.getMessage(), e); + } + } + + // ----------------------------------------------------------------------- + // CSV + // ----------------------------------------------------------------------- + + /** RFC 4180 CSV: a header row, then one record per row, CRLF after every record. */ + public static byte[] csv(List names, List> rows) { + StringBuilder out = new StringBuilder(); + if (EXPORT_CSV_BOM) out.append('\uFEFF'); + for (int i = 0; i < names.size(); i++) { + if (i > 0) out.append(','); + out.append(quote(names.get(i))); + } + out.append("\r\n"); + for (List row : rows) { + for (int i = 0; i < row.size(); i++) { + if (i > 0) out.append(','); + out.append(csvCell(row.get(i))); + } + out.append("\r\n"); + } + return out.toString().getBytes(StandardCharsets.UTF_8); + } + + /** One cell: null is empty, a guarded string is prefixed with an apostrophe when it starts + * like a formula, then the text is quoted when it needs to be. */ + static String csvCell(Cell cell) { + String value = cell.text(); + if (value == null) return ""; + if (cell.guarded() && !value.isEmpty()) { + char first = value.charAt(0); + if (first == '=' || first == '+' || first == '-' || first == '@' || first == '\t' || first == '\r') { + value = "'" + value; + } + } + return quote(value); + } + + private static String quote(String value) { + boolean needs = false; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"' || c == ',' || c == '\r' || c == '\n') { + needs = true; + break; + } + } + return needs ? "\"" + value.replace("\"", "\"\"") + "\"" : value; + } + + // ----------------------------------------------------------------------- + // XML + // ----------------------------------------------------------------------- + + /** {@code value......}: UTF-8, no declaration, no indentation. */ + public static byte[] xml(String root, List names, List> rows) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try { + XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(bytes, "UTF-8"); + w.writeStartElement(root); + if (EXPORT_XML_NIL) w.writeNamespace("xsi", XSI_NS); + for (List row : rows) { + w.writeStartElement("row"); + for (int i = 0; i < names.size(); i++) { + String value = row.get(i).text(); + if (value == null) { + w.writeEmptyElement(names.get(i)); + if (EXPORT_XML_NIL) w.writeAttribute("xsi", XSI_NS, "nil", "true"); + } else { + w.writeStartElement(names.get(i)); + w.writeCharacters(xmlText(value)); + w.writeEndElement(); + } + } + w.writeEndElement(); + } + w.writeEndElement(); + w.close(); + } catch (XMLStreamException e) { + throw new IllegalStateException("cannot write the report as XML: " + e.getMessage(), e); + } + return bytes.toByteArray(); + } + + /** A character XML 1.0 cannot hold becomes U+FFFD; the writer escapes {@code & < >}. */ + private static String xmlText(String value) { + StringBuilder out = null; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + boolean ok = c == '\t' || c == '\n' || c == '\r' || (c >= 0x20 && c <= 0xD7FF) + || (c >= 0xE000 && c <= 0xFFFD) || Character.isSurrogate(c); + if (!ok && out == null) { + out = new StringBuilder(value.length()).append(value, 0, i); + } + if (out != null) out.append(ok ? c : '\uFFFD'); + } + return out == null ? value : out.toString(); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java new file mode 100644 index 0000000000..104e4aa139 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java @@ -0,0 +1,201 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Tag entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/tags/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/tags") +public class TagController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "label"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** Components the server owns on create (primary key, @autoSet): a + * @NotNull on one of these describes the RESPONSE shape and must not + * reject a create body that legitimately omits it. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "label"); + + private final TagRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public TagController(TagRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @org.springframework.web.bind.annotation.ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) + public ResponseEntity onUnreadableBody(org.springframework.http.converter.HttpMessageNotReadableException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + TagRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), TagFilterAllowlist.FIELDS, TagFilterAllowlist.OPS_BY_FIELD, TagFilterAllowlist.DECIMAL_FIELDS, TagFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) { + return ResponseEntity.badRequest().body(new ValidationIssues() + .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), "request body must be a JSON object").body()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + TagDto dto; + try { + dto = objectMapper.treeToValue(filled, TagDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new TagDto(null, dto.label()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + TagDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + TagPatch __patch = null; + Map __assigned; + try { + __patch = TagPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(TagDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + ConstraintErrors.Failure failure = ConstraintErrors.classify(e); + if (failure == null) throw e; + return ResponseEntity.status(failure.status()) + .body(Map.of("error", failure.error(), "constraint", failure.constraint())); + } + } + + private static TagRepository.SortClause parseSort(String raw) { + String[] parts = raw.split(":", 2); + if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null; + String dir = parts.length == 2 ? parts[1].toLowerCase() + : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc"); + if (!dir.equals("asc") && !dir.equals("desc")) return null; + return new TagRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java new file mode 100644 index 0000000000..69ca37159e --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java @@ -0,0 +1,34 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Tag. + */ +public abstract class TagNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Tag"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "tags"; + + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String LABEL_FIELD = "label"; + public static final String LABEL_COLUMN = "label"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("id", ID_COLUMN), + Map.entry("label", LABEL_COLUMN) + ); + + protected TagNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java new file mode 100644 index 0000000000..698b8a2dd1 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java @@ -0,0 +1,23 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching TagController delegates to this interface. + */ +public interface TagRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + TagDto create(TagDto dto); + Optional update(Long id, TagDto dto); + Optional patch(Long id, TagPatch patch); + boolean delete(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json new file mode 100644 index 0000000000..3e3c1f6c3d --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json @@ -0,0 +1,74 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { "object.entity": { + "name": "Customer", + "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@required": true, "@maxLength": 80 } }, + { "field.enum": { "name": "status", "@required": true, "@values": ["ACTIVE", "SUSPENDED"] } }, + { "field.decimal": { "name": "balance", "@precision": 12, "@scale": 2 } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, + { "segment.filter": { "name": "active", "@filter": { "status": "ACTIVE" } } }, + { "dimension.attribute": { "name": "status", "@of": "Customer.status" } }, + { "measure.aggregate": { "name": "customers", "@agg": "count", "@of": "Customer.id" } }, + { "measure.aggregate": { "name": "activeCustomers", "@agg": "count", "@of": "Customer.id", "@segment": "active" } } + ] + }}, + { "object.entity": { + "name": "Order", + "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "customerId", "@required": true } }, + { "field.decimal": { "name": "total", "@required": true, "@precision": 12, "@scale": 2 } }, + { "field.date": { "name": "placedOn", "@required": true } }, + { "field.boolean": { "name": "rush" } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "OrderTag" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { "name": "fkCustomer", "@fields": "customerId", "@references": "Customer" } } + ] + }}, + { "object.entity": { + "name": "Tag", + "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "label", "@required": true, "@maxLength": 40 } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } + ] + }}, + { "object.entity": { + "name": "OrderTag", + "children": [ + { "source.rdb": { "@table": "order_tags" } }, + { "field.long": { "name": "orderId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "name": "pk", "@fields": ["orderId", "tagId"] } }, + { "identity.reference": { "name": "fkOrder", "@fields": "orderId", "@references": "Order" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ] + }}, + { "object.projection": { + "name": "OrderSummary", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_order_summary" } }, + { "field.long": { "name": "id", "extends": "Order.id", "@filterable": true, "@sortable": true } }, + { "field.decimal": { "name": "total", "extends": "Order.total", "@filterable": true, "@sortable": true } }, + { "field.date": { "name": "placedOn", "extends": "Order.placedOn", "@filterable": true, "@sortable": true } }, + { "identity.primary": { "name": "pk", "extends": "Order.pk" } } + ] + }}, + { "object.report": { + "name": "CustomerStatusTotals", + "@from": "Customer", + "@dimensions": ["status"], + "@measures": ["customers", "activeCustomers"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_customer_status_totals" } } ] + }} + ] + } +} 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/server/rust/metaobjects/src/config.rs b/server/rust/metaobjects/src/config.rs index 82d01149dd..054e5e86dd 100644 --- a/server/rust/metaobjects/src/config.rs +++ b/server/rust/metaobjects/src/config.rs @@ -65,6 +65,7 @@ pub const ALLOW_TOKENS: &[&str] = &[ const MIGRATE_DIALECTS: &[&str] = &["sqlite", "postgres", "d1"]; const MIGRATE_FORMATS: &[&str] = &["default", "flyway"]; const MIGRATE_ON_AMBIGUOUS: &[&str] = &["abort", "rename", "drop-add"]; +const MIGRATE_FOREIGN_KEY_TARGETS: &[&str] = &["refuse", "warn"]; macro_rules! string_enum { ($(#[$m:meta])* $name:ident { $($var:ident => $s:literal),+ $(,)? }) => { @@ -249,6 +250,9 @@ pub struct MigrateConfig { /// `migrate.checks` was present (possibly empty). pub checks_present: bool, pub foreign_key_indexes: Option, + /// `migrate.foreignKeyTargets`: `refuse` (the default) or `warn`. Validated and kept; the + /// foreign-key target check is the TypeScript migrate engine's, so nothing here reads it. + pub foreign_key_targets: Option, } /// One declared metadata dependency (FR-023). Parsed and validated only. @@ -724,6 +728,7 @@ fn parse_migrate(v: &Value, issues: &mut Issues) -> Option { "conventions", "checks", "foreignKeyIndexes", + "foreignKeyTargets", ]; let o = strict_object(v, "migrate", KEYS, issues)?; let s = |key: &str, issues: &mut Issues| { @@ -802,6 +807,15 @@ fn parse_migrate(v: &Value, issues: &mut Issues) -> Option { m.foreign_key_indexes = o .get("foreignKeyIndexes") .and_then(|v| bool_of(v, "migrate.foreignKeyIndexes", issues)); + m.foreign_key_targets = o.get("foreignKeyTargets").and_then(|v| { + enum_of( + v, + "migrate.foreignKeyTargets", + MIGRATE_FOREIGN_KEY_TARGETS, + None, + issues, + ) + }); Some(m) } diff --git a/server/rust/metaobjects/tests/config_reader.rs b/server/rust/metaobjects/tests/config_reader.rs index 2d64c54753..5639df357e 100644 --- a/server/rust/metaobjects/tests/config_reader.rs +++ b/server/rust/metaobjects/tests/config_reader.rs @@ -416,6 +416,20 @@ fn migrate_verify_requirements_scope_and_csharp_are_kept() { assert_eq!(c.csharp.unwrap().providers.unwrap()[0].type_name, "P.Prov"); } +#[test] +fn migrate_foreign_key_targets_is_refuse_or_warn() { + let read = |v: serde_json::Value| { + parse_config( + &json!({"schema_version": 1, "migrate": {"foreignKeyTargets": v}}), + "c.json", + &NamingRegistry::builtin(), + ) + }; + let m = read(json!("warn")).unwrap().config.migrate.unwrap(); + assert_eq!(m.foreign_key_targets.as_deref(), Some("warn")); + assert!(read(json!("ignore")).is_err()); +} + #[test] fn dependencies_are_validated_and_names_must_be_unique() { let n = NamingRegistry::builtin(); diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index 0487342c55..30328e7c5f 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -12,7 +12,8 @@ The MetaObjects CLI — scaffolds `metaobjects/` + `.metaobjects/`, runs codegen bun add -D @metaobjectsdev/cli ``` -The SQLite/Turso driver (`@libsql/kysely-libsql`) ships as a direct dependency — `meta migrate` against a `sqlite`/`libsql` URL works out of the box. Postgres remains an optional peer (install only if you target Postgres): +The SQLite/Turso driver (`@libsql/kysely-libsql`) is an optional peer, because it carries a native binary per platform and libc: `meta init` adds it to a SQLite project's `package.json` (run your package manager's install afterwards), and a project that skipped `init` adds it itself. Without it, `meta migrate` against a `sqlite`/`libsql` URL stops with the install command for your package manager. Postgres is an optional peer too (install only if you target Postgres): +- SQLite on Node: `bun add -D @libsql/kysely-libsql` - Postgres: `bun add -D pg` If a required driver is ever missing, the CLI prints an install command matching your project's package manager (npm / pnpm / yarn / bun, detected from the lockfile). @@ -28,7 +29,7 @@ bun run build:binary # → dist/meta (compiled for the build host's OS/ar ./dist/meta --help ``` -The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — codegen formats through the Node WebAssembly backend (`@biomejs/wasm-nodejs`), and the native Biome binary is not installed with the CLI. +The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — the owned-copy comparison uses the Node WebAssembly backend (`@biomejs/wasm-nodejs`), generation runs no formatter, and the native Biome binary is not installed with the CLI. ### Cross-compiling for other platforms @@ -44,7 +45,7 @@ bun build ./bin/meta.ts --compile --target=bun-windows-x64 --outfile dist/meta-w ### SQLite driver inside the binary -The standalone binary uses Bun's built-in **`bun:sqlite`** for the `sqlite` dialect (it ships inside the embedded Bun runtime). The npm/Node distribution uses the bundled `@libsql/kysely-libsql` dependency. This is automatic — the same `--db file:./app.db --dialect sqlite` flags work in both. (Postgres in the standalone binary still requires the `pg` peer to be resolvable, because `pg` is a native module that `--compile` cannot embed; sqlite is the fully self-contained path.) +The standalone binary uses Bun's built-in **`bun:sqlite`** for the `sqlite` dialect (it ships inside the embedded Bun runtime). The npm/Node distribution uses the `@libsql/kysely-libsql` driver your project declares. This is automatic — the same `--db file:./app.db --dialect sqlite` flags work in both. (Postgres in the standalone binary still requires the `pg` peer to be resolvable, because `pg` is a native module that `--compile` cannot embed; sqlite is the fully self-contained path.) Run schema ops from the compiled binary: @@ -109,7 +110,7 @@ Running `meta` with no arguments prints a concise status line (whether a `metaob Scaffolds `metaobjects/` (visible entity declarations, with a placeholder `meta.common.json`), `.metaobjects/` (hidden tool state: `config.json`, the always-on `AGENTS.md`, `.gitignore`, `.gen-state/`), the `metaobjects-*` skills under `.claude/skills/` (or `--skills-dir`), a root `AGENTS.md` / `CLAUDE.md` import of the always-on file, an **empty** `codegen/generators/` plus its `tsconfig.codegen.json`, and `metaobjects.config.ts` at the repo root. The scaffolded config carries `outputLayout: "package"` — one directory per metadata package, so two objects with one name in two packages are two files. The engine default stays `flat`; delete the line (or set `"flat"`) for the old layout. -**It copies no generators and declares no dependencies.** Codegen is opt-in (ADR-0034 Amendment 2): the scaffolded config carries `generators: []` and a comment pointing at the catalog. `meta gen --list --probe` shows what each generator would emit for your model, with the import line that runs it as shipped; `meta gen --list --format json` adds what to install (`install.dev`, `install.runtime`) and the config keys each generator reads (`configKeys`), which the text listing does not print. Import a generator from its package to use it unchanged; `meta eject ...` copies the ones you want to change into `codegen/generators/` — **yours to edit** — and prints the import line to swap in, the entry to add, the install command and any config keys those generators read. `meta gen` runs whatever `generators: [...]` holds: the package's generator where you imported it, your copy where you ejected it. +**It copies no generators.** It declares one dependency, the SQLite driver, and only in a SQLite project (see [Install](#install)). Codegen is opt-in (ADR-0034 Amendment 2): the scaffolded config carries `generators: []` and a comment pointing at the catalog. `meta gen --list --probe` shows what each generator would emit for your model, with the import line that runs it as shipped; `meta gen --list --format json` adds what to install (`install.dev`, `install.runtime`) and the config keys each generator reads (`configKeys`), which the text listing does not print. Import a generator from its package to use it unchanged; `meta eject ...` copies the ones you want to change into `codegen/generators/` — **yours to edit** — and prints the import line to swap in, the entry to add, the install command and any config keys those generators read. `meta gen` runs whatever `generators: [...]` holds: the package's generator where you imported it, your copy where you ejected it. Flags: - `--force` — overwrite scaffold files (memory records preserved) diff --git a/server/typescript/packages/cli/package.json b/server/typescript/packages/cli/package.json index 4664ba7cd7..5686d4a0a0 100644 --- a/server/typescript/packages/cli/package.json +++ b/server/typescript/packages/cli/package.json @@ -50,7 +50,6 @@ "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", - "@libsql/kysely-libsql": "^0.4.0", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/codegen-ts-react": "workspace:*", "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", @@ -64,16 +63,21 @@ "jiti": "^2.4.0" }, "peerDependencies": { + "@libsql/kysely-libsql": ">=0.4.0 <0.5.0", "kysely": ">=0.27.0 <0.30.0", "pg": ">=8.0.0 <9.0.0" }, "peerDependenciesMeta": { + "@libsql/kysely-libsql": { + "optional": true + }, "pg": { "optional": true } }, "devDependencies": { "@libsql/client": "^0.14.0", + "@libsql/kysely-libsql": "^0.4.1", "@metaobjectsdev/test-generators": "workspace:*", "@types/node": "^22.0.0", "@types/pg": "^8.0.0", diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index 8c6a638cce..29e51fe13a 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -16,6 +16,8 @@ import { currentContentHash } from "../lib/agent-context-staleness.js"; import { findWranglerConfig, parseWranglerConfig } from "@metaobjectsdev/migrate-ts"; import { DEFAULT_DOCS_DIR } from "@metaobjectsdev/codegen-ts"; import { describeError } from "../lib/error-text.js"; +import { ownPeerRange } from "../lib/install-set.js"; +import { declaredDependencyNames, type PackageManifest } from "../lib/package-manifest.js"; import { SUBTYPE_ROOT, TYPE_METADATA, TYPE_SUBTYPE_SEPARATOR } from "@metaobjectsdev/metadata/constants"; import { docsRefForVersion } from "@metaobjectsdev/metadata"; @@ -832,7 +834,7 @@ export async function init(opts: InitOptions): Promise { result.preserved.push(".gitignore"); } - await prepareManifestForScaffold(opts.cwd, result); + await prepareManifestForScaffold(opts.cwd, result, resolveInitDialect(opts)); return result; } @@ -859,7 +861,7 @@ export async function init(opts: InitOptions): Promise { * accreted a second, and the second silently inherited the first's early returns. The * declarations are unconditional on a readable manifest — see the comment at that point. */ -async function prepareManifestForScaffold(cwd: string, result: InitResult): Promise { +async function prepareManifestForScaffold(cwd: string, result: InitResult, dialect: InitDialect): Promise { const pkgPath = join(cwd, "package.json"); if (!(await fileExists(pkgPath))) { // No package.json at all: say what is needed rather than inventing a manifest @@ -929,22 +931,31 @@ async function prepareManifestForScaffold(cwd: string, result: InitResult): Prom } } - // NO DEPENDENCIES ARE ADDED. `meta init` used to declare five packages here — - // codegen-ts and metadata for the generators it copied, drizzle-orm / zod / fastify - // for the code those generators would write — and every one of them was a - // consequence of the scaffold WIRING a suite. It wires nothing now, so declaring - // anything would be declaring a dependency on code this project may never generate. + // THE DATABASE DRIVER IS THE ONE DEPENDENCY INIT DECLARES. It used to declare five packages, + // codegen-ts and metadata for the generators it copied and drizzle-orm / zod / fastify for the + // code those generators would write, and every one of them was a consequence of the scaffold + // WIRING a suite. It wires nothing now, so those stay out: the need moved to the moment a + // generator is chosen, where `meta eject ...` reports the exact install set for what you + // took (lib/install-set.ts) and `meta gen --list --format json` carries it per entry. // - // The need did not vanish, it MOVED to the moment a generator is chosen: - // `meta eject ...` reports the exact install set for what you took, with - // third-party ranges read from the runtime package's own peerDependencies (see - // lib/install-set.ts), and `meta gen --list --format json` carries the same set per - // entry before you commit to anything. - if (moduleSystemNote !== undefined) { + // A driver is different: it belongs to the DATABASE the project named, not to a generator, and + // `meta migrate` and `meta verify --db` need it before any generator exists. SQLite's driver + // (libSQL, with a native binary per platform and libc) is not installed with the CLI, so a + // sqlite project declares it here, at the range the CLI was tested against. Postgres, D1 and + // MySQL have no driver of this kind to add: `pg` is the project's own, and D1 goes through + // wrangler. + const driverAdded = dialect === "sqlite" ? declareSqliteDriver(pkg) : false; + if (driverAdded) { + result.warnings.push( + `package.json: added ${SQLITE_DRIVER} to dependencies, the driver \`meta migrate\` and \`meta verify --db\` use for SQLite. ` + + "Run your package manager's install to fetch it.", + ); + } + if (moduleSystemNote !== undefined || driverAdded) { // Preserve the file's existing indentation rather than reformatting someone's manifest. const indent = /\n(\s+)"/.exec(raw)?.[1] ?? " "; await writeFile(pkgPath, `${JSON.stringify(pkg, null, indent)}\n`, "utf8"); - result.warnings.push(moduleSystemNote); + if (moduleSystemNote !== undefined) result.warnings.push(moduleSystemNote); } } @@ -953,6 +964,21 @@ async function prepareManifestForScaffold(cwd: string, result: InitResult): Prom +/** The SQLite driver `meta migrate` loads on Node (under Bun the built-in `bun:sqlite` is used). */ +const SQLITE_DRIVER = "@libsql/kysely-libsql"; + +/** Declare the SQLite driver unless the manifest already does, in any dependency field. + * True when the manifest changed. */ +function declareSqliteDriver(pkg: Record): boolean { + if (declaredDependencyNames(pkg as PackageManifest).has(SQLITE_DRIVER)) return false; + const range = ownPeerRange(SQLITE_DRIVER); + const deps = (pkg.dependencies ?? {}) as Record; + // Without a readable range the driver is still declared, at any version, rather than not at all. + deps[SQLITE_DRIVER] = range ?? "*"; + pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b))); + return true; +} + /** True when the project has hand-written CommonJS at the root (excluding tooling dirs). */ async function hasCommonJsSources(cwd: string): Promise { const SKIP = new Set(["node_modules", ".git", "dist", "build", ".metaobjects", "codegen"]); diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 35f378714f..5551368f79 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -384,6 +384,17 @@ function refuseEngineError(err: Error, hint: string, fmt: OutputFormat): number return 1; } +/** + * The refusal for a foreign key onto a non-unique target. A text run drops every hint, and this + * one carries the off switch (`migrate.foreignKeyTargets`), which nothing else would tell a person + * whose database already holds the unique index by hand, so it is printed for text runs too. + */ +function refuseFkTargetError(err: Error, fmt: OutputFormat): number { + const rc = refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); + if (fmt === "text") log.error(`migrate: ${FK_TARGET_NOT_UNIQUE_HINT}`); + return rc; +} + const SCHEMA_CONVENTIONS_HINT = "set migrate.conventions in .metaobjects/config.json to one of the presets, or supply your own conventions from metaobjects.config.ts"; @@ -413,7 +424,8 @@ const DUPLICATE_SQL_NAME_HINT = const CHECK_NAME_HINT = "give each constraint on a table its own @constraintName, at most 63 bytes"; const FK_TARGET_NOT_UNIQUE_HINT = - "declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"; + "declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key; " + + "if the database already holds a unique index there that the metadata does not declare, set migrate.foreignKeyTargets to \"warn\" in .metaobjects/config.json"; const DECLARED_RENAME_HINT = "fix or remove the --rename-table / --rename-column flag; a table's name is its name in the metadata (the new name when it is renamed too)"; @@ -883,7 +895,7 @@ export async function migrateCommand( const expected = scoped.snapshot; logOutOfScope(scoped.outOfScope, scoped.importedOutOfScope ?? [], fmt); warnUngovernedFkTargets(scoped.ungovernedFkTargetViolations); - warnUnenforcedFkTargets("migrate", scoped.unenforcedFkTargetViolations); + warnUnenforcedFkTargets("migrate", scoped.unenforcedFkTargetViolations, scoped.fkTargetsAllowed !== undefined); let actual; try { actual = await introspect(kysely.db, kysely.dialect); @@ -1220,7 +1232,7 @@ export async function migrateCommand( // A metadata defect too: a declared CHECK name that duplicates another constraint or is too long. if (isInvalidCheckNameError(err)) return refuseEngineError(err, CHECK_NAME_HINT, fmt); // A metadata defect too: a foreign key whose target columns are not a unique key there. - if (isFkTargetNotUniqueError(err)) return refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); + if (isFkTargetNotUniqueError(err)) return refuseFkTargetError(err, fmt); // A metadata defect too: an enum member longer than the project's enums.maxLength. if (isEnumLengthRefusal(err)) return refuseEngineError(err, ENUM_LENGTH_HINT, fmt); // Unexpected error: emit structured error on stdout in the active format, then exit 1. @@ -1661,6 +1673,8 @@ export async function runOfflineGenerate( // for an unscoped run. const { diff: diffResult, nextSnapshot, expected: governedExpected } = plan; logOutOfScope(plan.outOfScope, plan.importedOutOfScope ?? [], fmt); + warnUngovernedFkTargets(plan.ungovernedFkTargetViolations); + warnUnenforcedFkTargets("migrate", plan.unenforcedFkTargetViolations, plan.fkTargetsAllowed !== undefined); const offlineNotes = viewRecreateNotes(diffResult.changes); // Which comparison ran (every Postgres run says so): this one never reads the database, so @@ -1907,7 +1921,7 @@ async function runD1Migrate( const expected = scoped.snapshot; logOutOfScope(scoped.outOfScope, scoped.importedOutOfScope ?? [], fmt); warnUngovernedFkTargets(scoped.ungovernedFkTargetViolations); - warnUnenforcedFkTargets("migrate", scoped.unenforcedFkTargetViolations); + warnUnenforcedFkTargets("migrate", scoped.unenforcedFkTargetViolations, scoped.fkTargetsAllowed !== undefined); let actual; try { actual = await introspectD1({ diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index e4c7a35c46..4c0c6ed8ca 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -1525,7 +1525,7 @@ export async function verifyCommand( return 1; } - warnUnenforcedFkTargets("verify", driftResult.unenforcedFkTargetViolations); + warnUnenforcedFkTargets("verify", driftResult.unenforcedFkTargetViolations, driftResult.fkTargetsAllowed !== undefined); if (driftResult.exprCanonPath !== undefined) { say(describeExprCanonPath(driftResult.exprCanonPath, driftResult.shadowUnavailable)); @@ -2442,5 +2442,6 @@ function buildVerifyPayload(input: { function refuseFkTarget(err: Error): number { log.error(`verify: ${err.message}`); log.error("verify: declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"); + log.error("verify: if the database already holds a unique index there that the metadata does not declare, set migrate.foreignKeyTargets to \"warn\" in .metaobjects/config.json"); return 1; } diff --git a/server/typescript/packages/cli/src/lib/fk-target-warning.ts b/server/typescript/packages/cli/src/lib/fk-target-warning.ts index 058397b236..b2de2b115a 100644 --- a/server/typescript/packages/cli/src/lib/fk-target-warning.ts +++ b/server/typescript/packages/cli/src/lib/fk-target-warning.ts @@ -6,8 +6,14 @@ import { log } from "./log.js"; * uniqueness when the table is created: reported, not refused. `prefix` is the command name that * leads each line (`migrate`, `verify`). */ -export function warnUnenforcedFkTargets(prefix: string, violations: readonly FkTargetViolation[] | undefined): void { +export function warnUnenforcedFkTargets( + prefix: string, + violations: readonly FkTargetViolation[] | undefined, + allowedBySetting = false, +): void { if (violations === undefined || violations.length === 0) return; log.warn(`${prefix}: ${new FkTargetNotUniqueError([...violations]).message}`); - log.warn(`${prefix}: SQLite creates the table anyway and checks foreign keys only with PRAGMA foreign_keys on, so nothing is refused; a write with it on fails with "foreign key mismatch".`); + log.warn(allowedBySetting + ? `${prefix}: migrate.foreignKeyTargets is "warn", so nothing is refused. The database decides: Postgres refuses the foreign key when it is applied unless a unique index it holds already covers the target, and a SQLite write with PRAGMA foreign_keys on fails with "foreign key mismatch". Declare the unique key on the target to make this go away.` + : `${prefix}: SQLite creates the table anyway and checks foreign keys only with PRAGMA foreign_keys on, so nothing is refused; a write with it on fails with "foreign key mismatch".`); } diff --git a/server/typescript/packages/cli/src/lib/install-set.ts b/server/typescript/packages/cli/src/lib/install-set.ts index c6252f0cbc..5f7c810cfa 100644 --- a/server/typescript/packages/cli/src/lib/install-set.ts +++ b/server/typescript/packages/cli/src/lib/install-set.ts @@ -20,6 +20,7 @@ import { createRequire } from "node:module"; import { existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { HTTP_RUNTIME_PACKAGE, type GeneratorRegistryEntry } from "@metaobjectsdev/codegen-ts"; import { cliVersion } from "./version.js"; import { packageOf } from "./catalog.js"; @@ -50,6 +51,30 @@ export function dependencyRangesOf(packageName: string): Record return manifestRangesOf(packageName, "dependencies"); } +/** + * A peer range the CLI itself declares, or `undefined` if it cannot be read. `meta init` writes + * the SQLite driver into a new project with it, so the range an adopter installs is the one this + * CLI was tested against and never a second copy kept here. + */ +export function ownPeerRange(name: string): string | undefined { + try { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let hops = 0; hops < 8; hops++) { + const candidate = join(dir, "package.json"); + if (existsSync(candidate)) { + const manifest = JSON.parse(readFileSync(candidate, "utf8")) as PackageManifest & { name?: string }; + if (manifest.name === "@metaobjectsdev/cli") return manifest.peerDependencies?.[name]; + } + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } catch { + // unreadable: the caller writes the package without a range + } + return undefined; +} + function manifestRangesOf(packageName: string, field: "peerDependencies" | "dependencies"): Record { try { const req = createRequire(import.meta.url); diff --git a/server/typescript/packages/cli/src/lib/owned-copy.ts b/server/typescript/packages/cli/src/lib/owned-copy.ts index 575349920b..addbe31936 100644 --- a/server/typescript/packages/cli/src/lib/owned-copy.ts +++ b/server/typescript/packages/cli/src/lib/owned-copy.ts @@ -32,7 +32,7 @@ // theirs and may not even parse), canonicalization degrades to trimmed raw lines. The // verdict then reads `differs` where it might have read `reformatted` — the pre-existing // behaviour, never a false `reformatted`. -import { Biome, Distribution } from "@biomejs/js-api"; +import type { Biome } from "@biomejs/js-api"; export type OwnedVerdict = /** Byte-for-byte the reference. */ @@ -53,11 +53,15 @@ export interface OwnedComparison { // One instance, created lazily and shared. Cache the PROMISE so concurrent first calls // (--list compares every owned copy) share one in-flight create rather than racing. +// The WebAssembly build is also LOADED lazily: it is about 14 MB of module that every other +// `meta` command (gen, verify, migrate, init) has no use for, so the import waits for the first +// comparison instead of being paid at start-up. let _biome: Promise | undefined; function getBiome(): Promise { if (!_biome) { - _biome = Biome.create({ distribution: Distribution.NODE }) + _biome = import("@biomejs/js-api") + .then(({ Biome: Formatter, Distribution }) => Formatter.create({ distribution: Distribution.NODE })) .then((biome) => { biome.applyConfiguration({ formatter: { enabled: true, indentStyle: "space", indentWidth: 2, lineWidth: 1 }, @@ -65,7 +69,7 @@ function getBiome(): Promise { }); return biome; }) - // A comparison is a REPORT LINE. If the formatter cannot start, say less — never + // A comparison is a REPORT LINE. If the formatter cannot load or start, say less — never // fail the command the adopter actually ran. .catch(() => undefined); } diff --git a/server/typescript/packages/cli/src/lib/schema-build-options.ts b/server/typescript/packages/cli/src/lib/schema-build-options.ts index 0179003092..bb2c30f30b 100644 --- a/server/typescript/packages/cli/src/lib/schema-build-options.ts +++ b/server/typescript/packages/cli/src/lib/schema-build-options.ts @@ -19,6 +19,8 @@ export interface SchemaBuildOptions { skipRedundantChecks: boolean; /** `migrate.foreignKeyIndexes`: index every foreign key nothing else indexes. */ foreignKeyIndexes: boolean; + /** `migrate.foreignKeyTargets`: `warn` reports a foreign key onto a non-unique target instead of refusing it. */ + foreignKeyTargets: "refuse" | "warn"; } /** @@ -28,13 +30,14 @@ export interface SchemaBuildOptions { * member (`isUnknownSchemaConventionsError` recognises both). */ export function schemaBuildOptions( - collection: Pick, + collection: Pick, tsConfig: Pick | undefined, ): SchemaBuildOptions { return { conventions: resolveSchemaConventions(tsConfig?.schemaConventions ?? collection.schemaConventions), skipRedundantChecks: collection.skipRedundantChecks, foreignKeyIndexes: collection.foreignKeyIndexes, + foreignKeyTargets: collection.foreignKeyTargets, }; } @@ -45,7 +48,7 @@ export function schemaBuildOptions( * refuse the same config with exit 2. */ export function schemaBuildOptionsOrWarn( - collection: Pick, + collection: Pick, tsConfig: Pick | undefined, warn: (message: string) => void, ): SchemaBuildOptions | undefined { diff --git a/server/typescript/packages/cli/test/init-esm-package-type.test.ts b/server/typescript/packages/cli/test/init-esm-package-type.test.ts index 60083a1e70..c4e6fb81a3 100644 --- a/server/typescript/packages/cli/test/init-esm-package-type.test.ts +++ b/server/typescript/packages/cli/test/init-esm-package-type.test.ts @@ -17,6 +17,7 @@ // every first-touch compile failure except the one it was written for. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from "node:fs"; +const rm = (path: string, opts: { recursive: boolean; force: boolean }): void => rmSync(path, opts); import { tmpdir } from "node:os"; import { join } from "node:path"; import { init } from "../src/commands/init.js"; @@ -109,7 +110,7 @@ describe("meta init — ESM package type", () => { }); }); -describe("meta init — the scaffold declares no dependencies", () => { +describe("meta init — the scaffold declares no generator dependencies", () => { // ADR-0034 puts real source in the adopter's repo, and init used to declare what that // source imported (@metaobjectsdev/codegen-ts + /metadata) plus what the code it would // GENERATE imported (drizzle-orm, zod, fastify). Both sets existed only because init @@ -120,12 +121,12 @@ describe("meta init — the scaffold declares no dependencies", () => { // generators you take — covered end-to-end in scaffold-output-imports-declared.test.ts, // which ejects a selection, applies its install set and then checks the generated // output against the manifest. - test("adds nothing to dependencies or devDependencies", async () => { + test("adds only the SQLite driver, and nothing to devDependencies", async () => { writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x", type: "commonjs" }, null, 2) + "\n"); await init({ cwd: dir, quiet: true }); const pkg = readPkg(); expect(pkg.devDependencies).toBeUndefined(); - expect(pkg.dependencies).toBeUndefined(); + expect(Object.keys(pkg.dependencies as Record)).toEqual(["@libsql/kysely-libsql"]); }); test("still leaves a pin the project already chose exactly as it was", async () => { @@ -138,8 +139,38 @@ describe("meta init — the scaffold declares no dependencies", () => { const pkg = readPkg(); expect((pkg.devDependencies as Record)["ts-poet"]).toBe("6.0.0"); expect((pkg.dependencies as Record)["@metaobjectsdev/codegen-ts"]).toBe("0.1.0"); - // ...and adds nothing beside them. + // ...and adds nothing beside them but the SQLite driver. expect(Object.keys(pkg.devDependencies as Record)).toEqual(["ts-poet"]); - expect(Object.keys(pkg.dependencies as Record)).toEqual(["@metaobjectsdev/codegen-ts"]); + expect(Object.keys(pkg.dependencies as Record)).toEqual(["@libsql/kysely-libsql", "@metaobjectsdev/codegen-ts"]); + }); +}); + +describe("meta init — the SQLite driver", () => { + // libSQL carries a native binary per platform and libc, so the CLI does not install it; the + // project that targets SQLite declares it, at the range the CLI declares as its peer. + const driverOf = (): string | undefined => + (readPkg().dependencies as Record | undefined)?.["@libsql/kysely-libsql"]; + + test("a sqlite project declares it at the range the CLI was tested against", async () => { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x" }, null, 2) + "\n"); + const result = await init({ cwd: dir, quiet: true }); + expect(driverOf()).toBe(">=0.4.0 <0.5.0"); + expect(result.warnings.join("\n")).toContain("added @libsql/kysely-libsql"); + }); + + test("a postgres, mysql or d1 project does not", async () => { + for (const dialect of ["postgres", "mysql", "d1"]) { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x" }, null, 2) + "\n"); + rm(join(dir, ".metaobjects"), { recursive: true, force: true }); + await init({ cwd: dir, quiet: true, dialect, force: true }); + expect(driverOf(), dialect).toBeUndefined(); + } + }); + + test("a project that already declares it keeps its pin and gets no second entry", async () => { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x", devDependencies: { "@libsql/kysely-libsql": "0.4.1" } }, null, 2) + "\n"); + await init({ cwd: dir, quiet: true }); + expect(driverOf()).toBeUndefined(); + expect((readPkg().devDependencies as Record)["@libsql/kysely-libsql"]).toBe("0.4.1"); }); }); diff --git a/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts index 15fe6b68ab..233f306fbe 100644 --- a/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts +++ b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts @@ -9,6 +9,7 @@ import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import pg from "pg"; +import { snapshotPath, writeSnapshot } from "@metaobjectsdev/migrate-ts"; import { migrateCommand } from "../src/commands/migrate.js"; import { log } from "../src/lib/log.js"; @@ -85,6 +86,42 @@ describe("meta migrate on SQLite: an FK to a non-unique target is warned, not re }); }); +/** A project whose committed snapshot is empty: the default `meta migrate` reads it and no database. */ +async function offlineProject(migrate: Record): Promise { + const root = await project(migrate); + await writeSnapshot(snapshotPath(join(root, ".metaobjects", "migrations"), "postgres"), { tables: [], views: [] }); + return root; +} + +describe("meta migrate offline on Postgres: the refusal has an off switch (migrate.foreignKeyTargets)", () => { + test("refused by default, and the refusal names the setting", async () => { + const root = await offlineProject({ dialect: "postgres" }); + const code = await migrateCommand(["--dry-run"], root); + + const text = out.join("\n"); + expect(code).toBe(1); + expect(text).toContain('reference "ref_person" targets [code] on "Person"'); + expect(text).toContain("migrate.foreignKeyTargets"); + expect(text).not.toContain("CREATE TABLE"); + }); + + test('"warn" reports the reference, names the setting, and plans the migration', async () => { + const root = await offlineProject({ dialect: "postgres", foreignKeyTargets: "warn" }); + const code = await migrateCommand(["--dry-run"], root); + + const text = out.join("\n"); + expect(code).toBe(0); + expect(text).toContain('reference "ref_person" targets [code] on "Person"'); + expect(text).toContain('migrate.foreignKeyTargets is "warn"'); + expect(text).toContain('CREATE TABLE "visits"'); + }); + + test("an unknown value is a config error, not a silent refuse", async () => { + const root = await offlineProject({ dialect: "postgres", foreignKeyTargets: "ignore" }); + expect(await migrateCommand(["--dry-run"], root)).toBe(2); + }); +}); + const PG_URL = process.env.MIGRATE_TS_PG_URL; async function withPgDatabase(fn: (url: string) => Promise): Promise { diff --git a/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts b/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts new file mode 100644 index 0000000000..88ee5194e9 --- /dev/null +++ b/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts @@ -0,0 +1,44 @@ +// Biome's WebAssembly build is ~14 MB of module that only the owned-copy comparison uses. +// Importing owned-copy must not load it; the first canonicalLines call must. +import { describe, expect, test } from "bun:test"; +import { join } from "node:path"; +import { canonicalLines } from "../src/lib/owned-copy.js"; + +// onResolve does not see a static import inside a module (only dynamic ones), so the probe +// counts Biome module loads in onLoad, which sees both kinds. +const probe = ` +import { plugin } from "bun"; +import { readFileSync } from "node:fs"; +const loaded = []; +plugin({ + name: "biome-probe", + setup(build) { + build.onLoad({ filter: /@biomejs\\/.*\\.m?js$/ }, (args) => { + loaded.push(args.path); + return { loader: "js", contents: readFileSync(args.path, "utf8") }; + }); + }, +}); +const { canonicalLines } = await import(${JSON.stringify(join(import.meta.dir, "..", "src", "lib", "owned-copy.ts"))}); +const afterImport = loaded.length; +await canonicalLines("const x = {a:1};\\n"); +console.log(JSON.stringify({ afterImport, afterCall: loaded.length })); +`; + +describe("owned-copy loads Biome on first use", () => { + test("importing the module does not load Biome; the first comparison does", () => { + const run = Bun.spawnSync([process.execPath, "-e", probe], { cwd: join(import.meta.dir, "..") }); + expect(run.exitCode).toBe(0); + const { afterImport, afterCall } = JSON.parse(run.stdout.toString().trim().split("\n").pop() ?? "{}"); + expect(afterImport).toBe(0); + expect(afterCall).toBeGreaterThan(0); + }); + + test("a comparison still formats, so the lazy load works", async () => { + // Biome runs at line width 1, so a one-line object and an exploded one reach the same lines. + const tight = await canonicalLines("const x = {a:1,b:2};\n"); + const loose = await canonicalLines("const x = {\n a: 1,\n b: 2,\n};\n"); + expect(tight).toEqual(loose); + expect(tight).toContain("a: 1"); + }); +}); diff --git a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts index d48e9110bb..9bbf2a78b9 100644 --- a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts +++ b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts @@ -49,7 +49,7 @@ function input(over: Partial & Pick([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -30,9 +23,7 @@ export function useSubscriberActiveGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -45,10 +36,7 @@ export function useSubscriberActiveGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "active", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts index ead5c11f9f..1abb35cf34 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts @@ -5,19 +5,12 @@ import { Program } from "./Program.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useProgramDefaultGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -29,9 +22,7 @@ export function useProgramDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -44,8 +35,7 @@ export function useProgramDefaultGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { @@ -63,10 +53,7 @@ export function useProgramDefaultGrid() { } export function useProgramCompactGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 50, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 50 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -78,9 +65,7 @@ export function useProgramCompactGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -93,8 +78,7 @@ export function useProgramCompactGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "compact", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts index a8497c2fd2..2c3b31f50f 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts @@ -5,21 +5,12 @@ import { Subscriber } from "./Subscriber.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useSubscriberDefaultGrid() { - const [sorting, setSorting] = useState([ - { id: "createdAt", desc: true }, - ]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [sorting, setSorting] = useState([{ id: "createdAt", desc: true }]); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -31,9 +22,7 @@ export function useSubscriberDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -46,10 +35,7 @@ export function useSubscriberDefaultGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts/package.json b/server/typescript/packages/codegen-ts/package.json index 723edd2e6e..0beda3bf1f 100644 --- a/server/typescript/packages/codegen-ts/package.json +++ b/server/typescript/packages/codegen-ts/package.json @@ -143,8 +143,6 @@ "@metaobjectsdev/docs-site": "workspace:*", "@metaobjectsdev/render": "workspace:*", "@metaobjectsdev/migrate-ts": "workspace:*", - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@toon-format/toon": "^2.3.0", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1" @@ -153,6 +151,14 @@ "drizzle-orm": ">=0.38.0 <1.0.0", "zod": ">=3.23.0 <5.0.0" }, + "peerDependenciesMeta": { + "drizzle-orm": { + "optional": true + }, + "zod": { + "optional": true + } + }, "devDependencies": { "@biomejs/biome": "^1.9.0", "@metaobjectsdev/codegen-ts-react": "workspace:*", diff --git a/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts b/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts index 3bdd0e4e96..a50e243433 100644 --- a/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts +++ b/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts @@ -12,7 +12,7 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { loadUris, type MetaObject, type MetaRoot, type WireFormat, wireFormatOf } from "@metaobjectsdev/metadata"; +import { type ApiPagination, loadUris, type MetaObject, type MetaRoot, type UnknownFieldsMode, type WireFormat, wireFormatOf } from "@metaobjectsdev/metadata"; import { defineConfig, type Generator, runGen } from "../src/index.js"; import { jsonSchemaFile, openApiFile } from "../src/generators/index.js"; import { readTree } from "./gen-cube-model-canonical.js"; @@ -22,6 +22,12 @@ const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..", "..", ".."); export const CONTRACT_CORPUS_DIR = join(REPO_ROOT, "fixtures", "contract-conformance"); +/** The parts of the `api` block of `.metaobjects/config.json` the document states. */ +interface ApiSettings { + readonly pagination?: ApiPagination; + readonly unknownFields?: UnknownFieldsMode; +} + /** This script, as a failing test names it. */ export const CONTRACT_SCRIPT = "server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts (bun run gen:contract-conformance)"; @@ -34,6 +40,8 @@ export interface ContractCase { /** The metadata file: the case's own `meta.json`, or a shared one `case.json` names. */ readonly meta: string; readonly wire?: Partial; + /** The project's `api` block, as in `.metaobjects/config.json`. */ + readonly api?: ApiSettings; /** Objects the strict profile leaves out, because the strict subset cannot state them. */ readonly strictExclude: readonly string[]; /** The project wires `report-export`, so a report's list route takes `format`. */ @@ -44,6 +52,7 @@ interface CaseJson { /** Repository-relative metadata file. Default: `meta.json` beside it. */ meta?: string; wire?: Partial; + api?: ApiSettings; strictExclude?: string[]; reportExport?: boolean; } @@ -57,6 +66,7 @@ function readCase(name: string): ContractCase { dir, meta: json.meta === undefined ? join(dir, "meta.json") : join(REPO_ROOT, json.meta), ...(json.wire !== undefined && { wire: json.wire }), + ...(json.api !== undefined && { api: json.api }), strictExclude: json.strictExclude ?? [], reportExport: json.reportExport ?? false, }; @@ -76,6 +86,8 @@ export async function loadCaseModel(c: ContractCase): Promise { throw new Error(`${c.meta}: metadata did not load cleanly: ${result.errors.map((e) => e.message).join("; ")}`); } if (c.wire !== undefined) result.root.wireFormat = { ...wireFormatOf(result.root), ...c.wire }; + if (c.api?.pagination !== undefined) result.root.apiPagination = c.api.pagination; + if (c.api?.unknownFields !== undefined) result.root.apiUnknownFields = c.api.unknownFields; return result.root; } diff --git a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts index f6f9e11ac7..126d40db34 100644 --- a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts +++ b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts @@ -5,10 +5,24 @@ // // It states the cross-port contract only. The TS-only filter extensions (`?search`, `filter[or]`) // are left out, and so are the `405` refusals on a read-only surface, which are not operations a -// caller can use (the api docs omit them for the same reason). +// caller can use (the api docs omit them for the same reason): a read-only resource says so in the +// description of its operations instead. +// +// It also states what the 1.3 routes do beyond the happy path: the project's page size +// (`api.pagination`), the refusal of an undeclared body key (`api.unknownFields`) and the list of +// validation issues. import { flatSurfaceFields } from "../flattened.js"; -import { type MetaField, type MetaObject, type MetaRoot, opsForField } from "@metaobjectsdev/metadata"; +import { + type ApiPagination, + apiPaginationOf, + apiUnknownFieldsOf, + type MetaField, + type MetaObject, + type MetaRoot, + opsForField, + UNKNOWN_FIELDS_REJECT, +} from "@metaobjectsdev/metadata"; import { FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_TIMESTAMP, FILTER_OP_IN, FILTER_OP_IS_NULL, FILTER_OP_LIKE } from "@metaobjectsdev/metadata/constants"; import { hasItemRoute, itemRouteField, servedPath, servesReadApi } from "../api-surface.js"; import { isProjection } from "../projection/projection-detector.js"; @@ -103,7 +117,15 @@ function errorResponse(description: string): JsonSchema { return { description, content: jsonContent({ $ref: componentRef(ERROR_COMPONENT) }) }; } +const READ_ONLY_NOTE = 'Read-only: a write to this resource answers 405 {"error": "method_not_allowed"}.'; + const BAD_REQUEST = errorResponse("The request was refused."); +const VALIDATION_REFUSED = errorResponse( + 'The request was refused. A body that fails validation answers error "validation" with an issue for every problem, not the first.', +); +const UNKNOWN_FIELDS_REFUSED = errorResponse( + 'The request was refused. A body key the model does not declare answers error "unknown_fields" with the keys in fields, and nothing is written. Any other problem answers error "validation" with an issue for every problem.', +); const NOT_FOUND = errorResponse("No such row."); const CONFLICT = errorResponse("A constraint refused the write."); @@ -141,9 +163,26 @@ function sortParameter(obj: MetaObject, excludeField: string | undefined, root: return [{ name: "sort", in: "query", schema: { type: "string", enum: values } }]; } -function pageParameters(minLimit: number): JsonSchema[] { +/** + * The page parameters. A project that sets `api.pagination` serves `defaultLimit` rows when `limit` + * is absent and refuses a `limit` above `maxLimit`, so the document says both. A report keeps its + * own row cap (a generator option the model does not hold), so it states neither. + */ +function pageParameters(minLimit: number, page: ApiPagination | undefined): JsonSchema[] { + const limit: JsonSchema = { + type: "integer", + minimum: minLimit, + ...(page !== undefined && { maximum: page.maxLimit, default: page.defaultLimit }), + }; return [ - { name: "limit", in: "query", schema: { type: "integer", minimum: minLimit } }, + { + name: "limit", + in: "query", + ...(page !== undefined && { + description: `Rows per page. Absent, the server answers ${page.defaultLimit}; above ${page.maxLimit} it answers 400 limit_too_large.`, + }), + schema: limit, + }, { name: "offset", in: "query", schema: { type: "integer", minimum: 0 } }, { name: "withCount", in: "query", description: "Answer { rows, total } instead of the array.", schema: { type: "integer", enum: [1] } }, ]; @@ -187,6 +226,8 @@ function idParameter(obj: MetaObject): JsonSchema { /** The operations of one resource: its collection path and, when it has rows by key, its item path. */ interface ResourceOps { + /** Writes are not served here (a projection or a report), and the operations say so. */ + readonly readOnly?: boolean; /** The object whose rows the routes answer, and whose name the operations carry. */ readonly row: MetaObject; readonly path: string; @@ -206,7 +247,7 @@ function listOperation(r: ResourceOps): JsonSchema { const parameters = [ ...filterParameters(row, r.excludeField, r.root), ...sortParameter(row, r.excludeField, r.root), - ...pageParameters(r.report ? 1 : 0), + ...pageParameters(r.report ? 1 : 0, r.report ? undefined : apiPaginationOf(r.root)), ...(r.reportExport ? [{ name: "format", in: "query", schema: { type: "string", enum: ["csv", "json", "xml"] } }] : []), ]; r.refs.listed.add(row); @@ -216,13 +257,22 @@ function listOperation(r: ResourceOps): JsonSchema { return { operationId: `list${row.name}`, tags: [row.name], + ...(r.readOnly === true && { description: READ_ONLY_NOTE }), parameters, responses: { "200": { description: "The rows.", content: { ...content, ...exports } }, "400": BAD_REQUEST }, }; } function writeBody(r: ResourceOps, shape: ContractShape): JsonSchema { - return { required: true, content: jsonContent(pathRef(r.refs, r.row, shape)) }; + const rejects = apiUnknownFieldsOf(r.root) === UNKNOWN_FIELDS_REJECT; + const description = rejects + ? "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped." + : "A top-level key the model does not declare is dropped, and the rest of the body is written."; + return { required: true, description, content: jsonContent(pathRef(r.refs, r.row, shape)) }; +} + +function writeRefused(r: ResourceOps): JsonSchema { + return apiUnknownFieldsOf(r.root) === UNKNOWN_FIELDS_REJECT ? UNKNOWN_FIELDS_REFUSED : VALIDATION_REFUSED; } function updateOperation(r: ResourceOps, operationId: string): JsonSchema { @@ -232,7 +282,7 @@ function updateOperation(r: ResourceOps, operationId: string): JsonSchema { requestBody: writeBody(r, "update"), responses: { "200": { description: "The row.", content: jsonContent(pathRef(r.refs, r.row, "read")) }, - "400": BAD_REQUEST, + "400": writeRefused(r), "404": NOT_FOUND, "409": CONFLICT, }, @@ -247,6 +297,7 @@ function itemOperations(r: ResourceOps): JsonSchema { get: { operationId: `get${row.name}`, tags, + ...(r.readOnly === true && { description: READ_ONLY_NOTE }), responses: { "200": { description: "The row.", content: jsonContent(pathRef(r.refs, row, "read")) }, "404": NOT_FOUND }, }, }), @@ -276,7 +327,7 @@ function collectionOperations(r: ResourceOps): JsonSchema { requestBody: writeBody(r, "create"), responses: { "201": { description: "The new row.", content: jsonContent(pathRef(r.refs, row, "read")) }, - "400": BAD_REQUEST, + "400": writeRefused(r), "409": CONFLICT, }, }, @@ -323,7 +374,7 @@ function pathsOf(obj: MetaObject, input: OpenApiBuildInput, refs: PathRefs): Rec if (isProjection(obj)) { return resourcePaths({ row: obj, path, report, reportExport: report && input.reportExport, item: hasItemRoute(obj), refs, root: input.root, - verbs: new Set(["list", "get"]), + readOnly: true, verbs: new Set(["list", "get"]), }); } const plan = tphPlan(obj, root); @@ -401,6 +452,21 @@ function collectSchemas(input: OpenApiBuildInput, refs: PathRefs): Record compareNames(a, b))); diff --git a/server/typescript/packages/codegen-ts/src/format.ts b/server/typescript/packages/codegen-ts/src/format.ts index 8e68172770..9e46d28a3f 100644 --- a/server/typescript/packages/codegen-ts/src/format.ts +++ b/server/typescript/packages/codegen-ts/src/format.ts @@ -1,50 +1,17 @@ -// Biome formatter integration. Used by generate() to format rendered TS before write. -// Per design §11: format errors are warnings, not throws. - -import { Biome, Distribution } from "@biomejs/js-api"; - -// Cache the Promise (not the resolved instance) so concurrent first calls -// share the same in-flight Biome.create() rather than racing to spawn two. -let _biomePromise: Promise | undefined; - -function getBiome(): Promise { - if (!_biomePromise) { - _biomePromise = Biome.create({ distribution: Distribution.NODE }).then((biome) => { - biome.applyConfiguration({ - formatter: { enabled: true, indentStyle: "space", indentWidth: 2 }, - javascript: { formatter: { quoteStyle: "double", semicolons: "always" } }, - }); - return biome; - }); - } - return _biomePromise; -} +// `formatTs` is a no-op kept only so an owned 1.2 generator copy still loads. +// +// Until 1.3.0 every reference generator piped its rendered text through Biome before it +// was written. Generation no longer runs a formatter: each generator writes the layout it +// means (the templates and `TsWriter`), and the adopter's own formatter owns the rest. A +// generator copied out with `meta eject` in 1.2 imports this name from the package entry, +// so the export stays and returns its input unchanged. A copy that wants a formatter calls +// the one it already depends on. /** - * Summarize Biome diagnostics into a single human-readable line, without - * dumping the raw diagnostic objects (which produce "[Object ...]" / - * "source: null" noise when stringified by console). + * Returns `content` unchanged. + * + * @deprecated Generation runs no formatter. A generator that wants one calls its own. */ -function summarizeDiagnostics(diagnostics: ReadonlyArray): string { - const count = diagnostics.length; - const first = diagnostics[0] as { description?: string; message?: string } | undefined; - const firstMsg = first?.description ?? first?.message ?? "(no description)"; - return count === 1 - ? `1 diagnostic: ${firstMsg}` - : `${count} diagnostics; first: ${firstMsg}`; -} - export async function formatTs(content: string): Promise { - try { - const biome = await getBiome(); - const result = biome.formatContent(content, { filePath: "in-memory.ts" }); - if (result.diagnostics.length > 0) { - console.warn(`[codegen-ts] Biome formatter: ${summarizeDiagnostics(result.diagnostics)}`); - return content; - } - return result.content; - } catch (err) { - console.warn(`[codegen-ts] Biome formatter error: ${(err as Error).message}`); - return content; - } + return content; } diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 3c6debf9f2..b6a2d2ea7c 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -14,7 +14,7 @@ export interface EmittedFile { path: string; /** The file's final contents, in any format — TypeScript, JSON, YAML, SQL, Markdown. * The runner writes it as given: it neither formats it nor adds a header, so a - * generator that wants either does it itself (`formatTs`, `GENERATED_HEADER`). */ + * generator that wants a header does it itself (`GENERATED_HEADER`). */ content: string; /** Set by the runner from generator.name — generators should not set this. */ generatedBy?: string; diff --git a/server/typescript/packages/codegen-ts/src/generators/barrel.ts b/server/typescript/packages/codegen-ts/src/generators/barrel.ts index 1638d0572c..4f324627ac 100644 --- a/server/typescript/packages/codegen-ts/src/generators/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/generators/barrel.ts @@ -1,6 +1,5 @@ import { oncePerRun, type Generator, type GeneratorFactory } from "../generator.js"; import { renderBarrel } from "../templates/barrel.js"; -import { formatTs } from "../format.js"; import { effectivePackage } from "../docs-paths.js"; import { claimBarrelNames } from "../naming/name-claims.js"; @@ -16,14 +15,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), ctx.renderContext!.extStyle, ctx.renderContext!.selfTarget, ctx.renderContext!.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts index f4500bd408..f33d1799e8 100644 --- a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts @@ -9,7 +9,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type Generator, type GeneratorFactory } from "../generator.js"; import { renderCallableFile, isCallableEntity } from "../templates/callable-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; @@ -34,7 +33,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts index d6eb4e4eb7..1d4c3f8534 100644 --- a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type EmittedFile, type GenContext, type Generator, type GeneratorFactory } from "../generator.js"; import { renderEntityFile } from "../templates/entity-file.js"; import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isAbstract } from "../instance-artifacts.js"; import { effectivePackage } from "../docs-paths.js"; @@ -45,7 +44,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntityFile(entity, ctx.renderContext, { allowlists })), + content: renderEntityFile(entity, ctx.renderContext, { allowlists }), }; }); @@ -67,7 +66,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator if (sharedEnums !== null) { files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, - content: await formatTs(sharedEnums), + content: sharedEnums, }); } return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts index 94debcf794..a9fc2e300c 100644 --- a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderQueriesFile } from "../templates/queries-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { claimModuleNames } from "../naming/name-claims.js"; @@ -52,7 +51,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueriesFile(entity, ctx.renderContext)), + content: renderQueriesFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts index 347504b4cd..1065766bce 100644 --- a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GenContext, EmittedFile } from "../generator.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; -import { formatTs } from "../format.js"; import { isReport } from "../source-detect.js"; import { DEFAULT_EXPORT_MAX_ROWS, DEFAULT_XML_NULLS, EXPORT_WRITERS_BASENAME, @@ -58,14 +57,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts index 2c5956e61c..eaf551807d 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderRoutesFileHono } from "../templates/routes-file-hono.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isTphSubtype } from "../tph.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; @@ -105,7 +104,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -120,7 +119,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts index f0a871f20a..cef0c6d9f5 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts @@ -4,7 +4,6 @@ import { renderRoutesFile } from "../templates/routes-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; import { effectivePackage } from "../docs-paths.js"; @@ -63,7 +62,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator claimRouteSegment(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -83,7 +82,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index e15436e26b..4cb6741bb4 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -112,6 +112,7 @@ export { CodegenError } from "./errors.js"; export { GENERATED_HEADER, GENERATED_EDIT_NOTE, NAMES_FILE_SUFFIX, DEFAULT_OUT_DIR, RETIRED_CODEGEN_ATTRS, sidecarLine, type RetiredCodegenAttr } from "./constants.js"; export { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; +// Kept so a generator copied out in 1.2 still loads; generation runs no formatter (format.ts). export { formatTs } from "./format.js"; export { pluralize, columnNameFromField, tableNameFromEntity, viewNameFromProjection, routesHandlerName, hookListNameSegment } from "./naming.js"; diff --git a/server/typescript/packages/codegen-ts/src/reference/barrel.ts b/server/typescript/packages/codegen-ts/src/reference/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/reference/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/callable.ts b/server/typescript/packages/codegen-ts/src/reference/callable.ts index 2faeaf9c8a..4cc0b17a8d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/callable.ts +++ b/server/typescript/packages/codegen-ts/src/reference/callable.ts @@ -31,7 +31,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -61,7 +60,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/entity.ts b/server/typescript/packages/codegen-ts/src/reference/entity.ts index 926da1c687..4931111a28 100644 --- a/server/typescript/packages/codegen-ts/src/reference/entity.ts +++ b/server/typescript/packages/codegen-ts/src/reference/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/server/typescript/packages/codegen-ts/src/reference/queries.ts b/server/typescript/packages/codegen-ts/src/reference/queries.ts index 8d03e08142..44617b4c61 100644 --- a/server/typescript/packages/codegen-ts/src/reference/queries.ts +++ b/server/typescript/packages/codegen-ts/src/reference/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/report-export.ts b/server/typescript/packages/codegen-ts/src/reference/report-export.ts index 77ec25579c..0b6a881dca 100644 --- a/server/typescript/packages/codegen-ts/src/reference/report-export.ts +++ b/server/typescript/packages/codegen-ts/src/reference/report-export.ts @@ -29,7 +29,6 @@ import { effectivePackage, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, - formatTs, isCredentialField, isReport, relativeModuleSpecifier, @@ -247,14 +246,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts index 10910a4297..e61313e354 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts @@ -63,7 +63,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -183,7 +182,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -238,7 +236,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, @@ -338,7 +335,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -358,7 +355,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/reference/routes.ts b/server/typescript/packages/codegen-ts/src/reference/routes.ts index 16837743da..3117986622 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 42b830eebc..6a9052139c 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts index 6c00f30691..8231b343b2 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts @@ -135,7 +135,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -190,7 +189,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts index 40918d6c70..a36408aa23 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts index 01f3ef64e9..e039ce477f 100644 --- a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts index 9738b0eff4..79be12d2ff 100644 --- a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts @@ -268,7 +268,7 @@ function evaluatePath(expr: string, ownPaths: ReadonlyMap): stri } /** - * Every mount in one emitted routes file. A line-oriented walk over the biome-formatted + * Every mount in one emitted routes file. A line-oriented walk over the emitted * output: a mount opens on `mount…CrudRoutes({` and closes on `});`, and the three * properties read are each one line. The count of openers is asserted against the * mounts recovered, so a formatting change that moved a property onto the opener line diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index fe5742c441..cc1773e117 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -391,6 +391,41 @@ describe("what a project's run changes", () => { }); }); +describe("the document states what the routes do beyond the happy path", () => { + type Operation = { description?: string; parameters?: Array<{ name: string; description?: string; schema?: JsonDoc }>; requestBody?: { description?: string }; responses?: Record }; + const operation = (doc: JsonDoc, path: string, method: string): Operation => + (((doc["paths"] as JsonDoc)[path] as JsonDoc)[method]) as Operation; + const document = async (name: string): Promise => jsonAt(await emit(corpusCase(name), [openApiFile({ title: "t", version: "1" })]), "openapi.json"); + + test("a project's page size is the limit's default and maximum, and absent it states neither", async () => { + const limitOf = (doc: JsonDoc) => operation(doc, "/api/authors", "get").parameters?.find((p) => p.name === "limit")?.schema; + expect(limitOf(await document("api-settings"))).toEqual({ type: "integer", minimum: 0, maximum: 1000, default: 50 }); + expect(limitOf(await document("blog"))).toEqual({ type: "integer", minimum: 0 }); + }); + + test("a write says an undeclared key is refused by default, and dropped under api.unknownFields: drop", async () => { + const reject = operation(await document("blog"), "/api/authors", "post"); + expect(reject.requestBody?.description).toContain("unknown_fields"); + expect(reject.responses?.["400"]?.description).toContain("unknown_fields"); + const drop = operation(await document("api-settings-drop"), "/api/authors", "post"); + expect(drop.requestBody?.description).toContain("dropped"); + expect(drop.responses?.["400"]?.description).not.toContain("unknown_fields"); + expect(drop.responses?.["400"]?.description).toContain("validation"); + }); + + test("the error envelope carries the validation issues and the undeclared keys", async () => { + const error = ((await document("blog"))["components"] as { schemas: Record }> }).schemas["ApiError"]; + expect(Object.keys(error?.properties ?? {})).toEqual(["error", "message", "field", "fields", "issues", "maxLimit"]); + }); + + test("a read-only resource says a write answers 405, though 405 is no operation", async () => { + const doc = await document("projection"); + expect(operation(doc, "/api/invoice_ledgers", "get").description).toContain("405"); + expect(operation(doc, "/api/invoices", "get").description).toBeUndefined(); + expect(Object.keys((doc["paths"] as JsonDoc)["/api/invoice_ledgers"] as JsonDoc)).toEqual(["get"]); + }); +}); + describe("the reference copies", () => { for (const c of contractCases()) { if (c.name.startsWith("error-")) continue; diff --git a/server/typescript/packages/codegen-ts/test/format.test.ts b/server/typescript/packages/codegen-ts/test/format.test.ts index 62b643b6fd..5155e62e3c 100644 --- a/server/typescript/packages/codegen-ts/test/format.test.ts +++ b/server/typescript/packages/codegen-ts/test/format.test.ts @@ -1,19 +1,28 @@ import { describe, test, expect } from "bun:test"; import { formatTs } from "../src/format.js"; +import { formatTs as formatTsFromEntry } from "../src/index.js"; +// Generation runs no formatter. `formatTs` stays exported only so a generator copied out +// with `meta eject` in 1.2 (which imports it from the package entry) still loads. describe("formatTs", () => { - test("formats unformatted TS into idiomatic Biome style", async () => { + test("is exported from the package entry, for owned 1.2 generator copies", () => { + expect(formatTsFromEntry).toBe(formatTs); + }); + + test("returns its input unchanged", async () => { const ugly = "import {x} from'y';export const a={b:1,c:2}"; - const formatted = await formatTs(ugly); - expect(formatted).not.toBe(ugly); - expect(formatted).toContain("import"); - expect(formatted.length).toBeGreaterThan(ugly.length); + expect(await formatTs(ugly)).toBe(ugly); }); - test("returns input unchanged on Biome error (with warning logged)", async () => { - const broken = "import { from 'x';"; // syntax error - const formatted = await formatTs(broken); - // Per design §11: format error → log warning, return unformatted - expect(typeof formatted).toBe("string"); + test("returns invalid TypeScript unchanged, with nothing logged", async () => { + const warnings: unknown[] = []; + const warn = console.warn; + console.warn = (...args: unknown[]) => warnings.push(args); + try { + expect(await formatTs("import { from 'x';")).toBe("import { from 'x';"); + } finally { + console.warn = warn; + } + expect(warnings).toEqual([]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts index c28721fad7..0041f533ab 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts @@ -5,27 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -35,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { @@ -67,17 +43,11 @@ export async function deleteTagById(db: Db, id: number): Promise { const deleted = await db.delete(tags).where(eq(tags.id, id)).returning(); return deleted.length > 0; } -export async function findTagsByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findTagsByCustomer(db: Db, customerId: number): Promise { return db.select().from(tags).where(eq(tags.customerId, customerId)); } -export async function findTagsByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findTagsByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts index c427da5bcc..9659dd6b2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "../db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts index e403eda9de..a1cdad130f 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts @@ -1,17 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { TagNames } from "./Tag.names"; import { customers } from "./shop/users/Customer"; @@ -19,23 +10,16 @@ import { customers } from "./shop/users/Customer"; export const tags = sqliteTable(TagNames.sources.primary.table, { id: integer(TagNames.fields.id.column).primaryKey({ autoIncrement: true }), label: text(TagNames.fields.label.column).notNull(), - customerId: integer(TagNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), + customerId: integer(TagNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), }); -export const tagsRelations = relations(tags, ({ one }) => ({ - customer: one(customers, { - fields: [tags.customerId], - references: [customers.id], - }), -})); +export const tagsRelations = relations( + tags, + ({ one }) => ({ customer: one(customers, { fields: [tags.customerId], references: [customers.id] }) }), +); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - label: z.string().min(1).max(100), - customerId: z.number().int(), -}); +export const TagInsertSchema = z.object({ label: z.string().min(1).max(100), customerId: z.number().int() }); export const TagUpdateSchema = z.object({ label: z.string().min(1).max(100).optional(), @@ -82,10 +66,7 @@ export const Tag = { label: "Label", view: "text", htmlType: "text", - rules: { - required: "Label is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Label is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, customerId: { name: "customerId", @@ -101,10 +82,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts index 559cb87f7c..bcfbfe2d2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts @@ -5,31 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Order, - OrderInsertSchema, - type OrderPatch, - orders, - OrderUpdateSchema, -} from "./Order"; +import { type Order, OrderInsertSchema, type OrderPatch, orders, OrderUpdateSchema } from "./Order"; export async function findOrderById(db: Db, id: number): Promise { - const [order] = await db - .select() - .from(orders) - .where(eq(orders.id, id)) - .limit(1); + const [order] = await db.select().from(orders).where(eq(orders.id, id)).limit(1); return order ?? null; } -export async function listOrders( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listOrders(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(orders).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -39,30 +22,19 @@ export async function listOrders( } return q; } -export async function createOrder( - db: Db, - data: z.input, -): Promise { +export async function createOrder(db: Db, data: z.input): Promise { const validated = OrderInsertSchema.parse(data); const [order] = await db.insert(orders).values(validated).returning(); return order!; } -export async function updateOrder( - db: Db, - id: number, - patch: OrderPatch, -): Promise { +export async function updateOrder(db: Db, id: number, patch: OrderPatch): Promise { const validated = OrderUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findOrderById(db, id); } - const [order] = await db - .update(orders) - .set(validated) - .where(eq(orders.id, id)) - .returning(); + const [order] = await db.update(orders).set(validated).where(eq(orders.id, id)).returning(); return order ?? null; } export async function deleteOrderById(db: Db, id: number): Promise { @@ -71,36 +43,21 @@ export async function deleteOrderById(db: Db, id: number): Promise { const deleted = await db.delete(orders).where(eq(orders.id, id)).returning(); return deleted.length > 0; } -export async function findOrdersByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findOrdersByCustomer(db: Db, customerId: number): Promise { return db.select().from(orders).where(eq(orders.customerId, customerId)); } -export async function findOrdersByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findOrdersByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } - return db - .select() - .from(orders) - .where(inArray(orders.customerId, customerIds)); + return db.select().from(orders).where(inArray(orders.customerId, customerIds)); } -export async function findOrdersByProduct( - db: Db, - productId: number, -): Promise { +export async function findOrdersByProduct(db: Db, productId: number): Promise { return db.select().from(orders).where(eq(orders.productId, productId)); } -export async function findOrdersByProductIn( - db: Db, - productIds: number[], -): Promise { +export async function findOrdersByProductIn(db: Db, productIds: number[]): Promise { if (productIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts index 6fe09bbd7a..0e3a90eb9c 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. import { db } from "../../../db"; -import { - Order, - OrderFilterAllowlist, - OrderInsertSchema, - orders, - OrderSortAllowlist, - OrderUpdateSchema, -} from "./Order"; +import { Order, OrderFilterAllowlist, OrderInsertSchema, orders, OrderSortAllowlist, OrderUpdateSchema } from "./Order"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts index c3b8a0b08e..679dc1380b 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts @@ -1,16 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { customers } from "../users/Customer"; import { OrderNames } from "./Order.names"; @@ -18,24 +10,17 @@ import { products } from "./Product"; export const orders = sqliteTable(OrderNames.sources.primary.table, { id: integer(OrderNames.fields.id.column).primaryKey({ autoIncrement: true }), - customerId: integer(OrderNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), - productId: integer(OrderNames.fields.productId.column) - .notNull() - .references((): AnySQLiteColumn => products.id), + customerId: integer(OrderNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), + productId: integer(OrderNames.fields.productId.column).notNull().references((): AnySQLiteColumn => products.id), quantity: integer(OrderNames.fields.quantity.column).notNull(), }); -export const ordersRelations = relations(orders, ({ one }) => ({ - customer: one(customers, { - fields: [orders.customerId], - references: [customers.id], +export const ordersRelations = relations( + orders, + ({ one }) => ({ + customer: one(customers, { fields: [orders.customerId], references: [customers.id] }), + product: one(products, { fields: [orders.productId], references: [products.id] }), }), - product: one(products, { - fields: [orders.productId], - references: [products.id], - }), -})); +); export type Order = InferSelectModel; export type OrderInsert = InferInsertModel; export type OrderUpdate = Partial; @@ -114,10 +99,4 @@ export const OrderFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const OrderSortAllowlist = {} as const satisfies SortAllowlist; -export type OrderFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: OrderFilter[]; - and?: OrderFilter[]; -}; +export type OrderFilter = { limit?: number; offset?: number; sort?: string; or?: OrderFilter[]; and?: OrderFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts index 5dac95be94..35f904c45e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts @@ -5,34 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Product, - ProductInsertSchema, - type ProductPatch, - products, - ProductUpdateSchema, -} from "./Product"; -export async function findProductById( - db: Db, - id: number, -): Promise { - const [product] = await db - .select() - .from(products) - .where(eq(products.id, id)) - .limit(1); +import { type Product, ProductInsertSchema, type ProductPatch, products, ProductUpdateSchema } from "./Product"; +export async function findProductById(db: Db, id: number): Promise { + const [product] = await db.select().from(products).where(eq(products.id, id)).limit(1); return product ?? null; } -export async function listProducts( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listProducts(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(products).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,52 +22,32 @@ export async function listProducts( } return q; } -export async function createProduct( - db: Db, - data: z.input, -): Promise { +export async function createProduct(db: Db, data: z.input): Promise { const validated = ProductInsertSchema.parse(data); const [product] = await db.insert(products).values(validated).returning(); return product!; } -export async function updateProduct( - db: Db, - id: number, - patch: ProductPatch, -): Promise { +export async function updateProduct(db: Db, id: number, patch: ProductPatch): Promise { const validated = ProductUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProductById(db, id); } - const [product] = await db - .update(products) - .set(validated) - .where(eq(products.id, id)) - .returning(); + const [product] = await db.update(products).set(validated).where(eq(products.id, id)).returning(); return product ?? null; } export async function deleteProductById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(products) - .where(eq(products.id, id)) - .returning(); + const deleted = await db.delete(products).where(eq(products.id, id)).returning(); return deleted.length > 0; } -export async function findProductsByTag( - db: Db, - tagId: number, -): Promise { +export async function findProductsByTag(db: Db, tagId: number): Promise { return db.select().from(products).where(eq(products.tagId, tagId)); } -export async function findProductsByTagIn( - db: Db, - tagIds: number[], -): Promise { +export async function findProductsByTagIn(db: Db, tagIds: number[]): Promise { if (tagIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts index 9a0149a188..3ab0fea323 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts @@ -1,40 +1,25 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Product (shop::commerce::Product) // Extend in your own module (e.g. Product.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { tags } from "../../Tag"; import { ProductNames } from "./Product.names"; export const products = sqliteTable(ProductNames.sources.primary.table, { - id: integer(ProductNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(ProductNames.fields.id.column).primaryKey({ autoIncrement: true }), name: text(ProductNames.fields.name.column).notNull(), - tagId: integer(ProductNames.fields.tagId.column) - .notNull() - .references((): AnySQLiteColumn => tags.id), + tagId: integer(ProductNames.fields.tagId.column).notNull().references((): AnySQLiteColumn => tags.id), }); -export const productsRelations = relations(products, ({ one }) => ({ - tag: one(tags, { fields: [products.tagId], references: [tags.id] }), -})); +export const productsRelations = relations( + products, + ({ one }) => ({ tag: one(tags, { fields: [products.tagId], references: [tags.id] }) }), +); export type Product = InferSelectModel; export type ProductInsert = InferInsertModel; export type ProductUpdate = Partial; -export const ProductInsertSchema = z.object({ - name: z.string().min(1).max(200), - tagId: z.number().int(), -}); +export const ProductInsertSchema = z.object({ name: z.string().min(1).max(200), tagId: z.number().int() }); export const ProductUpdateSchema = z.object({ name: z.string().min(1).max(200).optional(), @@ -81,10 +66,7 @@ export const Product = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, tagId: { name: "tagId", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts index 89fe94c91f..788988abeb 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts @@ -5,34 +5,14 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Customer, - CustomerInsertSchema, - type CustomerPatch, - customers, - CustomerUpdateSchema, -} from "./Customer"; -export async function findCustomerById( - db: Db, - id: number, -): Promise { - const [customer] = await db - .select() - .from(customers) - .where(eq(customers.id, id)) - .limit(1); +import { type Customer, CustomerInsertSchema, type CustomerPatch, customers, CustomerUpdateSchema } from "./Customer"; +export async function findCustomerById(db: Db, id: number): Promise { + const [customer] = await db.select().from(customers).where(eq(customers.id, id)).limit(1); return customer ?? null; } -export async function listCustomers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listCustomers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(customers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,38 +22,24 @@ export async function listCustomers( } return q; } -export async function createCustomer( - db: Db, - data: z.input, -): Promise { +export async function createCustomer(db: Db, data: z.input): Promise { const validated = CustomerInsertSchema.parse(data); const [customer] = await db.insert(customers).values(validated).returning(); return customer!; } -export async function updateCustomer( - db: Db, - id: number, - patch: CustomerPatch, -): Promise { +export async function updateCustomer(db: Db, id: number, patch: CustomerPatch): Promise { const validated = CustomerUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findCustomerById(db, id); } - const [customer] = await db - .update(customers) - .set(validated) - .where(eq(customers.id, id)) - .returning(); + const [customer] = await db.update(customers).set(validated).where(eq(customers.id, id)).returning(); return customer ?? null; } export async function deleteCustomerById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(customers) - .where(eq(customers.id, id)) - .returning(); + const deleted = await db.delete(customers).where(eq(customers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts index cae74ba52f..ba7db33bb8 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts @@ -7,21 +7,15 @@ import { z } from "zod"; import { CustomerNames } from "./Customer.names"; export const customers = sqliteTable(CustomerNames.sources.primary.table, { - id: integer(CustomerNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(CustomerNames.fields.id.column).primaryKey({ autoIncrement: true }), email: text(CustomerNames.fields.email.column).notNull(), }); export type Customer = InferSelectModel; export type CustomerInsert = InferInsertModel; export type CustomerUpdate = Partial; -export const CustomerInsertSchema = z.object({ - email: z.string().min(1).max(255), -}); +export const CustomerInsertSchema = z.object({ email: z.string().min(1).max(255) }); -export const CustomerUpdateSchema = z.object({ - email: z.string().min(1).max(255).optional(), -}); +export const CustomerUpdateSchema = z.object({ email: z.string().min(1).max(255).optional() }); /** Typed create shape for Customer: the insert schema's INPUT (pre-transform) type. A * renamed/dropped/misspelt field is a compile error at every `createCustomer` call site; @@ -63,10 +57,7 @@ export const Customer = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts index f3e8bda7c5..f4b4ee53ee 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Exercise, - ExerciseInsertSchema, - type ExercisePatch, - exercises, - ExerciseUpdateSchema, -} from "./Exercise"; -export async function findExerciseById( - db: Db, - id: number, -): Promise { - const [exercise] = await db - .select() - .from(exercises) - .where(eq(exercises.id, id)) - .limit(1); +import { type Exercise, ExerciseInsertSchema, type ExercisePatch, exercises, ExerciseUpdateSchema } from "./Exercise"; +export async function findExerciseById(db: Db, id: number): Promise { + const [exercise] = await db.select().from(exercises).where(eq(exercises.id, id)).limit(1); return exercise ?? null; } -export async function listExercises( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listExercises(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(exercises).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listExercises( } return q; } -export async function createExercise( - db: Db, - data: z.input, -): Promise { +export async function createExercise(db: Db, data: z.input): Promise { const validated = ExerciseInsertSchema.parse(data); const [exercise] = await db.insert(exercises).values(validated).returning(); return exercise!; } -export async function updateExercise( - db: Db, - id: number, - patch: ExercisePatch, -): Promise { +export async function updateExercise(db: Db, id: number, patch: ExercisePatch): Promise { const validated = ExerciseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findExerciseById(db, id); } - const [exercise] = await db - .update(exercises) - .set(validated) - .where(eq(exercises.id, id)) - .returning(); + const [exercise] = await db.update(exercises).set(validated).where(eq(exercises.id, id)).returning(); return exercise ?? null; } export async function deleteExerciseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(exercises) - .where(eq(exercises.id, id)) - .returning(); + const deleted = await db.delete(exercises).where(eq(exercises.id, id)).returning(); return deleted.length > 0; } -export async function findExercisesByWorkout( - db: Db, - workoutId: number, -): Promise { +export async function findExercisesByWorkout(db: Db, workoutId: number): Promise { return db.select().from(exercises).where(eq(exercises.workoutId, workoutId)); } -export async function findExercisesByWorkoutIn( - db: Db, - workoutIds: number[], -): Promise { +export async function findExercisesByWorkoutIn(db: Db, workoutIds: number[]): Promise { if (workoutIds.length === 0) { return []; } - return db - .select() - .from(exercises) - .where(inArray(exercises.workoutId, workoutIds)); + return db.select().from(exercises).where(inArray(exercises.workoutId, workoutIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts index e2770d23c9..b06b1cd536 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts @@ -1,40 +1,23 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Exercise (Exercise) // Extend in your own module (e.g. Exercise.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - text, - varchar, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, text, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { workouts } from "./Workout"; export const exercises = pgTable("exercises", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - workoutId: bigint("workout_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => workouts.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + workoutId: bigint("workout_id", { mode: "number" }).notNull().references((): AnyPgColumn => workouts.id), name: varchar("name", { length: 200 }).notNull(), sets: integer("sets"), reps: integer("reps"), notes: text("notes"), }); -export const exercisesRelations = relations(exercises, ({ one }) => ({ - workout: one(workouts, { - fields: [exercises.workoutId], - references: [workouts.id], - }), -})); +export const exercisesRelations = relations( + exercises, + ({ one }) => ({ workout: one(workouts, { fields: [exercises.workoutId], references: [workouts.id] }) }), +); export type Exercise = InferSelectModel; export type ExerciseInsert = InferInsertModel; export type ExerciseUpdate = Partial; @@ -101,10 +84,7 @@ export const Exercise = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, sets: { name: "sets", label: "Sets", view: "number", htmlType: "number" }, reps: { name: "reps", label: "Reps", view: "number", htmlType: "number" }, diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts index 41d300bf52..885445757e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: number, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: number): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: number, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: number, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts index d9389baea0..1acd334a76 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts @@ -45,14 +45,6 @@ export async function programRoutes(fastify: FastifyInstance) { filterAllowlist: ProgramFilterAllowlist, sortAllowlist: ProgramSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "slug", - "title", - "description", - "priceCents", - "isPublished", - "createdAt", - ], + knownFields: ["id", "slug", "title", "description", "priceCents", "isPublished", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts index aeffbeb30b..9432ac4f35 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts @@ -2,29 +2,17 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - integer, - pgTable, - text, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, integer, pgTable, text, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const programs = pgTable("programs", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), slug: varchar("slug", { length: 100 }).notNull().unique(), title: varchar("title", { length: 200 }).notNull(), description: text("description"), priceCents: integer("price_cents").notNull(), isPublished: boolean("is_published").notNull().default(false), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; @@ -36,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -48,9 +34,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const ProgramInsertSchema = z.object({ @@ -59,14 +43,10 @@ export const ProgramInsertSchema = z.object({ description: z.string().optional(), priceCents: z.number().int(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const ProgramUpdateSchema = z.object({ @@ -75,14 +55,10 @@ export const ProgramUpdateSchema = z.object({ description: z.string().optional().nullable(), priceCents: z.number().int().optional(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A @@ -125,27 +101,16 @@ export const Program = { label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, title: { name: "title", label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - description: { - name: "description", - label: "Description", - view: "text", - htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + description: { name: "description", label: "Description", view: "text", htmlType: "text" }, priceCents: { name: "priceCents", label: "Price Cents", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts index ec01f4c9d5..905dbdf2e3 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: number, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: number): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,79 +22,44 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: number, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: number, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesBySubscriber( - db: Db, - subscriberId: number, -): Promise { - return db - .select() - .from(purchases) - .where(eq(purchases.subscriberId, subscriberId)); +export async function findPurchasesBySubscriber(db: Db, subscriberId: number): Promise { + return db.select().from(purchases).where(eq(purchases.subscriberId, subscriberId)); } -export async function findPurchasesBySubscriberIn( - db: Db, - subscriberIds: number[], -): Promise { +export async function findPurchasesBySubscriberIn(db: Db, subscriberIds: number[]): Promise { if (subscriberIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.subscriberId, subscriberIds)); + return db.select().from(purchases).where(inArray(purchases.subscriberId, subscriberIds)); } -export async function findPurchasesByProgram( - db: Db, - programId: number, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: number): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: number[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: number[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts index 02caa5ee14..379b7a60b1 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts @@ -45,12 +45,6 @@ export async function purchaseRoutes(fastify: FastifyInstance) { filterAllowlist: PurchaseFilterAllowlist, sortAllowlist: PurchaseSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "subscriberId", - "programId", - "amountCents", - "purchasedAt", - ], + knownFields: ["id", "subscriberId", "programId", "amountCents", "purchasedAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts index f74457a592..4e68280019 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts @@ -1,47 +1,26 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - timestamp, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, timestamp } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; import { subscribers } from "./Subscriber"; export const purchases = pgTable("purchases", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - subscriberId: bigint("subscriber_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => subscribers.id), - programId: bigint("program_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => programs.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + subscriberId: bigint("subscriber_id", { mode: "number" }).notNull().references((): AnyPgColumn => subscribers.id), + programId: bigint("program_id", { mode: "number" }).notNull().references((): AnyPgColumn => programs.id), amountCents: integer("amount_cents").notNull(), - purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); -export const purchasesRelations = relations(purchases, ({ one }) => ({ - subscriber: one(subscribers, { - fields: [purchases.subscriberId], - references: [subscribers.id], +export const purchasesRelations = relations( + purchases, + ({ one }) => ({ + subscriber: one(subscribers, { fields: [purchases.subscriberId], references: [subscribers.id] }), + program: one(programs, { fields: [purchases.programId], references: [programs.id] }), }), - program: one(programs, { - fields: [purchases.programId], - references: [programs.id], - }), -})); +); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -52,10 +31,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -64,37 +41,27 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ subscriberId: z.number().int(), programId: z.number().int(), amountCents: z.number().int(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ subscriberId: z.number().int().optional(), programId: z.number().int().optional(), amountCents: z.number().int().optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts index aa17a0b323..b91662c023 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts @@ -14,21 +14,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,44 +28,24 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts index 5b0664743b..5f8729600d 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts @@ -45,13 +45,6 @@ export async function subscriberRoutes(fastify: FastifyInstance) { filterAllowlist: SubscriberFilterAllowlist, sortAllowlist: SubscriberSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "email", - "firstName", - "lastName", - "subscribed", - "createdAt", - ], + knownFields: ["id", "email", "firstName", "lastName", "subscribed", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts index dee5dcdb18..125d01af10 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts @@ -2,26 +2,16 @@ // Source metadata: Subscriber (Subscriber) // Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - pgTable, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgTable, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const subscribers = pgTable("subscribers", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), email: varchar("email", { length: 255 }).notNull().unique(), firstName: varchar("first_name", { length: 100 }).notNull(), lastName: varchar("last_name", { length: 100 }), subscribed: boolean("subscribed").notNull().default(true), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; @@ -33,10 +23,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -45,9 +33,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ @@ -55,14 +41,10 @@ export const SubscriberInsertSchema = z.object({ firstName: z.string().min(1).max(100), lastName: z.string().max(100).optional(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const SubscriberUpdateSchema = z.object({ @@ -70,14 +52,10 @@ export const SubscriberUpdateSchema = z.object({ firstName: z.string().min(1).max(100).optional(), lastName: z.string().max(100).optional().nullable(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A @@ -120,10 +98,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, firstName: { name: "firstName", @@ -140,9 +115,7 @@ export const Subscriber = { label: "Last Name", view: "text", htmlType: "text", - rules: { - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, subscribed: { name: "subscribed", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts index 3141474717..64c6e754a7 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts @@ -7,21 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -31,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts index 8dc41fe210..fd85d72620 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "~/server/db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts index 45b9c2c043..b6da2f7b23 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts @@ -6,19 +6,14 @@ import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const tags = pgTable("tags", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), name: varchar("name", { length: 50 }).notNull().unique(), slug: varchar("slug", { length: 50 }).notNull().unique(), }); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - name: z.string().min(1).max(50), - slug: z.string().min(1).max(50), -}); +export const TagInsertSchema = z.object({ name: z.string().min(1).max(50), slug: z.string().min(1).max(50) }); export const TagUpdateSchema = z.object({ name: z.string().min(1).max(50).optional(), @@ -65,20 +60,14 @@ export const Tag = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, slug: { name: "slug", label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; @@ -87,10 +76,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts index 5f5fe10e72..d56c7f45b5 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts @@ -7,25 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Video, - VideoInsertSchema, - type VideoPatch, - videos, - VideoUpdateSchema, -} from "./Video"; +import { type Video, VideoInsertSchema, type VideoPatch, videos, VideoUpdateSchema } from "./Video"; export async function findVideoById(db: Db, id: number): Promise