diff --git a/Source/Channel/ToChannel.Produce.cs b/Source/Channel/ToChannel.Produce.cs index d2a3cd8f..9e51dab3 100644 --- a/Source/Channel/ToChannel.Produce.cs +++ b/Source/Channel/ToChannel.Produce.cs @@ -223,8 +223,9 @@ IAsyncEnumerable> chunks AllowSynchronousContinuations = false, }); - // A failure reaches the channel through Complete; the task - // is dropped unobserved unless the caller asked for the count. + // A failure reaches the channel through Complete: the task's own + // fault is read so that a caller who drops the count never has it + // reported as unobserved. A caller who awaits it still sees it. readCount = ChannelPump .Run>( new(chunks), @@ -233,6 +234,13 @@ IAsyncEnumerable> chunks cancellationToken) .AsTask(); + _ = readCount.ContinueWith( + static task => task.Exception, + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted + | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + return channel; } } diff --git a/Source/Core/Core/RowErrors.cs b/Source/Core/Core/RowErrors.cs index 0080630f..4eac87b4 100644 --- a/Source/Core/Core/RowErrors.cs +++ b/Source/Core/Core/RowErrors.cs @@ -12,16 +12,6 @@ namespace Open.Database.Extensions; /// static class RowErrors { - /// - /// Creates the exception for a failure mapping a row whose number is not known (a reader whose caller owns the read loop). - /// - /// The error the read or the conversion raised. - /// The model type, or the type of the single value. - /// for a single value; otherwise, for a model. - /// The exception to throw. - public static ValueMappingException Create(Exception inner, Type target, bool singleValue) - => Create(inner, target, singleValue, -1); - /// /// Creates the exception for a failure mapping a row. /// @@ -151,16 +141,6 @@ public ValueMappingException Create(Type model, int row) #pragma warning restore IDE0079 // Remove unnecessary suppression sealed class RowMappingFailure(Exception inner, Type target, bool singleValue) : Exception(null, inner) { - /// - /// Creates the wrapper; called by the compiled row readers. - /// - /// The error the read or the conversion raised. - /// The model type, or the type of the single value. - /// for a single value; otherwise, for a model. - /// The wrapper to throw. - public static RowMappingFailure Defer(Exception inner, Type target, bool singleValue) - => new(inner, target, singleValue); - /// /// Returns the exception the read loop throws, naming the row. /// diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index b711bd7b..bdc16ca9 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -1807,9 +1807,18 @@ static Expression OnNull(CellRead read, Slot slot, string column) static BlockExpression Guard(Expression body, List variables, bool singleValue, bool rowKnown) { ParameterExpression ex = Expression.Parameter(typeof(Exception), "ex"); - MethodInfo fail = rowKnown - ? typeof(RowMappingFailure).GetMethod(nameof(RowMappingFailure.Defer))! - : typeof(RowErrors).GetMethod(nameof(RowErrors.Create), [typeof(Exception), typeof(Type), typeof(bool)])!; + Expression type = Expression.Constant(typeof(T)); + Expression single = Expression.Constant(singleValue); + Expression fail = rowKnown + ? Expression.New( + typeof(RowMappingFailure).GetConstructor( + [typeof(Exception), typeof(Type), typeof(bool)])!, + ex, type, single) + : Expression.Call( + typeof(RowErrors).GetMethod( + nameof(RowErrors.Create), + [typeof(Exception), typeof(Type), typeof(bool), typeof(int)])!, + ex, type, single, Expression.Constant(-1)); return Expression.Block( typeof(T), @@ -1823,13 +1832,7 @@ static BlockExpression Guard(Expression body, List variable Expression.TypeIs(ex, typeof(DbException)), Expression.TypeIs(ex, typeof(OperationCanceledException))), Expression.Rethrow(typeof(T)), - Expression.Throw( - Expression.Call( - fail, - ex, - Expression.Constant(typeof(T)), - Expression.Constant(singleValue)), - typeof(T)))))); + Expression.Throw(fail, typeof(T)))))); } /// diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index bcf5afb5..f9b580cf 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -19,20 +19,6 @@ static class DbQueryBinding public static bool Known(NameSet? names) => names is { Names.Length: > 0 }; - /// - /// Gets the real name an argument of AddParam(value) stands for. - /// - /// The facts of the argument's text. - /// The remembered names, or when they are not known. - /// The query definition. - /// The real name; the last member as written when the names are not known. - /// The expression matches none of the names, or more than one equally well. - public static string ResolveDerived( - ParameterNames.DerivedExpression derived, - NameSet? names, - DbQuery definition) - => ResolveDerived(derived, names, definition, out _); - /// /// Gets the real name an argument of AddParam(value) stands for, and its place in the names. /// diff --git a/Source/Core/DbQueryParams.cs b/Source/Core/DbQueryParams.cs index c58ff7f0..e31ea6ff 100644 --- a/Source/Core/DbQueryParams.cs +++ b/Source/Core/DbQueryParams.cs @@ -197,23 +197,20 @@ public bool Claims(string name, NameSet? names, DbQuery definition) Get(i, out object key, out _); switch (key) { - case string written: - if (DbQueryBinding.SameName(written, name)) return true; - break; - - case NameSet.Entry entry: - if (DbQueryBinding.SameName(entry.Real, name)) return true; - break; - - case ParameterNames.DerivedExpression derived: - if (DbQueryBinding.SameName( - DbQueryBinding.ResolveDerived(derived, names, definition), - name)) - { - return true; - } - - break; + case string written + when DbQueryBinding.SameName(written, name): + return true; + + case NameSet.Entry entry + when DbQueryBinding.SameName(entry.Real, name): + return true; + + case ParameterNames.DerivedExpression derived + when DbQueryBinding.SameName( + DbQueryBinding.ResolveDerived( + derived, names, definition, out _), + name): + return true; } } diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 82006a6a..775bb472 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -146,17 +146,6 @@ bool TryMove(int from, int to) } } - // Sets the state whatever it was, and returns what it was. - int Exchange(int to) - { - while (true) - { - long word = Volatile.Read(ref _word); - if (Interlocked.CompareExchange(ref _word, (word & ~StateMask) | (uint)to, word) == word) - return (int)(word & StateMask); - } - } - #endregion #region The consumer's side @@ -331,7 +320,9 @@ void Tick() async ValueTask DisposeCoreAsync() { - int was = Exchange(Disposed); + // The timestamp is only read while the state is Idle, so a disposed + // stream does not keep it. + int was = (int)(Interlocked.Exchange(ref _word, Disposed) & StateMask); if (was is NotStarted or Disposed) return; StopTimer(); diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 479363ad..704cb8e8 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -237,7 +237,11 @@ public static async ValueTask ExecuteReaderAsync(this IDbCommand command, if (command is DbCommand c) { - await c.ExecuteReaderAsync(reader => handler(reader), behavior, cancellationToken).ConfigureAwait(false); + // The cast selects the DbCommand overload without allocating a closure. + await c.ExecuteReaderAsync( + (Func)handler, + behavior, cancellationToken) + .ConfigureAwait(false); return; } @@ -322,7 +326,11 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, Contract.EndContractBlock(); return command is DbCommand c - ? ExecuteReaderAsync(c, reader => transform(reader), behavior, cancellationToken) + // The cast selects the DbCommand overload without allocating a closure. + ? ExecuteReaderAsync( + c, + (Func>)transform, + behavior, cancellationToken) : ExecuteReaderAsyncCore(command, transform, behavior); static async ValueTask ExecuteReaderAsyncCore(IDbCommand command, Func> transform, CommandBehavior behavior) diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index fdffebee..9bf87346 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -242,8 +242,12 @@ public static async ValueTask ExecuteTransactionAsync( Contract.EndContractBlock(); await connection - .ExecuteTransactionAsync( - async c => { await action(c).ConfigureAwait(false); return true; }, + .ExecuteTransactionConditionalAsync( + async t => + { + await action(t).ConfigureAwait(false); + return (true, true); + }, isolationLevel, cancellationToken) .ConfigureAwait(false); } diff --git a/Source/Core/IDbConnectionPool.cs b/Source/Core/IDbConnectionPool.cs index a408f615..cae3dd32 100644 --- a/Source/Core/IDbConnectionPool.cs +++ b/Source/Core/IDbConnectionPool.cs @@ -80,9 +80,6 @@ private readonly IDbConnectionPool _source public IDbConnection Take() => _source.Take(); - IDbConnection IDbConnectionPool.Take() - => _source.Take(); - /// public void Give(IDbConnection connection) => _source.Give(connection); diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index bf4f4bdc..d5f64e1f 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -310,15 +310,14 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) { if (HasAttribute(c.GetAttributes(), NullPolicyAttribute)) return true; + // Neither attribute can be put on a field. foreach (ISymbol m in c.GetMembers()) { - ImmutableArray attributes = m switch + if (m is IPropertySymbol p + && HasNullAttribute(p.GetAttributes())) { - IPropertySymbol p => p.GetAttributes(), - IFieldSymbol f => f.GetAttributes(), - _ => [], - }; - if (HasNullAttribute(attributes)) return true; + return true; + } } } @@ -463,12 +462,8 @@ static bool IsRetired(ISymbol? member) && a.ConstructorArguments.Length == 2 && a.ConstructorArguments[1].Value is true) == true; static bool HasAttribute(ImmutableArray attributes, string fullName) - { - foreach (AttributeData a in attributes) - if (a.AttributeClass is { } c && FullName(c) == fullName) return true; - - return false; - } + => attributes.Any( + a => a.AttributeClass is { } c && FullName(c) == fullName); // The metadata full name (namespace + nested types + arity), as reflection's Type.FullName gives it for a non-generic or definition type. public static string FullName(ITypeSymbol t) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs index fc609648..786afd5a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs @@ -146,4 +146,43 @@ public static async Task ExecuteReaderAsync_ClosedConnection_RequestsCloseConnec } #endregion + + #region An IDbCommand that is a DbCommand + + // The IDbCommand overloads hand a DbCommand to the DbCommand overloads + // with a delegate cast, which picks them without a closure. + [Fact] + public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTheHandlerOncePerCall() + { + CancellationToken token = TestContext.Current.CancellationToken; + FakeDbConnection connection = new(); + connection.SetState(ConnectionState.Open); + IDbCommand command = new FakeDbCommand( + connection, () => new CountingReader(3)); + int handled = 0; + + await command.ExecuteReaderAsync( + reader => + { + Assert.IsType(reader, exactMatch: false); + handled++; + return default; + }, + CommandBehavior.Default, + token); + int fields = await command.ExecuteReaderAsync( + reader => + { + Assert.IsType(reader, exactMatch: false); + handled++; + return new ValueTask(reader.FieldCount); + }, + CommandBehavior.Default, + token); + + Assert.Equal(2, handled); + Assert.Equal(1, fields); + } + + #endregion } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs new file mode 100644 index 00000000..a44ab990 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs @@ -0,0 +1,115 @@ +using System.Runtime.CompilerServices; +using static Open.Database.Extensions.Tests.ChannelFixtures; + +namespace Open.Database.Extensions.Tests; + +// A failed read reaches the channel; the read's task, which nobody holds, +// must not report the same failure as unobserved when it is collected. +// The collection runs alone: no other test raises an unobserved task +// into the handler while it listens. +[Collection("Heap measurements")] +[ExcludeFromCodeCoverage] +public static class ToChannelUnobservedTests +{ + const string Failure = "failed while reading"; + const string Sentinel = "sentinel of the unobserved-task test"; + + static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public static async Task ARowFailure_WhenNobodyAsksForTheCount_IsNotReportedUnobserved() + { + List unobserved = []; + List sentinels = []; + void OnUnobserved(object? s, UnobservedTaskExceptionEventArgs e) + { + string text = e.Exception.ToString(); + List? list = text.Contains( + Sentinel, StringComparison.Ordinal) + ? sentinels + : text.Contains(Failure, StringComparison.Ordinal) + ? unobserved + : null; + if (list is null) + { + return; + } + + lock (list) + { + list.Add(e.Exception); + } + } + + TaskScheduler.UnobservedTaskException += OnUnobserved; + try + { + // The three forms that drop the count; the last one hands the + // task out so that its collection can be checked. + DbTally[] tallies = [Tally(20, 9), Tally(20, 9), Tally(20, 9)]; + WeakReference countTask = Start( + tallies, out ChannelReader[] readers); + DropFaultedTask(); + + foreach (ChannelReader reader in readers) + { + (List _, Exception? error) = await ChannelWait.Collect(reader); + Assert.NotNull(error); + } + + foreach (DbTally tally in tallies) + { + await ChannelWait.Until( + () => tally.Connections[0].ClosedAfterOpen, + "the connection to close"); + } + + await Task.Delay(100, Ct); + for (int i = 0; i < 3; ++i) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + // The test can fail only if it could have seen the report: + // a faulted task nobody observes does raise it here, and the + // task of the read has been collected. + lock (sentinels) + { + Assert.NotEmpty(sentinels); + } + + Assert.False(countTask.IsAlive, "the read's task is still alive"); + lock (unobserved) + { + Assert.Empty(unobserved); + } + } + finally + { + TaskScheduler.UnobservedTaskException -= OnUnobserved; + } + } + + // Not inlined, so that no local of the test keeps a task alive. + [MethodImpl(MethodImplOptions.NoInlining)] + static WeakReference Start( + DbTally[] tallies, + out ChannelReader[] readers) + { + ChannelReader third = Read(tallies[2]) + .ToChannel(out Task count, Ct) + .Reader; + readers = + [ + Read(tallies[0]).ToChannelReader(Ct), + Read(tallies[1]).ToChannel(Ct).Reader, + third, + ]; + return new(count); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void DropFaultedTask() + => _ = Task.FromException(new InvalidOperationException(Sentinel)); +} \ No newline at end of file diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 58ee72c2..da19c7e8 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,6 +10,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter whose mode is `IN` (an input parameter), or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an `IN` parameter). See [Output parameters](expressive-commands.md#output-parameters). - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. +- **Fixed: a failed read through `ToChannel` or `ToChannelReader` was also raised as an unobserved task exception.** The failure reached the channel, as documented, but the read's task was dropped by the forms that do not return the count, so `TaskScheduler.UnobservedTaskException` fired when the task was collected. The task's fault is now read, so nothing is raised; the count you ask for with `ToChannel(out Task readCount)` still throws when awaited. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(out DbCapture value, name)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). - **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows).