From 3a2fbd1266b95eb60831491f1faa17e1092946c0 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:43:21 -0800 Subject: [PATCH] Source generator: ships in the Core package, on by default The `Map()` source generator is now part of `Open.Database.Extensions.Core`: the analyzer, built for Roslyn 4.14 or later so an older compiler never loads it, and the build targets that allow its interceptors. The other packages pass both on to their consumers. `false` switches it off, and holds even where the compiler does not receive the property. A partial model (or one with a partial base type) is checked once against the built type: if another source generator added constructors or settable properties this one could not see, the runtime map reads it, so no column is left unset. Fixed before it ships: on machines whose culture writes a minus sign C# does not read (Swedish, Norwegian, Persian and others), the generated file did not compile. A new test project references only the packed packages and runs the generator on, through MSSqlClient alone, switched off, and on C# 12, for net472, net10.0 and net11.0, against SQL Server LocalDB and a SQLite file. The generator CI job starts LocalDB, requires it, and runs those tests. Also adds tests for more declined and served model shapes. Documentation: a "Generated readers" section in the mapping article, the Core and generator READMEs, and a release note. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/tests.yml | 49 +++- .../Open.Database.Extensions.Channel.csproj | 3 +- .../Core/Open.Database.Extensions.Core.csproj | 8 + Source/Core/README.md | 4 + .../Open.Database.Extensions.Dataflow.csproj | 3 +- .../Open.Database.Extensions.csproj | 3 +- Source/Generator/Emitter.cs | 48 +++- Source/Generator/MapGenerator.cs | 2 +- Source/Generator/ModelReader.cs | 19 +- .../Open.Database.Extensions.Generator.csproj | 7 +- Source/Generator/README.md | 23 +- Source/Generator/Specs.cs | 7 +- ...Open.Database.Extensions.Generator.targets | 10 +- ...pen.Database.Extensions.MSSqlClient.csproj | 3 +- .../Open.Database.Extensions.SqlClient.csproj | 3 +- .../CultureTests.cs | 52 ++++ ...Database.Extensions.Generator.Tests.csproj | 6 +- .../ParityTests.Partial.cs | 90 ++++++ .../ParityTests.Shapes.cs | 160 ++++++++++- .../ParityTests.Trusted.cs | 17 +- .../ConsumerTests.cs | 263 ++++++++++++++++++ ...se.Extensions.PackageConsumer.Tests.csproj | 55 ++++ docsite/articles/mapping.md | 21 +- docsite/articles/release-notes.md | 1 + 24 files changed, 823 insertions(+), 34 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Generator.Tests/CultureTests.cs create mode 100644 Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Partial.cs create mode 100644 Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs create mode 100644 Tests/Open.Database.Extensions.PackageConsumer.Tests/Open.Database.Extensions.PackageConsumer.Tests.csproj diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b6e9fb5f..adccdaec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,7 +3,8 @@ name: Tests # Runs the Core test suite on every pull request and every push to master, and checks the packages for known vulnerabilities. # The suite runs on net10.0 and net11.0 in Release, and on net11.0 in Debug (Debug.Assert is live there). # A separate job runs the LegacyCompiler tests, which compile the public call shapes with older C# language versions. -# Another runs the source generator prototype's tests: each intercepted Map() against the runtime map on the same data. +# Another runs the source generator's tests: each intercepted Map() against the runtime map on the same data, then a consumer of the +# packed packages, with the generator on and off. # Another job builds the Benchmarks project (it is not in the solution), so a change to the public API cannot leave its call sites behind. # Another runs `dotnet format` style and analyzers at info severity on every project, which is what the IDE shows. # SQL Server LocalDB is part of the runner image. ODX_REQUIRE_SQL=1 makes the tests that need it fail, instead of skip, when it is missing. @@ -117,7 +118,7 @@ jobs: path: TestResults/legacy-compiler/*.trx generator: - name: Test the source generator prototype + name: Test the source generator runs-on: windows-latest timeout-minutes: 30 defaults: @@ -132,17 +133,59 @@ jobs: 10.0.x 11.0.x + # As in the test job: both steps below read from a real SQL Server. + - name: Start SQL Server LocalDB + run: | + $exe = (Get-Command SqlLocalDB.exe -ErrorAction SilentlyContinue)?.Source + if (-not $exe) { + $exe = Get-ChildItem "$env:ProgramFiles\Microsoft SQL Server\*\Tools\Binn\SqlLocalDB.exe" -ErrorAction SilentlyContinue | + Sort-Object FullName | Select-Object -Last 1 -ExpandProperty FullName + } + if (-not $exe) { throw 'SqlLocalDB.exe was not found on this runner image, so the SQL Server tests cannot run.' } + & $exe start MSSQLLocalDB + if ($LASTEXITCODE -ne 0) { throw "SqlLocalDB start MSSQLLocalDB failed with exit code $LASTEXITCODE" } + & $exe info MSSQLLocalDB + # The generator runs as an analyzer of the test project and intercepts its Map() calls on the models of another assembly; # each test compares those rows, or that exception, with the runtime map's on the same data. No -f: net10.0 and net11.0. - name: Run the generator tests + env: + ODX_REQUIRE_SQL: 1 run: dotnet test Tests/Open.Database.Extensions.Generator.Tests -c Release --logger "trx;LogFilePrefix=generator" --results-directory TestResults/generator + # What a NuGet user gets: the packages are packed, and a project that references only them is built and run with the generator on, + # arriving through MSSqlClient alone, switched off, and with C# 12. It runs on net472, net10.0 and net11.0, against LocalDB and SQLite. + - name: Run the package consumer tests + env: + ODX_REQUIRE_SQL: 1 + run: | + $suffix = "ci.${{ github.run_id }}.${{ github.run_attempt }}" + $feed = Join-Path $env:RUNNER_TEMP 'feed' + foreach ($project in 'Source/Core', 'Source/MSSqlClient') { + # GeneratePackageOnBuild (Source/Directory.Build.props) stops `dotnet pack` building first, which a clean checkout needs. + dotnet pack $project -c Release -o $feed -p:VersionSuffix=$suffix -p:GeneratePackageOnBuild=false + if ($LASTEXITCODE -ne 0) { throw "dotnet pack $project failed" } + } + $variants = [ordered]@{ core = @(); mssqlclient = @('-p:OdxVia=MSSqlClient'); off = @('-p:OdxGenerateMaps=false'); csharp12 = @('-p:LangVersion=12') } + $failed = @() + foreach ($variant in $variants.Keys) { + $options = @("-p:OdxFeed=$feed", "-p:OdxPackageVersion=11.0.0-$suffix") + $variants[$variant] + $consumer = 'Tests/Open.Database.Extensions.PackageConsumer.Tests' + dotnet build $consumer -c Release --no-incremental @options + if ($LASTEXITCODE -ne 0) { $failed += "$variant (build)"; continue } + dotnet test $consumer -c Release --no-build @options --logger "trx;LogFilePrefix=$variant" --results-directory TestResults/consumer + if ($LASTEXITCODE -ne 0) { $failed += $variant } + } + if ($failed.Count -gt 0) { throw "Package consumer tests failed: $($failed -join ', ')" } + - name: Upload the TRX files if: always() uses: actions/upload-artifact@v7 with: name: trx-generator - path: TestResults/generator/*.trx + path: | + TestResults/generator/*.trx + TestResults/consumer/*.trx benchmarks-build: name: Build the Benchmarks project diff --git a/Source/Channel/Open.Database.Extensions.Channel.csproj b/Source/Channel/Open.Database.Extensions.Channel.csproj index e82f56b3..53f46b7d 100644 --- a/Source/Channel/Open.Database.Extensions.Channel.csproj +++ b/Source/Channel/Open.Database.Extensions.Channel.csproj @@ -10,7 +10,8 @@ - + + diff --git a/Source/Core/Open.Database.Extensions.Core.csproj b/Source/Core/Open.Database.Extensions.Core.csproj index 85543134..400fff8a 100644 --- a/Source/Core/Open.Database.Extensions.Core.csproj +++ b/Source/Core/Open.Database.Extensions.Core.csproj @@ -21,6 +21,14 @@ + + + + + + + diff --git a/Source/Core/README.md b/Source/Core/README.md index 98323b92..27edfe92 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -30,6 +30,10 @@ Post[] posts = await connectionFactory `AddParam(author)` names the parameter `author` after the variable; `AddParam("author", 42)` names it yourself. Already have a connection? Start from it instead: `connection.Command("...")`. You own the connection; the command opens it only if it is closed and closes only what it opened. +## Generated row readers + +This package carries a source generator. With C# 12 or later and the .NET 9.0.300 SDK or Visual Studio 17.14, or newer, a plain `Map()` on a command or a reader gets its row reader written at build time, with nothing to add. While it is on, a model that declares every column's ordinal is read by position, unchecked. To switch it off, set `false` in the project. See [Generated readers](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#generated-readers). + ## Where to go next - [Getting started](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html) diff --git a/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj b/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj index 86b93193..899b71d1 100644 --- a/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj +++ b/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj @@ -14,7 +14,8 @@ - + + diff --git a/Source/Extensions/Open.Database.Extensions.csproj b/Source/Extensions/Open.Database.Extensions.csproj index 1bdb35e4..7e35a897 100644 --- a/Source/Extensions/Open.Database.Extensions.csproj +++ b/Source/Extensions/Open.Database.Extensions.csproj @@ -9,7 +9,8 @@ - + + diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index fd4bd950..0c7095df 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -40,7 +40,7 @@ public static string Emit(IReadOnlyList sites, Options options) { var sb = new StringBuilder(); sb.AppendLine("// "); - sb.AppendLine("// Open.Database.Extensions source generator (prototype): Map() served by generated row readers."); + sb.AppendLine("// Open.Database.Extensions source generator: Map() served by generated row readers."); sb.AppendLine("#nullable disable"); sb.AppendLine("#pragma warning disable"); sb.AppendLine(); @@ -193,6 +193,24 @@ public bool Matches(global::System.Data.Common.DbDataReader r) } } + // Whether the built type of a partial model has the constructors and settable properties the generator saw. + file static class OdxShape + { + public static bool AsSeen(global::System.Reflection.PropertyInfo[] properties, int constructors, int expected, string[] settable) + { + if (constructors != expected) return false; + int found = 0; + foreach (global::System.Reflection.PropertyInfo p in properties) + { + if (p.GetSetMethod() == null || p.GetIndexParameters().Length != 0) continue; + if (global::System.Array.IndexOf(settable, p.Name) < 0) return false; + found++; + } + + return found == settable.Length; + } + } + file static class OdxMatch { // The fed slots (a column, mapped) ordered by their column. @@ -355,6 +373,16 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine($"\t\tpublic static {Ns}.RowMap<{T}> Map => s_map ??= {Ns}.Generation.GeneratedRowMap.Create<{T}>(Bind);"); sb.AppendLine(); + if (m.Partial is { } shape) + { + // Another source generator may have added to a partial model what this one could not see, and the readers would not set it. Checked once + // per type against the built type; if it differs, Bind serves nothing and the runtime map reads this model. + string names = string.Concat(shape.Settable.Items.Select(static n => ", " + Str(n))); + sb.AppendLine($"\t\tstatic readonly bool s_asSeen = OdxShape.AsSeen(typeof({T}).GetProperties(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.Instance),"); + sb.AppendLine($"\t\t\ttypeof({T}).GetConstructors().Length, {shape.Constructors}, new string[] {{ {(names.Length == 0 ? "" : names.Substring(2))} }});"); + sb.AppendLine(); + } + if (m.AllOrdered) { EmitTrusted(sb, ByMemberType(m), options, styleB, literal, reader); @@ -367,7 +395,11 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\tstatic readonly OdxSlot[] Slots ="); sb.AppendLine("\t\t["); foreach (SlotSpec s in slots) - sb.AppendLine($"\t\t\tnew({Str(s.Name)}, {Str(s.Column)}, {s.Order}, {Bool(s.NotMapped)}, {Bool(s.Required)}),"); + { + // Invariant: Order is -1 where none is declared, and a culture's minus sign need not be the one C# reads. + string order = s.Order.ToString(System.Globalization.CultureInfo.InvariantCulture); + sb.AppendLine($"\t\t\tnew({Str(s.Name)}, {Str(s.Column)}, {order}, {Bool(s.NotMapped)}, {Bool(s.Required)}),"); + } sb.AppendLine("\t\t];"); sb.AppendLine(); @@ -396,6 +428,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\t// Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map."); sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r)"); sb.AppendLine("\t\t{"); + if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); sb.AppendLine("\t\t\tLayout[] layouts = s_layouts;"); sb.AppendLine("\t\t\tfor (int i = 0; i < layouts.Length; i++)"); sb.AppendLine("\t\t\t{"); @@ -404,7 +437,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\t\t}"); sb.AppendLine(); sb.AppendLine("\t\t\tLayout l = Resolve(r);"); - sb.AppendLine("\t\t\tglobal::System.Threading.Volatile.Write(ref layouts[(int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length)], l);"); + sb.AppendLine("\t\t\tglobal::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l);"); sb.AppendLine($"\t\t\treturn {(options.Counters ? "Count(l)" : "l.Row")};"); sb.AppendLine("\t\t}"); sb.AppendLine(); @@ -529,6 +562,7 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty { sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r)"); sb.AppendLine("\t\t{"); + if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);"); sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]);"); sb.AppendLine("\t\t\treturn ReadLiteral;"); @@ -536,13 +570,19 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty } else { - sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r) => ReadLiteral;"); + sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r) => {(m.Partial is null ? "ReadLiteral" : "s_asSeen ? ReadLiteral : null")};"); } sb.AppendLine(); EmitLiteralReader(sb, m, styleB, literal, reader); } + // A partial model the built type does not match: nothing served, so the runtime map reads the result set. + static string Unseen(Options options) + => options.Counters + ? "if (!s_asSeen) { global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Declined); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[0]); return null; }" + : "if (!s_asSeen) return null;"; + enum ReadMode { Literal, Full, Guarded, Converting } // The constant ordinal of each slot in the literal read mode, -1 for a slot not mapped: the declared Order of a trusted model, else diff --git a/Source/Generator/MapGenerator.cs b/Source/Generator/MapGenerator.cs index c494a863..4e900199 100644 --- a/Source/Generator/MapGenerator.cs +++ b/Source/Generator/MapGenerator.cs @@ -8,7 +8,7 @@ namespace Open.Database.Extensions.Generator; /// -/// PROTOTYPE (SG phase A). Intercepts each plain x.Map<T>() call bound to Open.Database.Extensions.CoreExtensions +/// Intercepts each plain x.Map<T>() call bound to Open.Database.Extensions.CoreExtensions /// (receivers IExecuteReader, IDbCommand, IDataReader) and serves it with generated row readers through the /// existing Map(RowMap<T>?) overload, the map made by Core's hidden GeneratedRowMap.Create. Emits nothing (the call keeps running today's code) when: /// C# is below 12, the interceptors feature is not enabled for Open.Database.Extensions.Generated, OdxGenerateMaps is false, diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index 8b36fa28..4b55d40f 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -1,5 +1,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Immutable; using System.Globalization; @@ -163,7 +164,23 @@ static class ModelReader constructor?.Parameters.Length ?? 0, decorated, allOrdered, - new EquatableArray([.. slots])); + new EquatableArray([.. slots]), + IsPartial(t) + ? new PartialShape(constructors.Count, new EquatableArray( + [.. properties.Where(static p => p.SetMethod is { DeclaredAccessibility: Accessibility.Public }).Select(static p => p.Name)])) + : null); + } + + // Whether the model or a base type is declared partial in this compilation. A type from a referenced assembly is already whole. + static bool IsPartial(INamedTypeSymbol t) + { + for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType) + { + if (c.DeclaringSyntaxReferences.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword))) + return true; + } + + return false; } // Shape.Judge, minus what the runtime would throw for (the call then runs today's code and throws there), plus what generated code cannot name. diff --git a/Source/Generator/Open.Database.Extensions.Generator.csproj b/Source/Generator/Open.Database.Extensions.Generator.csproj index 0cf76ff9..16362558 100644 --- a/Source/Generator/Open.Database.Extensions.Generator.csproj +++ b/Source/Generator/Open.Database.Extensions.Generator.csproj @@ -1,10 +1,9 @@ diff --git a/Source/Generator/README.md b/Source/Generator/README.md index a3aef858..5bb945e9 100644 --- a/Source/Generator/README.md +++ b/Source/Generator/README.md @@ -1,7 +1,7 @@ -# Open.Database.Extensions.Generator (unpackaged prototype) +# Open.Database.Extensions.Generator A Roslyn incremental source generator that serves a plain `Map()` with generated row readers, through C# interceptors. -It is an **unpackaged prototype**: not packaged, not referenced by Core, and Core builds, tests and ships without it. +It ships inside the `Open.Database.Extensions.Core` package, on by default; it is not a package of its own. ## What it does @@ -45,7 +45,13 @@ Core's hidden entry `GeneratedRowMap.Create(Bind)` (for this generator only; check, or cost the runtime map its clear NULL message for these types. Pinned by tests. - **NULL policies are not generated.** A model with `NullPolicy` or `NullValue` is declined to the runtime map (below). -## Use (in this repository) +## Use + +A project that references Core, directly or through another Open.Database.Extensions package, has it; there is nothing to add. +`false` switches it off for the project it is set in. It needs C# 12 or later and a compiler of Roslyn 4.14 or +later (.NET SDK 9.0.300, Visual Studio 17.14); an older compiler does not load it. + +In this repository, a project uses it as an analyzer: ```xml