From c710a08bbf047aa77ecc9351472a635e2d0bada7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 11:47:50 -0500 Subject: [PATCH 1/4] fix(csharp): compare before writing on the no-manifest gen path and under eject --force An unchanged file is never rewritten: CodegenRunner.WriteOne's no-manifest path, every eject copy (generator, emitter companions, helper runtime) and the gen fingerprint now read the file first and leave identical bytes alone. --- .../EjectCommandTests.cs | 21 +++++++++++++++++++ server/csharp/MetaObjects.Cli/EjectCommand.cs | 21 +++++++++++++++---- .../OverwriteHashManifestTests.cs | 14 +++++++++++++ .../MetaObjects.Codegen/CodegenRunner.cs | 13 ++++++++---- .../MetaObjects.Codegen/GenFingerprint.cs | 5 ++++- 5 files changed, 65 insertions(+), 9 deletions(-) diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs index a9c686e617..6a9f045acb 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs @@ -118,6 +118,27 @@ public void Force_replaces_an_edited_copy() Assert.DoesNotContain("hand edit", File.ReadAllText(copyPath)); } + [Fact] + public void Force_over_an_unedited_copy_rewrites_nothing() + { + // Compare before write: --force over files that already match the reference reports them + // unchanged and leaves their bytes and timestamps alone. + Assert.Equal(0, EjectCommand.Run(["routes"], _root, force: false).ExitCode); + var copyPath = Path.Combine(GeneratorsDir, "RoutesGenerator.cs"); + var parser = Path.Combine(RuntimeDir, "FilterParser.cs"); + var stamp = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(copyPath, stamp); + File.SetLastWriteTimeUtc(parser, stamp); + + var forced = EjectCommand.Run(["routes"], _root, force: true); + + Assert.Equal(0, forced.ExitCode); + Assert.Contains(forced.Out, l => l.Contains("RoutesGenerator.cs [unchanged]")); + Assert.Contains(forced.Out, l => l.Contains("FilterParser.cs [unchanged]")); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(copyPath)); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(parser)); + } + [Fact] public void A_second_eject_of_a_different_generator_does_not_touch_the_existing_scaffold() { diff --git a/server/csharp/MetaObjects.Cli/EjectCommand.cs b/server/csharp/MetaObjects.Cli/EjectCommand.cs index 8cd3d7e2af..d10edd8e4e 100644 --- a/server/csharp/MetaObjects.Cli/EjectCommand.cs +++ b/server/csharp/MetaObjects.Cli/EjectCommand.cs @@ -196,8 +196,7 @@ public static Outcome Run(IReadOnlyList names, string root, bool force) var file = entry.SourceFileName!; var rewritten = EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSource(name)!); var dest = Path.Combine(generatorsDir, file); - var status = File.Exists(dest) ? "replaced" : "created"; - File.WriteAllText(dest, rewritten); + var status = WriteOwnedCopy(dest, rewritten, File.Exists(dest) ? "replaced" : "created"); outLines.Add($"ejected \"{name}\" -> codegen/generators/{file} [{status}]"); } outLines.AddRange(EjectCompanions(root, names.Select(n => known[n]).ToList(), force)); @@ -352,6 +351,19 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) return new Outcome(0, lines, []); } + /// + /// Write one reference copy to and return the status to report: + /// when the bytes were written, unchanged when the file on + /// disk already holds exactly . An identical file is never + /// rewritten, so --force over an unedited copy leaves it, and its timestamp, alone. + /// + private static string WriteOwnedCopy(string dest, string content, string status) + { + if (File.Exists(dest) && File.ReadAllText(dest) == content) return "unchanged"; + File.WriteAllText(dest, content); + return status; + } + /// /// Copy the emitters the ejected write their output through /// () next to the generators, each once however @@ -382,7 +394,8 @@ private static List EjectCompanions(string root, IReadOnlyList EjectRuntime(string root, IReadOnlyList user lines.Add($" {HelperRuntime.OwnedDirectory}/{file} [kept — already yours]"); continue; } - File.WriteAllText(dest, HelperRuntime.OwnedReference(file)); + status = WriteOwnedCopy(dest, HelperRuntime.OwnedReference(file), status); lines.Add($" {HelperRuntime.OwnedDirectory}/{file} [{status}]"); } lines.Add( diff --git a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs index acb23ee248..b725e8f050 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs @@ -495,4 +495,18 @@ public void WithoutGenStateDir_LegacyMarkerRuleStands() File.WriteAllText(TargetPath, "// \nold\n"); Assert.Equal("written", Run("// \nnew\n", withState: false).Files[0].Status); } + + [Fact] + public void WithoutGenStateDir_AnUnchangedFileIsNotRewritten() + { + // The no-manifest path compares before writing, as the manifest path does: a second + // run over identical output reports "unchanged" and leaves the file untouched. + const string content = "// \nsame\n"; + Assert.Equal("written", Run(content, withState: false).Files[0].Status); + var stamp = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(TargetPath, stamp); + + Assert.Equal("unchanged", Run(content, withState: false).Files[0].Status); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(TargetPath)); + } } diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index 4d501b44ea..e46a4f4534 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -257,7 +257,8 @@ private static IEnumerable Emit(IGenerator generator, GenContext ct /// /// /// With no state dir the legacy marker rule stands, preserving the previous behaviour - /// (and its status string) for programmatic callers. + /// (and its status string) for programmatic callers; identical content is still + /// unchanged and never rewritten. /// /// private static string WriteOne( @@ -272,14 +273,18 @@ private static string WriteOne( if (config.GenStateDir is null || manifest is null) { - if (exists && !File.ReadAllText(full).Contains(GeneratedMarker, StringComparison.Ordinal)) + var onDisk = exists ? File.ReadAllText(full) : null; + // Identical bytes are left alone, as on the manifest path: an unchanged file is + // never rewritten, whichever path a run takes. + if (onDisk == content) return "unchanged"; + if (onDisk is not null && !onDisk.Contains(GeneratedMarker, StringComparison.Ordinal)) { warnings.Add($"refusing to overwrite hand-written file: {relPath}"); return "skipped-handwritten"; } WriteFile(full, content); - // "written" for both a create and an overwrite, preserving the exact status - // vocabulary this path had before the manifest existed — callers key on it. + // "written" for both a create and an overwrite, preserving the status vocabulary + // this path had before the manifest existed — callers key on it. return "written"; } diff --git a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs index 3adffd1284..08c2d0c39a 100644 --- a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs +++ b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs @@ -309,7 +309,10 @@ public static void Write( format = FormatVersion, model, identity, outputs, untracked = (untracked ?? []).Order(StringComparer.Ordinal).ToArray(), }, new JsonSerializerOptions { WriteIndented = true }); - File.WriteAllText(PathFor(projectRoot), json + "\n"); + // Compared first, like every other write: a run that changes nothing leaves the file alone. + var path = PathFor(projectRoot); + var text = json + "\n"; + if (!File.Exists(path) || File.ReadAllText(path) != text) File.WriteAllText(path, text); } private static string? DiskHash(string projectRoot, string key) From 0e80885293ffaa83ed383ea845223b58ce0dcf8b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:00:02 -0500 Subject: [PATCH 2/4] refactor(codegen-cs): build routes and the remaining generators from overridable pieces (ADR-0063 item 7) W-CS-4 polish. RoutesGenerator works out a file's plan once (PlanStandardRoutes, PlanTphRoutes) and writes it from one protected virtual method per piece: the header, the list, item, create, update and delete routes, the M:N traversals, the TPH polymorphic list and item routes and the sort dispatch. Its Append* helpers become protected virtual Write*, and its other helpers and records are protected. Expression-indexes, report-export, requirement-tests, shared-model and api-docs get the same shape; ApiDocsGenerator is no longer sealed. Output is byte-identical: every registered generator over the 394 loadable fixture models in four layouts hashes the same before and after. --- CHANGELOG.md | 15 + docs/ports/csharp.md | 11 +- .../EntityGeneratorTests.cs | 9 +- .../TphM2mRoutesTests.cs | 2 +- .../Generators/ApiDocsGenerator.cs | 18 +- .../Generators/ExpressionIndexesGenerator.cs | 81 +- .../Generators/KNOWN_GAPS.md | 2 +- .../Generators/ReportExportGenerator.cs | 14 +- .../Generators/RequirementTestsGenerator.cs | 52 +- .../Generators/RoutesGenerator.cs | 719 ++++++++++-------- .../Generators/SharedModelGenerator.cs | 10 +- .../MetaObjects.Codegen/Generators/TphPlan.cs | 2 +- .../ApiContractApiSettingsConformanceTest.cs | 2 +- .../Api/M2mReferenceServer.cs | 2 +- ...eObjectWriteBehaviorGeneratedServerTest.cs | 2 +- 15 files changed, 563 insertions(+), 378 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fc6b97f76..3e489091d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,21 @@ here.** ## [Unreleased] +- **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone + when the project keeps a hash manifest. It now does the same on the path with no manifest (output + written outside the project, or a program that runs the generators with no state directory), which + reports the file `unchanged` instead of `written`. `dotnet meta eject --force` compares each copy + (the generator, its emitters and the helper runtime) before writing it and reports one that already + matches the reference as `[unchanged]`. The gen fingerprint is rewritten only when it changes. +- **C#: the routes, expression-indexes, report-export, requirement-tests, shared-model and api-docs + generators are built from overridable pieces (ADR-0063 item 7).** The routes generator works out + what a file serves once (`PlanStandardRoutes`, `PlanTphRoutes`) and writes it from one + `protected virtual` method per piece: the file header, the list, item, create, update and delete + routes, the M:N traversals, the TPH polymorphic list and item routes, the sort dispatch and the + helper members. Its `Append*` helpers are renamed `Write*` and are `protected virtual`; its other + helpers and records are `protected`. The other generators follow the same rule, and `ApiDocsGenerator` + is no longer sealed. A subclass overrides the piece it wants and keeps the rest. Output is + byte-identical. These methods are not a stability contract. - **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` diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index ede23a890d..9a4934ddce 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -329,11 +329,12 @@ prints a warning naming the line to change. See **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. +blank lines, so a generator states what the file says and not how many spaces it takes. Every +generator is written on it. Each is a class whose file is built from one overridable method per +piece (`WriteFileHeader`, `WriteTypeDoc`, `WriteMembers` and so on; in the routes generator +`WriteListRoute`, `WriteCreateRoute`, `WriteUpdateRoute` and the rest, over a plan worked out once +by `PlanStandardRoutes` or `PlanTphRoutes`), 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. diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs index eb97630dff..c0e7c6425e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs @@ -409,9 +409,14 @@ public void Runner_writes_generated_files_but_refuses_handwritten() Assert.Contains(r1.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written"); Assert.True(File.Exists(Path.Combine(dir, "Subscriber.g.cs"))); - // Re-run overwrites the @generated file. + // Re-running over identical output leaves the file alone. var r2 = CodegenRunner.Run(config, Load(), [new EntityGenerator()]); - Assert.Contains(r2.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written"); + Assert.Contains(r2.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "unchanged"); + + // A stale @generated file is overwritten. + File.WriteAllText(Path.Combine(dir, "Subscriber.g.cs"), "// \n// stale\n"); + var r2b = CodegenRunner.Run(config, Load(), [new EntityGenerator()]); + Assert.Contains(r2b.Files, f => f.Path == "Subscriber.g.cs" && f.Status == "written"); // A hand-written file (no marker) is refused. File.WriteAllText(Path.Combine(dir, "Subscriber.g.cs"), "// my hand-written file\n"); diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs index c8b2d1d8ad..e6929e6eb5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs @@ -1,7 +1,7 @@ // TphM2mRoutesTests — FW-8: M:N traversal inside a TPH hierarchy (C# port). // // A TPH base's routes generator never consulted M2MNavigationBuilder at all — neither -// GenerateTphRoutes (the base + per-subtype CRUD emitter) nor AppendTphSubtypeRoutes +// GenerateTphRoutes (the base + per-subtype CRUD emitter) nor WriteTphSubtypeRoutes // asked the relation map a single question — so every many-to-many navigation declared // anywhere in a TPH hierarchy vanished from the generated API. Nothing failed: a route // that is never mounted is an ABSENCE, not a compile error, which is why the existing diff --git a/server/csharp/MetaObjects.Codegen/Generators/ApiDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ApiDocsGenerator.cs index e23bf4f5d4..18c96fbccd 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ApiDocsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ApiDocsGenerator.cs @@ -13,7 +13,7 @@ namespace MetaObjects.Codegen.Generators; -public sealed class ApiDocsGenerator : IGenerator +public class ApiDocsGenerator : IGenerator { /// The api-surface subdirectory of the cross-port docs contract. public const string DefaultApiSubDir = "api/csharp"; @@ -38,8 +38,8 @@ public sealed class ApiDocsGenerator : IGenerator public IEnumerable Generate(GenContext ctx) { - var model = new CSharpApiModelBuilder(ctx.Config, ctx.Applicability).Build(ctx.Root, ProjectName); - var renderer = new CSharpApiDocsRenderer(); + var model = BuildModel(ctx); + var renderer = NewRenderer(); const DocsPaths.Layout layout = DocsPaths.Layout.Package; // Refused before anything is yielded: two pages that are one file must not half-write. DocsPaths.AssertNoDuplicateDocPaths(model.Units.Select(u => ( @@ -58,5 +58,15 @@ public IEnumerable Generate(GenContext ctx) yield return Page("AGENT-API.md", renderer.RenderAgentApi(model)); } - private EmittedFile Page(string pagePath, string content) => new(ApiSubDir + "/" + pagePath, content); + // The pieces, one overridable method each (ADR-0063 item 7). Not a stability contract. + + /// The page model the pages are rendered from. + protected virtual CSharpApiModel BuildModel(GenContext ctx) => + new CSharpApiModelBuilder(ctx.Config, ctx.Applicability).Build(ctx.Root, ProjectName); + + /// The renderer that turns the page model into Markdown. + protected virtual CSharpApiDocsRenderer NewRenderer() => new(); + + /// One page, under . + protected virtual EmittedFile Page(string pagePath, string content) => new(ApiSubDir + "/" + pagePath, content); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs index b03ada4a77..b3587acde6 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs @@ -25,6 +25,28 @@ public class ExpressionIndexesGenerator : IGenerator public string FileName { get; init; } = "expression-indexes.g.sql"; public IEnumerable Generate(GenContext ctx) + { + var statements = CollectStatements(ctx); + if (statements.Count == 0) yield break; + + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + WriteStatements(w, statements.Values); + yield return new EmittedFile(FileName, 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(); + + /// + /// Every expression index of the model, keyed schema/name so the file lists them in a + /// stable order, each as one CREATE INDEX statement (). + /// + protected virtual SortedDictionary CollectStatements(GenContext ctx) { var statements = new SortedDictionary(StringComparer.Ordinal); foreach (var o in ctx.Entities.Where(o => o.IsEntity() && InstanceArtifacts.EmitsInstanceArtifacts(o))) @@ -45,52 +67,67 @@ MetaIndex mi when mi.IsLookup() => false, _ => null, }; if (unique is null || node.Attr(IDENTITY_ATTR_EXPR) is not string { Length: > 0 } expr) continue; - var table = CSharpNaming.Table(owner); var schema = owner.Sources().FirstOrDefault(s => s.SubType == SOURCE_SUBTYPE_RDB)?.Schema; - var relation = string.IsNullOrEmpty(schema) ? Quote(table) : Quote(schema) + "." + Quote(table); var name = IndexNaming.ResolveIndexName(node); - var sql = new StringBuilder() - .Append(unique.Value ? "CREATE UNIQUE INDEX IF NOT EXISTS " : "CREATE INDEX IF NOT EXISTS ") - .Append(Quote(name)).Append(" ON ").Append(relation); - if (node.Attr(IDENTITY_ATTR_USING) is string method && method.Trim().Length > 0 && method.Trim() != "btree") - sql.Append(" USING ").Append(method.Trim()); - sql.Append(" (").Append(expr.Trim()).Append(')'); - if (node.Attr(IDENTITY_ATTR_WHERE) is string where && where.Trim().Length > 0) - sql.Append(" WHERE ").Append(where.Trim()); // An index name is unique per schema, tables included (migrate's ERR_DUPLICATE_SQL_NAME): // two tables claiming one would leave the second unbuilt under IF NOT EXISTS. ctx.Claim($"the indexes of schema \"{(string.IsNullOrEmpty(schema) ? "(default)" : schema)}\"", name, owner.ResolutionKey(), "an index's name is used verbatim, so give each table its own (declare it on each concrete entity)"); - statements[$"{schema}/{name}"] = sql.Append(';').ToString(); + statements[$"{schema}/{name}"] = BuildStatement(node, owner, schema, name, unique.Value, expr); } } - if (statements.Count == 0) yield break; + return statements; + } - // 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(); + /// + /// One CREATE [UNIQUE] INDEX IF NOT EXISTS statement for on + /// 's table, with its @using (when not btree) and @where. + /// + protected virtual string BuildStatement(MetaData node, MetaObject owner, string? schema, string name, bool unique, string expr) + { + var table = CSharpNaming.Table(owner); + var relation = string.IsNullOrEmpty(schema) ? Quote(table) : Quote(schema) + "." + Quote(table); + var sql = new StringBuilder() + .Append(unique ? "CREATE UNIQUE INDEX IF NOT EXISTS " : "CREATE INDEX IF NOT EXISTS ") + .Append(Quote(name)).Append(" ON ").Append(relation); + if (node.Attr(IDENTITY_ATTR_USING) is string method && method.Trim().Length > 0 && method.Trim() != "btree") + sql.Append(" USING ").Append(method.Trim()); + sql.Append(" (").Append(expr.Trim()).Append(')'); + if (node.Attr(IDENTITY_ATTR_WHERE) is string where && where.Trim().Length > 0) + sql.Append(" WHERE ").Append(where.Trim()); + return sql.Append(';').ToString(); + } + + /// The two header comments. A SQL file, so the comments are --. + protected virtual void WriteFileHeader(CsWriter w) + { 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) + } + + /// + /// The statements, in order. The writer still owns the line breaks: an expression written over + /// several lines stays on several lines, each handed to the writer on its own. + /// + protected virtual void WriteStatements(CsWriter w, IEnumerable statements) + { + foreach (var statement in statements) { 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) => + protected static IEnumerable IndexNodes(MetaObject o) => o.SecondaryIdentities().Cast().Concat(o.LookupIndexes()); /// The nearest ancestor that is in the EF model itself (a concrete TPH level or the root). - private static MetaObject? NearestConcreteAncestor(MetaObject o) + protected static MetaObject? NearestConcreteAncestor(MetaObject o) { for (var s = o.SuperData as MetaObject; s is not null; s = s.SuperData as MetaObject) if (InstanceArtifacts.EmitsInstanceArtifacts(s)) return s; return null; } - private static string Quote(string name) => "\"" + name.Replace("\"", "\"\"") + "\""; + protected static string Quote(string name) => "\"" + name.Replace("\"", "\"\"") + "\""; } diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 79f2a1fcb8..94aefe522c 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -43,7 +43,7 @@ Update when a gap closes or a new one surfaces. **`field.map` is not in this gap.** A map column is not a navigation — it is a scalar-shaped property carrying a value converter (G9) — so `FindProperty` resolves it and the generic merge arm writes it on PATCH. Map columns are patch-settable here, as on Java; Kotlin alone stages them out of its patch set (see its `KNOWN_GAPS.md`). -**Today.** On the vanilla (non-TPH) PATCH/PUT handler a VO-typed column IS patch-settable. The handler passes the entity's VO fields into `AppendPartialMergeLoop` (`RoutesGenerator.cs:256`), which emits a Program D typed value-object arm for each one AHEAD of the generic `entry.Metadata.FindProperty(prop.Name)` arm — an owned navigation is invisible to `FindProperty`, so the generic scalar path alone would silently drop the column. Per arm: a present value is deserialized, recursively validated (`ValueObjectValidator.Validate`), and assigned to the CLR navigation property; a present `null` clears a nullable VO column — a nullable array-of-VO additionally takes a post-save raw UPDATE, since EF's `OwnsMany(...).ToJson` writes `[]` for a null collection nav rather than SQL NULL — or 400s a `@required` one; an absent key leaves the column untouched. This is the same Program D shipment Java's `KNOWN_GAPS.md` records as cross-port (TS / Python / Java / Kotlin / C#), gated by `fixtures/api-contract-conformance/jsonb/scenarios/jsonb-value-object-patch.yaml` in both lanes. +**Today.** On the vanilla (non-TPH) PATCH/PUT handler a VO-typed column IS patch-settable. The handler passes the entity's VO fields into `WritePartialMergeLoop` (`RoutesGenerator.cs`), which emits a Program D typed value-object arm for each one AHEAD of the generic `entry.Metadata.FindProperty(prop.Name)` arm — an owned navigation is invisible to `FindProperty`, so the generic scalar path alone would silently drop the column. Per arm: a present value is deserialized, recursively validated (`ValueObjectValidator.Validate`), and assigned to the CLR navigation property; a present `null` clears a nullable VO column — a nullable array-of-VO additionally takes a post-save raw UPDATE, since EF's `OwnsMany(...).ToJson` writes `[]` for a null collection nav rather than SQL NULL — or 400s a `@required` one; an absent key leaves the column untouched. This is the same Program D shipment Java's `KNOWN_GAPS.md` records as cross-port (TS / Python / Java / Kotlin / C#), gated by `fixtures/api-contract-conformance/jsonb/scenarios/jsonb-value-object-patch.yaml` in both lanes. **Residual.** TPH only: the per-subtype partial-update path passes an empty VO list (`RoutesGenerator.cs:961`), so VO columns on a TPH-rooted entity are still skipped on PATCH — the same staging-out Java's entry records for TPH. diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index e15f88f71f..cc3e32db60 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -86,9 +86,10 @@ public IEnumerable Generate(GenContext ctx) yield return new EmittedFile(OutputPaths.Of(report, ctx, CSharpNaming.Pascal(report.Name) + "Export.g.cs"), ReportModule(report, ctx)); } - private static string Literal(bool b) => b ? "true" : "false"; + protected static string Literal(bool b) => b ? "true" : "false"; - private string ReportModule(MetaObject report, GenContext ctx) + /// The <Report>Export.g.cs module of one served report: its columns and its two writers. + protected virtual 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. @@ -144,16 +145,17 @@ private string ReportModule(MetaObject report, GenContext ctx) // 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);"; + protected const string DurationDoc = "a duration as its canonical ISO-8601 string, "; + protected 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) => + protected 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) + /// The shared ReportExportWriter.g.cs: the CSV and XML writers and the wire form of a cell. + protected virtual string SharedWriter(GenContext ctx, bool durations) { var w = new CsWriter(); w.Text($$""" diff --git a/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs index cdf718188a..1a4798b54f 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RequirementTestsGenerator.cs @@ -48,10 +48,10 @@ public class RequirementTestsGenerator : IGenerator public const string ErrWitnessKeyCollision = "ERR_REQUIREMENT_WITNESS_KEY_COLLISION"; /// How many uncovered requirements to name before "and N more". - private const int MaxNamedUncovered = 5; + protected const int MaxNamedUncovered = 5; - private const string SkipPlanned = "planned - not built yet"; - private const string SkipRetired = "retired - the capability was deliberately removed; assert it stays removed"; + protected const string SkipPlanned = "planned - not built yet"; + protected const string SkipRetired = "retired - the capability was deliberately removed; assert it stays removed"; public string Name => "requirement-tests"; @@ -96,7 +96,7 @@ public class RequirementTestsGenerator : IGenerator public bool WarnUncovered { get; init; } = true; /// One test to write: its identity and the data its rendering is built from. - private sealed record Planned(RequirementTestIdentity Identity, RequirementTestArgs Args); + protected record Planned(RequirementTestIdentity Identity, RequirementTestArgs Args); public IEnumerable Generate(GenContext ctx) { @@ -145,14 +145,14 @@ public IEnumerable Generate(GenContext ctx) /// message can say the name as it was written, and the spelling that is emitted as code, where a segment that /// is a C# keyword is escaped with @. /// - private sealed record DottedName(IReadOnlyList Segments) + protected record DottedName(IReadOnlyList Segments) { public string Plain => string.Join('.', Segments); public string Code => string.Join('.', Segments.Select(s => Keywords.Contains(s) ? "@" + s : s)); } - private const string GlobalPrefix = "global::"; + protected const string GlobalPrefix = "global::"; /// /// Parse an option that names a namespace or a class. Each segment must be a legal C# identifier (non-ASCII @@ -160,7 +160,7 @@ private sealed record DottedName(IReadOnlyList Segments) /// on a namespace, which cannot carry one, and accepted and removed on a class, since the generator emits /// global:: itself. /// - private static DottedName ParsedName(string option, string value, bool allowGlobal) + protected static DottedName ParsedName(string option, string value, bool allowGlobal) { var text = value.Trim(); if (text.StartsWith(GlobalPrefix, StringComparison.Ordinal)) @@ -184,7 +184,7 @@ private static DottedName ParsedName(string option, string value, bool allowGlob /// connector punctuation and formatting characters (ECMA-334, "Identifiers"). The check is by Unicode category, /// so a legal non-ASCII name is accepted. /// - private static bool IsIdentifier(string s) + protected static bool IsIdentifier(string s) { if (s.Length == 0) return false; for (var i = 0; i < s.Length; i += char.IsSurrogatePair(s, i) ? 2 : 1) @@ -202,7 +202,7 @@ or UnicodeCategory.TitlecaseLetter or UnicodeCategory.ModifierLetter or UnicodeC } /// The C# keywords: a segment spelt like one is escaped with @ where it is emitted. - private static readonly HashSet Keywords = new(StringComparer.Ordinal) + protected static readonly HashSet Keywords = new(StringComparer.Ordinal) { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", @@ -217,7 +217,7 @@ or UnicodeCategory.TitlecaseLetter or UnicodeCategory.ModifierLetter or UnicodeC // planning // ------------------------------------------------------------------ - private static RequirementTestArgs ArgsFor( + protected static RequirementTestArgs ArgsFor( MetaRequirement node, RequirementTestIdentity identity, IReadOnlyList targets) => new( identity, @@ -228,11 +228,11 @@ private static RequirementTestArgs ArgsFor( node.TrackedBy); /// root for the empty package, otherwise the package with each run of non-ASCII-alphanumerics as one underscore. - private static string PackageKey(string package) => + protected static string PackageKey(string package) => package.Length == 0 ? "root" : RequirementTestIdentities.Mangle(package); /// Two tests with one witness key cannot be told apart by a witness: refuse, naming both. - private static void RefuseCollisions(List planned) + protected static void RefuseCollisions(List planned) { var pairs = RequirementTestIdentities.WitnessKeyCollisions(planned.Select(p => p.Identity)); if (pairs.Count == 0) return; @@ -246,7 +246,7 @@ private static void RefuseCollisions(List planned) throw new InvalidOperationException(w.ToString().TrimEnd()); } - private static string UncoveredWarning(IReadOnlyList uncovered) + protected static string UncoveredWarning(IReadOnlyList uncovered) { var shown = string.Join(", ", uncovered.Take(MaxNamedUncovered)); var more = uncovered.Count > MaxNamedUncovered @@ -261,10 +261,10 @@ private static string UncoveredWarning(IReadOnlyList uncovered) // ------------------------------------------------------------------ // 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."; + protected const string HeaderGenerated = "// "; + protected 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) + protected virtual string WitnessInterface(DottedName testNamespace, string name, DottedName witnessClass, List tests) { // A real member shows the shape; with none (every test skipped) the pattern stands in for a name. var example = tests.FirstOrDefault(t => t.Identity.Skip is null)?.Identity.WitnessKey ?? "req_
__"; @@ -294,7 +294,7 @@ private static string WitnessInterface(DottedName testNamespace, string name, Do return w.ToString(); } - private static string TestClass( + protected virtual string TestClass( DottedName testNamespace, string name, string witnesses, DottedName witnessClass, List tests, IRequirementTestRenderer? renderer) { var w = new CsWriter(); @@ -335,7 +335,7 @@ private static string TestClass( } /// The default rendering of one test: its comments, then a [Fact] calling the witness. - private static string DefaultTest(Planned p) + protected virtual string DefaultTest(Planned p) { var id = p.Identity; var w = new CsWriter(); @@ -354,7 +354,7 @@ private static string DefaultTest(Planned p) return w.ToString(); } - private static string SkipReason(string skip) => skip switch + protected static string SkipReason(string skip) => skip switch { RequirementConstants.REQUIREMENT_STATUS_PLANNED => SkipPlanned, RequirementConstants.REQUIREMENT_STATUS_RETIRED => SkipRetired, @@ -362,7 +362,7 @@ private static string DefaultTest(Planned p) }; /// The comment block above a test: id, statement, counterexample, status, claims, digest. - private static void WriteTestComments(CsWriter w, RequirementTestArgs a) + protected virtual void WriteTestComments(CsWriter w, RequirementTestArgs a) { var id = a.Identity; var claims = a.Targets.Count == 0 @@ -381,19 +381,19 @@ private static void WriteTestComments(CsWriter w, RequirementTestArgs a) // ------------------------------------------------------------------ // 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 Regex("\r\n|[\r\n\u0085\u2028\u2029]", RegexOptions.CultureInvariant); + protected 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 void WriteComment(CsWriter w, string text) + protected 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); + protected static string CommentText(string line) => line.Replace("*/", "* /", StringComparison.Ordinal); /// /// The text of a regular string literal. Every control character, and the three line terminators beyond @@ -401,10 +401,10 @@ private static void WriteComment(CsWriter w, string text) /// 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; + protected const char LineFeed = (char)0x0A; + protected const char CarriageReturn = (char)0x0D; - private static string StringLiteral(string s) + protected static string StringLiteral(string s) { var sb = new StringBuilder(); for (var i = 0; i < s.Length; i++) diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 006789c712..210b416e7b 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -23,7 +23,7 @@ // - Update accepts BOTH PATCH and PUT (TS reference exposes both; we match). // - 404 responses carry a JSON envelope: { "error": "not_found" }. // - A read-only projection mounts the reads AND every write verb, each answering -// 405 { "error": "method_not_allowed" } (F22) — see AppendProjectionRejects. +// 405 { "error": "method_not_allowed" } (F22) — see WriteProjectionRejects. // - A view-backed report (FR-044) is served as a keyless read: the list GET and a 405 // on POST, with no /{id} address at all (a report has no identity). // @@ -118,7 +118,7 @@ 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(CsWriter w, string cls, bool readOnly) + protected virtual void WriteUnauthenticatedRoutesDoc(CsWriter w, string cls, bool readOnly) { var verbs = readOnly ? "read endpoints" : "endpoints"; w.Line($"/// Maps {cls} REST routes. Unauthenticated — see remarks."); @@ -155,7 +155,7 @@ private static void AppendUnauthenticatedRoutesDoc(CsWriter w, string cls, bool // (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(CsWriter w, int? exportMaxRows) + protected virtual void WriteReportPaging(CsWriter w, int? exportMaxRows) { var max = ReportMaxRows.ToString(System.Globalization.CultureInfo.InvariantCulture); var tooLarge = "Results.BadRequest(new { error = \"report_too_large\", maxRows })"; @@ -197,7 +197,7 @@ private void AppendReportPaging(CsWriter w, int? exportMaxRows) // 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(CsWriter w, string cls, string route) + protected virtual void WriteReportExportBranch(CsWriter w, string cls, string route) { w.Blank(); w.Line("// Export (report-export): the same rows as a download. withCount with csv or xml was refused above."); @@ -210,7 +210,7 @@ private static void AppendReportExportBranch(CsWriter w, string cls, string rout // Every type the route file names bare — the entity itself, its value objects (owned and map // values) and the targets and junctions of its M:N traversals — so a split-namespace model gets // a `using` for each package namespace the home-namespace file reaches into. - private static IEnumerable ReferencedTypes(IEnumerable entities, MetaRoot root) + protected static IEnumerable ReferencedTypes(IEnumerable entities, MetaRoot root) { foreach (var entity in entities) { @@ -227,7 +227,31 @@ private static IEnumerable ReferencedTypes(IEnumerable ent } } - protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenContext ctx) + // The pieces of a routes 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 a routes file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// + /// Everything a standard (non-TPH) routes file is written from, worked out once by + /// so every piece reads the same answers. + /// + protected record StandardRoutesPlan( + MetaObject Entity, GenContext Ctx, string Cls, string DbSet, string Route, + IReadOnlyList PkFields, string? PkType, string? PkProp, + bool IsProjection, bool HasItem, bool Writable, bool WriteThrough, string ReadCls, string ReadDbSet, + List VoFields, List MapVoFields, List AutoSetFields, + List FrozenNavs, List DeniedFields, List Credentials, + string TableRef, string PkColumnRef, bool IsReport, int? ExportMaxRows, + List SortFieldNodes, List SortFields, HashSet DecimalSortFields, bool SqliteSort) + { + /// The generated DbContext's type, as the route handlers name it. + public string ContextType => ValueObjectNames.ContextTypeRef(Ctx.Config); + } + + /// Work out what the standard routes file for serves. + protected virtual StandardRoutesPlan PlanStandardRoutes(MetaObject entity, GenContext ctx) { var cls = CSharpNaming.Pascal(entity.Name); var dbSet = CSharpNaming.DbSetName(entity); @@ -270,7 +294,6 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // (insert stamps all; update stamps onUpdate; the merge loop skips them; an // InsertPreserving escape hatch is emitted when any exist). var autoSetFields = AutoSetFields(entity, ctx.Config); - var autoSetNavs = autoSetFields.Select(a => a.Nav).ToList(); // FR-037 R1 — readOnly / writeOnce are excluded from the PATCH merge. var frozenNavs = FrozenNavs(entity, ctx.Config); // #484 — write-denied (@formExclude or credential) keys are ignored on every write; credentials never leave. @@ -279,7 +302,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // Physical table + PK column for the post-save array-null clear (EF OwnsMany ToJson // writes [] for a null nav, so a nullable array column is NULLed via raw SQL). Both // are C# EXPRESSIONS — the Names constant when the names artifact is in this - // run, the quoted literal otherwise — spliced into that SQL by AppendArrayNullClears. + // run, the quoted literal otherwise — spliced into that SQL by WriteArrayNullClears. var tableRef = CSharpNaming.NameRef(entity, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, CSharpNaming.Table(entity), qualify: ctx.Config); var pkColumnRef = pkFields.Count == 1 && entity.Fields().FirstOrDefault(f => f.Name == pkFields[0]) is { } pkf ? CSharpNaming.ColumnRef(entity, pkf, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames, ctx.Config) @@ -320,9 +343,80 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte .ToHashSet(StringComparer.Ordinal); bool sqliteSort = sortFields.Any(decimalSortFields.Contains); - var w = new CsWriter(); + return new StandardRoutesPlan( + entity, ctx, cls, dbSet, route, pkFields, pkType, pkProp, + isProjection, hasItem, writable, writeThrough, readCls, readDbSet, + voFields, mapVoFields, autoSetFields, frozenNavs, deniedFields, credentials, + tableRef, pkColumnRef, isReport, export, sortFieldNodes, sortFields, decimalSortFields, sqliteSort); + } + + protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenContext ctx) + { + var p = PlanStandardRoutes(entity, ctx); + var w = NewWriter(); + WriteFileHeader(w, [entity], entity, ctx, tph: false); + w.Line($"public static class {p.Cls}Routes"); + w.Open("{"); + // Static sort allowlist (case-insensitive) so the qs ?sort=field:dir + // is gated against the entity's scalar fields. + WriteSortAllowlist(w, "SortAllowlist", p.SortFieldNodes, ctx.Config); + WriteSortDefaultOrder(w, entity, "SortDefaultDesc", ctx.Config); + if (p.Writable) WriteKnownFields(w, [entity], ctx.Root); + WriteUnauthenticatedRoutesDoc(w, p.Cls, p.IsProjection); + w.Line($"public static IEndpointRouteBuilder Map{p.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 (p.Credentials.Count > 0) + w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({p.ReadCls}) }}, {NamesLiteral(p.Credentials)});"); + WriteDecimalRangeGroup(w); + + WriteListRoute(w, p); + if (p.HasItem) WriteGetRoute(w, p); + if (p.Writable) + { + WriteCreateRoute(w, p); + WriteUpdateRoute(w, p); + WriteDeleteRoute(w, p); + } + else if (p.IsProjection) + { + WriteProjectionRejects(w, p.Route, p.PkType, p.HasItem, p.IsReport ? "report" : "projection"); + } + + // FR-018 M:N traversal — GET //{id}/ through the + // junction. Only on a single-PK source (the route addresses the source by id). + // Cross-port contract: source URL segment = pluralized ENTITY name, relation + // segment = relationship name. + if (p.HasItem) + foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) + WriteM2mRoute(w, nav, p.Route, p.PkType!, ctx.Root, ctx.Config); + + w.Blank(); + w.Line("return mount;"); + w.Close("}"); + w.Blank(); + WriteApplySort(w, p); + // 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 (p.Writable && p.AutoSetFields.Count > 0) + WriteInsertPreserving(w, p.Cls, p.DbSet, p.ContextType); + WriteOmitResultClass(w, p.Credentials.Count > 0 || (p.HasItem && M2mTargetHasCredentials([entity], ctx.Root, ctx.Config))); + w.Close("}"); + + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{p.Cls}Routes.g.cs"), w.ToString()); + } + + /// + /// The generated-file marker, the generator's name, the nullable context, the usings (one per + /// package namespace the file reaches into, from ) and the + /// namespace of . + /// + protected virtual void WriteFileHeader(CsWriter w, IEnumerable referenced, MetaObject home, GenContext ctx, bool tph) + { w.Line("// "); - w.Line("// Generated by MetaObjects routes-generator. Do not edit by hand."); + w.Line(tph + ? "// Generated by MetaObjects routes-generator (TPH). Do not edit by hand." + : "// 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;"); @@ -331,27 +425,18 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte 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))) w.Line(u); + foreach (var u in PackageBindingResolver.HomeUsings(ctx.Config, ReferencedTypes(referenced, ctx.Root))) w.Line(u); w.Blank(); - w.Line($"namespace {ValueObjectNames.CompanionNamespace(entity, ctx.Config)};"); + w.Line($"namespace {ValueObjectNames.CompanionNamespace(home, 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(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) - w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); - AppendDecimalRangeGroup(w); + } + /// The list route: GET /<route> with filter, sort, paging and withCount (and a report's export branch). + protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) + { + var (cls, route, readCls, readDbSet, credentials, export) = (p.Cls, p.Route, p.ReadCls, p.ReadDbSet, p.Credentials, p.ExportMaxRows); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. - w.Line("app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(ctx.Config) + " db) =>"); + w.Line("app.MapGet(prefix + \"/" + route + "\", async (HttpContext http, " + p.ContextType + " db) =>"); w.Open("{"); w.Line("var qs = http.Request.Query;"); if (export is not null) @@ -363,7 +448,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte 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); + var fm = FilterMapArg($"{cls}FilterAllowlist", p.Entity, p.Ctx.Config); 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 @@ -385,21 +470,21 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte 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) + if (p.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) + if (p.IsReport) { - AppendReportPaging(w, export); - if (export is not null) AppendReportExportBranch(w, cls, route); + WriteReportPaging(w, export); + if (export is not null) WriteReportExportBranch(w, cls, route); } else { w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); - AppendOffsetLimit(w, ctx.Root.Api.Pagination, "offsetRaw", "offset", "limitRaw", "limit"); + WriteOffsetLimit(w, p.Ctx.Root.Api.Pagination, "offsetRaw", "offset", "limitRaw", "limit"); w.Blank(); w.Line("var rows = await q.ToListAsync();"); } @@ -417,127 +502,135 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte else 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) - { - 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\" }));"); - } + /// The item route: GET /<route>/{id}, 404 not_found when absent. + protected virtual void WriteGetRoute(CsWriter w, StandardRoutesPlan p) + { + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + p.Route + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); + using (w.Hanging()) w.Line("await db." + p.ReadDbSet + ".FindAsync(id) is { } found"); + using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", p.Credentials)); + using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); + } - if (writable) + /// The create route: POST /<route> (see ). + protected virtual void WriteCreateRoute(CsWriter w, StandardRoutesPlan p) + { + var (entity, ctx) = (p.Entity, p.Ctx); + // FR-036 #4 — @required-key presence set (the non-PK @required fields whose keys + // must be PRESENT + non-null on a create body). A @required VALUE-TYPE field (e.g. + // 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 => p.PkFields.Contains(f.Name)); + 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). + WriteCreateHandler(w, "/" + p.Route, p.Cls, p.ContextType, p.DbSet, requiredKeys, + CreatedResult("prefix + \"/" + p.Route + "\"", "input", p.Credentials), p.VoFields, p.MapVoFields, p.AutoSetFields, + p.WriteThrough ? (p.ReadDbSet, p.PkProp!, p.Route) : null, + p.DeniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), p.Credentials, + ServerOwnedCreateResets(entity, ctx.Root, ctx.Config), ctx.Root, RequiredReadOnlyProps(entity, ctx.Config)); + } + + /// + /// The update handler and its two mounts, PATCH and PUT /<route>/{id}: a + /// partial merge of the JSON body. + /// + protected virtual void WriteUpdateRoute(CsWriter w, StandardRoutesPlan p) + { + var (entity, ctx, cls, dbSet, credentials) = (p.Entity, p.Ctx, p.Cls, p.DbSet, p.Credentials); + // PATCH + PUT share the same handler — TS reference exposes both verbs, and both + // return the updated row (HTTP 200), matching the cross-port api-contract. + // + // A PARTIAL merge of the JSON body, NOT a full-row overwrite. The previous + // implementation bound the body into a `cls input` and called + // `CurrentValues.SetValues(input)` — but a field ABSENT from a PATCH body + // deserializes to its CLR default (0 / null / false / DateTime.MinValue), and + // SetValues then wrote those defaults over the live row. A `PATCH {"name":"x"}` + // on a wide entity silently DESTROYED every other column. So enumerate the JSON + // that was actually sent and set only those properties — the same present-field + // merge the TPH per-subtype handler already uses. The PK stays route-authoritative. + // + // FR-035 PATCH-2 tristate: an OMITTED field is untouched; an explicit null + // 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 WritePartialMergeLoop. + w.Blank(); + w.Line("async System.Threading.Tasks.Task Update" + cls + "(" + p.PkType + " id, HttpContext http, " + p.ContextType + " 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();"); + WriteUnknownFieldsCheck(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);"); + WriteUpdateAutoSet(w, p.AutoSetFields); + WritePartialMergeLoop(w, null, p.VoFields, p.MapVoFields, p.AutoSetFields.Select(a => a.Nav).ToList(), p.FrozenNavs, HasDecimalField(entity), + p.DeniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), p.DeniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), HasIsoDurationField(entity, ctx.Root)); + WriteSaveChanges(w); + WriteArrayNullClears(w, p.VoFields, p.TableRef, p.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 (p.WriteThrough) { - // FR-036 #4 — @required-key presence set (the non-PK @required fields whose keys - // must be PRESENT + non-null on a create body). A @required VALUE-TYPE field (e.g. - // 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)); - 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(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, - ServerOwnedCreateResets(entity, ctx.Root, ctx.Config), ctx.Root, RequiredReadOnlyProps(entity, ctx.Config)); - - // PATCH + PUT share the same handler — TS reference exposes both verbs, and both - // return the updated row (HTTP 200), matching the cross-port api-contract. - // - // A PARTIAL merge of the JSON body, NOT a full-row overwrite. The previous - // implementation bound the body into a `cls input` and called - // `CurrentValues.SetValues(input)` — but a field ABSENT from a PATCH body - // deserializes to its CLR default (0 / null / false / DateTime.MinValue), and - // SetValues then wrote those defaults over the live row. A `PATCH {"name":"x"}` - // on a wide entity silently DESTROYED every other column. So enumerate the JSON - // that was actually sent and set only those properties — the same present-field - // merge the TPH per-subtype handler already uses. The PK stays route-authoritative. - // - // FR-035 PATCH-2 tristate: an OMITTED field is untouched; an explicit null - // 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. - 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(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) - { - 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). - w.Line($"return {OkResult("(object?)__view ?? existing", credentials)};"); - } - else - { - w.Line($"return {OkResult("existing", credentials)};"); - } - 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("});"); + w.Line($"var __view = await db.{p.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). + w.Line($"return {OkResult("(object?)__view ?? existing", credentials)};"); } - else if (isProjection) + else { - AppendProjectionRejects(w, route, pkType, hasItem, isReport ? "report" : "projection"); + w.Line($"return {OkResult("existing", credentials)};"); } - - // FR-018 M:N traversal — GET //{id}/ through the - // junction. Only on a single-PK source (the route addresses the source by id). - // Cross-port contract: source URL segment = pluralized ENTITY name, relation - // segment = relationship name. - if (hasItem) - foreach (var nav in M2MNavigationBuilder.For(entity, ctx.Root, ctx.Warn)) - AppendM2mRoute(w, nav, route, pkType!, ctx.Root, ctx.Config); - - w.Blank(); - w.Line("return mount;"); w.Close("}"); + w.Line("app.MapPatch(prefix + \"/" + p.Route + "/{id}\", Update" + cls + ");"); + w.Line("app.MapPut(prefix + \"/" + p.Route + "/{id}\", Update" + cls + ");"); + } + + /// The delete route: DELETE /<route>/{id}, 204 on success, 404 not_found when absent. + protected virtual void WriteDeleteRoute(CsWriter w, StandardRoutesPlan p) + { w.Blank(); + w.Line("app.MapDelete(prefix + \"/" + p.Route + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); + w.Open("{"); + w.Line("var existing = await db." + p.DbSet + ".FindAsync(id);"); + w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); + w.Line("db." + p.DbSet + ".Remove(existing);"); + WriteSaveChanges(w); + w.Line("return Results.NoContent();"); + w.Close("});"); + } + + /// + /// The sort dispatch, ApplySort<Cls>: each allowlisted property name to an + /// IOrderedQueryable through EF.Property. + /// + protected virtual void WriteApplySort(CsWriter w, StandardRoutesPlan p) + { + var readCls = p.ReadCls; // 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. - w.Line($"private static IOrderedQueryable<{readCls}> ApplySort{cls}(IQueryable<{readCls}> q, string field, bool desc{(sqliteSort ? ", bool sqlite" : "")})"); + w.Line($"private static IOrderedQueryable<{readCls}> ApplySort{p.Cls}(IQueryable<{readCls}> q, string field, bool desc{(p.SqliteSort ? ", bool sqlite" : "")})"); w.Open("{"); w.Line("return field switch"); w.Open("{"); - foreach (var name in sortFields) + foreach (var name in p.SortFields) { var exact = NullsLargestSort("q", $"EF.Property(x!, \"{name}\")"); - if (decimalSortFields.Contains(name)) + if (p.DecimalSortFields.Contains(name)) w.Line($"\"{name}\" => sqlite ? ({NullsLargestSort("q", $"(double?)EF.Property(x!, \"{name}\")")}) : ({exact}),"); else w.Line($"\"{name}\" => {exact},"); @@ -545,14 +638,6 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte 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(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"), w.ToString()); } // F22 — the write verbs on a read-only projection, each answering the cross-port @@ -572,20 +657,20 @@ 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(CsWriter w, string route, string? pkType, bool hasItem, string noun) + protected virtual void WriteProjectionRejects(CsWriter w, string route, string? pkType, bool hasItem, string noun) { w.Blank(); - AppendReject(w, "MapPost", "/" + route, "POST", null, noun); + WriteReject(w, "MapPost", "/" + route, "POST", null, noun); if (!hasItem) return; - AppendReject(w, "MapPatch", "/" + route + "/{id}", "PATCH", pkType, noun); - AppendReject(w, "MapPut", "/" + route + "/{id}", "PUT", pkType, noun); - AppendReject(w, "MapDelete", "/" + route + "/{id}", "DELETE", pkType, noun); + WriteReject(w, "MapPatch", "/" + route + "/{id}", "PATCH", pkType, noun); + WriteReject(w, "MapPut", "/" + route + "/{id}", "PUT", pkType, noun); + WriteReject(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(CsWriter w, string map, string path, string verb, string? pkType, string noun) + protected virtual void WriteReject(CsWriter w, string map, string path, string verb, string? pkType, string noun) { var parms = pkType is null ? "()" : "(" + pkType + " id)"; w.Line("app." + map + "(prefix + \"" + path + "\", " + parms + " =>"); @@ -604,7 +689,25 @@ private static void AppendReject(CsWriter w, string map, string path, string ver // // The base path (auths) is the pluralized base ENTITY name lowercased. ASP.NET routes // the static /auths/ ahead of the parametric /auths/{id}, so they coexist. - protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan tph, GenContext ctx) + /// + /// Everything a TPH base's routes file is written from, worked out once by + /// so every piece reads the same answers. + /// + protected record TphRoutesPlan( + MetaObject BaseEntity, TphPlan Tph, GenContext Ctx, string BaseCls, string DbSet, string BaseRoute, + string? PkType, string? PkProp, bool HasItem, string DiscProp, MetaField? DiscField, + List BaseCredentials, HashSet HierarchyCredentials, + List SortFieldNodes, List SortFields) + { + /// The generated DbContext's type, as the route handlers name it. + public string ContextType => ValueObjectNames.ContextTypeRef(Ctx.Config); + + /// The base followed by every concrete subtype. + public List Hierarchy => Tph.Subtypes.Select(st => st.Entity).Prepend(BaseEntity).ToList(); + } + + /// Work out what the routes file for the TPH base serves. + protected virtual TphRoutesPlan PlanTphRoutes(MetaObject baseEntity, TphPlan tph, GenContext ctx) { var baseCls = CSharpNaming.Pascal(baseEntity.Name); var dbSet = CSharpNaming.DbSetName(baseEntity); @@ -636,29 +739,25 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t .ToList(); var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); - 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))) w.Line(u); - w.Blank(); - w.Line($"namespace {ValueObjectNames.CompanionNamespace(baseEntity, ctx.Config)};"); - w.Blank(); + return new TphRoutesPlan(baseEntity, tph, ctx, baseCls, dbSet, baseRoute, pkType, pkProp, hasItem, + discProp, discField, baseCredentials, hierarchyCredentials, sortFieldNodes, sortFields); + } + + protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan tph, GenContext ctx) + { + var p = PlanTphRoutes(baseEntity, tph, ctx); + var baseCls = p.BaseCls; + + var w = NewWriter(); + WriteFileHeader(w, p.Hierarchy, baseEntity, ctx, tph: true); w.Line($"public static class {baseCls}Routes"); w.Open("{"); // Polymorphic sort allowlist over the base scalar columns. - AppendSortAllowlist(w, "SortAllowlist", sortFieldNodes, ctx.Config); - AppendSortDefaultOrder(w, baseEntity, "SortDefaultDesc", ctx.Config); + WriteSortAllowlist(w, "SortAllowlist", p.SortFieldNodes, ctx.Config); + WriteSortDefaultOrder(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(w, tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root); + WriteKnownFields(w, p.Hierarchy, 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 @@ -669,56 +768,27 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t { var subClsName = CSharpNaming.Pascal(st.Entity.Name); var subSortFields = st.Entity.Fields() - .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !hierarchyCredentials.Contains(f.Name)) + .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !p.HierarchyCredentials.Contains(f.Name)) .ToList(); - AppendSortAllowlist(w, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); - AppendSortDefaultOrder(w, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); + WriteSortAllowlist(w, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); + WriteSortDefaultOrder(w, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); } - AppendUnauthenticatedRoutesDoc(w, baseCls, readOnly: false); + WriteUnauthenticatedRoutesDoc(w, baseCls, readOnly: false); w.Line($"public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); w.Open("{"); - if (baseCredentials.Count > 0) + if (p.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)))); - w.Line($"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(p.BaseCredentials)});"); } - AppendDecimalRangeGroup(w); + WriteDecimalRangeGroup(w); - // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- - 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); - 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("});"); + WriteTphListRoute(w, p); - if (hasItem) + if (p.HasItem) { - // --- Polymorphic get: GET //{id} (one row of whatever subtype) --- - 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\" }));"); + WriteTphGetRoute(w, p); // 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 @@ -727,12 +797,12 @@ 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(w, nav, baseRoute, pkType!, ctx.Root, ctx.Config); + WriteM2mRoute(w, nav, p.BaseRoute, p.PkType!, ctx.Root, ctx.Config); // --- Per-subtype CRUD sets --- - var hierarchy = tph.Subtypes.Select(s => s.Entity).Prepend(baseEntity).ToList(); + var hierarchy = p.Hierarchy; foreach (var st in tph.Subtypes) - AppendTphSubtypeRoutes(w, st, hierarchy, ctx.Root, ctx.Config, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn); + WriteTphSubtypeRoutes(w, st, hierarchy, ctx.Root, ctx.Config, p.BaseRoute, baseCls, p.DbSet, p.PkType!, p.PkProp!, p.DiscProp, p.DiscField, ctx.Warn); } w.Blank(); @@ -740,29 +810,74 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t w.Close("}"); w.Blank(); - // Polymorphic sort dispatch over base scalar columns (reflection-free via EF.Property). - 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) - w.Line($"\"{name}\" => {NullsLargestSort("q", $"EF.Property(x!, \"{name}\")")},"); - w.Line("_ => (IOrderedQueryable<" + baseCls + ">)q.OrderBy(x => 0),"); - w.Close("};"); - w.Close("}"); + WriteTphApplySort(w, p); // 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) + if (p.HasItem) foreach (var st in tph.Subtypes) if (AutoSetFields(st.Entity, ctx.Config).Count > 0) - 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))); + WriteInsertPreserving(w, ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)), p.DbSet, p.ContextType); + WriteOmitResultClass(w, p.BaseCredentials.Count > 0 || (p.HasItem && M2mTargetHasCredentials(p.Hierarchy, ctx.Root, ctx.Config))); w.Close("}"); return new EmittedFile(OutputPaths.Of(baseEntity, ctx, $"{baseCls}Routes.g.cs"), w.ToString()); } + /// The polymorphic list, GET /<base>: the union of all subtypes, each row carrying its discriminator. + protected virtual void WriteTphListRoute(CsWriter w, TphRoutesPlan p) + { + var (baseCls, dbSet, ctx) = (p.BaseCls, p.DbSet, p.Ctx); + w.Line("app.MapGet(prefix + \"/" + p.BaseRoute + "\", async (HttpContext http, " + p.ContextType + " db) =>"); + w.Open("{"); + w.Line("var qs = http.Request.Query;"); + w.Line($"IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); + var fmB = FilterMapArg($"{baseCls}FilterAllowlist", p.BaseEntity, ctx.Config); + 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("}"); + WriteOffsetLimit(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", p.BaseCredentials)};"); + w.Line($"var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); + w.Line($"return {OkResult("new { rows, total }", p.BaseCredentials, envelope: true)};"); + w.Close("});"); + } + + /// The polymorphic item route, GET /<base>/{id}: one row of whatever subtype. + protected virtual void WriteTphGetRoute(CsWriter w, TphRoutesPlan p) + { + w.Blank(); + w.Line("app.MapGet(prefix + \"/" + p.BaseRoute + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); + using (w.Hanging()) w.Line($"await db.{p.DbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{p.PkProp} == id) is {{ }} found"); + using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", p.BaseCredentials)); + using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); + } + + /// The polymorphic sort dispatch over the base's scalar columns (reflection-free, through EF.Property). + protected virtual void WriteTphApplySort(CsWriter w, TphRoutesPlan p) + { + w.Line($"private static IOrderedQueryable<{p.BaseCls}> ApplySort(IQueryable<{p.BaseCls}> q, string field, bool desc)"); + w.Open("{"); + w.Line("return field switch"); + w.Open("{"); + foreach (var name in p.SortFields) + w.Line($"\"{name}\" => {NullsLargestSort("q", $"EF.Property(x!, \"{name}\")")},"); + w.Line("_ => (IOrderedQueryable<" + p.BaseCls + ">)q.OrderBy(x => 0),"); + w.Close("};"); + w.Close("}"); + } + // FR-036 #4 — the wire keys of the @required fields whose keys must be PRESENT (and // non-null) on a create body. Uses the SAME required-predicate as the DTO's [Required] // (MetaField.IsRequired = own @required OR a validator.required child), matching the @@ -770,7 +885,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // supplies the exclusion for the PK (server-/route-assigned) and, for a TPH subtype, the // (EF-injected) discriminator. Returns the camelCase field names — matched case-insensitively // against the raw JSON keys, so a camelCase wire key resolves to its PascalCase property. - private static List RequiredCreateKeys(MetaObject obj, Func isPkOrDisc) => + protected static List RequiredCreateKeys(MetaObject obj, Func isPkOrDisc) => obj.Fields() // Issue #203 — an @autoSet field is server-filled (the CRUD stamps now() on // insert), so it is OPTIONAL on the create body even when @required. Matching @@ -793,7 +908,7 @@ private static List RequiredCreateKeys(MetaObject obj, Func RequiredReadOnlyProps(MetaObject obj, GenConfig config) => + protected static List RequiredReadOnlyProps(MetaObject obj, GenConfig config) => obj.Fields() .Where(f => f.IsRequired && f.IsReadOnlyMutability && !f.IsDerived()) .Select(f => CSharpNaming.PropertyName(f, config)) @@ -804,7 +919,7 @@ private static List RequiredReadOnlyProps(MetaObject obj, GenConfig conf // COLUMN's temporal CLR type (generalizes beyond DateTimeOffset). OnUpdate columns // are stamped on both insert and update; onCreate columns are stamped on insert only // (never rewritten on update — the write-once created-at contract). - private sealed record AutoSetField(string Nav, string NowExpr, bool OnUpdate); + protected record AutoSetField(string Nav, string NowExpr, bool OnUpdate); // The @autoSet fields (effective — inherited @autoSet resolves) whose CLR type is a // temporal that has a now() form. A non-temporal @autoSet field (not expected per the @@ -820,7 +935,7 @@ private sealed record AutoSetField(string Nav, string NowExpr, bool OnUpdate); /// echoed in the RESPONSE even where EF omitted the column from the UPDATE. Skipping /// the key here is what makes the response and the row agree. /// - private static List FrozenNavs(MetaObject entity, GenConfig config) => + protected static List FrozenNavs(MetaObject entity, GenConfig config) => entity.Fields() .Where(f => f.Mutability != MetaObjects.Core.Field.FieldConstants.MUTABILITY_READ_WRITE) .Select(f => CSharpNaming.PropertyName(f, config)) @@ -832,17 +947,17 @@ private static List FrozenNavs(MetaObject entity, GenConfig config) => // #484 — write-denied: the generated create / PATCH / PUT IGNORE the key (never a 400): the // effective @formExclude (resolving) or a credential. - private static bool IsApiWriteDenied(MetaField f) => + protected static bool IsApiWriteDenied(MetaField f) => f.Attr(FIELD_ATTR_FORM_EXCLUDE) is true || IsCredentialField(f); - private static List WriteDeniedFields(MetaObject entity) => + protected static List WriteDeniedFields(MetaObject entity) => entity.Fields().Where(IsApiWriteDenied).ToList(); /// /// An entity's credential names plus, for a TPH base, those of every subtype: its rows are /// shared-table rows of every subtype (#484). /// - private static List TphUnionCredentialNames(MetaObject entity, MetaRoot root, GenConfig config) => + protected static List TphUnionCredentialNames(MetaObject entity, MetaRoot root, GenConfig config) => CredentialNames(entity, config) .Concat(TphPlanBuilder.For(entity, root) is { } tph ? tph.Subtypes.SelectMany(st => CredentialNames(st.Entity, config)) @@ -854,7 +969,7 @@ private static List TphUnionCredentialNames(MetaObject entity, MetaRoot /// its (the base and every subtype): a single-table column declared /// by several subtypes is one column (#484). /// - private static List HierarchyMarkedFields( + protected static List HierarchyMarkedFields( MetaObject subtype, IEnumerable hierarchy, Func isMarked) { var marked = hierarchy.SelectMany(o => o.Fields()).Where(isMarked) @@ -867,23 +982,23 @@ private static List HierarchyMarkedFields( // host's naming policy applied to the resolved name). Credential stripping and the PATCH // deny and value-object arms match on both, so a renamed property cannot escape them. Without // a rename the two differ at most by case and the list is the field name alone. - private static List WireKeys(MetaField f, GenConfig config) => + protected static List WireKeys(MetaField f, GenConfig config) => new[] { f.Name, CSharpNaming.PropertyName(f, config) } .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); // The CLR property names of an entity's credentials. The JSON key each is written under is not // derived here: the generated result asks the host's serializer (SerializerKeys.StripBody). - private static List CredentialNames(MetaObject entity, GenConfig config) => + protected static List CredentialNames(MetaObject entity, GenConfig config) => entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); // The CLR property first (what the serializer's contract is matched on), then the field name: the // normalized-spelling backstop in SerializerKeys.Strip also removes a key that spells it. Equal // ignoring case when no resolver renames, so the list is then the one CLR name. - private static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => + protected static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. - private static string KeyMatch(IEnumerable keys) => + protected static string KeyMatch(IEnumerable keys) => string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)")); // A sort allowlist (case-insensitive): `TryGetValue(key, out var resolved)` gives the CLR property to @@ -891,7 +1006,7 @@ 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(CsWriter w, string name, IReadOnlyList fields, GenConfig config) + protected virtual void WriteSortAllowlist(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))) @@ -915,35 +1030,35 @@ private static void AppendSortAllowlist(CsWriter w, string name, IReadOnlyList + protected static string FilterMapArg(string allowlistRef, MetaObject entity, GenConfig config) => CSharpNaming.RenamedProperties(entity, config).Count > 0 ? $", {allowlistRef}.PropertyByField" : ""; // A C# string[] expression of the names, spliced into the credential-omitting result. - private static string NamesLiteral(IEnumerable names) => + protected static string NamesLiteral(IEnumerable names) => "new string[] { " + string.Join(", ", names.Select(n => "\"" + n + "\"")) + " }"; // The ok / created result for a body that may carry credentials: byte-identical `Results.*` - // when there are none, else the nested CredentialOmittingResult (emitted by AppendOmitResultClass). - private static string OkResult(string value, IReadOnlyList credentials, bool envelope = false) => + // when there are none, else the nested CredentialOmittingResult (emitted by WriteOmitResultClass). + protected static string OkResult(string value, IReadOnlyList credentials, bool envelope = false) => credentials.Count == 0 ? $"Results.Ok({value})" : $"(IResult)new CredentialOmittingResult({value}, {NamesLiteral(credentials)}{(envelope ? ", envelope: true" : "")})"; // The credential arguments of a JSON report export (ReportExportHttp.Json), "" without a credential. - private static string ExportOmit(IReadOnlyList credentials, bool envelope) => + protected static string ExportOmit(IReadOnlyList credentials, bool envelope) => credentials.Count == 0 ? "" : $", {NamesLiteral(credentials)}{(envelope ? ", envelope: true" : "")}"; - private static string CreatedResult(string location, string value, IReadOnlyList credentials) => + protected static string CreatedResult(string location, string value, IReadOnlyList credentials) => credentials.Count == 0 ? $"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) => + protected 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(CsWriter w, bool used) + protected virtual void WriteOmitResultClass(CsWriter w, bool used) { if (!used) return; w.Blank(); @@ -973,7 +1088,7 @@ private static void AppendOmitResultClass(CsWriter w, bool used) w.Close("}"); } - private static List AutoSetFields(MetaObject entity, GenConfig config) + protected static List AutoSetFields(MetaObject entity, GenConfig config) { var list = new List(); foreach (var f in entity.Fields()) @@ -992,7 +1107,7 @@ private static List AutoSetFields(MetaObject entity, GenConfig con // (ADR-0036 Wave 2: field.timestamp is DateTimeOffset, or DateTime under @localTime; // field.date → DateOnly; field.time → TimeOnly). Fully qualified so no extra using is // needed. Returns null for a non-temporal field. - private static string? NowExprFor(MetaField field) => + protected static string? NowExprFor(MetaField field) => CSharpNaming.ScalarForField(field) switch { "DateTimeOffset" => "System.DateTimeOffset.UtcNow", @@ -1011,7 +1126,7 @@ private static List AutoSetFields(MetaObject entity, GenConfig con // is in the run, the quoted literal otherwise (CSharpNaming.ColumnRef's contract) — for // splicing into the post-save null-clear SQL; IsArray / Required drive the merge semantics // (present-null: a nullable single/array clears, a @required column 400s). - private sealed record VoField( + protected record VoField( IReadOnlyList WireKeys, string WireName, string Nav, string DeserType, string JsonColumnRef, bool IsArray, bool Required); // #362 — the `field.map @objectRef` columns, deliberately NOT folded into VoField. @@ -1020,14 +1135,14 @@ private sealed record VoField( // with a jsonb converter and none of that applies. What it DOES share is the nested // value-object graph, which the create and PATCH paths must validate — before this the // map reached neither, so its values were written unchecked on every write path. - private sealed record MapVoField(IReadOnlyList WireKeys, string WireName, string Nav, string DeserType); + protected record MapVoField(IReadOnlyList WireKeys, string WireName, string Nav, string DeserType); // A value object named from the routes file: bare in the earlier layout, global::-qualified // when package namespaces are on. - private static string VoTypeRef(MetaData target, MetaRoot root, GenConfig config) => + protected static string VoTypeRef(MetaData target, MetaRoot root, GenConfig config) => config.PackageNamespacesFromMetadata ? ValueObjectNames.GlobalRef(target, config) : ValueObjectNames.TypeName(target, root); - private static List MapValueObjectFields(MetaObject entity, MetaRoot root, GenConfig config) + protected static List MapValueObjectFields(MetaObject entity, MetaRoot root, GenConfig config) { var list = new List(); foreach (var f in entity.Fields()) @@ -1044,7 +1159,7 @@ private static List MapValueObjectFields(MetaObject entity, MetaRoot return list; } - private static List ValueObjectFields(MetaObject entity, MetaRoot root, ColumnNamingStrategy strategy, bool includeNames, GenConfig config) + protected static List ValueObjectFields(MetaObject entity, MetaRoot root, ColumnNamingStrategy strategy, bool includeNames, GenConfig config) { var list = new List(); foreach (var f in entity.Fields()) @@ -1078,7 +1193,7 @@ 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(CsWriter w, IEnumerable objects, MetaRoot root) + protected virtual void WriteKnownFields(CsWriter w, IEnumerable objects, MetaRoot root) { if (root.Api.UnknownFields != UnknownFieldsMode.Reject) return; var names = objects.SelectMany(o => o.Fields()).Select(f => f.Name) @@ -1092,7 +1207,7 @@ private static void AppendKnownFields(CsWriter w, IEnumerable object } // The unknown-field refusal, before any validation of the body. `bodyVar` is the parsed JsonDocument. - private static void AppendUnknownFieldsCheck(CsWriter w, MetaRoot root, string bodyVar) + protected virtual void WriteUnknownFieldsCheck(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. @@ -1101,7 +1216,7 @@ private static void AppendUnknownFieldsCheck(CsWriter w, MetaRoot root, string b // 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(CsWriter w, ApiPagination? page, string offRaw, string off, string limRaw, string lim) + protected virtual void WriteOffsetLimit(CsWriter w, ApiPagination? page, string offRaw, string off, string limRaw, string lim) { if (page is not null) { @@ -1132,7 +1247,7 @@ private static void AppendOffsetLimit(CsWriter w, ApiPagination? page, string of w.Line($"q = q.Take(__take);"); } - private static void AppendCreateHandler( + protected virtual void WriteCreateHandler( CsWriter w, string mapPath, string cls, string ctxType, string dbSet, IReadOnlyList requiredKeys, string createdExpr, IReadOnlyList voFields, IReadOnlyList mapVoFields, @@ -1149,14 +1264,14 @@ private static void AppendCreateHandler( // {error:"validation", issues:[...]} envelope), so the handler reads the body itself and collects them. w.Line($"app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, {ctxType} db) =>"); w.Open("{"); - AppendJsonOptsLocal(w); + WriteJsonOptsLocal(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"); + if (root is not null) WriteUnknownFieldsCheck(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 @@ -1175,13 +1290,13 @@ private static void AppendCreateHandler( 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); + WriteCreateServerOwned(w, serverOwned); + WriteCreateIgnoreDenied(w, deniedNavs); + WriteCreateValidation(w, readOnlyRequired); + WriteCreateVoValidation(w, voFields, mapVoFields); w.Line("if (__issues.Any) return __issues.ToResult();"); - AppendCreateAutoSet(w, autoSetFields); - AppendCreatePersist(w, dbSet, createdExpr, reRead, credentials ?? []); + WriteCreateAutoSet(w, autoSetFields); + WriteCreatePersist(w, dbSet, createdExpr, reRead, credentials ?? []); w.Close("});"); } @@ -1190,13 +1305,13 @@ private static void AppendCreateHandler( // . For a write-through entity (#214) // 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( + protected virtual void WriteCreatePersist( CsWriter w, string dbSet, string createdExpr, (string ReadDbSet, string PkProp, string Route)? reRead, IReadOnlyList credentials) { w.Line($"db.{dbSet}.Add(input);"); - AppendSaveChanges(w); + WriteSaveChanges(w); if (reRead is { } rr) { w.Line($"var __created = await db.{rr.ReadDbSet}.FindAsync(input.{rr.PkProp});"); @@ -1220,14 +1335,14 @@ 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(CsWriter w, IReadOnlyList? statements) + protected virtual void WriteCreateServerOwned(CsWriter w, IReadOnlyList? statements) { if (statements is null || statements.Count == 0) return; 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 + // The reset statements WriteCreateServerOwned emits for one entity (empty when it has none, so an // entity with an assigned key, no navigation and no discriminator keeps its output byte-identical). // A TPH subtype class declares no M:N property of its own — the navigations it carries are its // discriminator base class's — so a subtype route passes that base as navOwner. The key and @@ -1237,7 +1352,7 @@ private static void AppendCreateServerOwned(CsWriter w, IReadOnlyList? s // The M:N element type is spelled through ValueObjectNames.TypeRef from the routes file's own // namespace (a generated type's namespace is its metadata package), and the List is // global::-qualified, as every other emitted System reference here is. - private static List ServerOwnedCreateResets( + protected static List ServerOwnedCreateResets( MetaObject entity, MetaRoot root, GenConfig config, MetaField? discField = null, MetaObject? navOwner = null) { var list = new List(); @@ -1260,7 +1375,7 @@ 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(CsWriter w, IReadOnlyList? deniedNavs) + protected virtual void WriteCreateIgnoreDenied(CsWriter w, IReadOnlyList? deniedNavs) { if (deniedNavs is null || deniedNavs.Count == 0) return; w.Line("// @formExclude / credential: not settable through the generated create; the value is ignored."); @@ -1272,7 +1387,7 @@ private static void AppendCreateIgnoreDenied(CsWriter w, IReadOnlyList? // 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(CsWriter w, IReadOnlyList autoSetFields) + protected virtual void WriteCreateAutoSet(CsWriter w, IReadOnlyList autoSetFields) { foreach (var a in autoSetFields) w.Line($"input.{a.Nav} = {a.NowExpr};"); @@ -1283,7 +1398,7 @@ private static void AppendCreateAutoSet(CsWriter w, IReadOnlyList // are NOT stamped — they are never rewritten (the write-once created-at contract). The // merge loop skips every @autoSet column, so this assignment is authoritative. Assumes // the tracked entity local `existing` is in scope. - private static void AppendUpdateAutoSet(CsWriter w, IReadOnlyList autoSetFields) + protected virtual void WriteUpdateAutoSet(CsWriter w, IReadOnlyList autoSetFields) { foreach (var a in autoSetFields) if (a.OnUpdate) @@ -1295,7 +1410,7 @@ private static void AppendUpdateAutoSet(CsWriter w, IReadOnlyList // written verbatim), for import / restore / replication paths that must keep the // original timestamps. Emitted only for an entity that declares @autoSet fields (else // there is nothing to preserve — the normal POST already writes every column verbatim). - private static void AppendInsertPreserving(CsWriter w, string cls, string dbSet, string ctxType) + protected virtual void WriteInsertPreserving(CsWriter w, string cls, string dbSet, string ctxType) { w.Blank(); w.Line("/// Escape hatch: insert without @autoSet stamping (created-at/updated-at"); @@ -1318,7 +1433,7 @@ private static void AppendInsertPreserving(CsWriter w, string cls, string dbSet, // names artifact is in this run (the string stays a compile-time constant, concatenated), // 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( + protected virtual void WriteArrayNullClears( CsWriter w, IReadOnlyList voFields, string tableRef, string pkColumnRef) { for (int i = 0; i < voFields.Count; i++) @@ -1335,16 +1450,16 @@ private static void AppendArrayNullClears( // surrounding text, so the literal arm emits the single string it always did; a constant // reference closes the literal, concatenates, and reopens it — every piece is a compile-time // constant, so the whole expression still is one. - private static string SqlSplice(string nameExpr) => + protected static string SqlSplice(string nameExpr) => nameExpr.StartsWith('"') ? nameExpr[1..^1] : $"\" + {nameExpr} + \""; // Program D — validate each present value-object column on CREATE. The top-level - // TryValidateObject (AppendCreateValidation) does NOT recurse into an owned-nav VO, so a + // TryValidateObject (WriteCreateValidation) does NOT recurse into an owned-nav VO, so a // nested-constraint violation (e.g. a VO string member over @maxLength) would slip through. // ValueObjectValidator.Validate runs the VO's own DataAnnotations per element + recurses // 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( + protected virtual void WriteCreateVoValidation( CsWriter w, IReadOnlyList voFields, IReadOnlyList mapVoFields) { foreach (var vf in voFields) @@ -1370,7 +1485,7 @@ private static void AppendCreateVoValidation( // is emitted into its namespace). // A decimal reached through a value-object column counts too: its member is bound from the body // with the same exact-read rule, so the same {error:"validation"} envelope must answer a refusal. - private static bool HasDecimalField(MetaObject entity, HashSet? seen = null) + protected static bool HasDecimalField(MetaObject entity, HashSet? seen = null) { seen ??= []; if (!seen.Add(entity)) return false; @@ -1389,16 +1504,16 @@ private static bool HasDecimalField(MetaObject entity, HashSet? seen // {error:"validation"} envelope, and the PATCH merge reads the wire form explicitly. // Only under `wire.durations: iso`: the native form is System.Text.Json's own, so the default // binder and PATCH deserialization already read it and no duration arm is emitted. - private static bool HasIsoDurationField(MetaObject entity, MetaRoot root) => + protected 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(CsWriter w) + protected virtual void WriteDecimalRangeGroup(CsWriter w) { w.Line("IEndpointRouteBuilder mount = app;"); w.Line("app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter());"); } - private static void AppendJsonOptsLocal(CsWriter w) + protected virtual void WriteJsonOptsLocal(CsWriter w) { w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); @@ -1413,7 +1528,7 @@ private static void AppendJsonOptsLocal(CsWriter w) // 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(CsWriter w, IReadOnlyList? readOnlyRequired = null) + protected virtual void WriteCreateValidation(CsWriter w, IReadOnlyList? readOnlyRequired = null) { if (readOnlyRequired is null || readOnlyRequired.Count == 0) { @@ -1431,7 +1546,7 @@ private static void AppendCreateValidation(CsWriter w, IReadOnlyList? re // the TPH discriminator when `discProp` is non-null — is never written. Assumes the // locals `body` (JsonDocument), `existing` (the entity instance), `entry` (EntityEntry) // and `jsonOpts` are in scope. - private static void AppendPartialMergeLoop( + protected virtual void WritePartialMergeLoop( CsWriter w, string? discProp, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetNavs, IReadOnlyList frozenNavs, bool hasDecimal, @@ -1440,7 +1555,7 @@ private static void AppendPartialMergeLoop( // A nullable array-of-VO column that a request clears to null (present-null) can NOT be // NULLed by an owned-nav assignment — EF OwnsMany(...).ToJson writes `[]` for a null // collection nav, not SQL NULL. Track it via a flag + a post-save raw UPDATE - // (AppendArrayNullClears). Declared before the loop so the post-save clears see it. + // (WriteArrayNullClears). 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) w.Line($"var __clearVo{i} = false;"); @@ -1632,7 +1747,7 @@ private static void AppendPartialMergeLoop( // via db..OfType(); cross-subtype ids are invisible (404). Create binds the // 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( + protected virtual void WriteTphSubtypeRoutes( 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) { @@ -1678,7 +1793,7 @@ private static void AppendTphSubtypeRoutes( 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"); + WriteOffsetLimit(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)};"); @@ -1705,7 +1820,7 @@ private static void AppendTphSubtypeRoutes( }); w.Blank(); // VO columns on a TPH subtype are out of scope (Program D §6) — no typed arms. - AppendCreateHandler(w, "/" + subRoute, subType, ValueObjectNames.ContextTypeRef(config), dbSet, requiredKeys, + WriteCreateHandler(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, @@ -1723,19 +1838,19 @@ private static void AppendTphSubtypeRoutes( 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"); + WriteUnknownFieldsCheck(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); + WriteUpdateAutoSet(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(w, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), + WritePartialMergeLoop(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(w); + WriteSaveChanges(w); w.Line($"return {OkResult("existing", credentials)};"); w.Close("}"); w.Line("app.MapPatch(prefix + \"/" + subRoute + "/{id}\", Update" + subCls + ");"); @@ -1748,7 +1863,7 @@ private static void AppendTphSubtypeRoutes( 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); + WriteSaveChanges(w); w.Line("return Results.NoContent();"); w.Close("});"); @@ -1762,7 +1877,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(w, nav, subRoute, pkType, root, config, sourceScope); + WriteM2mRoute(w, nav, subRoute, pkType, root, config, sourceScope); } /// @@ -1783,7 +1898,7 @@ private static void AppendTphSubtypeRoutes( /// kind, identical on both ports. /// /// - private static void AppendSaveChanges(CsWriter w) + protected virtual void WriteSaveChanges(CsWriter w) { w.Line("try { await db.SaveChangesAsync(); }"); w.Line("catch (System.Exception __saveError)"); @@ -1797,7 +1912,7 @@ private static void AppendSaveChanges(CsWriter w) } // A junction/target column's CLR property, through the same resolver its entity class used. - private static string JunctionProperty(MetaObject owner, string fieldName, GenConfig config) => + protected static string JunctionProperty(MetaObject owner, string fieldName, GenConfig config) => owner.FindField(fieldName) is { } f ? CSharpNaming.PropertyName(f, config) : CSharpNaming.Pascal(fieldName); // Emit the M:N traversal handler for one navigation. The junction + target are @@ -1820,7 +1935,7 @@ private static string JunctionProperty(MetaObject owner, string fieldName, GenCo // junction FK still addresses the shared base table, so a sibling subtype's id would // 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( + protected virtual void WriteM2mRoute( CsWriter w, M2MNavigation nav, string sourceRoute, string pkType, MetaRoot root, GenConfig config, TphM2mSourceScope? sourceScope = null) { @@ -1889,11 +2004,11 @@ private static void AppendM2mRoute( /// property. Mirrors TS mount-m2m.ts's sourceDiscriminator option — this is /// the codegen-time descriptor for that runtime check. /// - private sealed record TphM2mSourceScope(string DbSet, string SubtypeClass, string PkProp); + protected record TphM2mSourceScope(string DbSet, string SubtypeClass, string PkProp); // The CLR type of the junction FK columns (and thus the related-id key). Both // junction references point at same-typed PKs; use the source FK field's subtype. - private static string JunctionFkType(M2MNavigation nav) + protected static string JunctionFkType(M2MNavigation nav) { var fkField = nav.Junction.FindField(nav.SourceField); return fkField is not null ? CSharpNaming.ScalarFor(fkField.SubType) ?? "long" : "long"; @@ -1911,7 +2026,7 @@ 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(CsWriter w, MetaObject owner, string constName, GenConfig config) + protected virtual void WriteSortDefaultOrder(CsWriter w, MetaObject owner, string constName, GenConfig config) { w.Line($"private static readonly System.Collections.Generic.Dictionary {constName} = new(System.StringComparer.OrdinalIgnoreCase)"); w.Open("{"); @@ -1933,6 +2048,6 @@ private static void AppendSortDefaultOrder(CsWriter w, MetaObject owner, string /// would otherwise put them first on ASC). A leading `col == null` key says it in a way /// every EF Core provider translates, where `NULLS LAST` is not portable. /// - private static string NullsLargestSort(string query, string column) => + protected static string NullsLargestSort(string query, string column) => $"desc ? {query}.OrderByDescending(x => {column} == null).ThenByDescending(x => {column}) : {query}.OrderBy(x => {column} == null).ThenBy(x => {column})"; } diff --git a/server/csharp/MetaObjects.Codegen/Generators/SharedModelGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/SharedModelGenerator.cs index 319822c697..dcd8746814 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/SharedModelGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/SharedModelGenerator.cs @@ -92,22 +92,22 @@ public IEnumerable Generate(GenContext ctx) return [new EmittedFile(files.ArtifactPath, files.Artifact), new EmittedFile(files.ManifestPath, files.Manifest)]; } - private static string Required(string? value, string option, string what) => + protected static string Required(string? value, string option, string what) => string.IsNullOrWhiteSpace(value) ? throw Missing(option, what) : value.Trim(); - private static InvalidOperationException Missing(string option, string what) => + protected static InvalidOperationException Missing(string option, string what) => new($"shared-model: set {option} on the generator ({what}): new SharedModelGenerator {{ {option} = ... }}"); /// The <Version> the project builds with: the project file in the root, then /// Directory.Build.props in the root or the nearest directory above it. null when none declares one, /// or when the one that does is an MSBuild expression ($(...)) this generator does not evaluate. - private static string? ProjectVersion(string projectRoot) + protected static string? ProjectVersion(string projectRoot) { var declared = DeclaredVersion(projectRoot); return declared is null || declared.Contains("$(", StringComparison.Ordinal) ? null : declared; } - private static string? DeclaredVersion(string projectRoot) + protected static string? DeclaredVersion(string projectRoot) { foreach (var project in Directory.EnumerateFiles(projectRoot, "*.csproj").Order(StringComparer.Ordinal)) if (VersionIn(project) is { } own) return own; @@ -116,7 +116,7 @@ private static InvalidOperationException Missing(string option, string what) => return null; } - private static string? VersionIn(string file) + protected static string? VersionIn(string file) { if (!File.Exists(file)) return null; // The MSBuild property: directly under an unconditional , never a diff --git a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs index d7f7c4610d..2678f04d49 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs @@ -177,7 +177,7 @@ public static HashSet HierarchyCredentialNames(MetaObject entity, MetaRo /// reaches this row" — e.g. a M:N relationship whose TARGET is a TPH subtype: that /// subtype has no DbSet of its own ( /// excludes TPH subtypes), so the generated route must bind to the BASE's DbSet and - /// narrow via OfType<Sub>() (see RoutesGenerator.AppendM2mRoute). + /// narrow via OfType<Sub>() (see RoutesGenerator.WriteM2mRoute). /// Exposing the existing walk here keeps that lookup the ONE place it happens, /// rather than a second copy of this loop living in RoutesGenerator. /// diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs index 2993de4f62..ecd9eaab34 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs @@ -28,7 +28,7 @@ public async Task Api_contract_api_settings_generated(string scenarioPath) // The corpus cannot pin this: Java/Kotlin answer Spring's type-mismatch 400 and Python FastAPI's 422 // for a non-numeric bound, so the generated C# route is exercised here against the cross-port 400 envelope. // Only the plain entity list is driven: the TPH base and per-subtype lists emit through the same - // AppendOffsetLimit, and no TPH fixture with api.pagination boots in this lane. + // WriteOffsetLimit, and no TPH fixture with api.pagination boots in this lane. [Theory] [InlineData("/api/items?limit=abc", "limit", "abc")] [InlineData("/api/items?limit=1O", "limit", "1O")] diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/M2mReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/M2mReferenceServer.cs index dee758f209..fdabbc5d82 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/M2mReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/M2mReferenceServer.cs @@ -8,7 +8,7 @@ // // FW-8 (FR-018 x FR-017 — M:N traversal inside a TPH hierarchy, over the `Account` // discriminator base): two independent scoping rules layer ON TOP of the plain -// M2MResolver traversal, mirroring what RoutesGenerator's AppendM2mRoute does for the +// M2MResolver traversal, mirroring what RoutesGenerator's WriteM2mRoute does for the // GENERATED lane (OfType() there; a raw discriminator-column check here) — // - SOURCE side (rule c): a subtype-scoped mount (e.g. /accounts/member/{id}/scopes) // must verify the id names a row of THAT subtype in the shared discriminator table diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs index deb5e74a0a..f245ff97f1 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/MapValueObjectWriteBehaviorGeneratedServerTest.cs @@ -137,7 +137,7 @@ public async Task An_enum_valued_map_component_persists_its_symbol_not_its_ordin // #362 — this test used to PIN the defect: it asserted 201, documenting that a // field.map @objectRef's nested value objects were written unvalidated because - // RoutesGenerator.ValueObjectFields (the source AppendCreateVoValidation walked) admits + // RoutesGenerator.ValueObjectFields (the source WriteCreateVoValidation walked) admits // only field.object, so a map never reached the recursively-validating VO arms. Two // changes closed it — MapValueObjectFields feeds the map columns to the same validation, // and ValueObjectValidator unwraps an IDictionary to its Values (a Dictionary previously From 1adda8dcaacc6bd2a6b8adeff34527e89447258f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:39:35 -0500 Subject: [PATCH 3/4] no-mistakes(document): docs: refresh C# codegen write and eject facts --- docs/features/own-your-codegen.md | 6 +++--- server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 0f2254a794..d5b5630a5f 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -469,7 +469,8 @@ they are handed **no gen-state directory at all**. Only an embedder calling `CodegenRunner.Run`, `decide_and_write` or a JVM generator directly can do that; `dotnet meta gen`, `metaobjects gen` and `mvn metaobjects:generate` always supply one. In that fallback a hand edit inside a generated file keeps its marker and is overwritten silently, which is exactly the failure the hash manifest exists to prevent — -so if you embed a runner, supply a gen-state directory. +so if you embed a runner, supply a gen-state directory. (C# leaves a file that already holds +exactly the generated bytes alone and reports it `unchanged`; the marker rule decides only a file that differs.) **Say the condition out loud, because it is where teams get surprised.** The merge is machine-local. Edit a generated file, push it, and the *next* clone — a colleague's, a CI @@ -1584,8 +1585,7 @@ The list names every generator the project runs, owned or packaged, so ejecting a nine-entry list changes one entry, not the other eight. `--generators` narrows a run to the declared entries named, matching an owned copy by its registry name too, and never adds one. The owned project finds metadata exactly as the tool does, including -`.metaobjects/config.json`'s `sources` and `libraries`. Eject never overwrites a copy without `--force`, and -`dotnet meta gen --list` marks owned copies `identical` or `DIFFERS: N behind, M of your +`.metaobjects/config.json`'s `sources` and `libraries`. Eject never overwrites a copy without `--force`; with it, a copy already byte-identical to the reference is left alone and reported `[unchanged]`. `dotnet meta gen --list` marks owned copies `identical` or `DIFFERS: N behind, M of your own`, and names an emitter that was edited or removed after eject (`Fr019SharedEnum.cs DIFFERS: 0 behind, 1 of your own`). The `template` primitive is not ejectable; it has no emit logic of its own. diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 94aefe522c..5add01d323 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -45,7 +45,7 @@ Update when a gap closes or a new one surfaces. **Today.** On the vanilla (non-TPH) PATCH/PUT handler a VO-typed column IS patch-settable. The handler passes the entity's VO fields into `WritePartialMergeLoop` (`RoutesGenerator.cs`), which emits a Program D typed value-object arm for each one AHEAD of the generic `entry.Metadata.FindProperty(prop.Name)` arm — an owned navigation is invisible to `FindProperty`, so the generic scalar path alone would silently drop the column. Per arm: a present value is deserialized, recursively validated (`ValueObjectValidator.Validate`), and assigned to the CLR navigation property; a present `null` clears a nullable VO column — a nullable array-of-VO additionally takes a post-save raw UPDATE, since EF's `OwnsMany(...).ToJson` writes `[]` for a null collection nav rather than SQL NULL — or 400s a `@required` one; an absent key leaves the column untouched. This is the same Program D shipment Java's `KNOWN_GAPS.md` records as cross-port (TS / Python / Java / Kotlin / C#), gated by `fixtures/api-contract-conformance/jsonb/scenarios/jsonb-value-object-patch.yaml` in both lanes. -**Residual.** TPH only: the per-subtype partial-update path passes an empty VO list (`RoutesGenerator.cs:961`), so VO columns on a TPH-rooted entity are still skipped on PATCH — the same staging-out Java's entry records for TPH. +**Residual.** TPH only: the per-subtype partial-update path passes an empty VO list (`WriteTphSubtypeRoutes` in `RoutesGenerator.cs`), so VO columns on a TPH-rooted entity are still skipped on PATCH — the same staging-out Java's entry records for TPH. **RULED (1.0.1, [#359](https://github.com/metaobjectsdev/metaobjects/issues/359)): narrowed to the TPH residual, and the residual is a deliberate cross-port stage-out — not a C# divergence.** The question the issue could not answer from C# alone was whether C# now patches VO columns while Java and Kotlin still do not, which would make this an api-contract divergence rather than a gap. It does not: Java stages out the same columns on the same path. `SpringGeneratorSupport.scalarFields` is documented as "every MetaField that is not an ObjectField", and the TPH union is built from it, so a `field.object` column never reaches a Java TPH per-subtype write path either — Java's own `KNOWN_GAPS.md` records the carve-out in the same terms. Both ports patch VO columns on the vanilla path and stage them out on TPH, which is exactly the uniform Day-1 simplification this entry was written to describe. From 2dfb3b4ca72d4fb76f043322fd4b186cda0116a4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:40:40 -0500 Subject: [PATCH 4/4] no-mistakes(document): docs: scope CsWriter claim to C# generators --- docs/ports/csharp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 9a4934ddce..3e6dcb667e 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -330,7 +330,8 @@ prints a warning naming the line to change. See **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. Every -generator is written on it. Each is a class whose file is built from one overridable method per +generator that emits C# source is written on it; the JSON, Markdown and template generators are +not. Each such generator is a class whose file is built from one overridable method per piece (`WriteFileHeader`, `WriteTypeDoc`, `WriteMembers` and so on; in the routes generator `WriteListRoute`, `WriteCreateRoute`, `WriteUpdateRoute` and the rest, over a plan worked out once by `PlanStandardRoutes` or `PlanTphRoutes`), so an owned copy, or a subclass of the shipped one,