diff --git a/Source/Core/Commands.docs.xml b/Source/Core/Commands.docs.xml
index f475e300..73f317f0 100644
--- a/Source/Core/Commands.docs.xml
+++ b/Source/Core/Commands.docs.xml
@@ -137,5 +137,8 @@
or is
.
+
+ The transaction has no connection.
+
diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs
index 30d7086e..92934243 100644
--- a/Source/Core/ExpressiveCommandBase.cs
+++ b/Source/Core/ExpressiveCommandBase.cs
@@ -97,6 +97,16 @@ private protected sealed class CommandOptions
static string CheckedCommand(string command)
=> DbQuery.Checked(command, nameof(command));
+ static TConnection ConnectionOf(IDbTransaction transaction)
+ {
+ if (transaction is null)
+ throw new ArgumentNullException(nameof(transaction));
+
+ return (TConnection)(transaction.Connection
+ ?? throw new InvalidOperationException(
+ TransactionMessages.NoConnection));
+ }
+
///
/// Gets the transaction the command runs in, or
/// when it was not given one.
@@ -200,8 +210,7 @@ protected ExpressiveCommandBase(
string command,
IEnumerable? @params)
: this(
- (TConnection)(transaction ?? throw new ArgumentNullException(nameof(transaction))).Connection!,
- transaction, type, command, @params)
+ ConnectionOf(transaction), transaction, type, command, @params)
{
}
diff --git a/Source/Core/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs
index e0c86103..e0767fe3 100644
--- a/Source/Core/Extensions/Command.AddParameter.cs
+++ b/Source/Core/Extensions/Command.AddParameter.cs
@@ -128,12 +128,12 @@ public static IDbDataParameter AddParameter(
/// Adds a typed parameter with the given name, value, and direction to the command.
///
///
- ///
+ /// The name of the parameter. It can be only when is .
/// The value of the parameter. It is assigned as given: a is not converted to , so pass to send a database null.
///
///
///
- ///
+ /// is , or is and is not .
///
public static IDbDataParameter AddParameter(
this IDbCommand target,
@@ -142,9 +142,8 @@ public static IDbDataParameter AddParameter(
DbType type,
ParameterDirection direction = ParameterDirection.Input)
{
- IDbDataParameter p = target.AddParameterType(name, type);
+ IDbDataParameter p = target.AddParameterType(name, type, direction);
p.Value = value;
- p.Direction = direction;
return p;
}
diff --git a/Source/Core/Extensions/ConnectionProvider.Command.cs b/Source/Core/Extensions/ConnectionProvider.Command.cs
index 422d3c45..1e266e17 100644
--- a/Source/Core/Extensions/ConnectionProvider.Command.cs
+++ b/Source/Core/Extensions/ConnectionProvider.Command.cs
@@ -42,6 +42,7 @@ public static ExpressiveCommand Command(
///
/// A new to configure with parameters and then execute.
/// or is .
+ ///
public static ExpressiveCommand Command(
this IDbTransaction transaction,
string command, CommandType type = CommandType.Text)
@@ -98,6 +99,7 @@ public static ExpressiveCommand StoredProcedure(
///
/// A new with to configure with parameters and then execute.
/// or is .
+ ///
public static ExpressiveCommand StoredProcedure(
this IDbTransaction transaction,
string procedureName)
diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs
index 75f9b8e3..1304e076 100644
--- a/Source/Core/ProcedureSchemaNames.cs
+++ b/Source/Core/ProcedureSchemaNames.cs
@@ -128,6 +128,9 @@ public static async ValueTask> GetAsync(DbConnection conn
}
catch (Exception ex) when (ex is NotSupportedException or NotImplementedException or ArgumentException)
{
+ // A cancellation that surfaced as one of these is a cancellation, not
+ // "no names": nothing is kept.
+ cancellationToken.ThrowIfCancellationRequested();
return default;
}
catch (Exception ex) when (ex is not OperationCanceledException && !cancellationToken.IsCancellationRequested)
diff --git a/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs b/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
index a586b43b..ccb0586e 100644
--- a/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
+++ b/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
@@ -40,6 +40,7 @@ public static ExpressiveSqlCommand Command(
///
/// A new to configure with parameters and then execute.
/// or is .
+ ///
public static ExpressiveSqlCommand Command(
this SqlTransaction transaction,
string command, CommandType type = CommandType.Text)
@@ -64,6 +65,7 @@ public static ExpressiveSqlCommand StoredProcedure(
///
/// A new with to configure with parameters and then execute.
/// or is .
+ ///
public static ExpressiveSqlCommand StoredProcedure(
this SqlTransaction transaction,
string procedureName)
diff --git a/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml b/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml
index a008efb2..539b8cb9 100644
--- a/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml
+++ b/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml
@@ -189,6 +189,9 @@
or is
.
+
+ The transaction has no connection.
+
diff --git a/Tests/Open.Database.Extensions.Core.Tests/AddParameterReturnTests.cs b/Tests/Open.Database.Extensions.Core.Tests/AddParameterReturnTests.cs
new file mode 100644
index 00000000..5447e324
--- /dev/null
+++ b/Tests/Open.Database.Extensions.Core.Tests/AddParameterReturnTests.cs
@@ -0,0 +1,57 @@
+namespace Open.Database.Extensions.Tests;
+
+#nullable enable
+
+// The name of a parameter may be null only when it is the return value; the
+// typed-value overload follows the same rule as AddParameterType.
+[ExcludeFromCodeCoverage]
+public static class AddParameterReturnTests
+{
+ static IDbCommand NewCommand(out IDbDataParameter parameter)
+ {
+ var command = Substitute.For();
+ parameter = Substitute.For();
+ command.CreateParameter().Returns(parameter);
+ command.Parameters.Returns(Substitute.For());
+ return command;
+ }
+
+ [Fact]
+ public static void AddParameterType_NullName_IsAllowedForReturnValue()
+ {
+ IDbCommand command = NewCommand(out _);
+
+ IDbDataParameter added = command.AddParameterType(
+ null,
+ DbType.Int32,
+ ParameterDirection.ReturnValue);
+
+ Assert.NotNull(added);
+ }
+
+ [Fact]
+ public static void AddParameter_NullName_IsAllowedForReturnValue()
+ {
+ IDbCommand command = NewCommand(out IDbDataParameter parameter);
+
+ IDbDataParameter added = command.AddParameter(
+ null!,
+ 0,
+ DbType.Int32,
+ ParameterDirection.ReturnValue);
+
+ Assert.Same(parameter, added);
+ Assert.Equal(ParameterDirection.ReturnValue, added.Direction);
+ }
+
+ [Fact]
+ public static void AddParameter_NullName_IsRefusedForInput()
+ {
+ IDbCommand command = NewCommand(out _);
+
+ var ex = Assert.Throws(
+ () => command.AddParameter(null!, 0, DbType.Int32));
+
+ Assert.Equal("name", ex.ParamName);
+ }
+}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CanceledLookupTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CanceledLookupTests.cs
new file mode 100644
index 00000000..50ce0e49
--- /dev/null
+++ b/Tests/Open.Database.Extensions.Core.Tests/CanceledLookupTests.cs
@@ -0,0 +1,96 @@
+using System.Data.Common;
+
+namespace Open.Database.Extensions.Tests;
+
+#nullable enable
+
+// A schema lookup that is canceled and surfaces as an ArgumentException (or a
+// NotSupportedException) must not be kept as "the provider reports no names":
+// the metadata twin stores nothing in that case, and the next call must read
+// the names again.
+[ExcludeFromCodeCoverage]
+public static class CanceledLookupTests
+{
+ // Cancels the caller's source inside the schema call of the first lookup and
+ // throws the given failure; every later lookup answers @order_id.
+ sealed class CancelingConnection(
+ Func failure,
+ CancellationTokenSource toCancel) : DbConnection
+ {
+ public DerivedParameterNameTests.RecordingDbCommand Command { get; } = new();
+ public int AsyncSchemaCalls { get; private set; }
+
+ [AllowNull]
+ public override string ConnectionString { get; set; } = "";
+ public override string Database => "fake";
+ public override string DataSource { get; } = NameServer.Unique();
+ public override string ServerVersion => "1.0";
+ public override ConnectionState State => ConnectionState.Open;
+ public override void ChangeDatabase(string databaseName) { }
+ public override void Open() { }
+ public override void Close() { }
+ protected override DbTransaction BeginDbTransaction(
+ IsolationLevel isolationLevel)
+ => throw new NotSupportedException();
+ protected override DbCommand CreateDbCommand() => Command;
+
+ public override DataTable GetSchema(
+ string collectionName,
+ string?[] restrictionValues)
+ => throw new InvalidOperationException("the async path was expected");
+
+ public override Task GetSchemaAsync(
+ string collectionName,
+ string?[] restrictionValues,
+ CancellationToken cancellationToken)
+ {
+ AsyncSchemaCalls++;
+ if (AsyncSchemaCalls == 1)
+ {
+ toCancel.Cancel();
+ throw failure();
+ }
+
+ DataTable table = ProcedureParametersTable.Create();
+ table.Rows.Add("dbo", "proc", 1, "@order_id");
+ return Task.FromResult(table);
+ }
+ }
+
+ public static TheoryData Failures => new()
+ {
+ new ArgumentException("canceled inside the provider"),
+ new NotSupportedException(),
+ };
+
+ [Theory]
+ [MemberData(nameof(Failures), DisableDiscoveryEnumeration = true)]
+ public static async Task ACanceledLookup_IsNotRemembered(
+ Exception failure)
+ {
+ const int orderId = 5;
+ using var source = new CancellationTokenSource();
+ var connection = new CancelingConnection(() => failure, source);
+ string procedure = ParameterNameHarness.NewProcedure();
+
+ await Assert.ThrowsAnyAsync(
+ () => new ExpressiveDbCommand(
+ connection, CommandType.StoredProcedure, procedure)
+ .AddParam(orderId)
+ .ExecuteNonQueryAsync(source.Token)
+ .AsTask());
+
+ Assert.Equal(1, connection.AsyncSchemaCalls);
+ connection.Command.Sent.Clear();
+
+ await new ExpressiveDbCommand(
+ connection, CommandType.StoredProcedure, procedure)
+ .AddParam(orderId)
+ .ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
+
+ Assert.Equal(2, connection.AsyncSchemaCalls);
+ Assert.Equal(
+ ["@order_id"],
+ connection.Command.Sent.Select(p => p.ParameterName));
+ }
+}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/CompletedTransactionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CompletedTransactionTests.cs
new file mode 100644
index 00000000..79f5c146
--- /dev/null
+++ b/Tests/Open.Database.Extensions.Core.Tests/CompletedTransactionTests.cs
@@ -0,0 +1,109 @@
+namespace Open.Database.Extensions.Tests;
+
+#nullable enable
+
+// A transaction that has completed (committed or rolled back) reports no
+// connection, as a provider's does. Every entry point that is given one
+// refuses it the same way: InvalidOperationException (as CreateCommand and
+// DbQuery.Using do), not ArgumentNullException named "connection".
+[ExcludeFromCodeCoverage]
+public static class CompletedTransactionTests
+{
+ static TrackedTransaction Completed(bool rollback)
+ {
+ var tally = new DbTally();
+ TrackedConnection connection = tally.NewOpenConnection();
+ var transaction = (TrackedTransaction)connection.BeginTransaction();
+ if (rollback)
+ {
+ transaction.Rollback();
+ }
+ else
+ {
+ transaction.Commit();
+ }
+
+ Assert.Null(transaction.Connection);
+ return transaction;
+ }
+
+ static readonly string[] Names =
+ [
+ "CreateCommand(IDbTransaction)",
+ "CreateCommand(DbTransaction)",
+ "DbQuery.Using(tx) run",
+ "new ExpressiveCommand(tx)",
+ "new ExpressiveDbCommand(tx)",
+ "IDbTransaction.Command",
+ "DbTransaction.Command",
+ "IDbTransaction.StoredProcedure",
+ "DbTransaction.StoredProcedure",
+ ];
+
+ public static TheoryData EntryPoints()
+ {
+ TheoryData data = [];
+ foreach (string name in Names)
+ {
+ data.Add(name, false);
+ data.Add(name, true);
+ }
+
+ return data;
+ }
+
+ static void Enter(string name, TrackedTransaction tx)
+ {
+ IDbTransaction asInterface = tx;
+ switch (name)
+ {
+ case "CreateCommand(IDbTransaction)":
+ asInterface.CreateCommand(CommandType.Text, "select 1")
+ .Dispose();
+ break;
+ case "CreateCommand(DbTransaction)":
+ tx.CreateCommand(CommandType.Text, "select 1").Dispose();
+ break;
+ case "DbQuery.Using(tx) run":
+ DbQuery.Text("select 1")
+ .Using(tx)
+ .ExecuteReader(static r => r.FieldCount);
+ break;
+ case "new ExpressiveCommand(tx)":
+ _ = new ExpressiveCommand(
+ asInterface, CommandType.Text, "select 1");
+ break;
+ case "new ExpressiveDbCommand(tx)":
+ _ = new ExpressiveDbCommand(
+ asInterface, CommandType.Text, "select 1");
+ break;
+ case "IDbTransaction.Command":
+ _ = asInterface.Command("select 1");
+ break;
+ case "DbTransaction.Command":
+ _ = tx.Command("select 1");
+ break;
+ case "IDbTransaction.StoredProcedure":
+ _ = asInterface.StoredProcedure("dbo.p");
+ break;
+ case "DbTransaction.StoredProcedure":
+ _ = tx.StoredProcedure("dbo.p");
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(name));
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(EntryPoints))]
+ public static void ACompletedTransaction_IsRefusedWithInvalidOperation(
+ string entryPoint,
+ bool rollback)
+ {
+ TrackedTransaction tx = Completed(rollback);
+
+ Exception? ex = Record.Exception(() => Enter(entryPoint, tx));
+
+ Assert.IsType(ex);
+ }
+}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandExecutionTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandExecutionTests.cs
index 39004e3c..484eb305 100644
--- a/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandExecutionTests.cs
+++ b/Tests/Open.Database.Extensions.Core.Tests/ExpressiveCommandExecutionTests.cs
@@ -157,7 +157,7 @@ public static void Transaction_WithoutConnection_Throws()
var transaction = Substitute.For();
transaction.Connection.Returns((IDbConnection)null!);
- Assert.Throws(() => transaction.Command("UPDATE t SET x = 1"));
+ Assert.Throws(() => transaction.Command("UPDATE t SET x = 1"));
}
[Fact]
diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md
index 25790597..613b8762 100644
--- a/docsite/articles/release-notes.md
+++ b/docsite/articles/release-notes.md
@@ -15,6 +15,9 @@ Version 11 is `11.0.0-rc.18`. For moving a 10.x codebase, read [Coming from earl
- **Fixed: the name of the `ArgumentNullException` from `AsGeneric(IDbConnectionPool)`.** A `null` pool threw with the parameter name `source`; it is now `connectionPool`.
- **Changed: more exception messages say what to do.** A blank command (on `CreateCommand` of a connection too), a blank parameter name, a negative count or index, a type with no public constructor given to `Map()`, a mapping with no property name, parameter names that collide, a parameter name that cannot be derived from an argument, and a stream enumerated a second time each name the cause and the fix.
- **Changed: `CreateCommand`, `CreateTextCommand` and `CreateStoredProcedureCommand` on a transaction that has no connection check the connection first.** With a null or blank command text as well, they now throw the `InvalidOperationException` for the missing connection; before, the text was checked first and `ArgumentException` was thrown.
+- **Fixed: `AddParameter(name, value, type, direction)` accepts a `null` name for a return value.** It threw `ArgumentNullException` for a `null` name whatever the direction, though a return value needs no name and `AddParameterType` already accepted it; it now adds an unnamed return parameter, as `AddParameterType` does, and still throws for any other direction.
+- **Fixed: a canceled parameter-name lookup is no longer remembered as "no names".** When the call was canceled while the provider's `GetSchemaAsync` threw `ArgumentException`, `NotSupportedException` or `NotImplementedException`, the lookup took that as "the provider reports no names" and kept it, so later calls of the procedure did not look again; the call ends canceled (`OperationCanceledException`) and nothing is kept, as for the output-parameter metadata.
+- **Changed: constructing a command or calling `Command` or `StoredProcedure` on a transaction that has no connection throws `InvalidOperationException`.** The constructors that take a transaction (`ExpressiveCommand`, `ExpressiveDbCommand`, `ExpressiveSqlCommand`) and the `Command` and `StoredProcedure` extensions of `IDbTransaction` and `DbTransaction` threw `ArgumentNullException` named `connection` for a transaction that has completed; they now throw `InvalidOperationException`, with a message that says the cause and the fix, as `CreateCommand` does. A `null` transaction still throws `ArgumentNullException` named `transaction`.
### Changes since rc.16