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: 30 additions & 5 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ 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'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 runs the source generator's tests and the package consumer tests (see its steps).
# 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 @@ -161,10 +160,36 @@ jobs:
run: |
$suffix = "ci.${{ github.run_id }}.${{ github.run_attempt }}"
$feed = Join-Path $env:RUNNER_TEMP 'feed'
foreach ($project in 'Source/Core', 'Source/MSSqlClient') {
$siblings = 'MSSqlClient', 'Channel', 'Dataflow', 'Extensions'
foreach ($project in @('Core') + $siblings) {
# 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" }
dotnet pack "Source/$project" -c Release -o $feed -p:VersionSuffix=$suffix -p:GeneratePackageOnBuild=false
if ($LASTEXITCODE -ne 0) { throw "dotnet pack Source/$project failed" }
}

# The Core package carries the generator and its build targets, and no sibling package holds them back from its consumers.
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Read-Package($id) {
$path = Join-Path $feed "$id.11.0.0-$suffix.nupkg"
[IO.Compression.ZipFile]::OpenRead($path)
}
$core = Read-Package 'Open.Database.Extensions.Core'
try {
foreach ($entry in 'analyzers/dotnet/roslyn4.14/cs/Open.Database.Extensions.Generator.dll', 'buildTransitive/Open.Database.Extensions.Core.targets') {
if (-not $core.GetEntry($entry)) { throw "The Core package has no $entry" }
}
} finally { $core.Dispose() }
foreach ($project in $siblings) {
$id = if ($project -eq 'Extensions') { 'Open.Database.Extensions' } else { "Open.Database.Extensions.$project" }
$package = Read-Package $id
try {
$reader = [IO.StreamReader]::new($package.GetEntry("$id.nuspec").Open())
[xml]$nuspec = $reader.ReadToEnd()
$reader.Dispose()
$dependencies = @($nuspec.package.metadata.dependencies.group.dependency | Where-Object id -eq 'Open.Database.Extensions.Core')
if ($dependencies.Count -eq 0) { throw "$id has no dependency on Core" }
if ($dependencies | Where-Object { $_.exclude -match 'Analyzers|Build' }) { throw "$id keeps Core's generator or build targets from its consumers" }
} finally { $package.Dispose() }
}
$variants = [ordered]@{ core = @(); mssqlclient = @('-p:OdxVia=MSSqlClient'); off = @('-p:OdxGenerateMaps=false'); csharp12 = @('-p:LangVersion=12') }
$failed = @()
Expand Down
3 changes: 2 additions & 1 deletion Source/Generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ A `dynamic` member is read as an `object` member. A model with a `char` member i
or `NullValue` on a property or on a constructor or positional record parameter.

A partial model (it or a base type declared `partial`) is checked once, when first read, against the built type: if another source generator added
constructors or settable properties that this one could not see, the runtime map reads that model. The check runs in the built program, so it cannot
constructors or settable properties that this one could not see, the runtime map reads that model. The check uses reflection on the built type,
with no trim or native AOT annotations. It runs in the built program, so it cannot
help the build: where another generator gives a constructor to a partial model that declares none, or adds a `required` property, the generated file
does not compile (CS1729, CS7036 or CS9035). Declare the constructor in your part of the model, or switch the generator off. Attributes another
generator puts on a partial member are not seen either.
Expand Down
100 changes: 100 additions & 0 deletions Tests/Open.Database.Extensions.Generator.Tests/GeneratorDriverTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Data;
using System.Reflection;

namespace Open.Database.Extensions.Generator.Tests;

/// <summary>The generator run here over a consumer's source, for what the test project's own build cannot set up.</summary>
public class GeneratorDriverTests
{
static readonly CSharpParseOptions Parse = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp12)
.WithFeatures([new("InterceptorsNamespaces", MapGenerator.GeneratedNamespace)]);

const string PartialConsumer = """
using Open.Database.Extensions;
using Open.Database.Extensions.Synchronous;
public partial class Post { public Post() { } public int Id { get; set; } }
public static class Reads { public static int Read(System.Data.IDataReader reader) => reader.Map<Post>().ToList()[0].Id; }
""";

const string AliasConsumer = """
extern alias Lib;
using Open.Database.Extensions;
public class Post { public int Id { get; set; } public Lib::Kind[]? Kinds { get; set; } }
public static class Reads { public static object Read(System.Data.IDbCommand command) => command.Map<Post>(); }
""";

static CSharpCompilation Compile(string name, string source, params MetadataReference[] more)
=> CSharpCompilation.Create(
name,
[CSharpSyntaxTree.ParseText(source, Parse, name + ".cs", cancellationToken: TestContext.Current.CancellationToken)],
[
.. ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
.Split(Path.PathSeparator)
.Select(static path => MetadataReference.CreateFromFile(path)),
.. more,
],
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

// The generators see the same input: none sees what another adds. What the first (the ODX generator) wrote is returned as text.
static (Compilation Built, string Generated) Generate(Compilation compilation, params ISourceGenerator[] others)
{
GeneratorDriver run = CSharpGeneratorDriver.Create([new MapGenerator().AsSourceGenerator(), .. others], parseOptions: Parse);
run = run.RunGeneratorsAndUpdateCompilation(compilation, out Compilation built, out _, TestContext.Current.CancellationToken);
Assert.Empty(built.GetDiagnostics(TestContext.Current.CancellationToken).Where(static d => d.Severity == DiagnosticSeverity.Error));
return (built, string.Concat(run.GetRunResult().Results[0].GeneratedSources.Select(static s => s.SourceText.ToString())));
}

static byte[] Emit(Compilation compilation)
{
using var image = new MemoryStream();
Assert.True(compilation.Emit(image, cancellationToken: TestContext.Current.CancellationToken).Success);
return image.ToArray();
}

// A long column into an int member tells the two apart: the runtime map converts it, a generated reader refuses it.
static object? ReadLongAsId(byte[] image)
{
var table = new DataTable();
table.Columns.Add("Id", typeof(long));
table.Rows.Add(7L);
using DataTableReader reader = table.CreateDataReader();
return Assembly.Load(image).GetType("Reads")!.GetMethod("Read")!.Invoke(null, [reader]);
}

[Fact]
public void A_constructor_another_generator_added_leaves_the_partial_model_to_the_runtime_map()
{
CSharpCompilation compilation = Compile("partial_consumer", PartialConsumer);

(Compilation alone, _) = Generate(compilation);
var refused = Assert.Throws<TargetInvocationException>(() => ReadLongAsId(Emit(alone)));
Assert.IsType<ValueMappingException>(refused.InnerException);

(Compilation added, string generated) = Generate(compilation, new AddsConstructor().AsSourceGenerator());
Assert.Contains("RowMap<global::Post>", generated, StringComparison.Ordinal);
Assert.Equal(7, ReadLongAsId(Emit(added)));
}

[Fact]
public void A_member_type_behind_an_extern_alias_alone_leaves_the_model_to_the_runtime_map()
{
byte[] library = Emit(Compile("aliased_library", "public enum Kind { None }"));

string With(params string[] aliases)
=> Generate(Compile("aliased_consumer", AliasConsumer, MetadataReference.CreateFromImage(library).WithAliases(aliases))).Generated;

// Under the global alias too, the generated file can name the type.
Assert.Contains("RowMap<global::Post>", With("global", "Lib"), StringComparison.Ordinal);
Assert.DoesNotContain("RowMap<global::Post>", With("Lib"), StringComparison.Ordinal);
}

// A second source generator: it gives the partial model a constructor the ODX generator cannot see.
sealed class AddsConstructor : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
=> context.RegisterSourceOutput(context.CompilationProvider, static (output, _)
=> output.AddSource("Added.g.cs", "public partial class Post { public Post(int id) : this() => Id = id; }"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Data.SqlTypes;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

#pragma warning disable IDE0290 // Explicit constructors are the shapes under test.

Expand Down Expand Up @@ -224,6 +225,19 @@ internal sealed class TuplePost
public (int Left, string Right)? Pair { get; set; }
}

internal class HiddenSetterPost
{
public int Id { get; set; }
public string Internal { get; internal set; } = "kept";
public string Protected { get; protected set; } = "kept";
}

internal sealed class DynamicDefaultPost(int id, [Optional, DefaultParameterValue("none")] dynamic tag)
{
public int Id { get; } = id;
public object Tag { get; } = tag;
}

#pragma warning disable ODXEXP001
[Experimental("ODXEXP001")]
internal enum ExperimentalState
Expand Down Expand Up @@ -364,14 +378,51 @@ public void Shapes_near_the_declined_ones_are_still_served()
var q = new TableQuery([Col.Of<int>("Id")], [1]);

var start = Counts.Now();
Assert.Equal(1, q.Map<SecondConstructorPost>().Single().Id);
Assert.Equal("kept", q.Map<SetsRequiredPost>().Single().Tag);
Assert.Equal(1, q.Map<PublicRequiredPost>().Single().Id);
Assert.Null(q.Map<ParamsPost>().Single().Tags);
Assert.Null(q.Map<TuplePost>().Single().Pair);
Assert.Equal(1, q.Map<ExperimentalTypePost>().Single().Id);

var second = q.Map<SecondConstructorPost>().ToList();
var setsRequired = q.Map<SetsRequiredPost>().ToList();
var publicRequired = q.Map<PublicRequiredPost>().ToList();
var parameters = q.Map<ParamsPost>().ToList();
var tuple = q.Map<TuplePost>().ToList();
var experimental = q.Map<ExperimentalTypePost>().ToList();
Served(Counts.Now().Since(start), sets: 6);

Parity.SameRows(q.Map(RowMap<SecondConstructorPost>.Default).ToList(), second);
Parity.SameRows(q.Map(RowMap<SetsRequiredPost>.Default).ToList(), setsRequired);
Parity.SameRows(q.Map(RowMap<PublicRequiredPost>.Default).ToList(), publicRequired);
Parity.SameRows(q.Map(RowMap<ParamsPost>.Default).ToList(), parameters);
Parity.SameRows(q.Map(RowMap<TuplePost>.Default).ToList(), tuple);
Parity.SameRows(q.Map(RowMap<ExperimentalTypePost>.Default).ToList(), experimental);
// Not public, so not compared above.
Assert.Equal("kept", setsRequired.Single().Tag);
}

[Fact]
public void A_setter_that_is_not_public_is_left_alone_as_the_runtime_leaves_it()
{
var q = new TableQuery([Col.Of<int>("Id"), Col.Of<string>("Internal"), Col.Of<string>("Protected")], [1, "a", "b"]);

var start = Counts.Now();
var generated = q.Map<HiddenSetterPost>().ToList();
Served(Counts.Now().Since(start));

Parity.SameRows(q.Map(RowMap<HiddenSetterPost>.Default).ToList(), generated);
Assert.Equal(("kept", "kept"), (generated.Single().Internal, generated.Single().Protected));
}

[Fact]
public void A_dynamic_constructor_parameter_with_a_default_takes_it_as_in_the_runtime_map()
{
var absent = new TableQuery([Col.Of<int>("Id")], [1]);
var fed = new TableQuery([Col.Of<int>("Id"), Col.Of<string>("Tag")], [1, "fed"]);

var start = Counts.Now();
var defaulted = absent.Map<DynamicDefaultPost>().ToList();
var read = fed.Map<DynamicDefaultPost>().ToList();
Served(Counts.Now().Since(start), sets: 2);

Parity.SameRows(absent.Map(RowMap<DynamicDefaultPost>.Default).ToList(), defaulted);
Parity.SameRows(fed.Map(RowMap<DynamicDefaultPost>.Default).ToList(), read);
Assert.Equal(("none", "fed"), (defaulted.Single().Tag, read.Single().Tag));
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,42 @@ public void A_trusted_member_over_a_column_its_getter_refuses_fails_as_a_mapping
RowError<InvalidCastException>(Catch(() => wider.Map<OrderedStruct>().ToList()), typeof(OrderedStruct), 0);
RowError<InvalidCastException>(Catch(() => date.Map<OrderedDatePost>().ToList()), typeof(OrderedDatePost), 0);
RowError<InvalidCastException>(Catch(() => narrower.Map<OrderedGapPost>().ToList()), typeof(OrderedGapPost), 0);

// The runtime map converts these too (under column names it can match).
var named = new TableQuery([Col.Of<int>("Id"), Col.Of<Guid>("unused"), Col.Of<byte>("State"), Col.Of<double>("Extra")], [7, Guid.NewGuid(), (byte)2, 1.5]);
Assert.Equal(new DateOnly(2026, 11, 30), Assert.Single(date.Map(RowMap<OrderedDatePost>.Default).ToList()).Day);
Assert.Equal(PostState.Archived, Assert.Single(named.Map(RowMap<OrderedGapPost>.Default).ToList()).State);
}

[Fact]
public void A_NULL_in_a_trusted_non_nullable_member_with_no_getter_fails_as_a_mapping_failure()
{
var q = new TableQuery([Col.Of<int>("Id"), Col.Of<DateOnly>("Day")], [1, null]);

// The documented difference: the exception of the read, where the runtime map reports the NULL.
RowError<InvalidCastException>(Catch(() => q.Map<OrderedDatePost>().ToList()), typeof(OrderedDatePost), 0);
RowError<SqlNullValueException>(Catch(() => q.Map(RowMap<OrderedDatePost>.Default).ToList()), typeof(OrderedDatePost), 0);
}

[Fact]
public void A_NULL_in_a_trusted_records_non_nullable_member_fails_as_a_mapping_failure()
{
Col[] columns = [Col.Of<int>("post_id"), Col.Of<string>("title"), Col.Of<int>("qty"), Col.Of<int>("state")];

var start = Counts.Now();
// Id, Title and the enum State.
foreach (int column in new[] { 0, 1, 3 })
{
object?[] row = [2, "two", 3, (int)PostState.Active];
row[column] = null;
var q = new TableQuery(columns, [1, "one", null, (int)PostState.Draft], row);
SameRowError<InvalidCastException>(
() => q.Map(RowMap<DecoratedRecord>.Default).ToList(),
() => q.Map<DecoratedRecord>().ToList(),
typeof(DecoratedRecord), 1);
}

Assert.Equal(3, Counts.Now().Since(start).Literal);
}

[Fact]
Expand All @@ -121,7 +149,10 @@ public void A_NULL_in_a_trusted_non_nullable_member_fails_as_a_mapping_failure()
{
var q = new TableQuery([Col.Of<int>("Id"), Col.Of<string>("Title")], [null, "one"]);

RowError<InvalidCastException>(Catch(() => q.Map<OrderedStruct>().ToList()), typeof(OrderedStruct), 0);
SameRowError<InvalidCastException>(
() => q.Map(RowMap<OrderedStruct>.Default).ToList(),
() => q.Map<OrderedStruct>().ToList(),
typeof(OrderedStruct), 0);
}

[Fact]
Expand Down Expand Up @@ -205,6 +236,7 @@ public void A_NULL_in_a_trusted_non_nullable_byte_array_or_object_fails_as_a_map

// A NULL byte[] is the documented difference: the generated read is a plain cast.
RowError<InvalidCastException>(Catch(() => blob.Map<TrustedReferences>().ToList()), typeof(TrustedReferences), 1);
RowError<SqlNullValueException>(Catch(() => blob.Map(RowMap<TrustedReferences>.Default).ToList()), typeof(TrustedReferences), 1);
SameRowError<SqlNullValueException>(
() => any.Map(RowMap<TrustedReferences>.Default).ToList(),
() => any.Map<TrustedReferences>().ToList(),
Expand Down
2 changes: 1 addition & 1 deletion docsite/articles/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Version 11 is `11.0.0-rc.15`. For moving a 10.x codebase, read [Coming from earl

- **Changed: sequential access is opt-in.** The library reads with the default access mode on every path; it no longer asks for `CommandBehavior.SequentialAccess` itself, as `Map<T>()`, `AsObjectArrays()`, `AsDictionaryRows()`, `AnyAsync`, `CountAsync` and `LoadTable`/`LoadTables` did, and the default `behavior` of `ToDataTable` and `ToDataTables` on an `IDbCommand` is now `CommandBehavior.Default`. SqlClient's default mode reads each row whole before your code reads it. Call `SequentialAccess()` on a command, a mapped view or a definition to opt in, above all for very large values; with `AsyncReads()` on such a value, opt in. See [Sequential access](expressive-commands.md#sequential-access-for-very-large-values).
- **New: generated row readers, on by default.** The Core 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. A generated reader reads each member with the provider's getter for the member's type, as a hand-written reader does, and does not make the runtime map's conversions; a model that declares every column's ordinal is read by position, unchecked. `<OdxGenerateMaps>false</OdxGenerateMaps>` switches it off. See [Generated readers](mapping.md#generated-readers).
- **Stored-procedure parameter names are read once and kept, an answer of no names included.** A call that cannot be built, or that the database rejects, forgets them and the next call reads them again. The five-minute expiry is gone, and an argument the kept names lack no longer reads them again before the call. See [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once).
- **Stored-procedure parameter names are read once and kept, an answer of no names included.** A call that cannot be built, or that the database rejects, forgets them and the next call reads them again. The kept names do not expire, and an argument they lack does not read them again before the call. See [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once).
- **Loop over a pooled buffer while it reads.** `AsAsyncEnumerable()` on what `ToPooledBuffer` returns gives its rows as a stream while the query is still running; each loop starts at the first row, and the rows can be looped over again until the buffer is disposed. Rows arrive an array at a time (16 rows, then 32, and so on). `Items` is unchanged. See [looping over the buffer](async-buffers.md#looping-over-the-buffer).

### Changes since rc.14
Expand Down