diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedControl.cs b/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedControl.cs index d4ea9d81..26610ba4 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedControl.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedControl.cs @@ -87,7 +87,7 @@ public static object ControlT20(IExecuteReader command) // CtlH_T: the same reads as ReadT20, written by hand on DbDataReader as a `static` lambda (a closed delegate, as the generated reader is), entering through // the GeneratedRowMap hook, so the entry (Map(RowMap)), the access mode and the delegate form are Gen_T's and only the generated code differs. The generated - // code also has two things this control leaves out, both read as part of a gap between them: its row reader is NoInlining, and its bind checks the + // code also has one thing this control leaves out, read as part of a gap between them: its bind checks the // result's columns once per result set (a fixed cost per query, visible with few rows). static readonly Func ReadT20Db = static r => new() { diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/GenParity.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/GenParity.cs index dfb0e6ae..a4b84d01 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/GenParity.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/GenParity.cs @@ -7,8 +7,8 @@ namespace Open.Database.Extensions.Benchmarks; // The ladder of the generated reader's row shape, at width 20, through the same Map(Func) entry V2 uses (SyntheticVariants.V2). // WHAT THE GENERATED READER DOES NOW: it enters through Map(RowMap) (Core's GeneratedRowMap hook); its row delegate is the reads and nothing else: a -// non-nullable member read UNCHECKED (no IsDBNull), a nullable member tested for NULL, NO try region; Core's loop reports a failure (one try/catch around -// the loop, as GP7 places it). The GP steps below are HISTORICAL steps toward V2n and toward former row shapes; they decompose the cost of those shapes, +// non-nullable member read UNCHECKED (no IsDBNull), a nullable member tested for NULL, NO try region; Core's loop reports a failure (a try around its +// call of the row reader). The GP steps below are HISTORICAL steps toward V2n and toward former row shapes; they decompose the cost of those shapes, // not of today's Gen. // V2n V2 plus IsDBNull on EVERY member (the former NULL rule: a NULL leaves the member's default), constant ordinals: the hand-written equal of a // check-every-member reader (named GP1 in the first decomposition run). GP2 to GP5 are V2n plus one thing each. @@ -29,8 +29,8 @@ namespace Open.Database.Extensions.Benchmarks; // cache line if queries ran in parallel); the row a failure reports is cumulative across queries, not the row of its own query as the generated // reader's per-binding counter gives. Nothing here checks the reported index. // GP7 the raw loop (as V10r): ExecuteReader's callback, while (db.Read()) list.Add(Read(db)), V2's read at constant ordinals on DbDataReader, -// with ONE try/catch around the whole loop (the row number a loop local): the placement the generator now gets from Core's loop through -// the GeneratedRowMap hook. GP7 and GP7c open the reader with the default behavior (as V10r, V2 and every +// with ONE try/catch around the whole loop (the row number a loop local): a placement Core's loop had before it +// caught around the row reader's call alone. GP7 and GP7c open the reader with the default behavior (as V10r, V2 and every // library read do), so GP7 against V2 or GP6 changes only the loop placement. GP7 against GP7c isolates the try. // GP7c GP7 with no try: the bar of the loop placement. // diff --git a/Source/Core/Core/RowErrors.cs b/Source/Core/Core/RowErrors.cs index 0a7643ef..0080630f 100644 --- a/Source/Core/Core/RowErrors.cs +++ b/Source/Core/Core/RowErrors.cs @@ -1,5 +1,4 @@ using System.Data.SqlTypes; -using System.Diagnostics; using System.Globalization; namespace Open.Database.Extensions; @@ -55,77 +54,33 @@ InvalidCastException when singleValue return new ValueMappingException(message, "", "", target, inner); } - // The read loops' filter. A runtime row reader carries its own failure to the loop (RowMappingFailure), and lets only a DbException or a - // cancellation through. A generated row reader (GeneratedRowMap) has no try region at all, so whatever else comes out of a loop over a - // generated map may be its failure: Report decides, on the failure path only. + // The read loops' filter, around the map call alone, so what it sees was thrown by the row reader. A runtime row reader carries its own + // failure to the loop (RowMappingFailure), and lets only a DbException or a cancellation through. A generated row reader + // (GeneratedRowMap) has no try region at all: anything else it throws is its failure. A caller's selector is not reported. /// - /// Returns whether a read loop over reports for the row. + /// Returns whether a read loop over reports , thrown by its row reader, for the row. /// /// The type of a mapped row. /// The mapping of the rows. - /// What the loop caught. - /// to hand it to ; otherwise, to let it through. + /// What the row reader threw. + /// to hand it to ; otherwise, to let it through. public static bool IsRowFailure(IRowSource source, Exception ex) => ex is RowMappingFailure || ex is not (DbException or OperationCanceledException) && source is RowMap { IsGenerated: true }; /// - /// Returns if is a generated map; otherwise, . - /// - // Only a generated reader's failure needs the reader to be known. A synchronous loop keeps this in a local of its own for its handler, - // so the handler does not read the loop's mapper (see RowReader.Fill). - public static Func? GeneratedReader(IRowSource source, Func map) - => source is RowMap { IsGenerated: true } ? map : null; - - /// - /// Returns the exception a read loop throws for a failure accepted, or to rethrow it unchanged. + /// Returns the exception a read loop throws for a failure accepted: it names the type and the row. /// /// - /// A runtime row reader's failure names the row. Any other failure is the generated row reader's when it was thrown from inside that reader - /// (its own frame is on the exception's stack trace): it is reported as the runtime reports its own typed read, the model and the row, the - /// exception inside. A failure of the loop's own Read or of the collection it fills is not the row's, and is rethrown as it is. + /// A generated row reader's failure is reported as the runtime reports its own typed read: the model and the row, the exception inside. /// Nothing is read from the reader here. /// - /// The type of the reader. /// The type of a mapped row. - /// What the loop caught. - /// The row reader the loop was calling; may be when the map is not generated. + /// What the row reader threw. /// The 0-based row in the result set. - /// The exception to throw, or . - public static Exception? Report(Exception ex, Func? map, int row) - => ex is RowMappingFailure failure ? failure.At(row) - : map is not null && ThrownBy(ex, map.Method) ? Create(ex, typeof(T), false, row) - : null; - - // Best effort, on the failure path only: the loop's try region also holds its Read and its Add, and only the row reader's own failure is - // attributed. The generated row readers are emitted NoInlining, so their frame is never folded into the loop by an inlining JIT. - // A stack trace without metadata (trimmed for NativeAOT) cannot tell: the failure is then attributed to the row. - /// - /// Returns whether is on the stack trace of . - /// - static bool ThrownBy(Exception ex, MethodInfo method) - { - // A runtime-compiled reader (a declined layout) is not a generated one, and its method has no declaring type and may refuse its metadata token. - // Its own failures arrive as RowMappingFailure, so this one is the loop's. - if (method.DeclaringType is null) return false; - - StackFrame[]? frames = new StackTrace(ex, false).GetFrames(); - if (frames is null) return true; - - Module module = method.Module; - int token = method.MetadataToken; - bool described = false; - foreach (StackFrame? frame in frames) - { - if (frame?.GetMethod() is not { } m) continue; - - described = true; - // The module first: a frame of a compiled expression is in no module of the generated code. - if (m.Module == module && m.MetadataToken == token) return true; - } - - return !described; - } + /// The exception to throw. + public static ValueMappingException Report(Exception ex, int row) + => ex is RowMappingFailure failure ? failure.At(row) : Create(ex, typeof(T), false, row); /// /// Returns the message for a NULL scalar read as a non-nullable value type. diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index 31b511dc..529cc37e 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -103,30 +103,29 @@ public static void Fill(IRowSource source, IDataReader reader, int if (!SkipRows(db, skip) || !db.Read()) return; Func map = source.Mapper(db); - // The handler's own reference to the reader (null unless generated). A handler that read map would keep it in the frame, - // and the loop would load it from there once per row. - Func? generated = RowErrors.GeneratedReader(source, map); int n = 0; - try + do { - do + T item; + try { - sink.Add(map(db)); - if (++n == take) - { - abandon?.CancelIfMore(db); - break; - } + item = map(db); + } + catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) + { + // The handler reads the sink's count, not n: a local the handler + // reads is stored to the frame on every update, once per row. + throw RowErrors.Report(ex, skip + sink.Count); + } + + sink.Add(item); + if (++n == take) + { + abandon?.CancelIfMore(db); + break; } - while (db.Read()); - } - catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) - { - // The handler reads the sink's count, not n: a local the handler - // reads is stored to the frame on every update, once per row. - if (RowErrors.Report(ex, generated, skip + sink.Count) is { } report) throw report; - throw; } + while (db.Read()); } /// Reads the rows into a . @@ -152,27 +151,28 @@ public static List ToList(IRowSource source, IDataReader reader, int sk if (!SkipRows(db, skip) || !db.Read()) return list; Func map = source.Mapper(db); - Func? generated = RowErrors.GeneratedReader(source, map); // See Fill. int n = 0; - try + do { - do + T item; + try { - list.Add(map(db)); - if (++n == take) - { - abandon?.CancelIfMore(db); - break; - } + item = map(db); + } + catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) + { + // The list's count, not n (see Fill). + throw RowErrors.Report(ex, skip + list.Count); + } + + list.Add(item); + if (++n == take) + { + abandon?.CancelIfMore(db); + break; } - while (db.Read()); - } - catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) - { - // The list's count, not n (see Fill). - if (RowErrors.Report(ex, generated, skip + list.Count) is { } report) throw report; - throw; } + while (db.Read()); return list; } @@ -249,14 +249,24 @@ public static T[] ToArray( if (!SkipRows(db, skip) || !db.Read()) return []; Func map = source.Mapper(db); - Func? generated = RowErrors.GeneratedReader(source, map); // See Fill. var buffer = new ArraySink(config); try { int n = 0; do { - buffer.Add(map(db)); + T item; + try + { + item = map(db); + } + catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) + { + // The buffer's count, not n (see Fill). + throw RowErrors.Report(ex, skip + buffer.Count); + } + + buffer.Add(item); if (++n == take) { abandon?.CancelIfMore(db); @@ -266,12 +276,6 @@ public static T[] ToArray( while (db.Read()); return buffer.ToArray(); } - catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) - { - // The buffer's count, not n (see Fill). - if (RowErrors.Report(ex, generated, skip + buffer.Count) is { } report) throw report; - throw; - } finally { buffer.Dispose(); @@ -381,9 +385,8 @@ public static IEnumerable Stream(IRowSource source, IDataReader reader, Func dbMap = source.Mapper(db); do { - // A try cannot hold a yield: it holds the map call only. The - // handler reads the iterator's fields; the row does nothing - // for it. + // The try holds the map call only. The handler reads the + // iterator's fields; the row does nothing for it. T item; try { @@ -391,8 +394,7 @@ public static IEnumerable Stream(IRowSource source, IDataReader reader, } catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) { - if (RowErrors.Report(ex, dbMap, first + n) is { } report) throw report; - throw; + throw RowErrors.Report(ex, first + n); } yield return item; @@ -420,8 +422,7 @@ public static IEnumerable Stream(IRowSource source, IDataReader reader, } catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) { - if (RowErrors.Report(ex, map, first + n) is { } report) throw report; - throw; + throw RowErrors.Report(ex, first + n); } yield return item; @@ -477,7 +478,8 @@ static bool SkipRows(DbDataReader reader, int skip) return true; } - // The loops that fill a collection catch around the loop: one try region for the whole loop. The iterators (Stream, StreamAsync) cannot catch around a yield, so they catch around the map call. The one-row terminals (First, Single) catch here. + // Every loop, and the one-row terminals (First, Single) here, catches around the map call alone: what is caught there is the row reader's + // failure. A Read, an Add or a cancel is outside it and passes through as it is. /// /// Maps the current row, and reports a failure of a row reader of the library for the row. /// @@ -496,8 +498,7 @@ static T MapAt(IRowSource source, Func map, TReader r } catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) { - if (RowErrors.Report(ex, map, row) is { } report) throw report; - throw; + throw RowErrors.Report(ex, row); } } @@ -547,25 +548,27 @@ public static async ValueTask FillAsync( Func map = source.Mapper(reader); int n = 0; - try + do { - do + T item; + try { - sink.Add(map(reader)); - if (++n == take) - { - if (abandon is not null) await abandon.CancelIfMoreAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false); - break; - } + item = map(reader); + } + catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) + { + // The sink's count, as in Fill. + throw RowErrors.Report(ex, skip + sink.Count); + } + + sink.Add(item); + if (++n == take) + { + if (abandon is not null) await abandon.CancelIfMoreAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false); + break; } - while (await ReadRowAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false)); - } - catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) - { - // The sink's count, as in Fill. - if (RowErrors.Report(ex, map, skip + sink.Count) is { } report) throw report; - throw; } + while (await ReadRowAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false)); return sink; } @@ -604,25 +607,27 @@ public static async ValueTask CollectAsync( { Func map = source.Mapper(reader); int n = 0; - try + do { - do + T item; + try { - chain.Add(map(reader)); - if (++n == take) - { - if (abandon is not null) await abandon.CancelIfMoreAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false); - break; - } + item = map(reader); + } + catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) + { + // The chain's count, as in Fill. + throw RowErrors.Report(ex, skip + chain.Count); + } + + chain.Add(item); + if (++n == take) + { + if (abandon is not null) await abandon.CancelIfMoreAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false); + break; } - while (await ReadRowAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false)); - } - catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) - { - // The chain's count, as in Fill. - if (RowErrors.Report(ex, map, skip + chain.Count) is { } report) throw report; - throw; } + while (await ReadRowAsync(reader, useReadAsync, cancellationToken).ConfigureAwait(false)); } // As in Collect. @@ -770,8 +775,7 @@ public static async IAsyncEnumerable StreamAsync( catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) { // As in Stream: the handler reads the iterator's fields. - if (RowErrors.Report(ex, map, skip + n) is { } report) throw report; - throw; + throw RowErrors.Report(ex, skip + n); } yield return item; diff --git a/Source/Core/Generation/GeneratedRowMap.cs b/Source/Core/Generation/GeneratedRowMap.cs index 4acea273..c7f93411 100644 --- a/Source/Core/Generation/GeneratedRowMap.cs +++ b/Source/Core/Generation/GeneratedRowMap.cs @@ -27,11 +27,6 @@ public static class GeneratedRowMap /// and the 0-based row (skipped rows counted), the exception inside; a or a cancellation passes through. /// A reader that is not a , object[] rows and a map made from this one (Convert) use the runtime map. /// - /// - /// A failure is reported that way when the row reader's own method is on the exception's stack trace: make the row reader a compiled method - /// marked . One that is inlined, or emitted at run time, can let the exception through unchanged. - /// Where a stack trace carries no method data (trimmed NativeAOT), a failure of the loop itself is reported for the row too. - /// /// /// The model type. /// diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index f51bf63f..5a914449 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -17,11 +17,9 @@ namespace Open.Database.Extensions.Generator; // * 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): 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 +// layout's ordinals from it. +// - errors: Core's loop catches around its call of the row reader alone and reports what the reader throws 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 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. @@ -29,7 +27,6 @@ static class Emitter { const string Ns = "global::Open.Database.Extensions"; const string DbReader = "global::System.Data.Common.DbDataReader"; - const string NoInlining = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; public static string Emit(IReadOnlyList sites, Options options) { @@ -498,7 +495,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] literal, string reader) { sb.AppendLine("\t\t// Every member at its constant ordinal: the reads, and nothing else."); - sb.AppendLine($"\t\tstatic readonly {reader} ReadLiteral = {NoInlining} static ({DbReader} r) =>"); + sb.AppendLine($"\t\tstatic readonly {reader} ReadLiteral = static ({DbReader} r) =>"); sb.AppendLine("\t\t{"); EmitRead(sb, m, styleB, ReadMode.Literal, literal, "\t\t\t"); sb.AppendLine("\t\t};"); @@ -572,7 +569,6 @@ static string Code(string name) // A row reader of the layout: an instance method (the delegate is closed over the layout, so no thunk), reading the layout's ordinals. static void EmitMethod(StringBuilder sb, ModelSpec m, string name, bool styleB, ReadMode mode, int[] literal) { - sb.AppendLine($"\t\t\t{NoInlining}"); sb.AppendLine($"\t\t\tpublic {m.Type} {name}({DbReader} r)"); sb.AppendLine("\t\t\t{"); EmitRead(sb, m, styleB, mode, literal, "\t\t\t\t"); diff --git a/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs b/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs index 5f316846..18793d72 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/GeneratedRowMapTests.cs @@ -1,4 +1,5 @@ using Open.Database.Extensions.Generation; +using System.Buffers; using System.Data.Common; using System.Data.SqlTypes; using System.Runtime.CompilerServices; @@ -19,7 +20,7 @@ internal sealed class HookRow /// /// What the source generator emits for , written by hand: a binder Core calls once per result set, and row readers that are the -/// reads and nothing else (no try region, no counter, no layout check), NoInlining as the generator emits them. +/// reads and nothing else (no try region, no counter, no layout check), as the generator emits them. /// [ExcludeFromCodeCoverage] internal sealed class HookBinder @@ -42,7 +43,7 @@ internal sealed class HookBinder { Interlocked.Increment(ref _calls); if (Decline) return null; - if (Fault is { } fault) return [MethodImpl(MethodImplOptions.NoInlining)] (row) => Throw(row, fault); + if (Fault is { } fault) return row => Throw(row, fault); // The layouts this binder serves: Id, Name[, ...] and Name, Id[, ...]; anything else is the runtime's. return r.FieldCount < 2 ? null @@ -51,20 +52,19 @@ internal sealed class HookBinder : null; } - [MethodImpl(MethodImplOptions.NoInlining)] static HookRow Throw(DbDataReader r, Func fault) { if (r is HookReader hook) hook.Faulted = true; throw fault(); } - static readonly Func Identity = [MethodImpl(MethodImplOptions.NoInlining)] static (r) => new() + static readonly Func Identity = static r => new() { Id = r.GetInt32(0), Name = r.IsDBNull(1) ? null : r.GetString(1), }; - static readonly Func Swapped = [MethodImpl(MethodImplOptions.NoInlining)] static (r) => + static readonly Func Swapped = static r => { string? name = r.IsDBNull(0) ? null : r.GetString(0); return new() { Id = r.GetInt32(1), Name = name }; @@ -321,8 +321,8 @@ public void A_failing_generated_read_reports_the_model_and_the_row_as_the_runtim Catch(() => _ = Core.RowReader.Stream(binder.Map, new HookReader(Columns, rows), 1, -1, token: Ct).ToList())); } - // Fully optimized from its first call, as a reader in a hot loop becomes: its frame must still be on the stack trace. - [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)] + // A reader the JIT may inline: the report does not depend on the reader having a frame of its own. + [MethodImpl(MethodImplOptions.AggressiveInlining)] static HookRow ThirdRowFails(DbDataReader r) { int id = r.GetInt32(0); @@ -330,7 +330,7 @@ static HookRow ThirdRowFails(DbDataReader r) } [Fact] - public void An_optimized_reader_is_still_named_by_every_synchronous_collecting_loop() + public void An_inlinable_reader_is_reported_by_every_synchronous_collecting_loop() { RowMap map = GeneratedRowMap.Create(static _ => ThirdRowFails); FakeExecuteReader q = Query(5); @@ -381,23 +381,142 @@ public async Task A_DbException_and_a_cancellation_pass_through_untouched() [Fact] public async Task A_failure_of_the_loops_own_read_is_not_reported_as_the_row() { - // The loop's try region holds its Read too: a provider failure there is not the row reader's, so it passes as the runtime lets it pass. + // The loops' try regions hold the row reader's call alone: a Read that fails is not the row reader's, so it passes as it is. FakeExecuteReader q = Query(() => new HookReader(Columns, Rows(5), failReadAt: 3)); var binder = new HookBinder(); + static HookRow Selector(IDataRecord r) => new() { Id = r.GetInt32(0) }; Exception? runtime = Catch(() => q.Map(RowMap.Default).ToList()); - Exception? generated = Catch(() => q.Map(binder.Map).ToList()); Assert.IsType(runtime); - SameError(runtime, generated); + foreach (Action read in new Action[] + { + () => _ = q.Map(binder.Map).ToList(), + () => _ = q.Map(binder.Map).ToArray(), + () => _ = q.Map(binder.Map).ToHashSet(), + () => _ = q.Map(Selector).ToList(), + () => _ = q.Map(Selector).ToArray(), + }) + { + SameError(runtime, Catch(read)); + } + + SameError(runtime, await CatchAsync(async () => await q.Map(binder.Map).ToListAsync(Ct))); + SameError(runtime, await CatchAsync(async () => await q.Map(binder.Map).ToArrayAsync(Ct))); + SameError(runtime, await CatchAsync(async () => await q.Map(Selector).ToListAsync(Ct))); + SameError(runtime, await CatchAsync(async () => { await foreach (HookRow _ in q.Map(binder.Map).Stream(Timeout.InfiniteTimeSpan, Ct)) { } })); + } + + [Fact] + public async Task A_selector_that_fails_passes_its_own_exception() + { + // A caller's selector is not a row reader of the library: nothing is added to what it throws. + var fault = new FormatException("bad value"); + FakeExecuteReader q = Query(5); + HookRow Selector(IDataRecord r) => r.GetInt32(0) == 3 ? throw fault : new() { Id = r.GetInt32(0) }; + + Assert.Same(fault, Catch(() => q.Map(Selector).ToList())); + Assert.Same(fault, Catch(() => q.Map(Selector).ToArray())); + Assert.Same(fault, Catch(() => q.Map(Selector).ToHashSet())); + Assert.Same(fault, Catch(() => q.Map(Selector).Skip(2).First())); + Assert.Same(fault, await CatchAsync(async () => await q.Map(Selector).ToListAsync(Ct))); + Assert.Same(fault, await CatchAsync(async () => { await foreach (HookRow _ in q.Map(Selector).Stream(Timeout.InfiniteTimeSpan, Ct)) { } })); + } + + [Fact] + public async Task A_failing_generated_read_is_reported_by_the_one_row_and_asynchronous_terminals() + { + object?[][] rows = [[1, "a", "x"], [null, "b", "x"]]; + FakeExecuteReader q = Query(() => new HookReader(Columns, rows)); + var binder = new HookBinder(); + + SameError(Catch(() => q.Map(RowMap.Default).Skip(1).Single()), Catch(() => q.Map(binder.Map).Skip(1).Single())); SameError( - await CatchAsync(async () => await q.Map(RowMap.Default).ToListAsync(Ct)), - await CatchAsync(async () => await q.Map(binder.Map).ToListAsync(Ct))); + await CatchAsync(async () => await q.Map(RowMap.Default).Skip(1).SingleAsync(Ct)), + await CatchAsync(async () => await q.Map(binder.Map).Skip(1).SingleAsync(Ct))); + SameError( + await CatchAsync(async () => await q.Map(RowMap.Default).Skip(1).FirstAsync(Ct)), + await CatchAsync(async () => await q.Map(binder.Map).Skip(1).FirstAsync(Ct))); + SameError( + await CatchAsync(async () => await q.Map(RowMap.Default).ToArrayAsync(Ct)), + await CatchAsync(async () => await q.Map(binder.Map).ToArrayAsync(Ct))); + SameError( + await CatchAsync(async () => await q.Map(RowMap.Default).AsyncReads().ToListAsync(Ct)), + await CatchAsync(async () => await q.Map(binder.Map).AsyncReads().ToListAsync(Ct))); + + var channel = Assert.IsType( + await CatchAsync(async () => { await foreach (HookRow _ in q.Map(binder.Map).ToChannelReader(Ct).ReadAllAsync(Ct)) { } })); + Assert.Contains(" at row 1.", channel.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task A_failure_of_the_read_that_an_early_stop_makes_is_not_reported_as_the_row() + { + // CancelOnEarlyStop() reads once more after the last row it takes, to see whether there is anything to cancel. A provider's Cancel that + // throws is swallowed by design, so that Read is what can fail here. + FakeExecuteReader q = Query(() => new HookReader(Columns, Rows(5), failReadAt: 3)); + var binder = new HookBinder(); + static HookRow Selector(IDataRecord r) => new() { Id = r.GetInt32(0) }; + + Exception? runtime = Catch(() => q.Map(RowMap.Default).CancelOnEarlyStop().Take(2).ToList()); + Assert.IsType(runtime); + SameError(runtime, Catch(() => q.Map(binder.Map).CancelOnEarlyStop().Take(2).ToList())); + SameError(runtime, Catch(() => q.Map(binder.Map).CancelOnEarlyStop().Take(2).ToArray())); + SameError(runtime, Catch(() => q.Map(binder.Map).CancelOnEarlyStop().Take(2).ToHashSet())); + SameError(runtime, Catch(() => q.Map(Selector).CancelOnEarlyStop().Take(2).ToList())); + SameError(runtime, await CatchAsync(async () => await q.Map(binder.Map).CancelOnEarlyStop().Take(2).ToListAsync(Ct))); + SameError(runtime, await CatchAsync(async () => await q.Map(binder.Map).CancelOnEarlyStop().Take(2).ToArrayAsync(Ct))); + SameError(runtime, await CatchAsync(async () => await q.Map(Selector).CancelOnEarlyStop().Take(2).ToListAsync(Ct))); + } + + [Fact] + public async Task A_failure_of_the_first_read_after_the_skip_is_not_reported_as_the_row() + { + FakeExecuteReader q = Query(() => new HookReader(Columns, Rows(5), failReadAt: 2)); + var binder = new HookBinder(); + + Exception? runtime = Catch(() => q.Map(RowMap.Default).Skip(1).First()); + Assert.IsType(runtime); + SameError(runtime, Catch(() => q.Map(binder.Map).Skip(1).First())); + SameError(runtime, Catch(() => q.Map(binder.Map).Skip(1).Single())); + SameError(runtime, await CatchAsync(async () => await q.Map(binder.Map).Skip(1).FirstAsync(Ct))); + SameError( + Catch(() => _ = Core.RowReader.Stream(RowMap.Default, new HookReader(Columns, Rows(5), failReadAt: 3), 0, -1, token: Ct).ToList()), + Catch(() => _ = Core.RowReader.Stream(binder.Map, new HookReader(Columns, Rows(5), failReadAt: 3), 0, -1, token: Ct).ToList())); + } + + // Rents once, then refuses: the failure of a loop's Add, not of its row reader. + sealed class OneRentPool : ArrayPool + { + int _rents; + + public override HookRow[] Rent(int minimumLength) + => ++_rents == 1 ? new HookRow[minimumLength] : throw new InvalidOperationException("The pool refused an array."); + + public override void Return(HookRow[] array, bool clearArray = false) { } + } + + [Fact] + public async Task A_failure_to_add_a_row_is_not_reported_as_the_row() + { + FakeExecuteReader q = Query(2_000); + var binder = new HookBinder(); + + var sync = Assert.IsType(Catch(() => q.Map(binder.Map).UsePool(new OneRentPool(), clearOnReturn: false).ToArray())); + Assert.Equal("The pool refused an array.", sync.Message); + var set = Assert.IsType(Catch(() => q.Map(binder.Map).UsePool(new OneRentPool(), clearOnReturn: false).ToHashSet())); + Assert.Equal("The pool refused an array.", set.Message); + var awaited = Assert.IsType( + await CatchAsync(async () => await q.Map(binder.Map).UsePool(new OneRentPool(), clearOnReturn: false).ToListAsync(Ct))); + Assert.Equal("The pool refused an array.", awaited.Message); + var array = Assert.IsType( + await CatchAsync(async () => await q.Map(binder.Map).UsePool(new OneRentPool(), clearOnReturn: false).ToArrayAsync(Ct))); + Assert.Equal("The pool refused an array.", array.Message); } [Fact] public async Task A_declined_layout_passes_a_failure_of_the_loops_own_read_unchanged() { - // The row reader is then the runtime's compiled expression, whose method has no metadata of its own on every runtime. + // The row reader is then the runtime's compiled expression. FakeExecuteReader q = Query(() => new HookReader(Columns, Rows(5), failReadAt: 3)); var declining = new HookBinder { Decline = true }; diff --git a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs index 05333627..d550da58 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs @@ -9,7 +9,7 @@ namespace Open.Database.Extensions.Generator.Tests; /// public partial class GeneratedSourceTests { - [GeneratedRegex(@"NoInlining\)\]\s+public ")] + [GeneratedRegex(@"public global::\S+ \w+\(global::System\.Data\.Common\.DbDataReader r\)")] private static partial Regex LayoutReader(); static string GeneratedSource() @@ -125,9 +125,10 @@ public void A_row_reader_is_the_reads_and_nothing_else(string model) foreach (string word in new[] { "try", "catch", "finally", "Rows", "Bound", "Mode", "Interlocked", "OdxGeneratedCounters", "FieldCount", "ReferenceEquals" }) Assert.DoesNotMatch($@"\b{word}\b", readers); - // 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); + // The literal reader is a static lambda (nothing captured: a closed delegate with no thunk). No row reader is marked NoInlining, so the JIT + // can treat it as it treats a hand-written one (Core's loop tells a row reader's failure apart by catching around its call). + Assert.Matches(@"ReadLiteral = static \(", readers); + Assert.DoesNotContain("NoInlining", readers, StringComparison.Ordinal); // 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 : 2, LayoutReader().Count(readers)); diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs index 3e409357..23ed6dfe 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Errors.cs @@ -3,7 +3,7 @@ namespace Open.Database.Extensions.Generator.Tests; -// The identity read mode (5), and the error report: a generated row reader is one try region per row, so a failure is reported as a +// The identity read mode (4), and the error report: Core's loop catches around its call of the generated row reader, so a failure is reported as a // ValueMappingException naming the model type and the row (0-based), the exception inside, worded by that exception's type; no member or column: // the runtime map's report, equal to it. A DbException and a cancellation pass through untouched, as the runtime map lets them. public partial class ParityTests