Skip to content

Commit 3fefe0a

Browse files
Generator: serve Map<T>() on the DbQuery types too (#280)
A plain `Map<T>()` on a `DbQuery`, a `DbQuery<TParams>`, a `DbQueryUsing` or a `DbQueryCall` now reads rows with a generated row reader, as it does on a command or a reader. These types declare `Map<T>()` themselves, and the generator only looked at the extension methods, so every query defined this way used the runtime map. No Core code changes. - Each interceptor calls the same type's existing `Map(RowMap<T>?)` with the model's generated map. The readonly structs are taken by `in`; the typed definition gets a generic interceptor that never names `TParams`, so a private parameter type or a type parameter of the caller works. - **Behavior change:** these calls no longer get the runtime map's conversions (see the generator's "Known differences"). `<OdxGenerateMaps>false</OdxGenerateMaps>` switches generation off, as before. - Generated output for a project with no such call is unchanged: the generator tests' output is byte-identical before and after on the unchanged test sources. - Tests compare each new receiver with its own runtime map and check that generated code served it, including from values, variables and an `in` parameter, with a private parameter type, inside a generic method, a default struct, and a single value (not intercepted). The package consumer tests use all four with the generator on, off and with C# 12. - Docs: the statements that a `DbQuery` is not generated are updated, `x?.Map<T>()` is listed as not intercepted, and the release notes record the change. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent a7946de commit 3fefe0a

9 files changed

Lines changed: 268 additions & 25 deletions

File tree

‎Source/Core/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Post[] posts = await connectionFactory
3232

3333
## Generated row readers
3434

35-
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).
35+
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).
3636

3737
## Where to go next
3838

‎Source/Generator/Emitter.cs‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
namespace Open.Database.Extensions.Generator;
44

55
// Writes the one generated file. Shape (SG.md section 2), through Core's one hidden entry, GeneratedRowMap.Create:
6-
// - per call site, an interceptor: Map_n(this <receiver> x) => CoreExtensions.Map<T>(x, M_T.Map), the existing Map(RowMap<T>?) overload;
6+
// - 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)
7+
// for a reader or command, x.Map<T>(M_T.Map) for a query type (see Interceptor);
78
// - 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
89
// provider converts or throws.
910
// - a model that declares every column's ordinal ([Column(Order = n)] on every mapped member) is trusted: Bind returns the literal reader and
@@ -104,18 +105,19 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList<Site> sites, Dictio
104105
{
105106
Site s = sites[i];
106107
sb.AppendLine($"\t\t[global::System.Runtime.CompilerServices.InterceptsLocation({s.Version}, \"{s.Data}\")]");
108+
(string signature, string? constraint, string call) = Interceptor(s, i, ids[s.Model]);
109+
sb.AppendLine("\t\t" + signature);
110+
if (constraint is not null) sb.AppendLine("\t\t\t" + constraint);
107111
if (options.Counters)
108112
{
109-
sb.AppendLine($"\t\tpublic static {s.ReturnType} Map_{i}(this {s.ReceiverType} source)");
110113
sb.AppendLine("\t\t{");
111114
sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted);");
112-
sb.AppendLine($"\t\t\treturn {Ns}.CoreExtensions.Map<{s.Model.Type}>(source, {ids[s.Model]}.Map);");
115+
sb.AppendLine($"\t\t\treturn {call};");
113116
sb.AppendLine("\t\t}");
114117
}
115118
else
116119
{
117-
sb.AppendLine($"\t\tpublic static {s.ReturnType} Map_{i}(this {s.ReceiverType} source)");
118-
sb.AppendLine($"\t\t\t=> {Ns}.CoreExtensions.Map<{s.Model.Type}>(source, {ids[s.Model]}.Map);");
120+
sb.AppendLine($"\t\t\t=> {call};");
119121
}
120122

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

130+
// 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
131+
// instance method of a readonly struct. It passes the model's map to that receiver's Map(RowMap<T>?).
132+
static (string Signature, string? Constraint, string Call) Interceptor(Site s, int i, string id)
133+
{
134+
string model = s.Model.Type;
135+
string map = id + ".Map";
136+
if (s.Receiver == Receiver.TypedQuery)
137+
{
138+
// As generic as the method and its containing type together, so TParams is never named. T is the model at every call this
139+
// replaces, which the cast restates.
140+
string mapped = $"{Ns}.MappedDbQuery<TParams, T>";
141+
return ($"public static {mapped} Map_{i}<TParams, T>(this {Ns}.DbQuery<TParams> source)",
142+
"where TParams : struct, global::System.IEquatable<TParams>",
143+
$"({mapped})(object)source.Map<{model}>({map})");
144+
}
145+
146+
string self = s.Receiver is Receiver.QueryCall or Receiver.QueryUsing ? "this in" : "this";
147+
string body = s.Receiver is Receiver.Query or Receiver.QueryCall or Receiver.QueryUsing
148+
? $"source.Map<{model}>({map})"
149+
: $"{Ns}.CoreExtensions.Map<{model}>(source, {map})";
150+
151+
return ($"public static {s.ReturnType} Map_{i}({self} {s.ReceiverType} source)", null, body);
152+
}
153+
128154
// What every model shares: the slot table entry, the layout base, and RowMap.Match for a map with no pairs.
129155
static void EmitShared(StringBuilder sb) => sb.AppendLine(
130156
"""

‎Source/Generator/MapGenerator.cs‎

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ namespace Open.Database.Extensions.Generator;
99

1010
/// <summary>
1111
/// Intercepts each plain <c>x.Map&lt;T&gt;()</c> call bound to <c>Open.Database.Extensions.CoreExtensions</c>
12-
/// (receivers <c>IExecuteReader</c>, <c>IDbCommand</c>, <c>IDataReader</c>) and serves it with generated row readers through the
13-
/// 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:
12+
/// (receivers <c>IExecuteReader</c>, <c>IDbCommand</c>, <c>IDataReader</c>) or to the method of <c>DbQuery</c>, <c>DbQuery&lt;TParams&gt;</c>,
13+
/// <c>DbQueryCall</c> or <c>DbQueryUsing</c>, and serves it with generated row readers through the same type's existing
14+
/// <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:
1415
/// C# is below 12, the interceptors feature is not enabled for <c>Open.Database.Extensions.Generated</c>, <c>OdxGenerateMaps</c> is false,
1516
/// or T is a shape the generated code does not describe exactly.
1617
/// </summary>
@@ -76,18 +77,10 @@ static bool IsCandidate(SyntaxNode node)
7677

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

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

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

99-
return new Site(location.Version, location.Data, kind.Value, receiver.ToDisplayString(Fq), method.ReturnType.ToDisplayString(Fq), spec);
92+
// The typed query's interceptor is generic and names neither type, so TParams may be a private or open type.
93+
(string receiverType, string returnType) = kind.Value == Receiver.TypedQuery
94+
? ("", "")
95+
: ((definition.IsExtensionMethod ? definition.Parameters[0].Type : definition.ContainingType).ToDisplayString(Fq), method.ReturnType.ToDisplayString(Fq));
96+
97+
return new Site(location.Version, location.Data, kind.Value, receiverType, returnType, spec);
98+
}
99+
100+
// CoreExtensions.Map<T>(this source), over a reader or a command.
101+
static Receiver? ExtensionReceiver(IMethodSymbol definition)
102+
{
103+
if (definition.Parameters.Length != 1 || ModelReader.FullName(definition.ContainingType) != "Open.Database.Extensions.CoreExtensions") return null;
104+
105+
return ModelReader.FullName(definition.Parameters[0].Type) switch
106+
{
107+
"Open.Database.Extensions.IExecuteReader" => Receiver.ExecuteReader,
108+
"System.Data.IDbCommand" => Receiver.Command,
109+
"System.Data.IDataReader" => Receiver.DataReader,
110+
_ => null, // DataTable: its rows are not a DbDataReader; the runtime serves them.
111+
};
112+
}
113+
114+
// The Map<T>() a query type declares itself: it wins over the extensions, so the call never binds to one of those.
115+
static Receiver? OwnReceiver(IMethodSymbol definition)
116+
{
117+
if (definition.IsStatic || definition.Parameters.Length != 0) return null;
118+
119+
return ModelReader.FullName(definition.ContainingType.OriginalDefinition) switch
120+
{
121+
"Open.Database.Extensions.DbQuery" => Receiver.Query,
122+
"Open.Database.Extensions.DbQuery`1" => Receiver.TypedQuery,
123+
"Open.Database.Extensions.DbQueryCall" => Receiver.QueryCall,
124+
"Open.Database.Extensions.DbQueryUsing" => Receiver.QueryUsing,
125+
_ => null,
126+
};
100127
}
101128
}

‎Source/Generator/README.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ It ships inside the `Open.Database.Extensions.Core` package, on by default; it i
55

66
## What it does
77

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

1213
- **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
1314
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
@@ -71,7 +72,7 @@ In this repository, a project uses it as an analyzer:
7172
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
7273
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),
7374
a `ref struct` property that can be set or a `ref struct` constructor parameter, a constructor, setter, property or type marked `[Obsolete(…, true)]`,
74-
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`).
75+
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`).
7576
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`
7677
or `NullValue` on a property or on a constructor or positional record parameter.
7778

‎Source/Generator/Specs.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,16 @@ sealed record ModelSpec(
9595

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

98-
/// <summary>Which overload of <c>Map&lt;T&gt;()</c> the call binds to.</summary>
98+
/// <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>
9999
enum Receiver
100100
{
101101
ExecuteReader,
102102
Command,
103103
DataReader,
104+
Query,
105+
TypedQuery,
106+
QueryCall,
107+
QueryUsing,
104108
}
105109

106110
/// <summary>One intercepted call: where it is, what it binds to, and the model it maps.</summary>
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
using Microsoft.Data.Sqlite;
2+
using System.ComponentModel.DataAnnotations.Schema;
3+
4+
namespace Open.Database.Extensions.Generator.Tests;
5+
6+
// The Map<T>() the query types declare themselves (DbQuery, DbQuery<TParams>, DbQueryUsing, DbQueryCall): intercepted as the extensions are,
7+
// and equal to the same type's Map(RowMap<T>.Default).
8+
9+
/// <summary>No annotations: matched by name.</summary>
10+
public sealed class QueryRow
11+
{
12+
public int Id { get; set; }
13+
public string Name { get; set; } = "";
14+
public int? Rank { get; set; }
15+
}
16+
17+
/// <summary>Every column's ordinal declared: read by position.</summary>
18+
public sealed class OrderedQueryRow
19+
{
20+
[Column(Order = 0)]
21+
public int Id { get; set; }
22+
23+
[Column(Order = 1)]
24+
public string Name { get; set; } = "";
25+
26+
[Column(Order = 2)]
27+
public int? Rank { get; set; }
28+
}
29+
30+
public partial class ParityTests
31+
{
32+
const string QueryRows = "select 1 as Id, 'a' as Name, 7 as Rank union all select 2, 'b', null order by Id";
33+
const string OneQueryRow = "select @id as Id, 'a' as Name, null as Rank";
34+
35+
// A parameter type only this class can name, as a repository declares one.
36+
readonly record struct ById(int Id);
37+
38+
static SqliteConnection Memory()
39+
{
40+
var connection = new SqliteConnection("Data Source=:memory:");
41+
connection.Open();
42+
return connection;
43+
}
44+
45+
/// <summary>One intercepted call, one result set served by generated code, the rows of the runtime map.</summary>
46+
static void QueryParity<T>(Func<List<T>> runtime, Func<List<T>> generated, int rows)
47+
{
48+
List<T> expected = runtime();
49+
var start = Counts.Now();
50+
List<T> actual = generated();
51+
Served(Counts.Now().Since(start));
52+
Parity.SameRows(expected, actual);
53+
Assert.Equal(rows, actual.Count);
54+
}
55+
56+
[Fact]
57+
public void DbQuery_definition_is_served()
58+
{
59+
using SqliteConnection connection = Memory();
60+
DbQuery query = DbQuery.Text(QueryRows);
61+
62+
QueryParity(
63+
() => query.Map(RowMap<QueryRow>.Default).Using(connection).ToList(),
64+
() => query.Map<QueryRow>().Using(connection).ToList(),
65+
2);
66+
67+
// On the value a factory returns, with no variable, and a model read by position.
68+
QueryParity(
69+
() => query.Map(RowMap<OrderedQueryRow>.Default).Using(connection).ToList(),
70+
() => DbQuery.Text(QueryRows).Map<OrderedQueryRow>().Using(connection).ToList(),
71+
2);
72+
}
73+
74+
[Fact]
75+
public void A_definition_mapped_once_serves_every_call()
76+
{
77+
using SqliteConnection connection = Memory();
78+
var start = Counts.Now();
79+
MappedDbQuery<QueryRow> mapped = DbQuery.Text(QueryRows).Map<QueryRow>();
80+
Assert.Equal(2, mapped.Using(connection).ToList().Count);
81+
Assert.Equal(2, mapped.Using(connection).ToList().Count);
82+
Counts c = Counts.Now().Since(start);
83+
Assert.True(c.Intercepted == 1 && c.Served == 2 && c.Declined == 0, c.ToString());
84+
}
85+
86+
[Fact]
87+
public void Typed_definition_with_a_private_parameter_type_is_served()
88+
{
89+
using SqliteConnection connection = Memory();
90+
DbQuery<ById> query = DbQuery.Text(OneQueryRow).Params<ById>();
91+
92+
QueryParity(
93+
() => query.Map(RowMap<QueryRow>.Default).Using(connection).AddParams(new(3)).ToList(),
94+
() => query.Map<QueryRow>().Using(connection).AddParams(new(3)).ToList(),
95+
1);
96+
}
97+
98+
[Fact]
99+
public void Typed_definition_inside_a_generic_method_is_served()
100+
{
101+
using SqliteConnection connection = Memory();
102+
103+
QueryParity(
104+
() => DbQuery.Text(OneQueryRow).Params<ById>().Map(RowMap<QueryRow>.Default).Using(connection).AddParams(new(4)).ToList(),
105+
() => MapTyped(DbQuery.Text(OneQueryRow).Params<ById>()).Using(connection).AddParams(new(4)).ToList(),
106+
1);
107+
108+
static MappedDbQuery<TValues, QueryRow> MapTyped<TValues>(DbQuery<TValues> query)
109+
where TValues : struct, IEquatable<TValues>
110+
=> query.Map<QueryRow>();
111+
}
112+
113+
[Fact]
114+
public void DbQueryUsing_is_served_from_a_value_a_variable_and_an_in_parameter()
115+
{
116+
using SqliteConnection connection = Memory();
117+
DbQuery query = DbQuery.Text(QueryRows);
118+
DbQueryUsing bound = query.Using(connection);
119+
List<QueryRow> Runtime() => query.Using(connection).Map(RowMap<QueryRow>.Default).ToList();
120+
121+
QueryParity(Runtime, () => query.Using(connection).Map<QueryRow>().ToList(), 2);
122+
QueryParity(Runtime, () => bound.Map<QueryRow>().ToList(), 2);
123+
QueryParity(Runtime, () => FromIn(bound), 2);
124+
125+
static List<QueryRow> FromIn(in DbQueryUsing source) => source.Map<QueryRow>().ToList();
126+
}
127+
128+
[Fact]
129+
public void DbQueryCall_is_served_from_a_value_and_a_variable()
130+
{
131+
using SqliteConnection connection = Memory();
132+
DbQuery query = DbQuery.Text(OneQueryRow);
133+
DbQueryCall call = query.Using(connection).AddParam("id", 5);
134+
List<QueryRow> Runtime() => query.Using(connection).AddParam("id", 5).Map(RowMap<QueryRow>.Default).ToList();
135+
136+
QueryParity(Runtime, () => query.Using(connection).AddParam("id", 5).Map<QueryRow>().ToList(), 1);
137+
QueryParity(Runtime, () => call.Map<QueryRow>().ToList(), 1);
138+
}
139+
140+
[Fact]
141+
public void A_default_bound_query_throws_as_the_runtime_map_does()
142+
{
143+
Parity.SameError(
144+
Catch(() => default(DbQueryUsing).Map(RowMap<QueryRow>.Default)),
145+
Catch(() => default(DbQueryUsing).Map<QueryRow>()));
146+
Parity.SameError(
147+
Catch(() => default(DbQueryCall).Map(RowMap<QueryRow>.Default)),
148+
Catch(() => default(DbQueryCall).Map<QueryRow>()));
149+
}
150+
151+
[Fact]
152+
public void A_single_value_on_a_query_is_not_intercepted()
153+
{
154+
using SqliteConnection connection = Memory();
155+
var start = Counts.Now();
156+
Assert.Equal([1, 2], DbQuery.Text(QueryRows).Map<int>().Using(connection).ToList());
157+
Assert.Equal([1, 2], DbQuery.Text(QueryRows).Using(connection).Map<int>().ToList());
158+
Assert.Equal(0, Counts.Now().Since(start).Intercepted);
159+
}
160+
}

0 commit comments

Comments
 (0)