diff --git a/Source/Core/README.md b/Source/Core/README.md index 1eba80b9..1b5ac9ba 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -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()` 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 `false` 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()` 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 `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 diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 78466a32..195ab98b 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -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 x) => CoreExtensions.Map(x, M_T.Map), the existing Map(RowMap?) overload; +// - per call site, an interceptor that passes M_T.Map to the receiver's existing Map(RowMap?) overload: CoreExtensions.Map(x, M_T.Map) +// for a reader or command, x.Map(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 @@ -104,18 +105,19 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList 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(); @@ -125,6 +127,30 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList 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?). + 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"; + return ($"public static {mapped} Map_{i}(this {Ns}.DbQuery source)", + "where TParams : struct, global::System.IEquatable", + $"({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( """ diff --git a/Source/Generator/MapGenerator.cs b/Source/Generator/MapGenerator.cs index 4e900199..dedc31d3 100644 --- a/Source/Generator/MapGenerator.cs +++ b/Source/Generator/MapGenerator.cs @@ -9,8 +9,9 @@ namespace Open.Database.Extensions.Generator; /// /// 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: +/// (receivers IExecuteReader, IDbCommand, IDataReader) or to the method of DbQuery, DbQuery<TParams>, +/// DbQueryCall or DbQueryUsing, and serves it with generated row readers through the same type's 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, /// or T is a shape the generated code does not describe exactly. /// @@ -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); @@ -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(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() 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, + }; } } diff --git a/Source/Generator/README.md b/Source/Generator/README.md index 526c5159..a29438f2 100644 --- a/Source/Generator/README.md +++ b/Source/Generator/README.md @@ -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()` with a closed model type `T`, where `x` is an `IExecuteReader`, an `IDbCommand` or an `IDataReader`, -it emits an interceptor `CoreExtensions.Map(x, M_T.Map)`: the existing public overload `Map(RowMap?)`, with one map per model type made by -Core's hidden entry `GeneratedRowMap.Create(Bind)` (for this generator only; not for direct use). +For each call `x.Map()` with a closed model type `T`, where `x` is an `IExecuteReader`, an `IDbCommand`, an `IDataReader`, +a `DbQuery`, a `DbQuery`, a `DbQueryCall` or a `DbQueryUsing`, it emits an interceptor that calls the receiver's existing public +overload `Map(RowMap?)`, with one map per model type made by Core's hidden entry `GeneratedRowMap.Create(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 @@ -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()` with an open `T`). +a file-local or extern-alias type, a constructor with an `OverloadResolutionPriority`, a `DataTable` receiver, a call written `x?.Map()`, and a call inside a generic method (`Map()` 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. diff --git a/Source/Generator/Specs.cs b/Source/Generator/Specs.cs index a32c6dd9..2866b120 100644 --- a/Source/Generator/Specs.cs +++ b/Source/Generator/Specs.cs @@ -95,12 +95,16 @@ sealed record ModelSpec( sealed record PartialShape(int Constructors, EquatableArray Settable); -/// Which overload of Map<T>() the call binds to. +/// Which Map<T>() the call binds to: an extension over a reader or command, or a query type's own method. enum Receiver { ExecuteReader, Command, DataReader, + Query, + TypedQuery, + QueryCall, + QueryUsing, } /// One intercepted call: where it is, what it binds to, and the model it maps. diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.DbQuery.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.DbQuery.cs new file mode 100644 index 00000000..65c81288 --- /dev/null +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.DbQuery.cs @@ -0,0 +1,160 @@ +using Microsoft.Data.Sqlite; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Open.Database.Extensions.Generator.Tests; + +// The Map() the query types declare themselves (DbQuery, DbQuery, DbQueryUsing, DbQueryCall): intercepted as the extensions are, +// and equal to the same type's Map(RowMap.Default). + +/// No annotations: matched by name. +public sealed class QueryRow +{ + public int Id { get; set; } + public string Name { get; set; } = ""; + public int? Rank { get; set; } +} + +/// Every column's ordinal declared: read by position. +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; + } + + /// One intercepted call, one result set served by generated code, the rows of the runtime map. + static void QueryParity(Func> runtime, Func> generated, int rows) + { + List expected = runtime(); + var start = Counts.Now(); + List 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.Default).Using(connection).ToList(), + () => query.Map().Using(connection).ToList(), + 2); + + // On the value a factory returns, with no variable, and a model read by position. + QueryParity( + () => query.Map(RowMap.Default).Using(connection).ToList(), + () => DbQuery.Text(QueryRows).Map().Using(connection).ToList(), + 2); + } + + [Fact] + public void A_definition_mapped_once_serves_every_call() + { + using SqliteConnection connection = Memory(); + var start = Counts.Now(); + MappedDbQuery mapped = DbQuery.Text(QueryRows).Map(); + 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 query = DbQuery.Text(OneQueryRow).Params(); + + QueryParity( + () => query.Map(RowMap.Default).Using(connection).AddParams(new(3)).ToList(), + () => query.Map().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().Map(RowMap.Default).Using(connection).AddParams(new(4)).ToList(), + () => MapTyped(DbQuery.Text(OneQueryRow).Params()).Using(connection).AddParams(new(4)).ToList(), + 1); + + static MappedDbQuery MapTyped(DbQuery query) + where TValues : struct, IEquatable + => query.Map(); + } + + [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 Runtime() => query.Using(connection).Map(RowMap.Default).ToList(); + + QueryParity(Runtime, () => query.Using(connection).Map().ToList(), 2); + QueryParity(Runtime, () => bound.Map().ToList(), 2); + QueryParity(Runtime, () => FromIn(bound), 2); + + static List FromIn(in DbQueryUsing source) => source.Map().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 Runtime() => query.Using(connection).AddParam("id", 5).Map(RowMap.Default).ToList(); + + QueryParity(Runtime, () => query.Using(connection).AddParam("id", 5).Map().ToList(), 1); + QueryParity(Runtime, () => call.Map().ToList(), 1); + } + + [Fact] + public void A_default_bound_query_throws_as_the_runtime_map_does() + { + Parity.SameError( + Catch(() => default(DbQueryUsing).Map(RowMap.Default)), + Catch(() => default(DbQueryUsing).Map())); + Parity.SameError( + Catch(() => default(DbQueryCall).Map(RowMap.Default)), + Catch(() => default(DbQueryCall).Map())); + } + + [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().Using(connection).ToList()); + Assert.Equal([1, 2], DbQuery.Text(QueryRows).Using(connection).Map().ToList()); + Assert.Equal(0, Counts.Now().Since(start).Intercepted); + } +} diff --git a/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs b/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs index 6da71e17..2c1ff59d 100644 --- a/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs +++ b/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs @@ -70,6 +70,14 @@ public class ConsumerTests const string PostColumns = "Id, Title, Created, State, Rank, Note"; const string OrderedColumns = "Id, Title, [Key], State, Rank"; + // A parameter type the generated file cannot name. Written out: a positional record needs an init accessor, which net472 lacks. + readonly record struct AfterId + { + public AfterId(int id) => Id = id; + + public int Id { get; } + } + // ---- what the generator did ---- static long Served() @@ -155,6 +163,19 @@ static void Check(DbConnection connection, string table) Assert.Equal(2, annotated.Count); Assert.Equal(HandOrdered(connection, ordered), annotated.Select(Row)); + // The query types' own Map(): a definition, a typed definition, a bound query and a bound call. + DbQuery all = DbQuery.Text(posts); + List defined = ServedBy(() => all.Map().Using(connection).ToList()); + Assert.Equal(unannotated.Select(Row), defined.Select(Row)); + List bound = ServedBy(() => all.Using(connection).Map().ToList()); + Assert.Equal(unannotated.Select(Row), bound.Select(Row)); + + DbQuery after = DbQuery.Text($"select {PostColumns} from {table} where Id > @id order by Id"); + List called = ServedBy(() => after.Using(connection).AddParam("id", 1).Map().ToList()); + Assert.Equal(unannotated.Skip(1).Select(Row), called.Select(Row)); + List typed = ServedBy(() => after.Params().Map().Using(connection).AddParams(new(1)).ToList()); + Assert.Equal(unannotated.Skip(1).Select(Row), typed.Select(Row)); + // Two result sets from one reader, each mapped where the reader stands. using DbCommand command = connection.CreateCommand(); command.CommandText = $"select Id, Title as Name from {table} order by Id; select Id, Note as Name from {table} where Note is not null"; diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index e67ef06d..883046ab 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -219,7 +219,7 @@ The attributes are read by their full name, so a model's own copy of them counts ## Generated readers -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()` on a command or a reader gets its row reader written at build time. The call and its terminals are the same, and so are the results except as below. Where the generator cannot describe a model or a result exactly, and with an older compiler, the runtime map described on this page reads the rows. A `Map()` on a `DbQuery` definition, or with a map or selector, is not generated. +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()` on a command, a reader or a `DbQuery` gets its row reader written at build time. The call and its terminals are the same, and so are the results except as below. Where the generator cannot describe a model or a result exactly, and with an older compiler, the runtime map described on this page reads the rows. A `Map` given a map or a selector is not generated. Unless the model declares every column's ordinal, a generated reader matches the columns by name once per result set; it then reads each member with the provider's getter for the member's type, as a hand-written reader does. Three differences follow: diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 51895297..0d13837a 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -4,6 +4,10 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl ## Version 11 release candidates +### Changes since rc.16 + +- **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. + ### Changes since rc.15 - **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()`, `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).