From 666077478fa38ead8f189a0b187fddddd0b417a8 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:16:13 -0800 Subject: [PATCH 1/3] Source generator: unannotated models read each member by its type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A generated reader now reads every member with the provider's getter for the member's type, as a hand-written reader does. This applies to unannotated models too: per result set they check only the column count and names, with no column types and no conversions. The runtime map is unchanged. - Where the column's type is not the member's, the provider converts, coerces or throws, and the value it gives is the provider's (on SQLite, the text `'true'` read into a `bool` is `false`). The generator README lists the conversions the runtime map makes that a generated reader does not. - A `char` or open type-parameter member leaves the model to the runtime map. - On SQLite, dates, time spans and `ulong` read from text or integers can differ from the runtime map's conversion (for example, a `DateTimeOffset` from text without an offset is taken as UTC, not local time). - Tests that exercise the runtime map's conversions now call `Map(RowMap.Default)`, and the fake reader has typed getters, as providers do. New tests on SQLite and SQL Server compare NULL handling with the runtime map: a nullable member gets null, and a NULL in a non-nullable member fails the row in both (the exception inside can differ, as the generator README says). - Benchmarks: the unannotated generated rung now runs on SQLite too. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 --- .../GateBenchmarks.cs | 17 +- .../RealParityBenchmarks.cs | 10 +- .../RealProviderBenchmarks.cs | 10 +- .../RealProviderChecks.cs | 1 - Source/Core/README.md | 2 +- Source/Generator/Emitter.cs | 160 +++++------------- Source/Generator/ModelReader.cs | 104 ++---------- Source/Generator/README.md | 44 ++--- Source/Generator/Specs.cs | 15 +- .../DateAndTimeMappingTests.cs | 16 +- .../RowMapNullTests.cs | 2 +- .../RowMapperTests.cs | 90 +++++----- .../SequentialAccessOrderTests.cs | 22 +-- .../TestHelpers/FakeReader.cs | 16 ++ .../GeneratedSourceTests.cs | 4 +- .../Harness.cs | 5 +- .../NullByTypeTests.cs | 142 ++++++++++++++++ .../ParityTests.Errors.cs | 6 +- .../ParityTests.Null.cs | 11 +- .../ParityTests.Review.cs | 21 +-- .../ParityTests.Shapes.cs | 4 +- .../ParityTests.cs | 77 +++------ .../SqliteReadTests.cs | 61 +++++++ .../ConsumerTests.cs | 10 +- docsite/articles/mapping.md | 10 +- docsite/articles/release-notes.md | 2 +- 26 files changed, 416 insertions(+), 446 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Generator.Tests/NullByTypeTests.cs create mode 100644 Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/GateBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/GateBenchmarks.cs index 4f508e9e..b306f466 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/GateBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/GateBenchmarks.cs @@ -174,7 +174,6 @@ protected void Open() // The oracle, read with plain ADO.NET: a process times one rung, and no other reading may go through the library's shared read loop first. _expected = Oracle(); if (_expected.Count != Rows) throw new InvalidOperationException($"{_expected.Count} rows, expected {Rows}."); - GeneratedServesUnannotated = Source != RealProviderParams.Sqlite; // One line per process in the log: which case it ran. Console.WriteLine($"// GATE-PID {Environment.ProcessId} {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription} {GetType().Name} {Source} width={Width} rows={Rows}"); @@ -210,9 +209,6 @@ protected void Check(string rung, ReadModeConnection connection, bool sequential [GlobalCleanup] public void Cleanup() => _case?.Cleanup(); - // SQLite stores a Guid as text, which the generated reader of an undecorated model leaves to the runtime map. - protected bool GeneratedServesUnannotated { get; private set; } - static ExpressiveDbCommand Command(ReadModeConnection connection) => connection.Command(RealProviderVariants.Sql); protected object Hand(ReadModeConnection c) @@ -225,10 +221,7 @@ protected object Annotated(ReadModeConnection c) => Width == 10 ? GeneratedReads.GenDT10(Command(c)) : GeneratedReads.GenDT20(Command(c)); protected object Unannotated(ReadModeConnection c) - { - if (!GeneratedServesUnannotated) throw new NotSupportedException("Gen_T is not served by generated code on SQLite."); - return Width == 10 ? GeneratedReads.GenT10(Command(c)) : GeneratedReads.GenT20(Command(c)); - } + => Width == 10 ? GeneratedReads.GenT10(Command(c)) : GeneratedReads.GenT20(Command(c)); protected object Written(ReadModeConnection c) => Width == 10 ? GeneratedControl.ControlT10(Command(c)) : GeneratedControl.ControlT20(Command(c)); @@ -258,7 +251,7 @@ public override void VerifyAll() CheckRung(nameof(CtlH_T), CtlH_T); CheckRung(nameof(CtlH_T2), CtlH_T2); CheckRung(nameof(GenD_T), GenD_T, generated: true); - if (GeneratedServesUnannotated) CheckRung(nameof(Gen_T), Gen_T, generated: true); + CheckRung(nameof(Gen_T), Gen_T, generated: true); CheckRung(nameof(Selector), Selector); } @@ -272,11 +265,7 @@ public override void VerifyAll() public void SetupGenD_T() { Prepare(); CheckRung(nameof(GenD_T), GenD_T, generated: true); } [GlobalSetup(Target = nameof(Gen_T))] - public void SetupGen_T() - { - Prepare(); - if (GeneratedServesUnannotated) CheckRung(nameof(Gen_T), Gen_T, generated: true); - } + public void SetupGen_T() { Prepare(); CheckRung(nameof(Gen_T), Gen_T, generated: true); } [GlobalSetup(Target = nameof(Selector))] public void SetupSelector() { Prepare(); CheckRung(nameof(Selector), Selector); } diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs index 4466ec2b..d1ac88e5 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs @@ -9,7 +9,7 @@ namespace Open.Database.Extensions.Benchmarks; /// /// The generated map against the hand-written reader and Dapper.AOT over the real databases, on one row type per width (10 and 20). -/// GenD_T (annotated) and Gen_T (not annotated; SQL Server only) are generated; CtlH_T is the same reads written by hand +/// GenD_T (annotated) and Gen_T (not annotated) are generated; CtlH_T is the same reads written by hand /// with the same entry and access mode; V2 is the hand-written selector; V7a_T is Dapper.AOT. /// Setup reads each once and compares the rows with V2's, so no case is timed over wrong rows. /// @@ -48,7 +48,7 @@ public void Setup() Same(nameof(GenD_T), expected, Generated(nameof(GenD_T), GenD_T)); Same(nameof(CtlH_T), expected, (IList)CtlH_T()); Same(nameof(V7a_T), expected, (IList)V7a_T()); - if (Provider == RealProviderParams.SqlServer) Same(nameof(Gen_T), expected, Generated(nameof(Gen_T), Gen_T)); + Same(nameof(Gen_T), expected, Generated(nameof(Gen_T), Gen_T)); } // Present only in a build with -p:OdxGeneratorCounters=true (never a timed run): then a generated rung must be served by generated code. @@ -110,13 +110,9 @@ public object GenD_T() [Benchmark] public object Gen_T() - { - // SQLite stores a Guid as text, which the generated reader of an undecorated model leaves to the runtime map. - if (Provider == RealProviderParams.Sqlite) throw new NotSupportedException("Gen_T is not served by generated code on SQLite."); - return Width == 10 + => Width == 10 ? GeneratedReads.GenT10(_case.Timed.Command(RealProviderVariants.Sql)) : GeneratedReads.GenT20(_case.Timed.Command(RealProviderVariants.Sql)); - } [Benchmark] public object V7a_T() diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs index ecb68691..105d4f1f 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs @@ -423,15 +423,7 @@ public void Cleanup() // The generated reader, the hand-written selector of the same row type, and Dapper.AOT building it: all on GenRowT20, whose members have the // table's nullability. Width 20 only (ODX_RP_WIDTHS=20). [Benchmark] - public object Gen_T_Sync() - { - _label = nameof(Gen_T_Sync); - WidthTwenty(); - - // SQLite stores a Guid as text, which the generated reader of an undecorated model leaves to the runtime map: this rung would measure that. - if (Provider == RealProviderParams.Sqlite) throw new NotSupportedException("Gen_T_Sync is not served by generated code on SQLite; GenD_T_Sync is."); - return GeneratedReads.GenT20(Case.Timed.Command(RealProviderVariants.Sql)); - } + public object Gen_T_Sync() { _label = nameof(Gen_T_Sync); WidthTwenty(); return GeneratedReads.GenT20(Case.Timed.Command(RealProviderVariants.Sql)); } // GenD_T: the decorated twin, read by the trusted generated reader at constant ordinals. [Benchmark] diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs index 7d438031..b6a30694 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs @@ -121,7 +121,6 @@ public static int VerifyRealProviders() { // The rungs on the 20-column row type run at width 20 only. if (width != 20 && method.Name is "Gen_T_Sync" or "GenD_T_Sync" or "Ctl_T_Sync" or "V7a_T_Sync") continue; - if (provider == RealProviderParams.Sqlite && method.Name == "Gen_T_Sync") continue; // Not a generated rung there (see the method). recorder.Reset(); bool generated = method.Name is "Gen_T_Sync" or "GenD_T_Sync" && GeneratorCounters is not null; long served = generated ? Counter("Served") : 0, declined = generated ? Counter("Declined") : 0; diff --git a/Source/Core/README.md b/Source/Core/README.md index 27edfe92..1eba80b9 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. While it is on, 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 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). ## Where to go next diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 0c7095df..92189415 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -4,18 +4,19 @@ 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; -// - a model that declares every column's ordinal ([Column(Order = n)] on every mapped member) is trusted: Bind returns the literal reader, each -// member read by its own type (ModelReader.Direct), and looks at nothing in the result (EmitTrusted). -// What follows about layouts is for every other model. +// - 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 +// looks at nothing in the result (EmitTrusted). What follows about layouts is for every other model. // - per model type, one class M_T holding one RowMap made by GeneratedRowMap.Create(Bind). Core's read loop calls Bind once per result -// set, after its first row is read and before it is mapped (a set with no row to map calls nothing): Bind compares the reader's names and types with the layouts met lately (a small static cache of immutable layouts, +// set, after its first row is read and before it is mapped (a set with no row to map calls nothing): Bind compares the reader's column count and names with the layouts met lately (a small static cache of immutable layouts, // swapped atomically) 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 it, exactly as the default map: its rows, its exceptions). A next result set is bound again, so it is always read at its own ordinals. // - the row reader is the reads and nothing else: typed getters, a NULL test only on a nullable member, the model built and set. No try region, // no row counter, no layout check, no mode switch: Bind chose the reader for the mode once per result set. -// * identity layouts (mode 5) and trusted models: a static lambda reading literal ordinals (a closed delegate on the compiler's +// * identity layouts (mode 4) and trusted models: a static lambda reading literal ordinals (a closed delegate on the compiler's // singleton: no state, no argument-shuffling thunk); -// * the other modes (full 1, guarded 2, converting 4): an instance method of the layout (a delegate closed over it, no thunk), reading the +// * the other modes (full 1, guarded 2): an instance method of the layout (a delegate closed over it, no thunk), reading the // layout's ordinals from it; // each is NoInlining, so its own frame is on the stack trace of anything it throws: that is how Core's loop tells a failure of the row reader // from a failure of its own Read (best effort, on the failure path only). @@ -24,8 +25,8 @@ namespace Open.Database.Extensions.Generator; // cancellation passes through. Nothing is read from the reader after a failure. // - NULL, by the member's type: a member declared non-nullable (a value type other than Nullable, a reference annotated non-nullable) is read // with its typed getter alone, or by a plain cast of GetValue, as a hand-written reader reads it; a NULL there throws (the getter, or the cast). -// Only a value type read by GetValue, or a type a cast of DBNull fits (object, an interface DBNull implements), makes the runtime's check and -// throws SqlNullValueException; a NULL in any other non-nullable reference read by GetValue fails the cast (InvalidCastException). +// Only a type a cast of DBNull fits (object, an interface DBNull implements) makes the runtime's check and throws SqlNullValueException; a +// NULL in any other non-nullable reference read by GetValue (byte[], an interface) fails the cast (InvalidCastException). // A nullable member (int?, string?, a reference in code with nullable annotations off) is tested with IsDBNull and gets null, which is stored // (IsDBNull ? default : value) whatever the created model holds there, as the runtime map calls the setter of every property a column feeds. // A model that declares NullPolicy or NullValue is not intercepted (ModelReader): the runtime map applies the policy. @@ -33,7 +34,6 @@ static class Emitter { const string Ns = "global::Open.Database.Extensions"; const string DbReader = "global::System.Data.Common.DbDataReader"; - const string TypeT = "global::System.Type"; const string NoInlining = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; public static string Emit(IReadOnlyList sites, Options options) @@ -98,8 +98,8 @@ static void EmitCounters(StringBuilder sb) sb.AppendLine("\t\tpublic static long Served;"); sb.AppendLine("\t\t/// Result sets bound and declined to the runtime map."); sb.AppendLine("\t\tpublic static long Declined;"); - sb.AppendLine("\t\t/// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 full with converting reads, 5 identity (constant ordinals)."); - sb.AppendLine("\t\tpublic static readonly long[] Modes = new long[6];"); + sb.AppendLine("\t\t/// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals)."); + sb.AppendLine("\t\tpublic static readonly long[] Modes = new long[5];"); sb.AppendLine("\t}"); sb.AppendLine(); } @@ -146,17 +146,15 @@ file sealed class OdxSlot(string name, string column, int order, bool notMapped, public readonly bool Required = required; } - // One result-set layout: the names and reported types (RowMap's Layout), and what the generated code does with it. + // One result-set layout: the column names, and what the generated code does with it. file abstract class OdxLayout { public readonly string[] Names; - public readonly global::System.Type[] Types; - // 0: the runtime map serves it. 1: every slot fed in ascending column order, every read exact (no presence test). + // 0: the runtime map serves it. 1: every slot fed in ascending column order (no presence test). // 2: some slots absent, or the columns not in slot order (guarded, read in column order). // 3: not a layout's mode: what the counters call a trusted model, which has no layout. - // 4: as 1, with a converting read chosen per column once per layout (a switch on it per cell, no presence test). - // 5: as 1, each slot at its declaration position among the mapped slots (columns 0..n-1, more columns after them ignored): constant ordinals, + // 4: as 1, each slot at its declaration position among the mapped slots (columns 0..n-1, more columns after them ignored): constant ordinals, // for a model that does not declare its ordinals. The common shape (SELECT the members in their order) reads like a hand-written selector. public int Mode; @@ -170,24 +168,15 @@ protected OdxLayout(global::System.Data.IDataRecord r) { int n = r.FieldCount; Names = new string[n]; - Types = new global::System.Type[n]; - for (int i = 0; i < n; i++) - { - Names[i] = r.GetName(i); - Types[i] = r.GetFieldType(i) ?? typeof(object); // As the runtime: tolerant of a provider that reports no type. - } + for (int i = 0; i < n; i++) Names[i] = r.GetName(i); } public bool Matches(global::System.Data.Common.DbDataReader r) { string[] names = Names; - global::System.Type[] types = Types; if (r.FieldCount != names.Length) return false; for (int i = 0; i < names.Length; i++) - { - if (!string.Equals(r.GetName(i), names[i], global::System.StringComparison.Ordinal) || (r.GetFieldType(i) ?? typeof(object)) != types[i]) - return false; - } + if (!string.Equals(r.GetName(i), names[i], global::System.StringComparison.Ordinal)) return false; return true; } @@ -385,7 +374,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) if (m.AllOrdered) { - EmitTrusted(sb, ByMemberType(m), options, styleB, literal, reader); + EmitTrusted(sb, m, options, styleB, literal, reader); sb.AppendLine("\t}"); sb.AppendLine(); return; @@ -403,21 +392,6 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\t];"); sb.AppendLine(); - // ---- the read cases of each slot ---- - for (int k = 0; k < slots.Length; k++) - { - SlotSpec s = slots[k]; - if (s.NotMapped) continue; - - var cases = s.Cases.Items; - string body = cases.Length == 0 - ? "-1" - : string.Join(" : ", cases.Select((c, i) => $"t == typeof({c.ColumnType}) ? {i}")) + " : -1"; - sb.AppendLine($"\t\tstatic int Case{k}({TypeT} t) => {body};"); - } - - sb.AppendLine(); - // The layouts met lately (a few, as queries over one model with different column lists alternate); a slot is replaced in turn. A layout is // complete before it is published, and references are swapped atomically, so concurrent queries share them safely. sb.AppendLine("\t\tstatic readonly Layout[] s_layouts = new Layout[8];"); @@ -459,24 +433,22 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\t\tvar l = new Layout(r);"); sb.AppendLine($"\t\t\tint[] o = OdxMatch.Slots(l.Names, Slots, {Bool(m.Decorated)});"); sb.AppendLine("\t\t\tif (o == null) return l; // A check the runtime throws for: it serves (throws) it."); - sb.AppendLine("\t\t\tbool full = true, exact = true, literal = true, ascending = true;"); + sb.AppendLine("\t\t\tbool full = true, literal = true, ascending = true;"); sb.AppendLine("\t\t\tint last = -1;"); for (int k = 0; k < slots.Length; k++) { SlotSpec s = slots[k]; if (s.NotMapped) { - sb.AppendLine($"\t\t\tl.O{k} = -1; l.C{k} = -1;"); + sb.AppendLine($"\t\t\tl.O{k} = -1;"); continue; } sb.AppendLine($"\t\t\tl.O{k} = o[{k}];"); sb.AppendLine($"\t\t\tif (o[{k}] >= 0)"); sb.AppendLine("\t\t\t{"); - sb.AppendLine($"\t\t\t\tif ((l.C{k} = Case{k}(l.Types[o[{k}]])) < 0) return l; // A read the generated code does not make."); sb.AppendLine($"\t\t\t\tif (o[{k}] <= last) ascending = false;"); sb.AppendLine($"\t\t\t\tlast = o[{k}];"); - sb.AppendLine($"\t\t\t\tif (l.C{k} != 0) exact = false;"); sb.AppendLine($"\t\t\t\tif (o[{k}] != {literal[k]}) literal = false;"); sb.AppendLine("\t\t\t}"); sb.AppendLine("\t\t\telse"); @@ -484,23 +456,21 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) if (s.InitBound) sb.AppendLine("\t\t\t\treturn l; // An init-only member with no column keeps what its type gives it, which an object initializer cannot leave alone."); else - sb.AppendLine($"\t\t\t\tl.C{k} = -1; full = false;"); + sb.AppendLine("\t\t\t\tfull = false;"); sb.AppendLine("\t\t\t}"); } sb.AppendLine("\t\t\tl.Ordinals = o;"); - // Every slot fed: constant ordinals when each sits at its declaration position (5, the identity: read in slot order, which is column order); - // else, in ascending column order, - // exact reads (1) or a converting read chosen per column (4). Anything else is guarded (2), read in column order. - sb.AppendLine("\t\t\tl.Mode = !full || !ascending ? 2 : exact ? literal ? 5 : 1 : 4;"); + // Every slot fed in ascending column order: constant ordinals when each sits at its declaration position (4, the identity: read in slot order, + // which is column order), else the layout's (1). Anything else is guarded (2), read in column order. + sb.AppendLine("\t\t\tl.Mode = !full || !ascending ? 2 : literal ? 4 : 1;"); sb.AppendLine("\t\t\tif (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots);"); sb.AppendLine("\t\t\t// The row reader of the mode, chosen here once: the rows never ask which mode they are in."); sb.AppendLine("\t\t\tswitch (l.Mode)"); sb.AppendLine("\t\t\t{"); - sb.AppendLine("\t\t\t\tcase 5: l.Row = ReadLiteral; break;"); - sb.AppendLine($"\t\t\t\tcase 1: l.Row = l.ReadFull; break;"); - sb.AppendLine($"\t\t\t\tcase 2: l.Row = l.ReadGuarded; break;"); - sb.AppendLine($"\t\t\t\tcase 4: l.Row = l.ReadConverting; break;"); + sb.AppendLine("\t\t\t\tcase 4: l.Row = ReadLiteral; break;"); + sb.AppendLine("\t\t\t\tcase 1: l.Row = l.ReadFull; break;"); + sb.AppendLine("\t\t\t\tcase 2: l.Row = l.ReadGuarded; break;"); sb.AppendLine("\t\t\t}"); sb.AppendLine(); sb.AppendLine("\t\t\treturn l;"); @@ -513,11 +483,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine("\t\t// One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout)."); sb.AppendLine("\t\tsealed class Layout : OdxLayout"); sb.AppendLine("\t\t{"); - if (slots.Length > 0) - { - sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};"); - sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "C" + k))};"); - } + if (slots.Length > 0) sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};"); sb.AppendLine(); sb.AppendLine("\t\t\t// The row reader Bind returns for this layout; null when the runtime serves it."); @@ -527,7 +493,6 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine(); EmitMethod(sb, m, "ReadFull", styleB, ReadMode.Full, literal); EmitMethod(sb, m, "ReadGuarded", styleB, ReadMode.Guarded, literal); - EmitMethod(sb, m, "ReadConverting", styleB, ReadMode.Converting, literal); sb.AppendLine("\t\t}"); sb.AppendLine("\t}"); @@ -545,13 +510,6 @@ static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] sb.AppendLine(); } - // The model with each member's one read: by the member's type, no column type to choose by. - static ModelSpec ByMemberType(ModelSpec m) - => m with - { - Slots = new EquatableArray([.. m.Slots.Items.Select(static s => s.NotMapped ? s : s with { Cases = new EquatableArray([s.Direct]) })]), - }; - // Every mapped member declares its ordinal ([Column(Order = n)]): the declaration is trusted, as a hand-written reader trusts its ordinals. // Nothing about the result set is checked (no name, type or count), so there is one reader and Bind has nothing to choose. A result that does // not match gives what the member's getter gives: the provider's conversion or its exception, or, where the types agree, the value at that position. @@ -583,10 +541,10 @@ static string Unseen(Options options) ? "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 } + enum ReadMode { Literal, Full, Guarded } // 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 - // the slot's position among the mapped slots (mode 5, the identity: Resolve checks a layout against these before it chooses the mode). + // the slot's position among the mapped slots (mode 4, the identity: Resolve checks a layout against these before it chooses the mode). static int[] LiteralOrdinals(ModelSpec m) { var slots = m.Slots.Items; @@ -641,7 +599,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, foreach (int k in ReadOrder(slots, mode, literal)) { SlotSpec s = slots[k]; - EmitSlot(sb, s, k, mode, at, literal[k], (read, general) => Statement(s, "item." + Code(s.Name), read, general)); + EmitSlot(sb, s, k, mode, at, literal[k], "item." + Code(s.Name)); } CloseSequence(sb, mode, I); @@ -663,7 +621,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, foreach (int k in ReadOrder(slots, mode, literal)) { SlotSpec s = slots[k]; - EmitSlot(sb, s, k, mode, readAt, literal[k], (read, general) => Statement(s, "v" + k, read, general)); + EmitSlot(sb, s, k, mode, readAt, literal[k], "v" + k); } CloseSequence(sb, mode, I); @@ -706,51 +664,22 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, sb.AppendLine($"{I}return item;"); } - // One slot's read: at a constant ordinal (Literal), the layout's (Full), or the layout's when the slot is fed, by the read case of its column - // (Guarded, Converting). - static void EmitSlot(StringBuilder sb, SlotSpec s, int k, ReadMode mode, string indent, int literal, Func statement) + // One slot's read into its target: at a constant ordinal (Literal) or the layout's (Full, Guarded). A guarded read sits inside the + // column-order loop (OpenSequence), as this slot's case. + static void EmitSlot(StringBuilder sb, SlotSpec s, int k, ReadMode mode, string indent, int literal, string target) { - var cases = s.Cases.Items; - if (mode is ReadMode.Literal or ReadMode.Full || mode == ReadMode.Converting && cases.Length == 1) + string o = mode == ReadMode.Literal ? literal.ToString(System.Globalization.CultureInfo.InvariantCulture) : "O" + k; + MemberRead r = s.Read; + string statement = Statement(s, target, r.General ? r.Expression : r.Expression.Replace("{0}", o), r.General).Replace("{O}", o); + if (mode != ReadMode.Guarded) { - string o = mode == ReadMode.Literal ? literal.ToString(System.Globalization.CultureInfo.InvariantCulture) : "O" + k; - ReadCase c = cases[0]; - sb.AppendLine(indent + statement(c.General ? c.Expression : c.Expression.Replace("{0}", o), c.General).Replace("{O}", o)); + sb.AppendLine(indent + statement); return; } - // Guarded: inside the column-order loop (OpenSequence), this slot's case. Converting: every slot is fed, in ascending column order, so no presence test. - // Either way the read case was chosen once per layout, by the column's type. - if (mode == ReadMode.Guarded) - { - sb.AppendLine($"{indent}case {k}:"); - EmitCase(sb, s, k, indent + "\t", statement); - sb.AppendLine($"{indent}\tbreak;"); - } - else - { - sb.AppendLine($"{indent}// {s.Name}"); - EmitCase(sb, s, k, indent, statement); - } - } - - // A slot's read by the case its column's type chose: { int o = O{k}; switch (C{k}) { ... } }. - static void EmitCase(StringBuilder sb, SlotSpec s, int k, string indent, Func statement) - { - var cases = s.Cases.Items; - sb.AppendLine(indent + "{"); - sb.AppendLine(indent + $"\tint o = O{k};"); - sb.AppendLine(indent + $"\tswitch (C{k})"); - sb.AppendLine(indent + "\t{"); - for (int i = 0; i < cases.Length; i++) - { - ReadCase c = cases[i]; - string read = c.General ? c.Expression : c.Expression.Replace("{0}", "o"); - sb.AppendLine(indent + $"\t\tcase {i}: {statement(read, c.General).Replace("{O}", "o")} break;"); - } - - sb.AppendLine(indent + "\t}"); - sb.AppendLine(indent + "}"); + sb.AppendLine($"{indent}case {k}:"); + sb.AppendLine($"{indent}\t{statement}"); + sb.AppendLine($"{indent}\tbreak;"); } // A guarded read walks the fed slots in column order (Layout.Sequence), one switch case per slot; the other modes read in slot order (their columns ascend). @@ -776,8 +705,8 @@ static void CloseSequence(StringBuilder sb, ReadMode mode, string indent) // The statement that reads a member's cell into its target (the property, or the local a constructor takes); {O} is the ordinal. // A member its type declares non-nullable is read as a hand-written reader reads it: its typed getter alone, or a plain cast of GetValue (a NULL makes - // the getter or the cast throw, and Core's loop reports it). Only where a cast of DBNull would succeed (object, an interface DBNull implements) or the member is a value type - // does a general read make the runtime's ConvertRequired check, so a NULL throws SqlNullValueException instead of passing as a value. + // the getter or the cast throw, and Core's loop reports it). Only where a cast of DBNull would succeed (object, an interface DBNull implements) does a + // general read check for it and throw SqlNullValueException, as the runtime does, instead of letting DBNull pass as a value. // A nullable member is tested for NULL first, and null is stored, so the setter sees it. static string Statement(SlotSpec s, string target, string read, bool general) { @@ -793,7 +722,6 @@ static string Statement(SlotSpec s, string target, string read, bool general) if (general) { string value = read.Replace("{0}", "c"); - if (s.NullableValue) value = $"({s.Type})({value})"; return $"{{ object c = r.GetValue({{O}}); {target} = c is null || c is global::System.DBNull ? default({s.Type}) : {value}; }}"; } diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index 4b55d40f..54a2e1a3 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -254,44 +254,43 @@ static bool IsScalar(ITypeSymbol t) // Slot.IsNonNullable: a value type other than Nullable, or a reference type the source declares non-nullable (oblivious: nullable), object and // the interfaces DBNull implements included. Such a member is read without a NULL test on a typed getter (the getter throws on a NULL), by a - // plain cast on a general read (GetValue: the cast of DBNull throws), and with the runtime's ConvertRequired check only where the cast of DBNull - // would succeed (CastRejectsNull false). + // plain cast on a general read (GetValue: the cast of DBNull throws), and with a SqlNullValueException check only where the cast of DBNull would + // succeed (CastRejectsNull false). bool nonNullable = type.IsValueType ? !nullableValue : nonNullableReference; - ImmutableArray cases = Cases(underlying); - if (cases.IsEmpty) return null; + // No generated read for a char (providers differ: SqlClient's GetChar always throws) or an open type parameter. + if (underlying.SpecialType == SpecialType.System_Char || underlying.TypeKind == TypeKind.TypeParameter) return null; return new SlotSpec( name, parameter, position, - type.ToDisplayString(Fq), underlying.ToDisplayString(Fq), nullableValue, + type.ToDisplayString(Fq), nullableValue, nonNullable, CastRejectsNull(type, dbNull), initBound, required, declared.Column, declared.Order, declared.NotMapped, fallback, - Direct(underlying), - new EquatableArray(cases)); + MemberReadOf(underlying)); } // The read a hand-written reader makes for a member of this type, whatever the column is: the typed getter; an enum over its underlying type's // getter, cast; a cast of GetValue for byte[], object and the interfaces; GetFieldValue for any other type (DateOnly, TimeSpan, unsigned and // so on). The provider converts or throws. - static ReadCase Direct(ITypeSymbol target) + static MemberRead MemberReadOf(ITypeSymbol target) { string type = target.ToDisplayString(Fq); if (target is INamedTypeSymbol { TypeKind: TypeKind.Enum, EnumUnderlyingType: { } underlying }) - return new ReadCase(type, "(" + type + ")" + Direct(underlying).Expression, false); + return new MemberRead("(" + type + ")" + MemberReadOf(underlying).Expression, false); bool guid = target.SpecialType == SpecialType.None && FullName(target) == "System.Guid"; foreach ((SpecialType source, string getter) in Getters) { if (guid ? getter == "GetGuid" : source != SpecialType.None && source == target.SpecialType) - return new ReadCase(type, "r." + getter + "({0})", false); + return new MemberRead("r." + getter + "({0})", false); } bool general = target.SpecialType == SpecialType.System_Object || target.TypeKind is TypeKind.Interface or TypeKind.Dynamic || target is IArrayTypeSymbol { Rank: 1, ElementType.SpecialType: SpecialType.System_Byte }; return general - ? new ReadCase(type, "(" + type + "){0}", true) - : new ReadCase(type, "r.GetFieldValue<" + type + ">({0})", false); + ? new MemberRead("(" + type + "){0}", true) + : new MemberRead("r.GetFieldValue<" + type + ">({0})", false); } // Whether a cast of DBNull to the reference type throws: anything but object, dynamic, DBNull itself and the interfaces DBNull implements @@ -337,12 +336,11 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) return false; } - // RowMap.TypedGetters, in the order the reads are offered when no exact read exists. + // The types a reader has a getter for (char is declined above). static readonly (SpecialType Type, string Getter)[] Getters = [ (SpecialType.System_Boolean, "GetBoolean"), (SpecialType.System_Byte, "GetByte"), - (SpecialType.System_Char, "GetChar"), (SpecialType.System_Int16, "GetInt16"), (SpecialType.System_Int32, "GetInt32"), (SpecialType.System_Int64, "GetInt64"), @@ -354,84 +352,6 @@ static readonly (SpecialType Type, string Getter)[] Getters = (SpecialType.System_String, "GetString"), ]; - static string TypeOf(SpecialType s) => s switch - { - SpecialType.System_Boolean => "global::System.Boolean", - SpecialType.System_Byte => "global::System.Byte", - SpecialType.System_Char => "global::System.Char", - SpecialType.System_Int16 => "global::System.Int16", - SpecialType.System_Int32 => "global::System.Int32", - SpecialType.System_Int64 => "global::System.Int64", - SpecialType.System_Single => "global::System.Single", - SpecialType.System_Double => "global::System.Double", - SpecialType.System_Decimal => "global::System.Decimal", - SpecialType.System_DateTime => "global::System.DateTime", - SpecialType.System_String => "global::System.String", - _ => "global::System.Guid", - }; - - static bool IsIntegral(SpecialType s) => s is SpecialType.System_Byte or SpecialType.System_SByte or SpecialType.System_Int16 or SpecialType.System_UInt16 - or SpecialType.System_Int32 or SpecialType.System_UInt32 or SpecialType.System_Int64 or SpecialType.System_UInt64; - - static bool IsFractional(SpecialType s) => s is SpecialType.System_Single or SpecialType.System_Double or SpecialType.System_Decimal; - - // RowMap.TypedRead + TryConvert, per column type a getter exists for; then, for a member type that has no getter of its own, - // the general path's exact case (ConvertValue returns a value that already is the type as it is). Anything else is the general path: not generated. - static ImmutableArray Cases(ITypeSymbol target) - { - // No generated read for a char: providers differ (SqlClient's GetChar always throws), so the model is left to the runtime map. - if (target.SpecialType == SpecialType.System_Char) return []; - - string targetFq = target.ToDisplayString(Fq); - bool targetIsGuid = target.SpecialType == SpecialType.None && FullName(target) == "System.Guid"; - SpecialType targetSpecial = targetIsGuid ? SpecialType.None : target.SpecialType; - bool targetHasGetter = targetIsGuid || targetSpecial != SpecialType.None && Getters.Any(g => g.Type == targetSpecial); - SpecialType t = target is INamedTypeSymbol { TypeKind: TypeKind.Enum, EnumUnderlyingType: { } u } ? u.SpecialType : targetSpecial; - bool isEnum = target.TypeKind == TypeKind.Enum; - - var exact = new List(); - var others = new List(); - foreach ((SpecialType source, string getter) in Getters) - { - string read = "r." + getter + "({0})"; - string column = TypeOf(source); - bool sourceIsGuid = getter == "GetGuid"; - string? expression = null; - - if (targetHasGetter && (sourceIsGuid ? targetIsGuid : !targetIsGuid && source == targetSpecial)) - expression = read; - else if (sourceIsGuid || targetIsGuid) - expression = null; - else if (targetSpecial == SpecialType.System_Boolean && IsIntegral(source)) - expression = read + " != 0"; - else if (source == SpecialType.System_String && targetSpecial == SpecialType.System_DateTime) - expression = "global::System.DateTime.Parse(" + read + ", global::System.Globalization.CultureInfo.InvariantCulture)"; - else if (source == SpecialType.System_String && targetSpecial == SpecialType.System_Decimal) - expression = "global::System.Decimal.Parse(" + read + ", global::System.Globalization.NumberStyles.Number, global::System.Globalization.CultureInfo.InvariantCulture)"; - else if (IsIntegral(source) && IsIntegral(t)) - expression = "checked((" + targetFq + ")" + read + ")"; - else if ((IsIntegral(source) || IsFractional(source)) && IsFractional(t) && !isEnum) - expression = "(" + targetFq + ")" + read; - - if (expression is null) continue; - - var c = new ReadCase(column, expression, false); - // The read Full mode takes: the column's own type, or for an enum the column of its underlying type. - if (expression == read || isEnum && source == t) exact.Add(c); - else others.Add(c); - } - - if (!targetHasGetter && target.TypeKind != TypeKind.TypeParameter) - { - // typeof(dynamic) does not compile (CS1962): the column of a dynamic member reports object, as the runtime reads the property. - var general = new ReadCase(target.TypeKind == TypeKind.Dynamic ? "global::System.Object" : targetFq, "(" + targetFq + "){0}", true); - if (exact.Count == 0) exact.Add(general); - else others.Add(general); - } - - return [.. exact, .. others]; - } - // NullAnnotations.IsNonNullableReference(PropertyInfo): a reference type with nullable annotations on, not declared as a type parameter, no [AllowNull]. static bool IsNonNullableReference(IPropertySymbol p) { diff --git a/Source/Generator/README.md b/Source/Generator/README.md index 5bb945e9..3a430340 100644 --- a/Source/Generator/README.md +++ b/Source/Generator/README.md @@ -9,10 +9,13 @@ For each call `x.Map()` with a closed model type `T`, where `x` is an `IExecu 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). -- **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 names and types against a small +- **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 that result set exactly as the default map would. A next result set is bound again, at its own ordinals. `Bind` is thread-safe. -- **The row reader is the reads and nothing else**: typed getters at the layout's ordinals, a NULL test only on a nullable member, the model built. +- **Each member is read by its own type**, as a hand-written reader reads it: a typed getter (`GetInt32`, `GetString` and so on), an enum its + underlying type's getter, `byte[]`, `object`, interfaces and `dynamic` a cast of `GetValue`, and any other type (`DateOnly`, `TimeSpan`, `uint` + and so on) `GetFieldValue`. The column's type is not looked at: the provider converts or throws. +- **The row reader is the reads and nothing else**: those reads at the layout's ordinals, a NULL test only on a nullable member, the model built. No try region, no row counter, no layout check per row. Identity layouts and trusted models use a `static` lambda reading literal ordinals; the other layouts use an instance method of the layout (a delegate closed over it). - **NULL.** A member declared non-nullable (a value type other than `Nullable`, a reference annotated non-nullable) is read with its typed getter @@ -26,23 +29,26 @@ Core's hidden entry `GeneratedRowMap.Create(Bind)` (for this generator only; ## Known differences from the runtime map +- **The runtime map converts; a generated reader does not.** Only what the provider's getter converts is converted: elsewhere the read fails + (`ValueMappingException`; a provider's own `DbException` passes through). The runtime map converts, and a generated reader does not: + - integers to other integer widths and to enums, numbers to `bool` and `bool` to numbers; + - between `float`, `double` and `decimal` in either direction, and fractions to integers (rounded); + - text to numbers, `bool`, `DateTime`, `DateTimeOffset`, `TimeSpan`, `DateOnly`, `TimeOnly`, `Guid` and enums, and bytes to `Guid`; + - any value but bytes to `string`; + - `DateTime` to `DateTimeOffset`, `DateOnly`, `TimeOnly` or `TimeSpan`, `TimeSpan` to `TimeOnly`, `DateTimeOffset` to `DateOnly` or `TimeOnly`; + - and any other pair `Convert.ChangeType` converts. + + What a provider does with a column of another kind (convert it, coerce it or throw) is the provider's, and so is the value it gives: SQLite, for one, + reads the text `'true'` into a `bool` member as `false`, without an error. Store an enum or a `Guid` as text only for a `string` member. - **A model that declares every column's ordinal is trusted.** When every mapped member has `[Column(Order = n)]`, the generated reader reads those - positions with each member's own getter and looks at nothing else in the result: no name, type or count, as a hand-written reader reads. A member - with a typed getter uses it (`GetInt32`, `GetString` and so on), an enum its underlying type's getter, `byte[]`, `object`, interfaces and - `dynamic` a cast of `GetValue`, and any other type (`DateOnly`, `TimeSpan`, `uint` and so on) `GetFieldValue`. The runtime map checks the declarations and converts. The - generated reader instead: - - gives the value at that position, with no error, where another column the getter accepts sits there (a swapped or inserted column); - - converts only what the provider's getter converts. Where the column is missing or the getter refuses its type, the read fails - (`ValueMappingException`; a provider's own `DbException` passes through): with SqlClient an `int` member over a `smallint` or `bigint` column - fails on every row, as does an enum over `uint`, `ushort`, `sbyte` or `ulong`, whose column types SQL Server does not have. SQLite's getters - convert more, and without an error. - - So a result for such a model must have its columns at the declared positions, with types the members' getters accept. A reader that is not a - `DbDataReader`, `object[]` rows and a converted map use the runtime map, which checks. Pinned by tests. -- **A NULL into a non-nullable reference a cast of `DBNull` does not fit, read by `GetValue`** (`byte[]`, a class, an interface `DBNull` - does not implement; a trusted model's classes use `GetFieldValue`, which reports the provider's own NULL exception): the runtime map reports `SqlNullValueException` inside, with its NULL message; the generated reader, a plain cast as a - hand-written reader casts, reports the cast's `InvalidCastException` (same row, same model). Agreeing would cost the generated hot path a NULL - check, or cost the runtime map its clear NULL message for these types. Pinned by tests. + positions and looks at nothing else in the result: no name or count, as a hand-written reader reads. Where another column the getter accepts sits + at a position (a swapped or inserted column), it gives that value with no error; a missing column fails the read. The runtime map checks the + declarations. A reader that is not a `DbDataReader`, `object[]` rows and a converted map use the runtime map, which checks. Pinned by tests. +- **A NULL into a non-nullable member** reports the exception of the getter or the cast that read it, where the runtime map may report + `SqlNullValueException` with its NULL message: for `byte[]` and an interface `DBNull` does not implement, the generated reader's plain cast, as a + hand-written reader casts, reports `InvalidCastException`; a class reads with `GetFieldValue`, which reports the provider's own error, and a + provider type with a null value of its own (`SqlInt32` and so on) takes it. Same row, same model. Agreeing would cost the generated hot path a NULL + check, or cost the runtime map its clear NULL message. Pinned by tests. - **NULL policies are not generated.** A model with `NullPolicy` or `NullValue` is declined to the runtime map (below). ## Use @@ -74,7 +80,7 @@ help the build: where another generator gives a constructor to a partial model t 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. -Per result set, handed to the runtime map (never for a trusted model, above): a column whose type has no exact or converting typed read, declared columns that do not match (the runtime then throws its own exception), +Per result set, handed to the runtime map (never for a trusted model, above): declared columns that do not match (the runtime then throws its own exception), and a layout that leaves an init-only or required member without a column. Such a result set reports a failed row as the runtime map does, with its row. ## Tests diff --git a/Source/Generator/Specs.cs b/Source/Generator/Specs.cs index afaee418..a32c6dd9 100644 --- a/Source/Generator/Specs.cs +++ b/Source/Generator/Specs.cs @@ -43,10 +43,10 @@ public override int GetHashCode() } /// -/// One way to read a column into a slot, for one reported column type. -/// holds {0} for the ordinal; a general read () is a cast of GetValue (for a nullable member its NULL is tested on the value). +/// How a member's cell is read, by the member's type. +/// holds {0} for the ordinal; a general read () casts what GetValue returns (for a nullable member its NULL is tested on the value). /// -sealed record ReadCase(string ColumnType, string Expression, bool General); +sealed record MemberRead(string Expression, bool General); /// What one column can feed (RowMap's Slot): a constructor parameter, or a settable public instance property, in slot order. sealed record SlotSpec( @@ -55,9 +55,8 @@ sealed record SlotSpec( string? Parameter, // The constructor parameter's position, -1 for a property that is set. int Position, - // The member's declared type, and the type a value of it is read as (the underlying type of a Nullable). + // The member's declared type. string Type, - string Underlying, bool NullableValue, // Declared non-nullable (a value type other than Nullable, or a reference annotated non-nullable): read without a NULL test. bool NonNullable, @@ -74,10 +73,8 @@ sealed record SlotSpec( bool NotMapped, // The C# expression a constructor parameter receives when no column feeds it; null for a property. string? Fallback, - // The read by the member's type alone, as a hand-written reader makes it (ModelReader.Direct): what a trusted model uses. - ReadCase Direct, - // The reads, the exact one first (the one Full mode needs). - EquatableArray Cases); + // The read by the member's type, as a hand-written reader makes it (ModelReader.MemberReadOf). + MemberRead Read); sealed record ModelSpec( string Type, diff --git a/Tests/Open.Database.Extensions.Core.Tests/DateAndTimeMappingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DateAndTimeMappingTests.cs index d10351c8..12b32bf8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DateAndTimeMappingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DateAndTimeMappingTests.cs @@ -37,7 +37,7 @@ public static void TheTypesAProviderReturns_AreMapped() [("Day", typeof(DateTime)), ("Time", typeof(TimeSpan)), ("Offset", typeof(DateTimeOffset)), ("Span", typeof(TimeSpan))], [Moment.Date, new TimeSpan(7, 8, 9), Zoned, new TimeSpan(1, 2, 3, 4)]); - Stamps item = Assert.Single(cmd.Map().ToList()); + Stamps item = Assert.Single(cmd.Map(RowMap.Default).ToList()); Assert.Equal(new DateOnly(2024, 5, 6), item.Day); Assert.Equal(new TimeOnly(7, 8, 9), item.Time); @@ -53,7 +53,7 @@ public static void Text_IsMapped_AsSqliteReturnsIt() [("Day", typeof(string)), ("Time", typeof(string)), ("Offset", typeof(string)), ("Span", typeof(string))], ["2024-05-06", "07:08:09", "2024-05-06T07:08:09+02:00", "1.02:03:04"]); - Stamps item = Assert.Single(cmd.Map().ToList()); + Stamps item = Assert.Single(cmd.Map(RowMap.Default).ToList()); Assert.Equal(new DateOnly(2024, 5, 6), item.Day); Assert.Equal(new TimeOnly(7, 8, 9), item.Time); @@ -69,7 +69,7 @@ public static void ADateTime_FeedsATimeOnly_ADateOnly_AndADateTimeOffset() [("Day", typeof(DateTime)), ("Time", typeof(DateTime)), ("Offset", typeof(DateTime)), ("Span", typeof(DateTime))], [Moment, Moment, Moment, Moment]); - Stamps item = Assert.Single(cmd.Map().ToList()); + Stamps item = Assert.Single(cmd.Map(RowMap.Default).ToList()); Assert.Equal(new DateOnly(2024, 5, 6), item.Day); Assert.Equal(new TimeOnly(7, 8, 9), item.Time); @@ -82,7 +82,7 @@ public static void ADateTimeOffset_FeedsADateOnly_AndATimeOnly_ByItsOwnClock() { var cmd = Cmd([("Day", typeof(DateTimeOffset)), ("Time", typeof(DateTimeOffset))], [Zoned, Zoned]); - Stamps item = Assert.Single(cmd.Map().ToList()); + Stamps item = Assert.Single(cmd.Map(RowMap.Default).ToList()); Assert.Equal(new DateOnly(2024, 5, 6), item.Day); Assert.Equal(new TimeOnly(7, 8, 9), item.Time); @@ -96,7 +96,7 @@ public static void Nullable_Members_GetNull_ForNull_AndTheValue_Otherwise() [Moment.Date, new TimeSpan(7, 8, 9), Zoned, new TimeSpan(1, 2, 3, 4)], [null, null, null, null]); - var items = cmd.Map().ToList(); + var items = cmd.Map(RowMap.Default).ToList(); Assert.Equal(new DateOnly(2024, 5, 6), items[0].Day); Assert.Equal(new TimeOnly(7, 8, 9), items[0].Time); @@ -114,7 +114,7 @@ public static void NullInANonNullableMember_IsAnError() { var cmd = Cmd([("Day", typeof(DateTime)), ("Time", typeof(TimeSpan))], new object?[] { null, null }); // one row of two NULLs, not two rows - NullAssert.Model(0, () => cmd.Map().ToList()); + NullAssert.Model(0, () => cmd.Map(RowMap.Default).ToList()); } [Fact] @@ -124,7 +124,7 @@ public static void Text_ThatIsNotADate_ThrowsValueMappingException_WithTheCause( NullAssert.Check( "Unable to map row 0 to 'Stamps'.", - Assert.Throws(() => cmd.Map().ToList())); + Assert.Throws(() => cmd.Map(RowMap.Default).ToList())); } [Fact] @@ -134,6 +134,6 @@ public static void ANumber_IsNotADate_ThrowsValueMappingException() NullAssert.Check( "Unable to map row 0 to 'Stamps': a NULL was read into a non-nullable member, or a column's type does not convert to its member's. Declare the member nullable (int?, string?), or match the member's type to the column's.", - Assert.Throws(() => cmd.Map().ToList())); + Assert.Throws(() => cmd.Map(RowMap.Default).ToList())); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/RowMapNullTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RowMapNullTests.cs index e3ca4557..956bffd5 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RowMapNullTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RowMapNullTests.cs @@ -105,7 +105,7 @@ public static void NullInANonNullableValueColumn_IsAnError(string column) } // Map() with no map is the same. - NullAssert.Model(0, () => Cmd(SolidColumns, SolidRow(column)).Map().ToList()); + NullAssert.Model(0, () => Cmd(SolidColumns, SolidRow(column)).Map(RowMap.Default).ToList()); } [Fact] diff --git a/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs b/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs index 7f68bfd3..4432e9e7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/RowMapperTests.cs @@ -79,7 +79,7 @@ static FakeExecuteReader SimpleRows(int count) [Fact] public static void Typed_MapsEveryType_IncludingNulls() { - var items = Cmd(WideColumns, WideRows()).Map().ToList(); + var items = Cmd(WideColumns, WideRows()).Map(RowMap.Default).ToList(); Assert.Equal(2, items.Count); Wide a = items[0], b = items[1]; @@ -108,7 +108,7 @@ public static void Typed_MapsEveryType_IncludingNulls() public static void Typed_NullInNonNullableValueProperty_IsAnError() { var cmd = Cmd([("Id", typeof(int)), ("Name", typeof(string))], [null, "x"]); - NullAssert.Model(0, () => cmd.Map().ToList()); + NullAssert.Model(0, () => cmd.Map(RowMap.Default).ToList()); } [Fact] @@ -116,7 +116,7 @@ public static void Conversion_AFailure_ThrowsValueMappingException_WithTheModelR { var cmd = Cmd([("Id", typeof(string)), ("Name", typeof(string))], ["abc", "x"]); // text that is not an int - var ex = Assert.Throws(() => cmd.Map().ToList()); + var ex = Assert.Throws(() => cmd.Map(RowMap.Default).ToList()); NullAssert.Check("Unable to map row 0 to 'Simple'.", ex); } @@ -124,7 +124,7 @@ public static void Conversion_AFailure_ThrowsValueMappingException_WithTheModelR [Fact] public static void ValueMappingException_IsADataException_NotAnInvalidOperationException() { - Exception ex = Assert.Throws(() => Cmd([("Id", typeof(string))], ["abc"]).Map().ToList()); + Exception ex = Assert.Throws(() => Cmd([("Id", typeof(string))], ["abc"]).Map(RowMap.Default).ToList()); Assert.False(ex is InvalidOperationException); Assert.IsType(ex, exactMatch: false); @@ -142,7 +142,7 @@ public static void Typed_ConversionsBetweenColumnAndPropertyTypes() [7, 8L, 9.5m, 2, "Green", Id1.ToString(), 42, 11L], [8, 9L, 1m, 1, "Red", Id2.ToString(), 43, null]); - var items = cmd.Map().ToList(); + var items = cmd.Map(RowMap.Default).ToList(); Assert.Equal(7L, items[0].FromInt); Assert.Equal(8, items[0].FromLong); @@ -164,7 +164,7 @@ public static void Columns_AreMatchedIgnoringCase_AndUnmappedOnesIgnored() { var cmd = Cmd([("ID", typeof(int)), ("nAmE", typeof(string)), ("Extra", typeof(string))], [5, "five", "ignored"]); - Simple item = cmd.Map().ToList().Single(); + Simple item = cmd.Map(RowMap.Default).ToList().Single(); Assert.Equal(5, item.Id); Assert.Equal("five", item.Name); } @@ -172,7 +172,7 @@ public static void Columns_AreMatchedIgnoringCase_AndUnmappedOnesIgnored() [Fact] public static void MissingColumns_LeaveDefaults() { - Simple item = Cmd([("Id", typeof(int))], [9]).Map().ToList().Single(); + Simple item = Cmd([("Id", typeof(int))], [9]).Map(RowMap.Default).ToList().Single(); Assert.Equal(9, item.Id); Assert.Null(item.Name); } @@ -198,7 +198,7 @@ public static void Overrides_UnknownField_Throws() public static void DuplicateColumnNames_FirstWins() { var cmd = Cmd([("Id", typeof(int)), ("Id", typeof(int))], [1, 2]); - Assert.Equal(1, cmd.Map().ToList().Single().Id); + Assert.Equal(1, cmd.Map(RowMap.Default).ToList().Single().Id); } // More distinct overrides (and layouts) than the cache bounds: results stay correct when entries are evicted. @@ -221,8 +221,8 @@ public static void Plans_AreCachedPerLayout_AndSwitchBetweenLayouts() for (int i = 0; i < 3; i++) { - Simple x = Cmd(a, [1, "one"]).Map().ToList().Single(); - Simple y = Cmd(b, ["two", 2L]).Map().ToList().Single(); + Simple x = Cmd(a, [1, "one"]).Map(RowMap.Default).ToList().Single(); + Simple y = Cmd(b, ["two", 2L]).Map(RowMap.Default).ToList().Single(); Assert.Equal((1, "one"), (x.Id, x.Name)); Assert.Equal((2, "two"), (y.Id, y.Name)); } @@ -233,22 +233,22 @@ public static void Plans_AreCachedPerLayout_AndSwitchBetweenLayouts() public static void Narrowing_OverflowThrows_InsteadOfWrapping() { var cmd = Cmd([("Id", typeof(long)), ("Name", typeof(string))], [4_294_967_301L, "x"]); - var ex = Assert.Throws(() => cmd.Map().ToList()); + var ex = Assert.Throws(() => cmd.Map(RowMap.Default).ToList()); NullAssert.Check("Unable to map row 0 to 'Simple'.", ex); } [Fact] public static void Narrowing_InRange_Works_AndFractionalToIntegerRounds() { - Assert.Equal(7, Cmd([("Id", typeof(long))], [7L]).Map().ToList().Single().Id); - Assert.Equal(4, Cmd([("Id", typeof(double))], [3.7]).Map().ToList().Single().Id); // Convert.ChangeType semantics. + Assert.Equal(7, Cmd([("Id", typeof(long))], [7L]).Map(RowMap.Default).ToList().Single().Id); + Assert.Equal(4, Cmd([("Id", typeof(double))], [3.7]).Map(RowMap.Default).ToList().Single().Id); // Convert.ChangeType semantics. } [Fact] public static void ByteArray_ToString_IsRejected() { var cmd = Cmd([("Id", typeof(int)), ("Name", typeof(byte[]))], [1, new byte[] { 1, 2 }]); - Assert.Throws(() => cmd.Map().ToList()); + Assert.Throws(() => cmd.Map(RowMap.Default).ToList()); } [Fact] @@ -264,7 +264,7 @@ public static void OverrideKeys_AreUnambiguous() public static void ProviderExceptions_AreNotWrapped() { var cmd = new FakeExecuteReader(() => new ThrowingReader()); - Assert.Throws(() => cmd.Map().ToList()); + Assert.Throws(() => cmd.Map(RowMap.Default).ToList()); } sealed class ThrowingReader() : TypedReader([("Id", typeof(int)), ("Name", typeof(string))], [[1, "x"]]) @@ -281,14 +281,14 @@ public static void Take_StopsReadingOnceSatisfied() { var cmd = Cmd(out var reader, [("Id", typeof(int))], [1], [2], [3], [4]); - Assert.Equal([1, 2], cmd.Map().Take(2).ToList().Select(s => s.Id)); + Assert.Equal([1, 2], cmd.Map(RowMap.Default).Take(2).ToList().Select(s => s.Id)); Assert.Equal(2, reader()!.RowsRead); } [Fact] public static void SkipThenTake_OnArray() { - var items = SimpleRows(10).Map().Skip(3).Take(4).ToArray(); + var items = SimpleRows(10).Map(RowMap.Default).Skip(3).Take(4).ToArray(); Assert.Equal([4, 5, 6, 7], items.Select(s => s.Id)); } @@ -297,17 +297,17 @@ public static void Take_Zero_ReadsNothing() { var cmd = Cmd(out var reader, [("Id", typeof(int))], [1], [2]); - Assert.Empty(cmd.Map().Take(0).ToList()); - Assert.Empty(cmd.Map().Take(0).ToArray()); + Assert.Empty(cmd.Map(RowMap.Default).Take(0).ToList()); + Assert.Empty(cmd.Map(RowMap.Default).Take(0).ToArray()); Assert.Equal(0, reader()!.RowsRead); } [Fact] public static void Skip_PastTheEnd_IsEmpty() { - Assert.Empty(SimpleRows(3).Map().Skip(10).ToList()); - Assert.Empty(SimpleRows(3).Map().Skip(10).ToArray()); - Assert.Null(SimpleRows(3).Map().Skip(10).FirstOrDefault()); + Assert.Empty(SimpleRows(3).Map(RowMap.Default).Skip(10).ToList()); + Assert.Empty(SimpleRows(3).Map(RowMap.Default).Skip(10).ToArray()); + Assert.Null(SimpleRows(3).Map(RowMap.Default).Skip(10).FirstOrDefault()); } [Fact] @@ -315,20 +315,20 @@ public static void FirstOrDefault_ReadsOnlyOneRow() { var cmd = Cmd(out var reader, [("Id", typeof(int))], [1], [2], [3]); - Assert.Equal(1, cmd.Map().FirstOrDefault()!.Id); + Assert.Equal(1, cmd.Map(RowMap.Default).FirstOrDefault()!.Id); Assert.Equal(1, reader()!.RowsRead); } [Fact] public static void FirstOrDefault_AfterSkip() - => Assert.Equal(3, SimpleRows(5).Map().Skip(2).FirstOrDefault()!.Id); + => Assert.Equal(3, SimpleRows(5).Map(RowMap.Default).Skip(2).FirstOrDefault()!.Id); [Fact] public static void SingleOrDefault_ThrowsOnSecondRow_UnlessTakeLimitsIt() { - Assert.Throws(() => SimpleRows(2).Map().SingleOrDefault()); - Assert.Equal(1, SimpleRows(2).Map().Take(1).SingleOrDefault()!.Id); - Assert.Null(SimpleRows(0).Map().SingleOrDefault()); + Assert.Throws(() => SimpleRows(2).Map(RowMap.Default).SingleOrDefault()); + Assert.Equal(1, SimpleRows(2).Map(RowMap.Default).Take(1).SingleOrDefault()!.Id); + Assert.Null(SimpleRows(0).Map(RowMap.Default).SingleOrDefault()); } public struct Point @@ -340,7 +340,7 @@ public struct Point [Fact] public static void ValueTypeModels_AreMapped() { - var points = Cmd([("X", typeof(int)), ("Y", typeof(int))], [1, 2], [3, 4]).Map().ToArray(); + var points = Cmd([("X", typeof(int)), ("Y", typeof(int))], [1, 2], [3, 4]).Map(RowMap.Default).ToArray(); Assert.Equal([(1, 2), (3, 4)], points.Select(p => (p.X, p.Y))); } @@ -354,7 +354,7 @@ public sealed class Guarded [Fact] public static void OnlyPublicSettersAreMapped() { - var item = Cmd([("Id", typeof(int)), ("ReadOnly", typeof(int)), ("PrivateSet", typeof(int))], [1, 99, 99]).Map().ToList().Single(); + var item = Cmd([("Id", typeof(int)), ("ReadOnly", typeof(int)), ("PrivateSet", typeof(int))], [1, 99, 99]).Map(RowMap.Default).ToList().Single(); Assert.Equal((1, 5, 6), (item.Id, item.ReadOnly, item.PrivateSet)); } @@ -368,21 +368,21 @@ public static void Selector_RunsOverTypedReader() [Fact] public static void DictionaryHashSetAndImmutableArray_BuildDirectly() { - var dictionary = SimpleRows(4).Map().Skip(1).ToDictionary(s => s.Id); + var dictionary = SimpleRows(4).Map(RowMap.Default).Skip(1).ToDictionary(s => s.Id); Assert.Equal([2, 3, 4], dictionary.Keys.OrderBy(k => k)); Assert.Equal("n3", dictionary[3].Name); - var set = SimpleRows(4).Map().Take(3).ToHashSet(new IdComparer()); + var set = SimpleRows(4).Map(RowMap.Default).Take(3).ToHashSet(new IdComparer()); Assert.Equal(3, set.Count); - var immutable = SimpleRows(3).Map().ToImmutableArray(); + var immutable = SimpleRows(3).Map(RowMap.Default).ToImmutableArray(); Assert.Equal([1, 2, 3], immutable.Select(s => s.Id)); - Assert.True(SimpleRows(0).Map().ToImmutableArray().IsEmpty); + Assert.True(SimpleRows(0).Map(RowMap.Default).ToImmutableArray().IsEmpty); } [Fact] public static void Dictionary_DuplicateKey_Throws() - => Assert.Throws(() => SimpleRows(3).Map().ToDictionary(_ => 1)); + => Assert.Throws(() => SimpleRows(3).Map(RowMap.Default).ToDictionary(_ => 1)); sealed class IdComparer : IEqualityComparer { @@ -397,13 +397,13 @@ public static async Task Async_DictionaryHashSetAndImmutableArray() { var ct = TestContext.Current.CancellationToken; - var dictionary = await SimpleRows(4).Map().Take(2).ToDictionaryAsync(s => s.Name!, cancellationToken: ct); + var dictionary = await SimpleRows(4).Map(RowMap.Default).Take(2).ToDictionaryAsync(s => s.Name!, cancellationToken: ct); Assert.Equal(["n1", "n2"], dictionary.Keys.OrderBy(k => k)); - var set = await SimpleRows(5).Map().Skip(1).ToHashSetAsync(new IdComparer(), ct); + var set = await SimpleRows(5).Map(RowMap.Default).Skip(1).ToHashSetAsync(new IdComparer(), ct); Assert.Equal(4, set.Count); - var immutable = await SimpleRows(3).Map().ToImmutableArrayAsync(ct); + var immutable = await SimpleRows(3).Map(RowMap.Default).ToImmutableArrayAsync(ct); Assert.Equal([1, 2, 3], immutable.Select(s => s.Id)); } @@ -412,18 +412,18 @@ public static async Task Async_ListArrayFirstSingle() { var ct = TestContext.Current.CancellationToken; - var list = await SimpleRows(4).Map().ToListAsync(ct); + var list = await SimpleRows(4).Map(RowMap.Default).ToListAsync(ct); Assert.Equal([1, 2, 3, 4], list.Select(s => s.Id)); - var array = await SimpleRows(4).Map().Skip(1).Take(2).ToArrayAsync(ct); + var array = await SimpleRows(4).Map(RowMap.Default).Skip(1).Take(2).ToArrayAsync(ct); Assert.Equal([2, 3], array.Select(s => s.Id)); - var first = await SimpleRows(4).Map().Skip(2).FirstOrDefaultAsync(ct); + var first = await SimpleRows(4).Map(RowMap.Default).Skip(2).FirstOrDefaultAsync(ct); Assert.Equal(3, first!.Id); - Assert.Null(await SimpleRows(0).Map().FirstOrDefaultAsync(ct)); - Assert.Equal(1, (await SimpleRows(1).Map().SingleOrDefaultAsync(ct))!.Id); - await Assert.ThrowsAsync(async () => await SimpleRows(2).Map().SingleOrDefaultAsync(ct)); + Assert.Null(await SimpleRows(0).Map(RowMap.Default).FirstOrDefaultAsync(ct)); + Assert.Equal(1, (await SimpleRows(1).Map(RowMap.Default).SingleOrDefaultAsync(ct))!.Id); + await Assert.ThrowsAsync(async () => await SimpleRows(2).Map(RowMap.Default).SingleOrDefaultAsync(ct)); } [Fact] @@ -432,7 +432,7 @@ public static async Task Async_Stream_HonorsSkipAndTake() var ct = TestContext.Current.CancellationToken; var ids = new List(); - await foreach (Simple s in SimpleRows(10).Map().Skip(2).Take(3).Stream(Timeout.InfiniteTimeSpan, ct)) + await foreach (Simple s in SimpleRows(10).Map(RowMap.Default).Skip(2).Take(3).Stream(Timeout.InfiniteTimeSpan, ct)) ids.Add(s.Id); Assert.Equal([3, 4, 5], ids); @@ -444,6 +444,6 @@ public static async Task Async_Cancelled_Throws() using var cts = new CancellationTokenSource(); cts.Cancel(); - await Assert.ThrowsAnyAsync(async () => await SimpleRows(3).Map().ToListAsync(cts.Token)); + await Assert.ThrowsAnyAsync(async () => await SimpleRows(3).Map(RowMap.Default).ToListAsync(cts.Token)); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/SequentialAccessOrderTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SequentialAccessOrderTests.cs index 2ecbb47f..b6c85d31 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SequentialAccessOrderTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SequentialAccessOrderTests.cs @@ -92,7 +92,7 @@ public static void MapOfT_ReadsEachRowInColumnOrder_WhateverTheDeclarationOrder( SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(3)); - var items = command.Map().ToList(); + var items = command.Map(RowMap.Default).ToList(); Assert.Equal(3, items.Count); for (int n = 1; n <= 3; n++) @@ -110,7 +110,7 @@ public static void NullCells_AreStillReadInColumnOrder() SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(2, withNulls: true)); - var items = command.Map().ToList(); + var items = command.Map(RowMap.Default).ToList(); Assert.All(items, item => { @@ -122,7 +122,7 @@ public static void NullCells_AreStillReadInColumnOrder() // A NULL into the non-nullable Alpha, the last column read, is the error of that row. var alphaNull = new SequentialReader(Columns, [Row(1), [.. Row(2)[..^1], null]]); - NullAssert.Model(1, () => new FakeExecuteReader(() => alphaNull).Map().ToList()); + NullAssert.Model(1, () => new FakeExecuteReader(() => alphaNull).Map(RowMap.Default).ToList()); } [Fact] @@ -155,7 +155,7 @@ public static async Task TheAsyncRead_ReadsInColumnOrderToo() SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(2)); - List items = await command.Map().ToListAsync(TestContext.Current.CancellationToken); + List items = await command.Map(RowMap.Default).ToListAsync(TestContext.Current.CancellationToken); Assert.Equal(2, items.Count); AssertAscendingAndComplete(reader!, 2); @@ -205,7 +205,7 @@ public static void APositionalRecord_IsReadInColumnOrder_WhateverTheParameterOrd SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(3)); - var items = command.Map().ToList(); + var items = command.Map(RowMap.Default).ToList(); Assert.Equal(3, items.Count); for (int n = 1; n <= 3; n++) @@ -223,7 +223,7 @@ public static void ParametersThatReadTheFirstColumns_AreReadInColumnOrderToo() SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(2)); - var items = command.Map().ToList(); + var items = command.Map(RowMap.Default).ToList(); Assert.Equal(2, items.Count); for (int n = 1; n <= 2; n++) @@ -239,7 +239,7 @@ public static void ParametersThatReadTheFirstColumns_AreReadInColumnOrderToo() public static void AGeneralPathProperty_OfAConstructorModel_IsReadOnce_AndSetAfterTheConstructor() { SequentialReader? reader = null; - var items = new FakeExecuteReader(() => reader = NewReader(2)).Map().ToList(); + var items = new FakeExecuteReader(() => reader = NewReader(2)).Map(RowMap.Default).ToList(); Assert.Equal(2, items.Count); Assert.All(items, item => Assert.Equal(Shade.Green, item.Epsilon)); @@ -248,7 +248,7 @@ public static void AGeneralPathProperty_OfAConstructorModel_IsReadOnce_AndSetAft // A NULL text cell into the non-nullable property is an error, and the cell was read once. ImmutableArray columns = [("Eta", typeof(int)), ("Epsilon", typeof(string)), ("Delta", typeof(int))]; var nulls = new SequentialReader(columns, [[1, null, null]]); - NullAssert.Model(0, () => new FakeExecuteReader(() => nulls).Map().ToList()); + NullAssert.Model(0, () => new FakeExecuteReader(() => nulls).Map(RowMap.Default).ToList()); Assert.Equal(1, nulls.TouchedPerRow.Single().Count(o => o == 1)); } @@ -258,7 +258,7 @@ public static void NullCells_OfAConstructorModel_AreStillReadInColumnOrder() SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(2, withNulls: true)); - var records = command.Map().ToList(); + var records = command.Map(RowMap.Default).ToList(); Assert.All(records, item => { Assert.Null(item.Beta); @@ -267,7 +267,7 @@ public static void NullCells_OfAConstructorModel_AreStillReadInColumnOrder() Assert.Equal([3, 4], records.Select(r => r.Alpha)); AssertEachCellOnceInOrder(reader!, 2); - var leading = new FakeExecuteReader(() => reader = NewReader(2, withNulls: true)).Map().ToList(); + var leading = new FakeExecuteReader(() => reader = NewReader(2, withNulls: true)).Map(RowMap.Default).ToList(); Assert.All(leading, item => { Assert.Null(item.Beta); @@ -309,7 +309,7 @@ public static async Task TheAsyncRead_OfAConstructorModel_ReadsInColumnOrderToo( SequentialReader? reader = null; var command = new FakeExecuteReader(() => reader = NewReader(2)); - List items = await command.Map().ToListAsync(TestContext.Current.CancellationToken); + List items = await command.Map(RowMap.Default).ToListAsync(TestContext.Current.CancellationToken); Assert.Equal(2, items.Count); AssertEachCellOnceInOrder(reader!, 2); diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/FakeReader.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/FakeReader.cs index 03753bac..14cb007e 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/FakeReader.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/FakeReader.cs @@ -60,6 +60,22 @@ static void Configure(IDataReader reader, IReadOnlyList columns, object? reader.Read().Returns(_ => c.MoveNext()); reader.GetValue(Arg.Any()).Returns(ci => AsDbValue(c.Current[ci.Arg()])); + + // The typed getters, as a provider has them: the value cast to the getter's type, never converted, so a NULL or another type throws. + object Cell(NSubstitute.Core.CallInfo ci) => AsDbValue(c.Current[ci.Arg()]); + reader.IsDBNull(Arg.Any()).Returns(ci => Cell(ci) is DBNull); + reader.GetBoolean(Arg.Any()).Returns(ci => (bool)Cell(ci)); + reader.GetByte(Arg.Any()).Returns(ci => (byte)Cell(ci)); + reader.GetInt16(Arg.Any()).Returns(ci => (short)Cell(ci)); + reader.GetInt32(Arg.Any()).Returns(ci => (int)Cell(ci)); + reader.GetInt64(Arg.Any()).Returns(ci => (long)Cell(ci)); + reader.GetFloat(Arg.Any()).Returns(ci => (float)Cell(ci)); + reader.GetDouble(Arg.Any()).Returns(ci => (double)Cell(ci)); + reader.GetDecimal(Arg.Any()).Returns(ci => (decimal)Cell(ci)); + reader.GetString(Arg.Any()).Returns(ci => (string)Cell(ci)); + reader.GetDateTime(Arg.Any()).Returns(ci => (DateTime)Cell(ci)); + reader.GetGuid(Arg.Any()).Returns(ci => (Guid)Cell(ci)); + reader[Arg.Any()].Returns(ci => AsDbValue(c.Current[ci.Arg()])); reader[Arg.Any()].Returns(ci => AsDbValue(c.Current[OrdinalOf(columns, ci.Arg())])); diff --git a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs index dcecfae5..05333627 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs @@ -128,9 +128,9 @@ public void A_row_reader_is_the_reads_and_nothing_else(string model) // The literal reader is a static lambda (nothing captured: a closed delegate with no thunk); every row reader is NoInlining, so its frame is on // the stack trace of what it throws (how Core's loop tells it from its own Read). Assert.Matches(@"ReadLiteral = \[global::System\.Runtime\.CompilerServices\.MethodImpl\(global::System\.Runtime\.CompilerServices\.MethodImplOptions\.NoInlining\)\] static \(", readers); - // A model that declares every ordinal has the literal reader alone; the others also have the three that read a layout's ordinals. + // A model that declares every ordinal has the literal reader alone; the others also have the two that read a layout's ordinals. bool trusted = model is "GenRowD20" or "DecoratedPost" or "DecoratedRecord" or "DecoratedInit" or "OrderedStruct" or "OrderedGapPost" or "OrderedDatePost" or "OrderedUnsignedPost" or "OrderedKindsPost"; - Assert.Equal(trusted ? 0 : 3, LayoutReader().Count(readers)); + Assert.Equal(trusted ? 0 : 2, LayoutReader().Count(readers)); Assert.Equal(!trusted, Binder(GeneratedSource(), model).Contains("Matches(r)", StringComparison.Ordinal)); } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs b/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs index 9ce6025f..04f99734 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/Harness.cs @@ -108,7 +108,6 @@ internal readonly record struct Counts( long Full, long Guarded, long Literal, - long Converting, long Identity) { public static Counts Now() => new( @@ -118,8 +117,7 @@ internal readonly record struct Counts( Interlocked.Read(ref OdxGeneratedCounters.Modes[1]), Interlocked.Read(ref OdxGeneratedCounters.Modes[2]), Interlocked.Read(ref OdxGeneratedCounters.Modes[3]), - Interlocked.Read(ref OdxGeneratedCounters.Modes[4]), - Interlocked.Read(ref OdxGeneratedCounters.Modes[5])); + Interlocked.Read(ref OdxGeneratedCounters.Modes[4])); public Counts Since(Counts start) => new( Intercepted - start.Intercepted, @@ -128,7 +126,6 @@ internal readonly record struct Counts( Full - start.Full, Guarded - start.Guarded, Literal - start.Literal, - Converting - start.Converting, Identity - start.Identity); } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/NullByTypeTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/NullByTypeTests.cs new file mode 100644 index 00000000..1665f3b4 --- /dev/null +++ b/Tests/Open.Database.Extensions.Generator.Tests/NullByTypeTests.cs @@ -0,0 +1,142 @@ +using Microsoft.Data.SqlClient; +using Microsoft.Data.Sqlite; +using System.Data; + +namespace Open.Database.Extensions.Generator.Tests; + +// A NULL cell by the member's type, on real providers: the generated reader and the runtime map give the same row, or both fail the row. + +public sealed class NullableKinds +{ + public int Id { get; set; } + public string? Text { get; set; } + public byte[]? Blob { get; set; } + public Uri? Link { get; set; } + public DateTimeOffset? At { get; set; } + public int? Number { get; set; } +} + +public sealed class RequiredText +{ + public string Value { get; set; } = ""; +} + +public sealed class RequiredBytes +{ + public byte[] Value { get; set; } = []; +} + +public sealed class RequiredUri +{ + public Uri Value { get; set; } = null!; +} + +public sealed class RequiredOffset +{ + public DateTimeOffset Value { get; set; } +} + +public class NullByTypeTests +{ + const string SqliteNulls = "select 1 as Id, NULL as Text, NULL as Blob, NULL as Link, NULL as At, NULL as Number"; + + const string SqlServerNulls = """ + SELECT 1 AS Id, CAST(NULL AS nvarchar(10)) AS Text, CAST(NULL AS varbinary(10)) AS Blob, CAST(NULL AS nvarchar(100)) AS Link, + CAST(NULL AS datetimeoffset) AS At, CAST(NULL AS int) AS Number + """; + + static void SameNulls(IDbCommand command, string sql) + { + command.CommandText = sql; + var start = Counts.Now(); + var generated = command.Map().ToList(); + Assert.Equal(1, Counts.Now().Since(start).Served); + + Parity.SameRows(command.Map(RowMap.Default).ToList(), generated); + NullableKinds row = generated.Single(); + Assert.Null(row.Text); + Assert.Null(row.Blob); + Assert.Null(row.Link); + Assert.Null(row.At); + Assert.Null(row.Number); + } + + // The generated call is written at each caller: a call over a type parameter is not intercepted. + static string Fails(Func read, Func runtimeRead) + { + var start = Counts.Now(); + var generated = Assert.Throws(read); + Assert.Equal(1, Counts.Now().Since(start).Served); + + var runtime = Assert.Throws(runtimeRead); + Assert.Equal(typeof(T), generated.TargetType); + Assert.Equal(typeof(T), runtime.TargetType); + return $"{typeof(T).Name}: runtime {runtime.InnerException?.GetType().Name}, generated {generated.InnerException?.GetType().Name}"; + } + + static string[] Failures(IDbCommand command, string nullAsValue) + { + command.CommandText = nullAsValue; + return + [ + Fails(() => command.Map().ToList(), () => command.Map(RowMap.Default).ToList()), + Fails(() => command.Map().ToList(), () => command.Map(RowMap.Default).ToList()), + Fails(() => command.Map().ToList(), () => command.Map(RowMap.Default).ToList()), + Fails(() => command.Map().ToList(), () => command.Map(RowMap.Default).ToList()), + ]; + } + + [Fact] + public void Sqlite_NULL_in_a_nullable_member_of_each_kind_is_null_as_in_the_runtime_map() + { + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + using SqliteCommand command = connection.CreateCommand(); + SameNulls(command, SqliteNulls); + } + + [Fact] + public void SqlServer_NULL_in_a_nullable_member_of_each_kind_is_null_as_in_the_runtime_map() + { + LocalDb.SkipUnlessAvailable(); + using var connection = new SqlConnection(LocalDb.ConnectionString); + connection.Open(); + using SqlCommand command = connection.CreateCommand(); + SameNulls(command, SqlServerNulls); + } + + [Fact] + public void Sqlite_NULL_in_a_non_nullable_member_of_each_kind_fails_as_in_the_runtime_map() + { + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + using SqliteCommand command = connection.CreateCommand(); + // Microsoft.Data.Sqlite's getters throw InvalidOperationException on a NULL; byte[] is a plain cast (README, Known differences). + Assert.Equal( + [ + "RequiredText: runtime SqlNullValueException, generated InvalidOperationException", + "RequiredBytes: runtime SqlNullValueException, generated InvalidCastException", + "RequiredUri: runtime SqlNullValueException, generated InvalidOperationException", + "RequiredOffset: runtime SqlNullValueException, generated InvalidOperationException", + ], + Failures(command, "select NULL as Value")); + } + + [Fact] + public void SqlServer_NULL_in_a_non_nullable_member_of_each_kind_fails_as_in_the_runtime_map() + { + LocalDb.SkipUnlessAvailable(); + using var connection = new SqlConnection(LocalDb.ConnectionString); + connection.Open(); + using SqlCommand command = connection.CreateCommand(); + // SqlClient's getters throw SqlNullValueException, as the runtime map does; byte[] is a plain cast (README, Known differences). + Assert.Equal( + [ + "RequiredText: runtime SqlNullValueException, generated SqlNullValueException", + "RequiredBytes: runtime SqlNullValueException, generated InvalidCastException", + "RequiredUri: runtime SqlNullValueException, generated SqlNullValueException", + "RequiredOffset: runtime SqlNullValueException, generated SqlNullValueException", + ], + Failures(command, "SELECT CAST(NULL AS nvarchar(100)) AS Value")); + } +} diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs index 8eef5cc9..3e409357 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs @@ -269,15 +269,11 @@ public void A_provider_failure_mid_row_reports_the_row_in_every_read_mode() FaultReport(PostRuntime, PostGenerated, typeof(PlainPost), partial, partialRows, 1, 2, c => c.Guarded); FaultReport(PostRuntime, PostGenerated, typeof(PlainPost), partial, partialRows, 1, 2, c => c.Guarded, sequential: true); - // A constructor parameter and a member set after the constructor, at constant ordinals (5) and through converting reads (4). + // A constructor parameter and a member set after the constructor, at constant ordinals (4). Col[] record = [Col.Of("Id"), Col.Of("Title"), Col.Of("Qty"), Col.Of("State"), Col.Of("Tag"), Col.Of("Note")]; object?[][] recordRows = [[1, "one", 2, 1, "t", "n"], [2, "two", 3, 2, "u", "m"]]; FaultReport(RecordRuntime, RecordGenerated, typeof(PlainRecord), record, recordRows, 1, 3, c => c.Identity); FaultReport(RecordRuntime, RecordGenerated, typeof(PlainRecord), record, recordRows, 1, 5, c => c.Identity); - Col[] converting = [Col.Of("Id"), Col.Of("Title"), Col.Of("Qty"), Col.Of("State"), Col.Of("Tag"), Col.Of("Note")]; - object?[][] convertingRows = [[1L, "one", 2L, 1, "t", "n"], [2L, "two", 3L, 2, "u", "m"]]; - FaultReport(RecordRuntime, RecordGenerated, typeof(PlainRecord), converting, convertingRows, 1, 2, c => c.Converting); - FaultReport(RecordRuntime, RecordGenerated, typeof(PlainRecord), converting, convertingRows, 1, 5, c => c.Converting); } [Fact] diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Null.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Null.cs index 15670f68..3ac8db0d 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Null.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Null.cs @@ -29,7 +29,7 @@ public void Null_in_each_non_nullable_member_reports_the_row_in_every_read_mode( var start = Counts.Now(); foreach (int column in NonNullablePostColumns) { - // Identity (5): the members in their order; a NULL in the middle of a result set (the row before it is read). + // Identity (4): the members in their order; a NULL in the middle of a result set (the row before it is read). var identity = new TableQuery(PostColumns, PostRows[0], PostRowWithNull(column), PostRows[2]); SameRowError(() => identity.Map(RowMap.Default).ToList(), () => identity.Map().ToList(), typeof(PlainPost), 1); @@ -50,18 +50,11 @@ public void Null_in_each_non_nullable_member_reports_the_row_in_every_read_mode( } [Fact] - public void Null_in_a_non_nullable_member_reports_the_row_when_guarded_or_converting() + public void Null_in_a_non_nullable_member_reports_the_row_when_guarded() { // Guarded (2): members absent, columns out of order. var guarded = new TableQuery([Col.Of("Note"), Col.Of("Id"), Col.Of("Title")], ["n", 1, "t"], [null, null, "u"]); SameRowError(() => guarded.Map(RowMap.Default).ToList(), () => guarded.Map().ToList(), typeof(PlainPost), 1); - - // Converting (4): a long column into the int member. - var converting = new TableQuery( - [Col.Of("Id"), Col.Of("Title"), Col.Of("Qty"), Col.Of("State"), Col.Of("Tag"), Col.Of("Note")], - [1L, "one", 2L, 1, "t", "n"], - [null, "two", null, 2, "b", null]); - SameRowError(() => converting.Map(RowMap.Default).ToList(), () => converting.Map().ToList(), typeof(PlainRecord), 1); } [Fact] diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Review.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Review.cs index 6877d8e5..7284ce0e 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Review.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Review.cs @@ -10,25 +10,6 @@ public partial class ParityTests { // ---- read modes ---- - [Fact] - public void Full_layout_with_a_converting_read_is_served_without_presence_tests() - { - // Every member fed in ascending order; Id and Qty come as long: the converting read is chosen once per layout (mode 4), not guarded. - var q = new TableQuery( - [Col.Of("Id"), Col.Of("Title"), Col.Of("Qty"), Col.Of("State"), Col.Of("Tag"), Col.Of("Note")], - [1L, "one", 2L, 1, "t", "n"], - [2L, "two", null, 2, "b", null]); - var runtime = q.Map(RowMap.Default).ToList(); - - var start = Counts.Now(); - var generated = q.Map().ToList(); - Counts c = Counts.Now().Since(start); - - Parity.SameRows(runtime, generated); - Served(c); - Assert.Equal(1, c.Converting); - } - [Fact] public void Order_without_a_name_reads_at_constant_ordinals() { @@ -147,7 +128,7 @@ static DataSet Sets() { var set = new DataSet(); set.Tables.Add(TableQuery.Table(PostColumns, PostRows)); - set.Tables.Add(TableQuery.Table([Col.Of("Title"), Col.Of("Id")], ["second", 7L], ["third", 8L])); + set.Tables.Add(TableQuery.Table([Col.Of("Title"), Col.Of("Id")], ["second", 7], ["third", 8])); return set; } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Shapes.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Shapes.cs index 4477ef01..bcbb1aac 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Shapes.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Shapes.cs @@ -335,11 +335,11 @@ public void A_NULL_or_another_column_type_for_a_dynamic_member_gives_what_the_ru () => nulls.Map().ToList(), typeof(DynamicPost), 0); - // An int column: no generated read for it, so the runtime map serves the result set. + // An int column: the member's read is a cast of GetValue, which takes any value. var numbers = new TableQuery([Col.Of("Id"), Col.Of("Value")], [1, 5]); var start = Counts.Now(); var generated = numbers.Map().ToList(); - Declined(Counts.Now().Since(start)); + Served(Counts.Now().Since(start)); Parity.SameRows(numbers.Map(RowMap.Default).ToList(), generated); } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.cs index 6a71b62c..2ed02557 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.cs @@ -92,7 +92,7 @@ public void Plain_full_layout_is_served() Parity.SameRows(runtime, generated); Served(c); - // The columns are the members in their declared order: the identity layout, read at constant ordinals (mode 5). + // The columns are the members in their declared order: the identity layout, read at constant ordinals (mode 4). Assert.Equal(1, c.Identity); Assert.Equal(PostRows.Length, generated.Count); Assert.Null(generated[1].Label); @@ -140,61 +140,24 @@ public void Plain_extra_and_missing_columns_are_served_guarded() Assert.Equal(1, c.Guarded); } - [Fact] - public void Plain_converting_reads_match_the_runtime() - { - var q = new TableQuery( - [ - Col.Of("Id"), // long → int - Col.Of("Created"), // string → DateTime (invariant) - Col.Of("Price"), // string → decimal (invariant) - Col.Of("Qty"), // short → int? - Col.Of("IsActive"), // integral → bool - Col.Of("Score"), // integral → double - Col.Of("Big"), // int → long - Col.Of("State"), // long → enum - ], - [7L, "2026-03-04T05:06:07", "12.50", (short)4, 1, 3, 11, 2L], - [8L, "2026-03-05", "-0.01", null, 0, -2, int.MinValue, 0L]); - - var runtime = q.Map(RowMap.Default).ToList(); - - var start = Counts.Now(); - var generated = q.Map().ToList(); - Counts c = Counts.Now().Since(start); - - Parity.SameRows(runtime, generated); - Served(c); - } - - [Fact] - public void Plain_overflow_reports_the_row_with_the_runtime_inner_exception() + // Each member is read by its own type, as a hand-written reader reads it: where the runtime map would convert, the provider's getter + // converts or throws, and the failure is reported as any mapping failure. DataTableReader converts nothing. + [Theory] + [InlineData("Id", typeof(long), 7L)] + [InlineData("Created", typeof(string), "2026-03-04T05:06:07")] + [InlineData("Price", typeof(string), "12.50")] + [InlineData("Qty", typeof(short), (short)4)] + [InlineData("IsActive", typeof(int), 1)] + [InlineData("Score", typeof(int), 3)] + [InlineData("State", typeof(long), 2L)] + public void A_column_the_member_s_getter_refuses_fails_though_the_runtime_converts(string column, Type type, object value) { - var q = new TableQuery([Col.Of("Id"), Col.Of("Big"), Col.Of("Qty")], [1, 2L, 5_000_000_000L]); + var q = new TableQuery([new Col(column, type)], [value]); + Assert.Single(q.Map(RowMap.Default).ToList()); var start = Counts.Now(); - Exception? generated = Catch(() => q.Map().ToList()); - Counts c = Counts.Now().Since(start); - - // Both name the model and the row, the conversion's exception inside. - RowError(generated, typeof(PlainPost), 0); - Parity.SameError(Catch(() => q.Map(RowMap.Default).ToList()), generated); - Served(c); - } - - [Fact] - public void Plain_unsupported_conversion_declines_to_the_runtime() - { - // No typed getter reads a string into an int: the runtime's general path decides, so the generated code hands the result set to it. - var q = new TableQuery([Col.Of("Id"), Col.Of("Title")], ["12", "a"], ["x", "b"]); - - var start = Counts.Now(); - SameOutcome( - () => q.Map(RowMap.Default).ToList(), - () => q.Map().ToList()); - Counts c = Counts.Now().Since(start); - - Declined(c); + RowError(Catch(() => q.Map().ToList()), typeof(PlainPost), 0); + Served(Counts.Now().Since(start)); } // ---- the decorated twin: declared names and ordinals are hard rules ---- @@ -295,7 +258,7 @@ public void Decorated_different_type_columns_swapped_fail_in_the_typed_read() Assert.Throws(() => q.Map().ToList()); } - // Not a rare case: with no look at the result there is no converting read either, as in a hand-written reader. + // Not a rare case: the member's getter reads the column, as in a hand-written reader. [Fact] public void Decorated_column_of_another_type_is_not_converted() { @@ -575,9 +538,9 @@ public void One_call_site_follows_each_layout_it_meets() { var byName = new TableQuery(PostColumns, PostRows); var reordered = new TableQuery( - [Col.Of("Title"), Col.Of("Id"), Col.Of("Unused")], - ["one", 1L, "x"], - ["two", 2L, null]); + [Col.Of("Title"), Col.Of("Id"), Col.Of("Unused")], + ["one", 1, "x"], + ["two", 2, null]); TableQuery[] queries = [byName, reordered, byName, reordered]; var start = Counts.Now(); diff --git a/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs new file mode 100644 index 00000000..c22e3f73 --- /dev/null +++ b/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs @@ -0,0 +1,61 @@ +using Microsoft.Data.Sqlite; + +namespace Open.Database.Extensions.Generator.Tests; + +// What the provider does with a column of another kind is the provider's. The one example the documentation gives, on SQLite. + +public sealed class SqliteFlag +{ + public bool Flag { get; set; } +} + +public sealed class SqliteRequired +{ + public int Id { get; set; } + public string Name { get; set; } = ""; +} + +public sealed class SqliteLink +{ + public Uri Link { get; set; } = null!; +} + +public class SqliteReadTests +{ + [Theory] + [InlineData("select NULL as Id, 'a' as Name")] + [InlineData("select 1 as Id, NULL as Name")] + public void Sqlite_NULL_into_a_non_nullable_number_or_string_fails(string sql) + { + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + + var start = Counts.Now(); + Assert.Throws(() => connection.Command(sql).Map().ToList()); + Assert.Equal(1, Counts.Now().Since(start).Served); + } + + [Fact] + public void Sqlite_NULL_into_a_class_member_read_by_GetFieldValue_fails() + { + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + + var start = Counts.Now(); + Assert.Throws(() => connection.Command("select NULL as Link").Map().ToList()); + Assert.Equal(1, Counts.Now().Since(start).Served); + } + + [Fact] + public void Sqlite_reads_the_text_true_into_a_bool_as_false() + { + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + + var start = Counts.Now(); + SqliteFlag row = connection.Command("select 'true' as Flag").Map().ToList().Single(); + Assert.Equal(1, Counts.Now().Since(start).Served); + + Assert.False(row.Flag); + } +} diff --git a/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs b/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs index d7178cc2..6da71e17 100644 --- a/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs +++ b/Tests/Open.Database.Extensions.PackageConsumer.Tests/ConsumerTests.cs @@ -186,15 +186,9 @@ public void Sqlite_file() Check(connection, "Posts"); - // SQLite stores a Guid as text. Without annotations the runtime map reads that result set; the values are the same. - long declined = Declined(); - List keyed = connection.Command("select Id, [Key] from Posts order by Id").Map().ToList(); + // SQLite stores a Guid as text: the member's getter, GetGuid, reads it. + List keyed = ServedBy(() => connection.Command("select Id, [Key] from Posts order by Id").Map().ToList()); Assert.Equal([(1, key), (2, key)], keyed.Select(p => (p.Id, p.Key))); -#if ODX_GENERATED - Assert.Equal(1, Declined() - declined); -#else - _ = declined; -#endif } finally { diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index b0fe50e9..1579eade 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -221,11 +221,11 @@ The attributes are read by their full name, so a model's own copy of them counts 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. -Two differences: - -- A model whose mapped members **all** declare `[Column(Order = n)]` is trusted. Its reader takes those positions with each member's own getter and looks at nothing else in the result, as a hand-written reader does: no declared name or column count is checked, and only what the provider's getter converts is converted. -- A NULL in a non-nullable `byte[]` or class member can be reported with `InvalidCastException` inside the `ValueMappingException`, where the runtime map reports `SqlNullValueException`. +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: +- **No conversions.** Only what the provider's getter converts is converted: elsewhere the read fails (`ValueMappingException`). What a provider does with a column of another kind (convert, coerce or throw), and the value it then gives, is the provider's: SQLite reads the text `'true'` into a `bool` as `false`. The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Generator/README.md#known-differences-from-the-runtime-map) lists the conversions the runtime map makes that a generated reader does not. Make the member the column's type, store an enum or a `Guid` as text only for a `string` member, or switch the generator off. +- A model whose mapped members **all** declare `[Column(Order = n)]` is trusted. Its reader takes those positions and looks at nothing else in the result: no declared name or column count is checked. +- A NULL in a non-nullable member is reported with the provider's or the cast's own exception inside the `ValueMappingException`, where the runtime map may report `SqlNullValueException`. To switch the generator off for a project (the setting applies to the project it is in: a library built with the generator keeps its generated readers): ```xml @@ -238,7 +238,7 @@ The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Ext ## Types and NULL -Values are read with the provider's typed getters (`GetInt32`, `GetString`, ...), so nothing is boxed on the common path. When the column type and the property type differ: +This section, and the NULL messages below, describe the runtime map; a [generated reader](#generated-readers) reads each member with its type's getter and converts nothing of its own. Values are read with the provider's typed getters (`GetInt32`, `GetString`, ...), so nothing is boxed on the common path. When the column type and the property type differ: - integers convert to other integer types and to enums, range-checked (an overflow throws `ValueMappingException`); - integers and floating-point values widen to `float`, `double` and `decimal`; diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 6e029427..56684d23 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -7,7 +7,7 @@ Version 11 is `11.0.0-rc.15`. For moving a 10.x codebase, read [Coming from earl ### 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). -- **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()` on a command or a reader gets its row reader written at build time. A model that declares every column's ordinal is read by position, unchecked. `false` switches it off. See [Generated readers](mapping.md#generated-readers). +- **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()` 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. `false` 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). - **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). From 6da004e1a9f994860944661238edd746d4d57b34 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:35:34 -0800 Subject: [PATCH 2/3] Source generator: prove the SQL Server type mismatch example, keep one example in the docs A SQL Server test shows that an int member over a bigint column fails, and it is now the only provider example in the generator README and the mapping article. A repeated NULL comment in the emitter header is shortened. Co-Authored-By: Claude Sonnet 5.5 --- Source/Generator/Emitter.cs | 9 ++---- Source/Generator/README.md | 5 +-- .../SqlServerReadTests.cs | 32 +++++++++++++++++++ .../SqliteReadTests.cs | 2 +- docsite/articles/mapping.md | 2 +- 5 files changed, 39 insertions(+), 11 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 92189415..f51bf63f 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -23,13 +23,8 @@ namespace Open.Database.Extensions.Generator; // - errors: Core's loop catches around the whole loop and reports a failure of the row reader as it reports a failure of the runtime's typed read: // a ValueMappingException naming the model type and the 0-based row (skipped rows counted), the exception inside; a DbException or a // cancellation passes through. Nothing is read from the reader after a failure. -// - NULL, by the member's type: a member declared non-nullable (a value type other than Nullable, a reference annotated non-nullable) is read -// with its typed getter alone, or by a plain cast of GetValue, as a hand-written reader reads it; a NULL there throws (the getter, or the cast). -// Only a type a cast of DBNull fits (object, an interface DBNull implements) makes the runtime's check and throws SqlNullValueException; a -// NULL in any other non-nullable reference read by GetValue (byte[], an interface) fails the cast (InvalidCastException). -// A nullable member (int?, string?, a reference in code with nullable annotations off) is tested with IsDBNull and gets null, which is stored -// (IsDBNull ? default : value) whatever the created model holds there, as the runtime map calls the setter of every property a column feeds. -// A model that declares NullPolicy or NullValue is not intercepted (ModelReader): the runtime map applies the policy. +// - NULL is handled by the member's type (see Statement). A model that declares NullPolicy or NullValue is not intercepted (ModelReader): the +// runtime map applies the policy. static class Emitter { const string Ns = "global::Open.Database.Extensions"; diff --git a/Source/Generator/README.md b/Source/Generator/README.md index 3a430340..47a8f575 100644 --- a/Source/Generator/README.md +++ b/Source/Generator/README.md @@ -38,8 +38,9 @@ Core's hidden entry `GeneratedRowMap.Create(Bind)` (for this generator only; - `DateTime` to `DateTimeOffset`, `DateOnly`, `TimeOnly` or `TimeSpan`, `TimeSpan` to `TimeOnly`, `DateTimeOffset` to `DateOnly` or `TimeOnly`; - and any other pair `Convert.ChangeType` converts. - What a provider does with a column of another kind (convert it, coerce it or throw) is the provider's, and so is the value it gives: SQLite, for one, - reads the text `'true'` into a `bool` member as `false`, without an error. Store an enum or a `Guid` as text only for a `string` member. + What a provider does with a column of another kind (convert it, coerce it or throw) is the provider's, and so is the value it gives: on SQL Server, + for one, an `int` member over a `bigint` column fails. Match the member type to the column, and store an enum or a `Guid` as text only for a + `string` member. - **A model that declares every column's ordinal is trusted.** When every mapped member has `[Column(Order = n)]`, the generated reader reads those positions and looks at nothing else in the result: no name or count, as a hand-written reader reads. Where another column the getter accepts sits at a position (a swapped or inserted column), it gives that value with no error; a missing column fails the read. The runtime map checks the diff --git a/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs new file mode 100644 index 00000000..fc0679bc --- /dev/null +++ b/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs @@ -0,0 +1,32 @@ +using Microsoft.Data.SqlClient; +using System.Data; + +namespace Open.Database.Extensions.Generator.Tests; + +// What the provider does with a column of another kind is the provider's. The one example the documentation gives, on SQL Server. + +public sealed class SqlServerCounted +{ + public int Total { get; set; } +} + +public class SqlServerReadTests +{ + [Fact] + public void SqlServer_an_int_member_over_a_bigint_column_fails() + { + LocalDb.SkipUnlessAvailable(); + using var connection = new SqlConnection(LocalDb.ConnectionString); + connection.Open(); + using SqlCommand sql = connection.CreateCommand(); + IDbCommand command = sql; + command.CommandText = "SELECT CAST(1 AS bigint) AS Total"; + + var start = Counts.Now(); + var error = Assert.Throws(() => command.Map().ToList()); + Assert.Equal(1, Counts.Now().Since(start).Served); + + Assert.IsType(error.InnerException); + Assert.Equal(typeof(SqlServerCounted), error.TargetType); + } +} diff --git a/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs index c22e3f73..6a6241ae 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/SqliteReadTests.cs @@ -2,7 +2,7 @@ namespace Open.Database.Extensions.Generator.Tests; -// What the provider does with a column of another kind is the provider's. The one example the documentation gives, on SQLite. +// What the provider does with a column of another kind is the provider's, on SQLite too. public sealed class SqliteFlag { diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 1579eade..e67ef06d 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -223,7 +223,7 @@ The Core package carries a source generator. With C# 12 or later and the .NET 9. 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: -- **No conversions.** Only what the provider's getter converts is converted: elsewhere the read fails (`ValueMappingException`). What a provider does with a column of another kind (convert, coerce or throw), and the value it then gives, is the provider's: SQLite reads the text `'true'` into a `bool` as `false`. The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Generator/README.md#known-differences-from-the-runtime-map) lists the conversions the runtime map makes that a generated reader does not. Make the member the column's type, store an enum or a `Guid` as text only for a `string` member, or switch the generator off. +- **No conversions.** Only what the provider's getter converts is converted: elsewhere the read fails (`ValueMappingException`). What a provider does with a column of another kind (convert, coerce or throw), and the value it then gives, is the provider's: on SQL Server, for one, an `int` member over a `bigint` column fails. The [generator's README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Generator/README.md#known-differences-from-the-runtime-map) lists the conversions the runtime map makes that a generated reader does not. Make the member the column's type, store an enum or a `Guid` as text only for a `string` member, or switch the generator off. - A model whose mapped members **all** declare `[Column(Order = n)]` is trusted. Its reader takes those positions and looks at nothing else in the result: no declared name or column count is checked. - A NULL in a non-nullable member is reported with the provider's or the cast's own exception inside the `ValueMappingException`, where the runtime map may report `SqlNullValueException`. To switch the generator off for a project (the setting applies to the project it is in: a library built with the generator keeps its generated readers): From 61ce6d0790f1434ee7d07a1f2b4516e4a406221c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:47:11 -0800 Subject: [PATCH 3/3] Source generator: fix the analyzer finding in the SQL Server test Co-Authored-By: Claude Sonnet 5.5 --- .../SqlServerReadTests.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs index fc0679bc..28e207cf 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/SqlServerReadTests.cs @@ -1,5 +1,4 @@ using Microsoft.Data.SqlClient; -using System.Data; namespace Open.Database.Extensions.Generator.Tests; @@ -18,8 +17,7 @@ public void SqlServer_an_int_member_over_a_bigint_column_fails() LocalDb.SkipUnlessAvailable(); using var connection = new SqlConnection(LocalDb.ConnectionString); connection.Open(); - using SqlCommand sql = connection.CreateCommand(); - IDbCommand command = sql; + using SqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT CAST(1 AS bigint) AS Total"; var start = Counts.Now();