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..f51bf63f 100644
--- a/Source/Generator/Emitter.cs
+++ b/Source/Generator/Emitter.cs
@@ -4,36 +4,31 @@ 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).
// - 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 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).
-// 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";
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 +93,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 +141,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 +163,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 +369,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 +387,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 +428,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 +451,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 +478,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 +488,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 +505,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 +536,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 +594,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 +616,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 +659,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 +700,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 +717,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..47a8f575 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,27 @@ 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: 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 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 +81,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