diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 9e5dbbeb..4113629d 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -103,6 +103,56 @@ internal static IDataReader OpenAndExecuteReader(this IDbCommand command, Comman static ValueTask OpenAndExecuteReaderAsync(this DbCommand command, CommandBehavior behavior, CancellationToken cancellationToken) => OpenAndExecuteReaderAsync(command, behavior, static (c, b, ct) => c.ExecuteReaderAsync(b, ct), cancellationToken); + // Every handler and transform overload ends up in one of these two cores, + // which own opening the connection and disposing the reader. + // There are two because a ValueTask cannot wrap a ValueTask + // without a second state machine. + // The overload passes its handler as the argument together with a static + // lambda that calls it, so there is no closure. + // The null checks are here, inside the async method, + // so a null is still reported through the returned task. + static async ValueTask ExecuteReaderCoreAsync( + DbCommand command, + TArg arg, + string argName, + Func handle, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (command is null) throw new ArgumentNullException(nameof(command)); + if (arg is null) throw new ArgumentNullException(argName); + Contract.EndContractBlock(); + +#if NETSTANDARD2_0 + using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); +#else + DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); + await using var readerDisposal = reader.ConfigureAwait(false); +#endif + await handle(reader, arg).ConfigureAwait(false); + } + + static async ValueTask ExecuteReaderCoreAsync( + DbCommand command, + TArg arg, + string argName, + Func> handle, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (command is null) throw new ArgumentNullException(nameof(command)); + if (arg is null) throw new ArgumentNullException(argName); + Contract.EndContractBlock(); + +#if NETSTANDARD2_0 + using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); +#else + DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); + await using var readerDisposal = reader.ConfigureAwait(false); +#endif + return await handle(reader, arg).ConfigureAwait(false); + } + #endregion /// @@ -157,23 +207,17 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// /// A task that represents the asynchronous operation. /// - public static async ValueTask ExecuteReaderAsync(this DbCommand command, + public static ValueTask ExecuteReaderAsync(this DbCommand command, Action handler, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (handler is null) throw new ArgumentNullException(nameof(handler)); - Contract.EndContractBlock(); - -#if NETSTANDARD2_0 - using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - handler(reader); - } + => ExecuteReaderCoreAsync(command, handler, nameof(handler), + static (reader, h) => + { + h(reader); + return default; + }, + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this IDbCommand command, @@ -230,23 +274,13 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// /// A task that represents the asynchronous operation. /// - public static async ValueTask ExecuteReaderAsync(this DbCommand command, + public static ValueTask ExecuteReaderAsync(this DbCommand command, Func handler, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (handler is null) throw new ArgumentNullException(nameof(handler)); - Contract.EndContractBlock(); - -#if NETSTANDARD2_0 - using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - await handler(reader).ConfigureAwait(false); - } + => ExecuteReaderCoreAsync(command, handler, nameof(handler), + static (reader, h) => h(reader), + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this DbCommand command, @@ -270,23 +304,13 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// Its result is the result of the transform. /// /// - public static async ValueTask ExecuteReaderAsync(this DbCommand command, + public static ValueTask ExecuteReaderAsync(this DbCommand command, Func transform, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (transform is null) throw new ArgumentNullException(nameof(transform)); - Contract.EndContractBlock(); - -#if NETSTANDARD2_0 - using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - return transform(reader); - } + => ExecuteReaderCoreAsync(command, transform, nameof(transform), + static (reader, t) => new ValueTask(t(reader)), + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this IDbCommand command, @@ -326,21 +350,11 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, => ExecuteReaderAsync(command, transform, CommandBehavior.Default, cancellationToken); /// - public static async ValueTask ExecuteReaderAsync(this DbCommand command, + public static ValueTask ExecuteReaderAsync(this DbCommand command, Func> transform, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (transform is null) throw new ArgumentNullException(nameof(transform)); - Contract.EndContractBlock(); - -#if NETSTANDARD2_0 - using DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - DbDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - return await transform(reader).ConfigureAwait(false); - } + => ExecuteReaderCoreAsync(command, transform, nameof(transform), + static (reader, t) => t(reader), + behavior, cancellationToken); } diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index 20187cd0..fdffebee 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -279,7 +279,7 @@ internal static void RestoreConnection(DbConnection connection, ConnectionState /// Asynchronously closes the connection as does. /// /// - static ValueTask RestoreConnectionAsync(DbConnection connection, ConnectionState priorState) + internal static ValueTask RestoreConnectionAsync(DbConnection connection, ConnectionState priorState) => ConnectionExtensions.NeedsOpen(priorState) ? ConnectionExtensions.CloseQuietlyAsync(connection) : default; diff --git a/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs b/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs index 8c4725e8..86a8c765 100644 --- a/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs +++ b/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs @@ -18,6 +18,56 @@ public static partial class SqlCommandExtensions /// A task whose result is the reader. static ValueTask OpenAndExecuteReaderAsync(this SqlCommand command, CommandBehavior behavior, CancellationToken cancellationToken) => CommandExtensions.OpenAndExecuteReaderAsync(command, behavior, static (c, b, ct) => c.ExecuteReaderAsync(b, ct), cancellationToken); + + // Every handler and transform overload ends up in one of these two cores, + // which own opening the connection and disposing the reader. + // There are two because a ValueTask cannot wrap a ValueTask + // without a second state machine. + // The overload passes its handler as the argument together with a static + // lambda that calls it, so there is no closure. + // The null checks are here, inside the async method, + // so a null is still reported through the returned task. + static async ValueTask ExecuteReaderCoreAsync( + SqlCommand command, + TArg arg, + string argName, + Func handle, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (command is null) throw new ArgumentNullException(nameof(command)); + if (arg is null) throw new ArgumentNullException(argName); + Contract.EndContractBlock(); + +#if NET472 + using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); +#else + SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); + await using var readerDisposal = reader.ConfigureAwait(false); +#endif + await handle(reader, arg).ConfigureAwait(false); + } + + static async ValueTask ExecuteReaderCoreAsync( + SqlCommand command, + TArg arg, + string argName, + Func> handle, + CommandBehavior behavior, + CancellationToken cancellationToken) + { + if (command is null) throw new ArgumentNullException(nameof(command)); + if (arg is null) throw new ArgumentNullException(argName); + Contract.EndContractBlock(); + +#if NET472 + using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); +#else + SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); + await using var readerDisposal = reader.ConfigureAwait(false); +#endif + return await handle(reader, arg).ConfigureAwait(false); + } #endregion /// @@ -37,23 +87,13 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// or is . The exception is reported through the returned task. /// was canceled before or while the connection was being opened or the command executed. - public static async ValueTask ExecuteReaderAsync(this SqlCommand command, + public static ValueTask ExecuteReaderAsync(this SqlCommand command, Func handler, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (handler is null) throw new ArgumentNullException(nameof(handler)); - Contract.EndContractBlock(); - -#if NET472 - using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - await handler(reader).ConfigureAwait(false); - } + => ExecuteReaderCoreAsync(command, handler, nameof(handler), + static (reader, h) => h(reader), + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this SqlCommand command, @@ -66,23 +106,17 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// A task that represents the asynchronous operation. It completes after has completed and the reader has been disposed. /// - public static async ValueTask ExecuteReaderAsync(this SqlCommand command, + public static ValueTask ExecuteReaderAsync(this SqlCommand command, Action handler, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (handler is null) throw new ArgumentNullException(nameof(handler)); - Contract.EndContractBlock(); - -#if NET472 - using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - handler(reader); - } + => ExecuteReaderCoreAsync(command, handler, nameof(handler), + static (reader, h) => + { + h(reader); + return default; + }, + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this SqlCommand command, @@ -102,23 +136,13 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// or is . The exception is reported through the returned task. /// was canceled before or while the connection was being opened or the command executed. - public static async ValueTask ExecuteReaderAsync(this SqlCommand command, + public static ValueTask ExecuteReaderAsync(this SqlCommand command, Func transform, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (transform is null) throw new ArgumentNullException(nameof(transform)); - Contract.EndContractBlock(); - -#if NET472 - using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - return transform(reader); - } + => ExecuteReaderCoreAsync(command, transform, nameof(transform), + static (reader, t) => new ValueTask(t(reader)), + behavior, cancellationToken); /// public static ValueTask ExecuteReaderAsync(this SqlCommand command, @@ -131,21 +155,11 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// A task that represents the asynchronous operation; its result is the value produced by . /// - public static async ValueTask ExecuteReaderAsync(this SqlCommand command, + public static ValueTask ExecuteReaderAsync(this SqlCommand command, Func> transform, CommandBehavior behavior, CancellationToken cancellationToken = default) - { - if (command is null) throw new ArgumentNullException(nameof(command)); - if (transform is null) throw new ArgumentNullException(nameof(transform)); - Contract.EndContractBlock(); - -#if NET472 - using SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); -#else - SqlDataReader reader = await command.OpenAndExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(false); - await using var readerDisposal = reader.ConfigureAwait(false); -#endif - return await transform(reader).ConfigureAwait(false); - } + => ExecuteReaderCoreAsync(command, transform, nameof(transform), + static (reader, t) => t(reader), + behavior, cancellationToken); } diff --git a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs index c72f59cf..8a4db417 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -10,11 +10,13 @@ public static partial class SqlTransactionExtensions /// /// /// or is . + /// The transaction has no connection. public static SqlCommand CreateCommand(this SqlTransaction transaction, CommandType type, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection."); Contract.EndContractBlock(); SqlCommand command = transaction @@ -42,6 +44,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, /// /// /// or is . + /// The transaction has no connection. public static SqlCommand CreateTextCommand(this SqlTransaction transaction, string commandText, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) => transaction.CreateCommand(CommandType.Text, commandText, secondsTimeout); @@ -54,6 +57,7 @@ public static SqlCommand CreateTextCommand(this SqlTransaction transaction, /// /// /// or is . + /// The transaction has no connection. public static SqlCommand CreateStoredProcedureCommand(this SqlTransaction transaction, string procedureName, int secondsTimeout = CommandTimeout.DEFAULT_SECONDS) => transaction.CreateCommand(CommandType.StoredProcedure, procedureName, secondsTimeout); diff --git a/Source/MSSqlClient/Extensions/Transaction.cs b/Source/MSSqlClient/Extensions/Transaction.cs index d4a79c4c..b9658cc9 100644 --- a/Source/MSSqlClient/Extensions/Transaction.cs +++ b/Source/MSSqlClient/Extensions/Transaction.cs @@ -3,6 +3,7 @@ // Keep it in sync with Source/Core/Extensions/Transaction.cs; only the type names and the TFM seams differ. // A copy of the TransactionExtensions methods for DbConnection with the types replaced by their Sql versions, // so that the SqlTransaction type flows through to the action rather than a plain transaction. +// Restoring the connection afterwards is not copied: it takes a DbConnection, so TransactionExtensions.RestoreConnection serves both. /// /// Provides Microsoft.Data.SqlClient specific extension methods that run work in a database transaction on a . @@ -74,7 +75,7 @@ public static partial class SqlTransactionExtensions } finally { - await RestoreConnectionAsync(connection, priorState).ConfigureAwait(false); + await TransactionExtensions.RestoreConnectionAsync(connection, priorState).ConfigureAwait(false); } } @@ -203,38 +204,6 @@ await connection .ConfigureAwait(false); } - #region Restoring the connection - - // By the time this runs the transaction has already been disposed: that ordering matters because some providers - // (for example Microsoft.Data.Sqlite and MySqlConnector) only roll back an uncommitted transaction on dispose - // while the connection is still open. - // A failure to close is deliberately ignored. By then the transaction has already been committed or rolled back, - // so it must neither turn a completed operation into an error nor replace the exception of a failed one. - // Only a connection that was already Open belongs to the caller. One that was Closed, or Broken and therefore - // repaired by EnsureOpen, is a connection this operation opened, so it is closed again here. - /// - /// Closes (never disposes) a connection that this operation opened, so the caller's connection is left the way it was found. - /// - /// The connection the operation ran on. - /// The state the connection was in before the operation opened it. - /// A failure to close is ignored. - internal static void RestoreConnection(SqlConnection connection, ConnectionState priorState) - { - if (ConnectionExtensions.NeedsOpen(priorState)) - ConnectionExtensions.CloseQuietly(connection); - } - - /// - /// Asynchronously closes the connection as does. - /// - /// - static ValueTask RestoreConnectionAsync(SqlConnection connection, ConnectionState priorState) - => ConnectionExtensions.NeedsOpen(priorState) - ? ConnectionExtensions.CloseQuietlyAsync(connection) - : default; - - #endregion - #region Cancellation token in place of the isolation level // The isolation level is almost always left unspecified, so a token may be passed right after the action. diff --git a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs index 17da9846..c66f2cf6 100644 --- a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs +++ b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs @@ -55,7 +55,7 @@ public static (bool Commit, T Value) ExecuteTransactionConditional( } finally { - RestoreConnection(connection, priorState); + TransactionExtensions.RestoreConnection(connection, priorState); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs index c3ccc82f..63a77382 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs @@ -492,6 +492,20 @@ public static async Task ProcedureParameterNames_ACancellation_IsNotAFailureOfTh Assert.False(ex.Data.Contains("Procedure")); } + // ---- SqlTransactionExtensions.CreateCommand: a transaction with no connection is refused as Core's is ---- + + [Fact] + public static void CreateCommand_OnATransactionWithNoConnection_Throws() + { + // An uninitialized transaction reports no connection, as one that has ended does, and needs no server. + var transaction = (SqlTransaction)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(SqlTransaction)); + Assert.Null(transaction.Connection); + + Assert.Equal("Transaction has no connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); + Assert.Throws(() => SqlTx.CreateTextCommand(transaction, "select 1")); + Assert.Throws(() => SqlTx.CreateStoredProcedureCommand(transaction, "dbo.p")); + } + // ---- SqlTransactionExtensions.ExecuteTransactionConditional and its async twin: a typed copy of Core's, which BeginTransaction keeps synchronous so the SqlTransaction type flows ---- static void Insert(SqlTransaction transaction, string table, int id) diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 0d13837a..140ead46 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -7,6 +7,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl ### Changes since rc.16 - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. +- **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. ### Changes since rc.15