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
49 changes: 46 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>() against the runtime map on the same data.
# Another runs the source generator's tests: each intercepted Map<T>() 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.
Expand Down Expand Up @@ -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:
Expand All @@ -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<T>() 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
Expand Down
3 changes: 2 additions & 1 deletion Source/Channel/Open.Database.Extensions.Channel.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" />
<!-- PrivateAssets: Core's source generator and build targets reach this package's consumers too (NuGet keeps them back by default). -->
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" PrivateAssets="contentfiles" />
</ItemGroup>

</Project>
8 changes: 8 additions & 0 deletions Source/Core/Open.Database.Extensions.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
</PackageReference>
</ItemGroup>

<!-- The Map<T>() source generator ships inside this package, with the build targets that allow its interceptors. Its folder names the compiler it
is built against, so an older one never loads it. A consumer sets OdxGenerateMaps=false to switch it off. -->
<ItemGroup>
<ProjectReference Include="..\Generator\Open.Database.Extensions.Generator.csproj" ReferenceOutputAssembly="false" PrivateAssets="all" />
<None Include="..\Generator\bin\$(Configuration)\netstandard2.0\Open.Database.Extensions.Generator.dll" Pack="true" PackagePath="analyzers\dotnet\roslyn4.14\cs" Visible="false" />
<None Include="..\Generator\build\Open.Database.Extensions.Generator.targets" Pack="true" PackagePath="buildTransitive\Open.Database.Extensions.Core.targets" Visible="false" />
</ItemGroup>

<!-- The sibling assemblies use Core's internals: the internal OverloadResolutionPriorityAttribute polyfill on the netstandard shims, and on every
target the conversion of the tuple convenience overloads into a RowMap<T>. -->
<ItemGroup>
Expand Down
4 changes: 4 additions & 0 deletions Source/Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()` 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 `<OdxGenerateMaps>false</OdxGenerateMaps>` 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)
Expand Down
3 changes: 2 additions & 1 deletion Source/Dataflow/Open.Database.Extensions.Dataflow.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" />
<!-- PrivateAssets: Core's source generator and build targets reach this package's consumers too (NuGet keeps them back by default). -->
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" PrivateAssets="contentfiles" />
</ItemGroup>

<ItemGroup>
Expand Down
3 changes: 2 additions & 1 deletion Source/Extensions/Open.Database.Extensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" />
<!-- PrivateAssets: Core's source generator and build targets reach this package's consumers too (NuGet keeps them back by default). -->
<ProjectReference Include="..\Core\Open.Database.Extensions.Core.csproj" PrivateAssets="contentfiles" />
</ItemGroup>

</Project>
48 changes: 44 additions & 4 deletions Source/Generator/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static string Emit(IReadOnlyList<Site> sites, Options options)
{
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("// Open.Database.Extensions source generator (prototype): Map<T>() served by generated row readers.");
sb.AppendLine("// Open.Database.Extensions source generator: Map<T>() served by generated row readers.");
sb.AppendLine("#nullable disable");
sb.AppendLine("#pragma warning disable");
sb.AppendLine();
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand All @@ -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();

Expand Down Expand Up @@ -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{");
Expand All @@ -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();
Expand Down Expand Up @@ -529,20 +562,27 @@ 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;");
sb.AppendLine("\t\t}");
}
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
Expand Down
2 changes: 1 addition & 1 deletion Source/Generator/MapGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace Open.Database.Extensions.Generator;

/// <summary>
/// PROTOTYPE (SG phase A). Intercepts each plain <c>x.Map&lt;T&gt;()</c> call bound to <c>Open.Database.Extensions.CoreExtensions</c>
/// Intercepts each plain <c>x.Map&lt;T&gt;()</c> call bound to <c>Open.Database.Extensions.CoreExtensions</c>
/// (receivers <c>IExecuteReader</c>, <c>IDbCommand</c>, <c>IDataReader</c>) and serves it with generated row readers through the
/// existing <c>Map(RowMap&lt;T&gt;?)</c> overload, the map made by Core's hidden <c>GeneratedRowMap.Create</c>. Emits nothing (the call keeps running today's code) when:
/// C# is below 12, the interceptors feature is not enabled for <c>Open.Database.Extensions.Generated</c>, <c>OdxGenerateMaps</c> is false,
Expand Down
19 changes: 18 additions & 1 deletion Source/Generator/ModelReader.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Immutable;
using System.Globalization;

Expand Down Expand Up @@ -163,7 +164,23 @@ static class ModelReader
constructor?.Parameters.Length ?? 0,
decorated,
allOrdered,
new EquatableArray<SlotSpec>([.. slots]));
new EquatableArray<SlotSpec>([.. slots]),
IsPartial(t)
? new PartialShape(constructors.Count, new EquatableArray<string>(
[.. 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.
Expand Down
7 changes: 3 additions & 4 deletions Source/Generator/Open.Database.Extensions.Generator.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<!--
PROTOTYPE (SG phase A). The source generator that serves a plain Map<T>() through C# interceptors.
Isolated on purpose: Core never references this project, builds, tests and ships without it.
Consumers in this repository reference it as an analyzer and import build/Open.Database.Extensions.Generator.targets,
which stands in for the buildTransitive targets the Core package would carry.
The source generator that serves a plain Map<T>() through C# interceptors. It ships inside the Core package (see the Core
project file), which does not reference its assembly. Projects in this repository reference it as an analyzer and import
build/Open.Database.Extensions.Generator.targets, the file the Core package carries as its buildTransitive targets.
-->
<PropertyGroup>
<!-- Source/Directory.Build.props targets the library frameworks and packs every project: an analyzer is netstandard2.0 only and is not a package (yet). -->
Expand Down
Loading