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
2 changes: 1 addition & 1 deletion Source/Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Post[] posts = await connectionFactory

## 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. A generated reader reads each member with the provider's getter for its type, without the runtime map's conversions, and 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).
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, a reader or a `DbQuery` gets its row reader written at build time, with nothing to add. A generated reader reads each member with the provider's getter for its type, without the runtime map's conversions, and 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

Expand Down
36 changes: 31 additions & 5 deletions Source/Generator/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
namespace Open.Database.Extensions.Generator;

// Writes the one generated file. Shape (SG.md section 2), through Core's one hidden entry, GeneratedRowMap.Create:
// - per call site, an interceptor: Map_n(this <receiver> x) => CoreExtensions.Map<T>(x, M_T.Map), the existing Map(RowMap<T>?) overload;
// - per call site, an interceptor that passes M_T.Map to the receiver's existing Map(RowMap<T>?) overload: CoreExtensions.Map<T>(x, M_T.Map)
// for a reader or command, x.Map<T>(M_T.Map) for a query type (see Interceptor);
// - every member is read by its own type, as a hand-written reader reads it (ModelReader.MemberReadOf): the column's type is not looked at, and the
// provider converts or throws.
// - a model that declares every column's ordinal ([Column(Order = n)] on every mapped member) is trusted: Bind returns the literal reader and
Expand Down Expand Up @@ -104,18 +105,19 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList<Site> sites, Dictio
{
Site s = sites[i];
sb.AppendLine($"\t\t[global::System.Runtime.CompilerServices.InterceptsLocation({s.Version}, \"{s.Data}\")]");
(string signature, string? constraint, string call) = Interceptor(s, i, ids[s.Model]);
sb.AppendLine("\t\t" + signature);
if (constraint is not null) sb.AppendLine("\t\t\t" + constraint);
if (options.Counters)
{
sb.AppendLine($"\t\tpublic static {s.ReturnType} Map_{i}(this {s.ReceiverType} source)");
sb.AppendLine("\t\t{");
sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted);");
sb.AppendLine($"\t\t\treturn {Ns}.CoreExtensions.Map<{s.Model.Type}>(source, {ids[s.Model]}.Map);");
sb.AppendLine($"\t\t\treturn {call};");
sb.AppendLine("\t\t}");
}
else
{
sb.AppendLine($"\t\tpublic static {s.ReturnType} Map_{i}(this {s.ReceiverType} source)");
sb.AppendLine($"\t\t\t=> {Ns}.CoreExtensions.Map<{s.Model.Type}>(source, {ids[s.Model]}.Map);");
sb.AppendLine($"\t\t\t=> {call};");
}

sb.AppendLine();
Expand All @@ -125,6 +127,30 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList<Site> sites, Dictio
sb.AppendLine();
}

// An interceptor takes the receiver as the method it replaces does: by value for a class or an extension's parameter, by `in` for the
// instance method of a readonly struct. It passes the model's map to that receiver's Map(RowMap<T>?).
static (string Signature, string? Constraint, string Call) Interceptor(Site s, int i, string id)
{
string model = s.Model.Type;
string map = id + ".Map";
if (s.Receiver == Receiver.TypedQuery)
{
// As generic as the method and its containing type together, so TParams is never named. T is the model at every call this
// replaces, which the cast restates.
string mapped = $"{Ns}.MappedDbQuery<TParams, T>";
return ($"public static {mapped} Map_{i}<TParams, T>(this {Ns}.DbQuery<TParams> source)",
"where TParams : struct, global::System.IEquatable<TParams>",
$"({mapped})(object)source.Map<{model}>({map})");
}

string self = s.Receiver is Receiver.QueryCall or Receiver.QueryUsing ? "this in" : "this";
string body = s.Receiver is Receiver.Query or Receiver.QueryCall or Receiver.QueryUsing
? $"source.Map<{model}>({map})"
: $"{Ns}.CoreExtensions.Map<{model}>(source, {map})";

return ($"public static {s.ReturnType} Map_{i}({self} {s.ReceiverType} source)", null, body);
}

// What every model shares: the slot table entry, the layout base, and RowMap.Match for a map with no pairs.
static void EmitShared(StringBuilder sb) => sb.AppendLine(
"""
Expand Down
53 changes: 40 additions & 13 deletions Source/Generator/MapGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ namespace Open.Database.Extensions.Generator;

/// <summary>
/// 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:
/// (receivers <c>IExecuteReader</c>, <c>IDbCommand</c>, <c>IDataReader</c>) or to the method of <c>DbQuery</c>, <c>DbQuery&lt;TParams&gt;</c>,
/// <c>DbQueryCall</c> or <c>DbQueryUsing</c>, and serves it with generated row readers through the same type's 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,
/// or T is a shape the generated code does not describe exactly.
/// </summary>
Expand Down Expand Up @@ -76,18 +77,10 @@ static bool IsCandidate(SyntaxNode node)

// An extension call binds to the REDUCED symbol (no receiver parameter): the definition is what it was reduced from (SG.probe A3).
IMethodSymbol definition = method.ReducedFrom ?? method;
if (definition.Name != "Map" || !definition.IsExtensionMethod || definition.Parameters.Length != 1) return null;
if (ModelReader.FullName(definition.ContainingType) != "Open.Database.Extensions.CoreExtensions") return null;
if (definition.Name != "Map") return null;
if (method.TypeArguments.Length != 1 || method.TypeArguments[0] is not INamedTypeSymbol model) return null; // A type parameter: not interceptable.

ITypeSymbol receiver = definition.Parameters[0].Type;
Receiver? kind = ModelReader.FullName(receiver) switch
{
"Open.Database.Extensions.IExecuteReader" => Receiver.ExecuteReader,
"System.Data.IDbCommand" => Receiver.Command,
"System.Data.IDataReader" => Receiver.DataReader,
_ => null, // DataTable: its rows are not a DbDataReader; the runtime serves them.
};
Receiver? kind = definition.IsExtensionMethod ? ExtensionReceiver(definition) : OwnReceiver(definition);
if (kind is null) return null;

ModelSpec? spec = ModelReader.Read(model, ctx.SemanticModel.Compilation);
Expand All @@ -96,6 +89,40 @@ static bool IsCandidate(SyntaxNode node)
ct.ThrowIfCancellationRequested();
if (ctx.SemanticModel.GetInterceptableLocation(invocation, ct) is not { } location) return null;

return new Site(location.Version, location.Data, kind.Value, receiver.ToDisplayString(Fq), method.ReturnType.ToDisplayString(Fq), spec);
// The typed query's interceptor is generic and names neither type, so TParams may be a private or open type.
(string receiverType, string returnType) = kind.Value == Receiver.TypedQuery
? ("", "")
: ((definition.IsExtensionMethod ? definition.Parameters[0].Type : definition.ContainingType).ToDisplayString(Fq), method.ReturnType.ToDisplayString(Fq));

return new Site(location.Version, location.Data, kind.Value, receiverType, returnType, spec);
}

// CoreExtensions.Map<T>(this source), over a reader or a command.
static Receiver? ExtensionReceiver(IMethodSymbol definition)
{
if (definition.Parameters.Length != 1 || ModelReader.FullName(definition.ContainingType) != "Open.Database.Extensions.CoreExtensions") return null;

return ModelReader.FullName(definition.Parameters[0].Type) switch
{
"Open.Database.Extensions.IExecuteReader" => Receiver.ExecuteReader,
"System.Data.IDbCommand" => Receiver.Command,
"System.Data.IDataReader" => Receiver.DataReader,
_ => null, // DataTable: its rows are not a DbDataReader; the runtime serves them.
};
}

// The Map<T>() a query type declares itself: it wins over the extensions, so the call never binds to one of those.
static Receiver? OwnReceiver(IMethodSymbol definition)
{
if (definition.IsStatic || definition.Parameters.Length != 0) return null;

return ModelReader.FullName(definition.ContainingType.OriginalDefinition) switch
{
"Open.Database.Extensions.DbQuery" => Receiver.Query,
"Open.Database.Extensions.DbQuery`1" => Receiver.TypedQuery,
"Open.Database.Extensions.DbQueryCall" => Receiver.QueryCall,
"Open.Database.Extensions.DbQueryUsing" => Receiver.QueryUsing,
_ => null,
};
}
}
9 changes: 5 additions & 4 deletions Source/Generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ It ships inside the `Open.Database.Extensions.Core` package, on by default; it i

## What it does

For each call `x.Map<T>()` with a closed model type `T`, where `x` is an `IExecuteReader`, an `IDbCommand` or an `IDataReader`,
it emits an interceptor `CoreExtensions.Map<T>(x, M_T.Map)`: the existing public overload `Map(RowMap<T>?)`, with one map per model type made by
Core's hidden entry `GeneratedRowMap.Create<T>(Bind)` (for this generator only; not for direct use).
For each call `x.Map<T>()` with a closed model type `T`, where `x` is an `IExecuteReader`, an `IDbCommand`, an `IDataReader`,
a `DbQuery`, a `DbQuery<TParams>`, a `DbQueryCall` or a `DbQueryUsing`, it emits an interceptor that calls the receiver's existing public
overload `Map(RowMap<T>?)`, with one map per model type made by Core's hidden entry `GeneratedRowMap.Create<T>(Bind)` (for this generator
only; not for direct use). `TParams` may be a private type or a type parameter of the caller; `T` may not be.

- **Binding.** Core's read loop calls `Bind` once per result set, after the first row is read and before it is mapped (not for a result set with no row to map). Except for a trusted model (below), `Bind` matches the reader's column count and names against a small
cache of layouts (or resolves a new one) and returns that layout's row reader, or `null` for a layout it does not serve: the runtime map then serves
Expand Down Expand Up @@ -71,7 +72,7 @@ In this repository, a project uses it as an analyzer:
Not intercepted (the call runs the runtime map): scalars, tuples, anonymous, abstract, open generic or inaccessible types, a model with more than one public constructor
and no parameterless one, overridden or hidden properties, a required member fed by a constructor parameter, a required field or a required property without a public setter (unless the constructor sets the required members),
a `ref struct` property that can be set or a `ref struct` constructor parameter, a constructor, setter, property or type marked `[Obsolete(…, true)]`,
a file-local or extern-alias type, a constructor with an `OverloadResolutionPriority`, a `DataTable` receiver, and a call inside a generic method (`Map<T>()` with an open `T`).
a file-local or extern-alias type, a constructor with an `OverloadResolutionPriority`, a `DataTable` receiver, a call written `x?.Map<T>()`, and a call inside a generic method (`Map<T>()` with an open `T`).
A `dynamic` member is read as an `object` member. A model with a `char` member is not intercepted. A model that declares a NULL policy is not intercepted either, so the policy is never silently ignored: `NullPolicy` on the type or a base type, `NullPolicy`
or `NullValue` on a property or on a constructor or positional record parameter.

Expand Down
6 changes: 5 additions & 1 deletion Source/Generator/Specs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,16 @@ sealed record ModelSpec(

sealed record PartialShape(int Constructors, EquatableArray<string> Settable);

/// <summary>Which overload of <c>Map&lt;T&gt;()</c> the call binds to.</summary>
/// <summary>Which <c>Map&lt;T&gt;()</c> the call binds to: an extension over a reader or command, or a query type's own method.</summary>
enum Receiver
{
ExecuteReader,
Command,
DataReader,
Query,
TypedQuery,
QueryCall,
QueryUsing,
}

/// <summary>One intercepted call: where it is, what it binds to, and the model it maps.</summary>
Expand Down
160 changes: 160 additions & 0 deletions Tests/Open.Database.Extensions.Generator.Tests/ParityTests.DbQuery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using Microsoft.Data.Sqlite;
using System.ComponentModel.DataAnnotations.Schema;

namespace Open.Database.Extensions.Generator.Tests;

// The Map<T>() the query types declare themselves (DbQuery, DbQuery<TParams>, DbQueryUsing, DbQueryCall): intercepted as the extensions are,
// and equal to the same type's Map(RowMap<T>.Default).

/// <summary>No annotations: matched by name.</summary>
public sealed class QueryRow
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int? Rank { get; set; }
}

/// <summary>Every column's ordinal declared: read by position.</summary>
public sealed class OrderedQueryRow
{
[Column(Order = 0)]
public int Id { get; set; }

[Column(Order = 1)]
public string Name { get; set; } = "";

[Column(Order = 2)]
public int? Rank { get; set; }
}

public partial class ParityTests
{
const string QueryRows = "select 1 as Id, 'a' as Name, 7 as Rank union all select 2, 'b', null order by Id";
const string OneQueryRow = "select @id as Id, 'a' as Name, null as Rank";

// A parameter type only this class can name, as a repository declares one.
readonly record struct ById(int Id);

static SqliteConnection Memory()
{
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
return connection;
}

/// <summary>One intercepted call, one result set served by generated code, the rows of the runtime map.</summary>
static void QueryParity<T>(Func<List<T>> runtime, Func<List<T>> generated, int rows)
{
List<T> expected = runtime();
var start = Counts.Now();
List<T> actual = generated();
Served(Counts.Now().Since(start));
Parity.SameRows(expected, actual);
Assert.Equal(rows, actual.Count);
}

[Fact]
public void DbQuery_definition_is_served()
{
using SqliteConnection connection = Memory();
DbQuery query = DbQuery.Text(QueryRows);

QueryParity(
() => query.Map(RowMap<QueryRow>.Default).Using(connection).ToList(),
() => query.Map<QueryRow>().Using(connection).ToList(),
2);

// On the value a factory returns, with no variable, and a model read by position.
QueryParity(
() => query.Map(RowMap<OrderedQueryRow>.Default).Using(connection).ToList(),
() => DbQuery.Text(QueryRows).Map<OrderedQueryRow>().Using(connection).ToList(),
2);
}

[Fact]
public void A_definition_mapped_once_serves_every_call()
{
using SqliteConnection connection = Memory();
var start = Counts.Now();
MappedDbQuery<QueryRow> mapped = DbQuery.Text(QueryRows).Map<QueryRow>();
Assert.Equal(2, mapped.Using(connection).ToList().Count);
Assert.Equal(2, mapped.Using(connection).ToList().Count);
Counts c = Counts.Now().Since(start);
Assert.True(c.Intercepted == 1 && c.Served == 2 && c.Declined == 0, c.ToString());
}

[Fact]
public void Typed_definition_with_a_private_parameter_type_is_served()
{
using SqliteConnection connection = Memory();
DbQuery<ById> query = DbQuery.Text(OneQueryRow).Params<ById>();

QueryParity(
() => query.Map(RowMap<QueryRow>.Default).Using(connection).AddParams(new(3)).ToList(),
() => query.Map<QueryRow>().Using(connection).AddParams(new(3)).ToList(),
1);
}

[Fact]
public void Typed_definition_inside_a_generic_method_is_served()
{
using SqliteConnection connection = Memory();

QueryParity(
() => DbQuery.Text(OneQueryRow).Params<ById>().Map(RowMap<QueryRow>.Default).Using(connection).AddParams(new(4)).ToList(),
() => MapTyped(DbQuery.Text(OneQueryRow).Params<ById>()).Using(connection).AddParams(new(4)).ToList(),
1);

static MappedDbQuery<TValues, QueryRow> MapTyped<TValues>(DbQuery<TValues> query)
where TValues : struct, IEquatable<TValues>
=> query.Map<QueryRow>();
}

[Fact]
public void DbQueryUsing_is_served_from_a_value_a_variable_and_an_in_parameter()
{
using SqliteConnection connection = Memory();
DbQuery query = DbQuery.Text(QueryRows);
DbQueryUsing bound = query.Using(connection);
List<QueryRow> Runtime() => query.Using(connection).Map(RowMap<QueryRow>.Default).ToList();

QueryParity(Runtime, () => query.Using(connection).Map<QueryRow>().ToList(), 2);
QueryParity(Runtime, () => bound.Map<QueryRow>().ToList(), 2);
QueryParity(Runtime, () => FromIn(bound), 2);

static List<QueryRow> FromIn(in DbQueryUsing source) => source.Map<QueryRow>().ToList();
}

[Fact]
public void DbQueryCall_is_served_from_a_value_and_a_variable()
{
using SqliteConnection connection = Memory();
DbQuery query = DbQuery.Text(OneQueryRow);
DbQueryCall call = query.Using(connection).AddParam("id", 5);
List<QueryRow> Runtime() => query.Using(connection).AddParam("id", 5).Map(RowMap<QueryRow>.Default).ToList();

QueryParity(Runtime, () => query.Using(connection).AddParam("id", 5).Map<QueryRow>().ToList(), 1);
QueryParity(Runtime, () => call.Map<QueryRow>().ToList(), 1);
}

[Fact]
public void A_default_bound_query_throws_as_the_runtime_map_does()
{
Parity.SameError(
Catch(() => default(DbQueryUsing).Map(RowMap<QueryRow>.Default)),
Catch(() => default(DbQueryUsing).Map<QueryRow>()));
Parity.SameError(
Catch(() => default(DbQueryCall).Map(RowMap<QueryRow>.Default)),
Catch(() => default(DbQueryCall).Map<QueryRow>()));
}

[Fact]
public void A_single_value_on_a_query_is_not_intercepted()
{
using SqliteConnection connection = Memory();
var start = Counts.Now();
Assert.Equal([1, 2], DbQuery.Text(QueryRows).Map<int>().Using(connection).ToList());
Assert.Equal([1, 2], DbQuery.Text(QueryRows).Using(connection).Map<int>().ToList());
Assert.Equal(0, Counts.Now().Since(start).Intercepted);
}
}
Loading