diff --git a/CHANGELOG.md b/CHANGELOG.md index b407990cf..8ff2da2f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,7 +81,54 @@ there is described in full here. This list is where to start. TypeScript and Python, `csharp.packageNamespaces` in C#. Java and Kotlin never renamed. - **`meta init` and `metaobjects init` scaffold the package output layout.** New projects get `outputLayout: "package"` (one directory per metadata package); `dotnet meta init` writes the - matching C# keys. An existing project changes nothing: the engine default stays flat. + matching C# keys. A project generated by 1.2.0 to 1.2.3 changes nothing: the engine default + stays flat. +- **C#, from a 1.2.4 release candidate: the package layout and package namespaces are opt-in.** + The 1.2.4 candidates always wrote C# under one directory per metadata package and declared + each type, materialized shared enums included, in its package's namespace. 1.3.0 keeps the flat + default of 1.2.0, so the same project regenerated with neither key set moves every file into one + directory and every type into `Namespace`, and `Fr019SharedEnum.SharedEnumTypeReference` returns + the bare enum name instead of a `global::`-qualified one (code that splits the namespace off it + finds no `.`). To keep the candidates' output, set + `"csharp": { "outputLayout": "package", "packageNamespaces": true }` in + `.metaobjects/config.json`; a self-hosted runner that builds its own `GenConfig` sets + `OutputLayout = OutputLayout.Package` and `PackageNamespacesFromMetadata = true`. +- **A hand-composed registry adds the four vocabulary packs.** Reporting + (`metaobjects-reporting`: `object.report`, `dimension.*`, `measure.*`, `segment.filter`, + `@segment`) and requirements (`metaobjects-requirements`) were part of the core provider in 1.2 + and are now their own providers. View expressions (`metaobjects-view-expressions`: + `origin.function`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`) is new in 1.3.0 for a + project on 1.2.0 to 1.2.3; the 1.2.4 candidates carried it in core. Rules (`metaobjects-rules`: + `api.*`, `operation.*`, `binding.*`, `transition.*`) is new in 1.3.0. Every port's default + bundle carries all four, so a project that loads through the default changes nothing. A registry + composed from a 1.2 provider list does not carry the packs split from its core. A model that + uses a type or subtype of a missing pack (`object.report`, `segment.filter`, `origin.function`) + fails to load with an unknown type or subtype, naming it. An attribute that a missing pack adds + (`@segment`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`) is refused with + `ERR_UNKNOWN_ATTR` only by a strict load; a non-strict load, the C# `MetaDataLoader` default, + does not report it. Compose from the default bundle (C# + `Provider.ComposeRegistry(CoreTypes.LibraryProviders)`, TypeScript `coreProviders`, Python + `core_providers`), or add the four providers to your list. Java and Kotlin discover them + through `META-INF/services`, as before. +- **Postgres views qualify a relation only when its entity declares `@schema`.** The 1.2.4 + candidates wrote every relation in a generated view body as `public."X"`; 1.3.0 writes `"X"` + unless the entity declares `@schema` (1.2.0 to 1.2.3 qualified none). From a candidate, expect + every regenerated Postgres view body to differ in `meta migrate`: one view replacement per view, + as with the `LEFT OUTER` item below. An unqualified relation is resolved through the + `search_path` in force when the view is created, so a migration that replaces views under a + non-default `search_path` should set it first (`SET LOCAL search_path TO , public;`). +- **C#, EF Core on Postgres: an index name over 63 bytes is now the name Postgres stores.** The + context declares a declared, `@unique` or foreign-key index name longer than 63 bytes cut to 63 + UTF-8 bytes, as Postgres cuts it. A migration snapshot from an earlier build still holds the + long name, so the first `dotnet ef migrations add` after upgrading scaffolds a `RenameIndex` + from the long name to the cut one, which Postgres refuses: the index already has the cut name. + Delete the `RenameIndex` calls from that migration's `Up` and `Down` (leaving them empty when + nothing else changed) and keep its snapshot, so the snapshot catches up without touching the + database. +- **C#, from a 1.2.4 release candidate: `UseIdentityStartMigrations()` is gone.** The candidates + generated it in `DesignTimeServices.g.cs`, latterly as an `[Obsolete]` no-op beside the + design-time services that replaced it. 1.3.0 does not generate it, so a call no longer compiles: + delete every `.UseIdentityStartMigrations()` call. Nothing else changes, since it did nothing. - **`@dbSetName` is `@collectionName`.** The attr was never published under its first name, so there is no alias: a model that set `@dbSetName` in a pre-release build renames it. - **`api.unknownFields: reject` is the one deliberate default change.** A generated create, PUT @@ -3158,8 +3205,8 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru apply. EF finds the services through an `[assembly: DesignTimeServicesReference]` generated beside them when the migrations live in the context's project, EF's default; for any other migrations or startup project, `dotnet meta gen` warns and prints the line to add there. Nothing - is registered at runtime. `UseIdentityStartMigrations()` is kept as an `[Obsolete]` no-op so a - call to it compiles; remove it. + is registered at runtime. `UseIdentityStartMigrations()`, which the 1.2.4 release candidates + generated (latterly as an `[Obsolete]` no-op), is not generated: remove the call. - **C#, upgrade note: a self-hosted codegen runner sets `GenConfig.Dialect`.** `@sequenceStart` and the identity-start rewrite are emitted only when the dialect is `postgres`. `CodegenCli` reads it from `.metaobjects/config.json` `migrate.dialect`; a runner that builds its own `GenConfig` must @@ -3551,6 +3598,17 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ### Fixed +- **TypeScript: a literal compared with an enum is written as the stored value.** A view over an + `@intValueMap` enum wrote `= 'Unknown'` against an integer column when the enum sat behind a + computed operand (`coalesce`, `nullif`, `greatest`, `least`, a `case` result) as well as a bare + field. The emitter now writes the mapped integer (or the `@stringValueMap` string) on every + operand that yields an enum. +- **C#: a parameter or argument list has no trailing comma.** A broken `Piece.Args` list ends + with its last item and no comma whatever `trailingComma` says; a broken `Piece.List` keeps its + trailing comma, which C# accepts in an initializer or collection expression. +- **C#: `CsWriter.Braced("")` writes the lone `{` of an anonymous block.** An empty head used to + write a blank line, because `Line("")` requests one. + - **TypeScript: the service, queries and CRUD-route generators no longer import an entity module nobody wrote.** When the filter of `serviceFile()`, `serviceRoutesFile()`, `serviceRoutesHonoFile()`, `queriesFile()`, `routesFile()` or `routesFileHono()` admitted an diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index ddfacc4a3..d023591f9 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -72,7 +72,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 91 cases (33 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 13 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 93 cases (33 core + 10 TypeScript + 9 Java + 12 Kotlin + 8 C# + 13 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | ✓ (`metaobjects::docs_view`, and the `docs-site` generator end to end) | diff --git a/docs/features/cli.md b/docs/features/cli.md index 9b2fb4ee5..2461ddc87 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -397,6 +397,9 @@ points to `docsSiteFile()` for people and `agentDocsFile()` for agents. relationships, and enums with their member sets. It **cites the migrations rather than restating the DDL** — the migration files are the DDL, they are generated, and a page that reproduces `CREATE TABLE` is a second spelling that goes stale. + It lists the tables `meta migrate` manages: an abstract base, a sourceless object, an + `@unmanaged` object and an object outside the project's scope have none, and a TPH + hierarchy is one table. A project whose tables are all owned elsewhere gets views only. - **`agent/ui.md`** — before touching a form or a grid. Per field: the control the form renders, label, HTML type, rules, form-excluded, and what the LIST endpoint accepts for filtering and sorting; plus each declared `layout.dataGrid`. The endpoint under each diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 27ccc911a..6fde15ec1 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -257,6 +257,8 @@ column type is that subtype's. A string cast may name a text `@dbColumnType` spe NULL of an unbounded varchar is `{ cast: { value: null }, as: string, dbColumnType: varchar }`. An enum casts to an integer only when it is stored as one (`@intValueMap`), which is also how an int-stored enum and an int meet in one `case`: `then: { cast: { field: status }, as: int }`. +A literal compared with an enum (`{ value: }`) is written as the member's stored value, +on either side and on any operand that yields the enum, a computed one included. **Functions** (`{ fn, args }`). Beside `coalesce`: `greatest` and `least` (ordered arguments of one type), `nullif` (two of one type), `lower`, `upper`, `btrim` (a string, optionally the diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index a114a6786..e78de7627 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -627,8 +627,8 @@ design-time services from assembly …" when they are found. The start in the model, and the services, are emitted only for a project whose `.metaobjects/config.json` names `"migrate": { "dialect": "postgres" }` (a self-hosted runner sets `GenConfig.Dialect`). Any other project gets neither, with a warning, and never needs the Npgsql -package. `UseIdentityStartMigrations()`, the registration of an earlier runtime SQL rewrite, is -kept as an `[Obsolete]` no-op so a call to it still compiles; remove the call. +package. `UseIdentityStartMigrations()`, the registration of an earlier runtime SQL rewrite in the +1.2.4 release candidates, is no longer generated, so a call to it does not compile; remove the call. **CHECK constraints** are the ones `meta migrate` creates: each scalar `field.enum` diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index 954505e1c..17ceb435e 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -25,7 +25,9 @@ The `kotlin` ops are `package` (a name), `use` (a name), `useAs` (a name, then t dialect's defaults unless it states options. The `csharp` ops are `header` (lines), `using`, `usingStatic` (a namespace or type), `usingAlias` -(alias, target) and `docSummary` (lines), beside the core ops. A `csharp` case may state +(alias, target), `docSummary` (lines) and `braced` (a head, then the ops written inside the +block), beside the core ops. A `csharp` list may state `"trailingComma": false`, the C# writer's +`Piece.Args`. A `csharp` case may state `"options": {"usingOrder": "sorted"}`; the default order is the order the generator named them. The `rust` ops are `use` (a path, then the names), `doc` and `prose` (one text each), diff --git a/fixtures/writer-conformance/cases/cs-braced-anonymous-block.json b/fixtures/writer-conformance/cases/cs-braced-anonymous-block.json new file mode 100644 index 000000000..bacac8e4d --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-braced-anonymous-block.json @@ -0,0 +1,35 @@ +{ + "description": "Braced with an empty head writes a lone { for an anonymous block, not a blank line, and Braced with a head writes the head then { on its own line.", + "dialect": "csharp", + "ops": [ + [ + "braced", + "public void M()", + [ + [ + "line", + "var a = 1;" + ], + [ + "braced", + "", + [ + [ + "line", + "var b = a;" + ] + ] + ] + ] + ] + ], + "expected": [ + "public void M()", + "{", + " var a = 1;", + " {", + " var b = a;", + " }", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/cs-list-args-no-trailing-comma.json b/fixtures/writer-conformance/cases/cs-list-args-no-trailing-comma.json new file mode 100644 index 000000000..e18ae8968 --- /dev/null +++ b/fixtures/writer-conformance/cases/cs-list-args-no-trailing-comma.json @@ -0,0 +1,53 @@ +{ + "description": "An argument or parameter list (Piece.Args) that breaks puts no comma after its last item, which C# refuses there, while the dialect's other lists keep the trailing comma.", + "dialect": "csharp", + "ops": [ + [ + "line", + "public static void Configure", + { + "list": { + "open": "(", + "items": [ + "ModelBuilder modelBuilder", + "IReadOnlyDictionary columnNamesByProperty", + "ILogger logger" + ], + "close": ")", + "trailingComma": false + } + } + ], + [ + "line", + "var names = new[] ", + { + "list": { + "open": "{", + "items": [ + "\"alphaAlphaAlphaAlphaAlpha\"", + "\"betaBetaBetaBetaBetaBetaBeta\"", + "\"gammaGammaGammaGammaGamma\"", + "\"deltaDeltaDelta\"" + ], + "close": "}", + "pad": true + } + }, + ";" + ] + ], + "expected": [ + "public static void Configure(", + " ModelBuilder modelBuilder,", + " IReadOnlyDictionary columnNamesByProperty,", + " ILogger logger", + ")", + "var names = new[] {", + " \"alphaAlphaAlphaAlphaAlpha\",", + " \"betaBetaBetaBetaBetaBetaBeta\",", + " \"gammaGammaGammaGammaGamma\",", + " \"deltaDeltaDelta\",", + "};" + ] +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs index 41dc086cb..48d412595 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs @@ -181,20 +181,3 @@ private static bool OnlyTheStart(AlterColumnOperation operation, string oldOptio : Equals(operation[n], o[n])); } } - -/// Kept for one release so code written against the earlier runtime registration still -/// compiles. It does nothing: the identity start is applied at design time. -public static class AppDbContextIdentityStartMigrations -{ - private const string Message = "UseIdentityStartMigrations() is no longer needed and does nothing: the identity start is " + - "applied at design time by AppDbContextDesignTimeServices, which dotnet ef migrations add finds on its own. Remove the call."; - - /// Does nothing. - [Obsolete(Message)] - public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) => options; - - /// Does nothing. - [Obsolete(Message)] - public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) - where TContext : DbContext => options; -} diff --git a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs index 5b1d2950e..fb05e7c9f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartDialectTests.cs @@ -68,11 +68,10 @@ public void A_postgres_project_gets_the_design_time_services_and_the_start() Assert.DoesNotContain("Npgsql.EntityFrameworkCore.PostgreSQL.", services.Replace("\"Npgsql.EntityFrameworkCore.PostgreSQL\"", "")); Assert.DoesNotContain(".Internal", services); Assert.DoesNotContain("EF1001", services); - // The earlier runtime registration survives for one release as an [Obsolete] no-op, so - // an adopter's UseIdentityStartMigrations() call still compiles (EfModelGapsTests proves it). - Assert.Contains("public static class AppDbContextIdentityStartMigrations", services); - Assert.Equal(2, services.Split("[Obsolete(Message)]").Length - 1); - Assert.Contains("DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) => options;", services); + // The earlier runtime registration's [Obsolete] no-op, kept through the 1.2.4 candidates, is + // not generated: 1.3.0 removes it (EfModelGapsTests proves a call to it no longer compiles). + Assert.DoesNotContain("UseIdentityStartMigrations", services); + Assert.DoesNotContain("[Obsolete", services); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs index 1fb2d52c2..6c331d3e3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs @@ -71,7 +71,13 @@ private static string Run(JsonElement c, string dialect) { var options = c.TryGetProperty("options", out var o) ? o : default; CodeWriter w = dialect == DialectCore ? new CodeWriter(CoreOptions(options)) : new CsWriter { UsingOrder = CsOrder(options) }; - foreach (var op in c.GetProperty("ops").EnumerateArray()) + RunOps(w, c.GetProperty("ops")); + return w.ToString(); + } + + private static void RunOps(CodeWriter w, JsonElement ops) + { + foreach (var op in ops.EnumerateArray()) { var items = op.EnumerateArray().ToList(); var name = items[0].GetString()!; @@ -85,7 +91,7 @@ private static string Run(JsonElement c, string dialect) case "text": w.Text(args[0].GetString()!); break; default: var cs = w as CsWriter ?? throw new InvalidOperationException($"op {name} is not a core op"); - var s = args.Select(a => a.GetString()!).ToArray(); + var s = args.Where(a => a.ValueKind == JsonValueKind.String).Select(a => a.GetString()!).ToArray(); switch (name) { case "header": cs.Header(s); break; @@ -93,12 +99,15 @@ private static string Run(JsonElement c, string dialect) case "usingStatic": cs.UsingStatic(s[0]); break; case "usingAlias": cs.UsingAlias(s[0], s[1]); break; case "docSummary": cs.DocSummary(s); break; + // A Braced scope: the head, then the ops written inside it. + case "braced": + using (cs.Braced(args[0].GetString()!)) RunOps(cs, args[1]); + break; default: throw new InvalidOperationException($"unknown op {name}"); } break; } } - return w.ToString(); } private static CodeWriterOptions CoreOptions(JsonElement o) => new() @@ -127,5 +136,6 @@ private static UsingOrder CsOrder(JsonElement o) => l.GetProperty("open").GetString()!, l.GetProperty("items").EnumerateArray().Select(ToPiece).ToList(), l.GetProperty("close").GetString()!, - l.TryGetProperty("pad", out var pad) && pad.GetBoolean()); + l.TryGetProperty("pad", out var pad) && pad.GetBoolean(), + l.TryGetProperty("trailingComma", out var tc) ? tc.GetBoolean() : null); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index a781e9a71..c92cf943d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1255,23 +1255,6 @@ private static bool OnlyTheStart(AlterColumnOperation operation, string oldOptio : Equals(operation[n], o[n])); } } - - /// Kept for one release so code written against the earlier runtime registration still - /// compiles. It does nothing: the identity start is applied at design time. - public static class {{contextName}}IdentityStartMigrations - { - private const string Message = "UseIdentityStartMigrations() is no longer needed and does nothing: the identity start is " + - "applied at design time by {{className}}, which dotnet ef migrations add finds on its own. Remove the call."; - - /// Does nothing. - [Obsolete(Message)] - public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) => options; - - /// Does nothing. - [Obsolete(Message)] - public static DbContextOptionsBuilder UseIdentityStartMigrations(this DbContextOptionsBuilder options) - where TContext : DbContext => options; - } """); return w.ToString(); } diff --git a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs index c9e155496..55dfc0903 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs @@ -46,12 +46,20 @@ public abstract class Piece { public static implicit operator Piece(string text) => new Text(text); - /// A list with no padding inside its brackets: [a, b], f(a, b), <A, B>. + /// A list with no padding inside its brackets, such as [a, b]. Broken, it takes the writer's + /// trailing comma, so use where C# refuses one (an argument, parameter or type list). public static Piece List(string open, IEnumerable items, string close) => new Group(open, items, close); /// A list padded inside its brackets when it stays on one line: { a, b }. public static Piece Padded(string open, IEnumerable items, string close) => new Group(open, items, close, pad: true); + /// + /// An argument or parameter list, f(a, b): unpadded, and when it breaks its last item takes no + /// comma, whatever the writer's . C# refuses a trailing + /// comma in a parameter or argument list, though it accepts one in an initializer. + /// + public static Piece Args(string open, IEnumerable items, string close) => new Group(open, items, close, trailingComma: false); + /// Several parts of one line, concatenated. public static Piece Seq(params Piece[] parts) => new Sequence(parts); @@ -92,13 +100,17 @@ public sealed class Group : Piece public string Close { get; } /// { a, b } (true) versus [a, b] or f(a, b) (false) when printed on one line. public bool Pad { get; } + /// Whether this list, broken, puts a comma after its last item: null takes the writer's + /// , false never does (). + public bool? TrailingComma { get; } - public Group(string open, IEnumerable items, string close, bool pad = false) + public Group(string open, IEnumerable items, string close, bool pad = false, bool? trailingComma = null) { Open = open; Items = items.ToList(); Close = close; Pad = pad; + TrailingComma = trailingComma; } internal override void FlatInto(StringBuilder sb) @@ -300,7 +312,7 @@ protected CodeWriter Put(Piece piece) OpenPiece(before + group.Open); for (var n = 0; n < group.Items.Count; n++) { - var comma = n < group.Items.Count - 1 || TrailingComma ? "," : ""; + var comma = n < group.Items.Count - 1 || (group.TrailingComma ?? TrailingComma) ? "," : ""; Put(Piece.Seq(group.Items[n], comma)); } return ClosePiece(group.Close + after); diff --git a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs index 7b8a095c8..4124fc9b6 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs @@ -19,7 +19,8 @@ public enum UsingOrder /// /// The writer a C# generator writes through. Four-space indent, 120 columns, a trailing comma in -/// broken lists. Not final: every method is public or protected. +/// broken lists (except an argument or parameter list, ). Not final: every +/// method is public or protected. /// public class CsWriter : CodeWriter { @@ -111,11 +112,12 @@ private CsWriter AddUsing(string directive) /// /// A block whose braces are on their own lines, the way C# is written: /// using (w.Braced("public class A")) { ... } writes public class A, {, the - /// body, then }. Pass a different for };. + /// body, then }. Pass a different for };. An empty head + /// writes a lone {: an anonymous block (a blank line would be a blank-line request). /// public IDisposable Braced(Piece head, string tail = "}") { - Line(head); + if (head.Flat().Length > 0) Line(head); return Block("{", tail); } diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 74fef9ba1..064a467b8 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -1189,29 +1189,26 @@ public void A_pooled_context_needs_no_registration() Assert.NotNull(db.Model); } - // One release of compatibility: the earlier runtime registration still compiles and does nothing. + // The earlier runtime registration, kept as an [Obsolete] no-op through the 1.2.4 candidates, is gone in + // 1.3.0: a call to it no longer compiles, and the model builds on stock Npgsql without it. [Fact] - public void A_caller_of_the_earlier_UseIdentityStartMigrations_still_compiles_and_does_nothing() + public void The_earlier_UseIdentityStartMigrations_registration_is_no_longer_generated() { - var gen = GeneratedEfModel.Compile(StartVocabularyModel.Replace("__START__", ", \"@sequenceStart\": 200"), "Acme.StartCompat", + var model = StartVocabularyModel.Replace("__START__", ", \"@sequenceStart\": 200"); + var failure = Assert.Throws(() => GeneratedEfModel.Compile(model, "Acme.StartCompat", c => c with { Dialect = "postgres" }, handWritten: [""" using Microsoft.EntityFrameworkCore; namespace Acme.StartCompat; public static class LegacyRegistration { - #pragma warning disable CS0618 public static DbContextOptionsBuilder Configure(DbContextOptionsBuilder o) => o.UseNpgsql("Host=unused").UseIdentityStartMigrations(); - public static DbContextOptionsBuilder Typed(DbContextOptionsBuilder o) => o.UseNpgsql("Host=unused").UseIdentityStartMigrations(); } - """]); - var shim = gen.Type("AppDbContextIdentityStartMigrations"); - var method = shim.GetMethod("UseIdentityStartMigrations", [typeof(DbContextOptionsBuilder)])!; - var obsolete = (ObsoleteAttribute)Attribute.GetCustomAttribute(method, typeof(ObsoleteAttribute))!; - Assert.Contains("AppDbContextDesignTimeServices", obsolete.Message); - var builder = new DbContextOptionsBuilder().UseNpgsql("Host=unused"); - Assert.Same(builder, method.Invoke(null, [builder])); - // It registers nothing: the model builds on stock Npgsql either way. - using var db = gen.NewContext(o => { method.Invoke(null, [o.UseNpgsql("Host=unused")]); }); + """])); + Assert.Contains("UseIdentityStartMigrations", failure.Message); + + var gen = GeneratedEfModel.Compile(model, "Acme.StartCompat", c => c with { Dialect = "postgres" }); + Assert.Null(MetaObjects.IntegrationTests.GeneratedTypes.Find(gen.Assembly, "Acme.StartCompat.AppDbContextIdentityStartMigrations")); + using var db = gen.NewContext(o => o.UseNpgsql("Host=unused")); Assert.NotNull(db.Model); Assert.DoesNotContain("RESTART", Sql(Differ(DesignTime(db, gen.Assembly)) .GetDifferences(DesignModel(Stock(StartModel(null))), DesignModel(db))), StringComparison.OrdinalIgnoreCase); diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index 6f62e3af5..0e4a1a6ea 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -931,10 +931,15 @@ function resolveExprNode( const name = raw.field; if (typeof name !== "string") return undefined; const own = lookup?.(name); - if (own !== undefined) return own.expr; + if (own !== undefined) { + refFields.set(own.expr, own.field); + return own.expr; + } const field = base.fields().find((f) => f.name === name); if (!field) return undefined; - return { kind: "col", ref: `${baseAlias}.${sourceColumnNameFor(field, ctx)}` }; + const col: ViewExprNode = { kind: "col", ref: `${baseAlias}.${sourceColumnNameFor(field, ctx)}` }; + refFields.set(col, field); + return col; } if ("value" in raw) { return { kind: "lit", value: raw.value as ViewExprLiteral }; @@ -958,9 +963,11 @@ function resolveExprNode( const whens: { when: ViewExprNode; then: ViewExprNode }[] = []; for (const arm of arms) { if (!isPlainObject(arm)) return undefined; - const when = sub(arm[EXPR_CASE_WHEN]); + let when = sub(arm[EXPR_CASE_WHEN]); const then = sub(arm[EXPR_CASE_THEN]); if (when === undefined || then === undefined) return undefined; + // A simple CASE compares each WHEN value with the operand, so the operand's encoding applies. + if (operand !== undefined) when = asStoredLiteral(arm[EXPR_CASE_WHEN], when, operand); whens.push({ when, then }); } const otherwise = EXPR_CASE_ELSE in raw ? sub(raw[EXPR_CASE_ELSE]) : undefined; @@ -999,7 +1006,9 @@ function resolveExprNode( const rf = fieldOf(raw.right); const left = sub(raw.left, rf !== undefined ? temporalOfField(rf) : nowTemporal); const right = sub(raw.right, lf !== undefined ? temporalOfField(lf) : nowTemporal); - return left && right ? { kind: "cmp", op, left, right } : undefined; + return left && right + ? { kind: "cmp", op, left: asStoredLiteral(raw.left, left, right), right: asStoredLiteral(raw.right, right, left) } + : undefined; } if (op === FILTER_OP_IS_NULL || op === EXPR_OP_IS_NOT_NULL) { const arg = sub(raw.arg); @@ -1025,6 +1034,36 @@ interface ResolvedRef { readonly field: MetaField; } +/** The field each resolved `{ field }` ref names, by the node it resolved to. */ +const refFields = new WeakMap(); + +/** The field whose column form `node` has: the one a ref names, else the first among the operands + * whose value the node returns (coalesce, a same-typed function, a case's results). */ +function storedFieldOf(node: ViewExprNode): MetaField | undefined { + const ref = refFields.get(node); + if (ref !== undefined) return ref; + const results = node.kind === "coalesce" || (node.kind === "fn" && EXPR_FUNCTIONS[node.name]?.result === "same") ? node.args + : node.kind === "case" ? [...node.whens.map((w) => w.then), ...(node.else !== undefined ? [node.else] : [])] + : []; + for (const result of results) { + const field = storedFieldOf(result); + if (field !== undefined) return field; + } + return undefined; +} + +/** `node` (resolved from `raw`) as compared with `other`: a literal member symbol facing a + * stored-encoded field.enum is the value the column holds (the @intValueMap integer / + * @stringValueMap string), not the symbol. */ +function asStoredLiteral(raw: unknown, node: ViewExprNode, other: ViewExprNode): ViewExprNode { + if (!isPlainObject(raw) || typeof raw.value !== "string") return node; + const field = storedFieldOf(other); + const map = field !== undefined && field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field) : undefined; + if (field === undefined || map === undefined) return node; + const stored = encodeIntEnumFilterValue(raw.value, FILTER_OP_EQ, map, field.name, "origin.computed @expr"); + return { kind: "lit", value: stored as ViewExprLiteral }; +} + /** The relative-date kind of a temporal field; an instant for anything else. */ function temporalOfField(f: MetaField): ReportTemporal { return f.subType === FIELD_SUBTYPE_DATE || f.subType === FIELD_SUBTYPE_TIMESTAMP ? temporalOf(f) : "instant"; diff --git a/server/typescript/packages/codegen-ts/test/projection/enum-literal-in-computed-expr.test.ts b/server/typescript/packages/codegen-ts/test/projection/enum-literal-in-computed-expr.test.ts new file mode 100644 index 000000000..b37c623a8 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/enum-literal-in-computed-expr.test.ts @@ -0,0 +1,85 @@ +// An origin.computed expression comparing a stored-encoded field.enum with a literal writes the +// STORED value (the @intValueMap integer / @stringValueMap string), never the member name. + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +async function view(enumAttrs: Record, expr: unknown): Promise { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Device", children: [ + { "source.rdb": { "@table": "devices" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Unknown", "Active"], ...enumAttrs } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "DeviceFlags", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_device_flags" } }, + { "field.long": { name: "id", extends: "Device.id" } }, + { "field.boolean": { name: "flag", children: [{ "origin.computed": { "@expr": expr } }] } }, + { "identity.primary": { name: "id", extends: "Device.id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + return buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; +} + +const INT = { "@intValueMap": { Unknown: 0, Active: 1 } }; +const STR = { "@stringValueMap": { Unknown: "unk", Active: "act" } }; +const cmp = (op: string, v: unknown) => ({ op, left: { field: "status" }, right: { value: v } }); + +test("eq on an int-stored enum writes the mapped integer", async () => { + const sql = await view(INT, cmp("eq", "Unknown")); + expect(sql).toMatch(/d\.status = 0\b/); + expect(sql).not.toContain("'Unknown'"); +}); + +test("ne and a literal on the left are mapped too", async () => { + expect(await view(INT, cmp("ne", "Active"))).toMatch(/d\.status <> 1\b/); + const { op: _o, ...rest } = cmp("eq", "Active"); + const flipped = await view(INT, { op: "eq", left: { value: "Active" }, right: rest.left }); + expect(flipped).toMatch(/1 = d\.status/); + expect(flipped).not.toContain("'Active'"); +}); + +test("a simple CASE on an int-stored enum maps its WHEN literals", async () => { + const sql = await view(INT, { case: [{ when: { value: "Unknown" }, then: { value: true } }], operand: { field: "status" }, else: { value: false } }); + expect(sql).not.toContain("'Unknown'"); + expect(sql).toMatch(/WHEN 0 THEN/); +}); + +const STATUS = { field: "status" }; +const compound: [string, unknown][] = [ + ["coalesce", { fn: "coalesce", args: [STATUS, STATUS] }], + ["nullif", { fn: "nullif", args: [STATUS, STATUS] }], + ["greatest", { fn: "greatest", args: [STATUS, STATUS] }], + ["least", { fn: "least", args: [STATUS, STATUS] }], + ["case result", { case: [{ when: { op: "isNull", arg: STATUS }, then: STATUS }], else: STATUS }], +]; + +test.each(compound)("a literal facing a %s over an int-stored enum is mapped on either side", async (_name, operand) => { + for (const [left, right] of [[operand, { value: "Unknown" }], [{ value: "Unknown" }, operand]]) { + const sql = await view(INT, { op: "eq", left, right }); + expect(sql).toMatch(/(= 0\b|\b0 =)/); + expect(sql).not.toContain("'Unknown'"); + } +}); + +test("a simple CASE over a coalesce operand maps its WHEN literals", async () => { + const sql = await view(INT, { case: [{ when: { value: "Unknown" }, then: { value: true } }], operand: compound[0]![1], else: { value: false } }); + expect(sql).not.toContain("'Unknown'"); + expect(sql).toMatch(/WHEN 0 THEN/); +}); + +test("a literal facing a coalesce over a @stringValueMap enum writes the stored string", async () => { + const sql = await view(STR, { op: "eq", left: compound[0]![1], right: { value: "Unknown" } }); + expect(sql).toContain("'unk'"); + expect(sql).not.toContain("'Unknown'"); +}); + +test("eq on a @stringValueMap enum writes the stored string", async () => { + const sql = await view(STR, cmp("eq", "Unknown")); + expect(sql).toContain("'unk'"); + expect(sql).not.toContain("'Unknown'"); +}); + +test("a plain string enum keeps the member name", async () => { + expect(await view({}, cmp("eq", "Unknown"))).toContain("'Unknown'"); +}); diff --git a/spec/code-writer.md b/spec/code-writer.md index 2e697e526..9adf77d05 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -266,7 +266,11 @@ Case `dialect` is `csharp`. The defaults are four-space indent, width 120 and a the rest, each group in ordinal order of the namespace. - One alias naming two different targets is **`ERR_WRITER_IMPORT_CONFLICT`**. - **`Braced(head)`** writes `head`, then a `{` on its own line, indents, and writes `}` when the scope - ends: the Allman form C# generators emit. + ends: the Allman form C# generators emit. An empty head writes only the `{`, an anonymous block. +- **`Piece.Args(open, items, close)`** is a list for a parameter or argument list. It is unpadded + and, broken, puts no comma after its last item, whatever `trailingComma` says: C# accepts a + trailing comma in an initializer or a collection expression, and refuses one in a parameter or + argument list. In a case it is a list with `"trailingComma": false`. - **`DocSummary(lines...)`** writes `/// `, one `/// text` line per entry (a bare `///` for an empty entry) and `/// `, at the current indent. - **`Hanging()`** is a scope for a statement that carries on after a line that is not finished. It