Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2560,6 +2560,41 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru

### Changed

- **C#: generators qualify framework references as they write them; the runner no longer rewrites
output.** With `csharp.packageNamespaces` on, a package segment can shadow a framework namespace
(`acme::app::system` derives `Acme.App.System`), so a bare `System.Text.Json` inside `Acme.App`
does not compile. The runner used to fix that by rewriting every `System.`/`Microsoft.` reference
in every emitted `.cs` file to `global::`, including the output of owned generators. Each
reference generator now spells framework names through `CSharpNaming.Framework(config, name)` /
`CSharpNaming.FrameworkPrefix(config)`, or its own `Fx` prefix, which is set when a run starts.
Through the runner the output is byte-identical. A generator called directly with package
namespaces on now writes the `global::` form itself. What stays in the runner is a check. A file
that still writes a bare reference that a namespace of the run actually shadows is named in a
warning, with the fix; the warning means that file will not compile. In practice that is an
owned copy ejected from a 1.3.0 candidate.
- **C#: `DbContextGenerator`'s text hooks have `CsWriter` overloads.** `OwnedTypeConfig`,
`FieldTypeConfig`, `DbColumnTypeConfig`, `DefaultValueConfig`, `ReferenceConfig`,
`TphSubtypeFieldConfig`, `EntityConfigTrailer`, `EmitCheckConfig`, `DbSetLine`,
`ContextMemberLines`, `ContextPreambleLines` and `ContextTrailerLines` each take the writer as
their first argument as well. An override writes a nested block with `Braced` (an `OwnsOne(x =>
x.Nav, b => { … })`, an `if` around several statements) instead of building one string with
embedded newlines. Each writer overload defaults to its text hook, so an existing override keeps
working and a generator that overrides none writes the same bytes and the same `ConfigureModelNN`
split. What one writer overload writes is one model entry, never split across two methods. An
`OwnedTypeConfig` override that writes nothing leaves the field unconfigured.
- **C#: `Fr019SharedEnum.ProvidedEnumNamespace(SharedEnum, GenConfig)` is public.** It returns the
namespace a provided shared enum is referenced in: the package binding, else
`ProvidedEnumNamespace`. It throws, naming the package, when neither is set. Before, only the
materialized case had a namespace seam (`MaterializedNamespace`). `SharedEnumTypeReference`
calls it, so the two never disagree.
- **C#: an object-typed field a view class cannot carry is reported once by `verify`, not on every
`gen`.** The entity generator leaves an object-typed field off a read-only projection, and a
flattened value object off a write-through entity's `<Entity>View` read model. It used to print a
warning on every regen. `gen` now prints nothing. `dotnet meta verify` lists each such field once,
when the run includes the entity generator, with the fix. For a projection: remove the field, or
read the value through its entity. For a read model: store the value object `@storage: jsonb`,
which the read model carries.

- **Java and Kotlin: Mustache treats a zero or `NaN` number as a falsy section.** mustache.java
treats any non-null `Number` as true, so `{{#count}}…{{/count}}` with `count = 0` rendered its
body in Java and dropped it in TypeScript, C# and Python. `com.metaobjects.render.Renderer` now
Expand Down
17 changes: 17 additions & 0 deletions docs/ports/csharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ run: unflagged cross-file redeclarations (`WARN_OVERLAY_IMPLICIT`), whitespace i
The overlay lint reads the raw files, so it runs even when the model does not load; the name and
deprecation lints read the loaded model and print nothing when it does not load (the load error
is the gate's report).
When the run includes the entity generator, `dotnet meta verify` also lists, once, each object-typed field that
generator leaves off a projection or a write-through read model, with its fix. `gen` prints nothing for it.
Mute each with `--no-overlay-lint`, `--no-name-lint`, `--no-deprecation-lint` or
`--no-field-lint`, or the matching `META_NO_*_LINT=1`. The codes and message text match Node
`meta verify`, gated by `fixtures/model-lint-conformance/` and `fixtures/field-lint-conformance/`.
Expand Down Expand Up @@ -559,6 +561,21 @@ written. An entry that already carries an indent still reads right, because the
common margin before it indents. A `ContextUsings` line is a `using ...;` directive, which the writer
prints once, in the order given.

Each of those statement hooks also has an overload that takes the `CsWriter` as its first argument
(`OwnedTypeConfig(CsWriter w, ...)`, `EntityConfigTrailer(CsWriter w, ...)` and the rest, all but
`ContextUsings`). Override that one to write a nested block with `w.Braced(...)`, such as an
`OwnsOne(x => x.Nav, b => { ... })` or an `if` around several statements, instead of returning one string
with embedded newlines. Its default writes what the text hook returns, so an existing text override still
works. What one writer overload writes is a single model entry: `ModelConfigChunkSize` never splits it
across two `ConfigureModelNN` methods.

**Framework names.** With `csharp.packageNamespaces` on, a package segment can shadow a framework
namespace (`acme::app::system` derives `Acme.App.System`). Each generator therefore writes a framework
reference through its `Fx` prefix (`$"{Fx}System.Text.Json.JsonSerializer"`), or through
`CSharpNaming.Framework(config, name)`, which gives `global::System...` exactly when package namespaces
are on. Nothing rewrites generated text afterwards. If an emitted file still writes a bare reference that
a namespace of the run shadows, the runner names that file in a warning.

**One line at a time.** Each of these is a `protected virtual` hook whose default is the line it
replaces; override it, call base, and adjust. On `EntityGenerator`: `ValueObjectMemberAttributes`
(the `[JsonPropertyName]` before each value-object member), `ColumnAttributeArguments` (the
Expand Down
3 changes: 3 additions & 0 deletions server/csharp/MetaObjects.Cli/VerifyCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,9 @@ private static Codegen.CodegenDrift.Result RunCodegenDrift(Options opts, List<st
// The committed output imports the helper runtime package its project may not reference (1.3.0).
advisories.AddRange(HelperRuntimeReference.ForRun(config, generators, config.ProjectRoot)
.Select(w => $"warning: {w}"));
// Object-typed fields the entity generator leaves off a view-mapped class: said once, here.
advisories.AddRange(Codegen.Generators.EntityGenerator.UnemittedObjectFields(load.Root, generators.Select(g => g.Unwrap()))
.Select(w => $"warning: {w}"));
return Codegen.CodegenDrift.Compute(config, load.Root, generators);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private static MetaRoot LoadCorpus()

/// <summary>The same selections under the opt-in package layout, with the corpus package bound to
/// a namespace that has a <c>System</c> segment: a bare <c>System.*</c> reference in a file in
/// it resolves into that namespace, which is what the runner's framework qualification exists for.</summary>
/// it resolves into that namespace, which is why every generator writes its framework references through CSharpNaming.FrameworkPrefix.</summary>
public static TheoryData<string, bool> PackageSelections => new()
{
{ "entity,db-context,filter-allowlist,callable,names", true },
Expand Down Expand Up @@ -176,7 +176,7 @@ private static void CompileSelection(string selection, bool includeNames, bool p
}

// The runner's post-pass: every file goes through it before it is written.
var files = generators.SelectMany(g => g.Generate(ctx)).Select(f => FrameworkQualifier.Apply(ctx.Config, f)).ToList();
var files = generators.SelectMany(g => g.Generate(ctx)).ToList();
Assert.True(files.Count > 0, $"selection '{selection}' generated no files at all");

// FR-044 — every view-backed report of the corpus (twenty-five today) generates a keyless
Expand Down
231 changes: 231 additions & 0 deletions server/csharp/MetaObjects.Codegen.Tests/DbContextWriterHooksTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
// DbContextWriterHooksTests — the CsWriter overloads of DbContextGenerator's text hooks.
//
// Every text hook (OwnedTypeConfig, FieldTypeConfig, DbColumnTypeConfig, DefaultValueConfig,
// ReferenceConfig, TphSubtypeFieldConfig, EntityConfigTrailer, EmitCheckConfig, DbSetLine,
// ContextMemberLines, ContextPreambleLines, ContextTrailerLines) has an overload that takes the
// writer, so an override writes a nested block with Braced instead of building text with embedded
// newlines. Three properties:
//
// * an override that calls base writes exactly what the text hook would (byte-identical);
// * a block written through the writer lands at its place, indented by the writer;
// * what one writer overload writes is ONE model entry, never split across ConfigureModelNN,
// while a generator that overrides no writer overload keeps its entries (and splits) as before.

using MetaObjects.Codegen.Generators;
using MetaObjects.Codegen.Writer;
using MetaObjects.Loader;
using MetaObjects.Meta;
using Xunit;

namespace MetaObjects.Codegen.Tests;

public class DbContextWriterHooksTests
{
private const string Model = """
{ "metadata.root": { "package": "acme", "children": [
{ "object.value": { "name": "Address", "children": [
{ "field.string": { "name": "street", "@required": true, "@maxLength": 120 } },
{ "field.enum": { "name": "kind", "@values": ["HOME", "WORK"] } }
]}},
{ "object.entity": { "name": "Auth", "@discriminator": "type", "children": [
{ "source.rdb": { "@table": "auths" } },
{ "field.long": { "name": "id" } },
{ "field.enum": { "name": "type", "@values": ["Bridge", "Plain"] } },
{ "field.string": { "name": "note", "@maxLength": 80 } },
{ "field.string": { "name": "uid", "@dbColumnType": "uuid" } },
{ "field.boolean": { "name": "active", "@default": true } },
{ "field.decimal": { "name": "amount", "@precision": 10, "@scale": 2 } },
{ "field.enum": { "name": "statuses", "isArray": true, "@values": ["DRAFT", "LIVE"] } },
{ "field.object": { "name": "home", "@objectRef": "Address", "@storage": "flattened" } },
{ "field.object": { "name": "config", "@objectRef": "Address", "@storage": "jsonb" } },
{ "field.long": { "name": "parentId" } },
{ "identity.primary": { "@fields": "id" } },
{ "identity.reference": { "name": "refParent", "@fields": "parentId", "@references": "Auth" } }
]}},
{ "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [
{ "field.int": { "name": "quantity", "@required": true, "@default": 3 } }
]}}
]}}
""";

private static MetaRoot Load()
{
var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "writer-hooks.json")]);
Assert.Empty(r.Errors);
return r.Root;
}

private static GenContext Ctx(MetaRoot root) => new()
{
Entities = root.Objects(), Root = root,
Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", Dialect = "postgres" },
};

private static string Db(DbContextGenerator g, MetaRoot root) =>
g.Generate(Ctx(root)).Single(f => f.Path == "AppDbContext.g.cs").Content;

// Every writer overload overridden, each calling base.
private sealed class BaseCallingDb : DbContextGenerator
{
public BaseCallingDb(int chunk = 200) { ModelConfigChunkSize = chunk; }
protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx) => base.OwnedTypeConfig(w, owner, entity, field, ctx);
protected override void FieldTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField f, GenContext ctx) => base.FieldTypeConfig(w, owner, entity, f, ctx);
protected override void DbColumnTypeConfig(CsWriter w, string owner, MetaField f) => base.DbColumnTypeConfig(w, owner, f);
protected override void DefaultValueConfig(CsWriter w, MetaObject entity, MetaField f, GenContext ctx) => base.DefaultValueConfig(w, entity, f, ctx);
protected override void ReferenceConfig(CsWriter w, MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) => base.ReferenceConfig(w, entity, reference, ctx);
protected override void TphSubtypeFieldConfig(CsWriter w, MetaObject root, MetaObject subtype, GenContext ctx) => base.TphSubtypeFieldConfig(w, root, subtype, ctx);
protected override void EntityConfigTrailer(CsWriter w, MetaObject entity, GenContext ctx) => base.EntityConfigTrailer(w, entity, ctx);
protected override void EmitCheckConfig(CsWriter w, string owner, MetaObject entity, GenContext ctx) => base.EmitCheckConfig(w, owner, entity, ctx);
protected override void DbSetLine(CsWriter w, MetaObject entity, GenContext ctx) => base.DbSetLine(w, entity, ctx);
protected override void ContextMemberLines(CsWriter w, GenContext ctx) => base.ContextMemberLines(w, ctx);
protected override void ContextPreambleLines(CsWriter w, GenContext ctx) => base.ContextPreambleLines(w, ctx);
protected override void ContextTrailerLines(CsWriter w, GenContext ctx) => base.ContextTrailerLines(w, ctx);
}

[Fact]
public void A_writer_overload_that_calls_base_writes_what_the_text_hook_would()
{
var root = Load();
Assert.Equal(Db(new DbContextGenerator(), root), Db(new BaseCallingDb(), root));
}

// Finding 9: a nested OwnsOne block, written with Braced, not built as text.
private sealed class NestedOwnedDb : DbContextGenerator
{
protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx)
{
if (field.Name != "config")
{
base.OwnedTypeConfig(w, owner, entity, field, ctx);
return;
}
using (w.Braced($"modelBuilder.Entity<{owner}>().OwnsOne(x => x.Config, b =>", "});"))
{
w.Line("b.ToJson(\"config\");");
using (w.Braced("if (Database.IsNpgsql())"))
w.Line("b.Property(x => x.Street).HasMaxLength(120);");
}
}
}

[Fact]
public void An_owned_type_block_written_through_the_writer_is_indented_at_its_place()
{
var src = Db(new NestedOwnedDb(), Load());
Assert.Contains(
" modelBuilder.Entity<Auth>().OwnsOne(x => x.Config, b =>\n" +
" {\n" +
" b.ToJson(\"config\");\n" +
" if (Database.IsNpgsql())\n" +
" {\n" +
" b.Property(x => x.Street).HasMaxLength(120);\n" +
" }\n" +
" });\n", src);
// The flattened value object keeps its default configuration.
Assert.Contains("OwnsOne(x => x.Home", src);
}

[Fact]
public void An_owned_type_override_that_writes_nothing_leaves_the_field_unconfigured()
{
var src = Db(new SkipOwnedDb(), Load());
Assert.DoesNotContain("OwnsOne(x => x.Config", src);
Assert.Contains("OwnsOne(x => x.Home", src);
}

private sealed class SkipOwnedDb : DbContextGenerator
{
protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx)
{
if (field.Name != "config") base.OwnedTypeConfig(w, owner, entity, field, ctx);
}
}

// Finding 10: several statements from one hook, written as statements, not one string.
private sealed class TrailerBlockDb : DbContextGenerator
{
public TrailerBlockDb(int chunk) { ModelConfigChunkSize = chunk; }
protected override void EntityConfigTrailer(CsWriter w, MetaObject entity, GenContext ctx)
{
using (w.Braced("if (Database.IsNpgsql())"))
{
w.Line($"modelBuilder.Entity<{entity.Name}>().HasIndex(x => x.Id);");
w.Line($"modelBuilder.Entity<{entity.Name}>().HasComment(\"t\");");
}
}
protected override void ContextPreambleLines(CsWriter w, GenContext ctx)
{
w.Line("base.OnModelCreating(modelBuilder);");
w.Line("OnModelCreatingFirst(modelBuilder);");
}
protected override void DbSetLine(CsWriter w, MetaObject entity, GenContext ctx)
{
w.Line("[System.ComponentModel.Browsable(false)]");
base.DbSetLine(w, entity, ctx);
}
}

[Fact]
public void A_writer_entry_of_several_statements_is_written_whole()
{
var src = Db(new TrailerBlockDb(chunk: 200), Load());
Assert.Contains(
" if (Database.IsNpgsql())\n" +
" {\n" +
" modelBuilder.Entity<Auth>().HasIndex(x => x.Id);\n" +
" modelBuilder.Entity<Auth>().HasComment(\"t\");\n" +
" }\n", src);
Assert.Contains(
" {\n base.OnModelCreating(modelBuilder);\n OnModelCreatingFirst(modelBuilder);\n", src);
Assert.Contains(
" [System.ComponentModel.Browsable(false)]\n public DbSet<Auth> Auths { get; set; } = default!;\n", src);
}

[Fact]
public void A_writer_entry_is_never_split_across_ConfigureModel_methods()
{
// A chunk of one entry: the trailer block is its own ConfigureModelNN, whole.
var src = Db(new TrailerBlockDb(chunk: 1), Load());
var at = src.IndexOf("if (Database.IsNpgsql())", StringComparison.Ordinal);
Assert.True(at > 0);
var method = src.LastIndexOf("private void ConfigureModel", at, StringComparison.Ordinal);
var next = src.IndexOf("private void ConfigureModel", at, StringComparison.Ordinal);
var body = next < 0 ? src[method..] : src[method..next];
Assert.Contains("HasIndex(x => x.Id);", body);
Assert.Contains("HasComment(\"t\");", body);
}

[Fact]
public void Text_hook_entries_and_split_points_are_unchanged_while_no_writer_overload_is_overridden()
{
// One entry per chunk: each text-hook line is still its own ConfigureModelNN, so a project
// that overrides no writer overload gets the same split it always had.
var root = Load();
var stock = new DbContextGenerator { ModelConfigChunkSize = 1 };
var src = Db(stock, root);
var methods = src.Split("private void ConfigureModel").Length - 1;
var oneChunk = Db(new DbContextGenerator(), root);
var open = oneChunk.IndexOf("protected override void OnModelCreating", StringComparison.Ordinal);
var statements = oneChunk[open..].Split('\n').Count(l => l.StartsWith(" modelBuilder.", StringComparison.Ordinal));
Assert.True(statements > 1);
// Every entry of the stock model here is a single statement line, so one method per statement.
Assert.Equal(statements, methods);
}

private sealed class UsingFragmentDb : DbContextGenerator
{
protected override void ContextPreambleLines(CsWriter w, GenContext ctx)
{
w.Using("Fragment.Only.Ns");
w.Line("var fragmentMarker = 1;");
}
}

[Fact]
public void A_writer_overload_that_calls_Using_puts_no_using_line_in_the_method_body()
{
var src = Db(new UsingFragmentDb(), Load());
Assert.Contains("var fragmentMarker = 1;", src);
Assert.DoesNotContain("Fragment.Only.Ns", src);
}
}
Loading
Loading