Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Source/Core/Commands.docs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,8 @@
<paramref name="transaction"/> or <paramref name="command"/> is
<see langword="null"/>.
</exception>
<exception cref="InvalidOperationException">
The transaction has no connection.
</exception>
</members>
</docs>
13 changes: 11 additions & 2 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

/// <summary>
/// Gets the transaction the command runs in, or <see langword="null"/>
/// when it was not given one.
Expand Down Expand Up @@ -200,8 +210,7 @@ protected ExpressiveCommandBase(
string command,
IEnumerable<Param>? @params)
: this(
(TConnection)(transaction ?? throw new ArgumentNullException(nameof(transaction))).Connection!,
transaction, type, command, @params)
ConnectionOf(transaction), transaction, type, command, @params)
{
}

Expand Down
7 changes: 3 additions & 4 deletions Source/Core/Extensions/Command.AddParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,12 @@ public static IDbDataParameter AddParameter(
/// Adds a typed parameter with the given name, value, and direction to the command.
/// </summary>
/// <include file="Readers.docs.xml" path="docs/members[@name='param-target']/*" />
/// <include file="Readers.docs.xml" path="docs/members[@name='param-name']/*" />
/// <param name="name">The name of the parameter. It can be <see langword="null"/> only when <paramref name="direction"/> is <see cref="ParameterDirection.ReturnValue"/>.</param>
/// <param name="value">The value of the parameter. It is assigned as given: a <see langword="null"/> is not converted to <see cref="DBNull.Value"/>, so pass <see cref="DBNull.Value"/> to send a database null.</param>
/// <include file="Readers.docs.xml" path="docs/members[@name='param-type']/*" />
/// <include file="Readers.docs.xml" path="docs/members[@name='param-direction']/*" />
/// <include file="Readers.docs.xml" path="docs/members[@name='param-created']/*" />
/// <include file="Readers.docs.xml" path="docs/members[@name='null-target-name']/*" />
/// <exception cref="ArgumentNullException"><paramref name="target"/> is <see langword="null"/>, or <paramref name="name"/> is <see langword="null"/> and <paramref name="direction"/> is not <see cref="ParameterDirection.ReturnValue"/>.</exception>
/// <include file="Readers.docs.xml" path="docs/members[@name='blank-name']/*" />
public static IDbDataParameter AddParameter(
this IDbCommand target,
Expand All @@ -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;
}

Expand Down
2 changes: 2 additions & 0 deletions Source/Core/Extensions/ConnectionProvider.Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public static ExpressiveCommand Command(
/// <include file="Connections.docs.xml" path="docs/members[@name='command-text']/*" />
/// <returns>A new <see cref="ExpressiveCommand"/> to configure with parameters and then execute.</returns>
/// <exception cref="ArgumentNullException"><paramref name="transaction"/> or <paramref name="command"/> is <see langword="null"/>.</exception>
/// <include file="Connections.docs.xml" path="docs/members[@name='transaction-no-connection']/*" />
public static ExpressiveCommand Command(
this IDbTransaction transaction,
string command, CommandType type = CommandType.Text)
Expand Down Expand Up @@ -98,6 +99,7 @@ public static ExpressiveCommand StoredProcedure(
/// <include file="Connections.docs.xml" path="docs/members[@name='procedure']/*" />
/// <returns>A new <see cref="ExpressiveCommand"/> with <see cref="CommandType.StoredProcedure"/> to configure with parameters and then execute.</returns>
/// <exception cref="ArgumentNullException"><paramref name="transaction"/> or <paramref name="procedureName"/> is <see langword="null"/>.</exception>
/// <include file="Connections.docs.xml" path="docs/members[@name='transaction-no-connection']/*" />
public static ExpressiveCommand StoredProcedure(
this IDbTransaction transaction,
string procedureName)
Expand Down
3 changes: 3 additions & 0 deletions Source/Core/ProcedureSchemaNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ public static async ValueTask<ImmutableArray<string>> 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)
Expand Down
2 changes: 2 additions & 0 deletions Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public static ExpressiveSqlCommand Command(
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='command-text']/*" />
/// <returns>A new <see cref="ExpressiveSqlCommand"/> to configure with parameters and then execute.</returns>
/// <exception cref="ArgumentNullException"><paramref name="transaction"/> or <paramref name="command"/> is <see langword="null"/>.</exception>
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='transaction-no-connection']/*" />
public static ExpressiveSqlCommand Command(
this SqlTransaction transaction,
string command, CommandType type = CommandType.Text)
Expand All @@ -64,6 +65,7 @@ public static ExpressiveSqlCommand StoredProcedure(
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='procedure']/*" />
/// <returns>A new <see cref="ExpressiveSqlCommand"/> with <see cref="CommandType.StoredProcedure"/> to configure with parameters and then execute.</returns>
/// <exception cref="ArgumentNullException"><paramref name="transaction"/> or <paramref name="procedureName"/> is <see langword="null"/>.</exception>
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='transaction-no-connection']/*" />
public static ExpressiveSqlCommand StoredProcedure(
this SqlTransaction transaction,
string procedureName)
Expand Down
3 changes: 3 additions & 0 deletions Source/MSSqlClient/Extensions/MSSqlClient.docs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@
<paramref name="transaction"/> or <paramref name="command"/> is
<see langword="null"/>.
</exception>
<exception cref="InvalidOperationException">
The transaction has no connection.
</exception>
</members>

<members name="condition">
Expand Down
Original file line number Diff line number Diff line change
@@ -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<IDbCommand>();
parameter = Substitute.For<IDbDataParameter>();
command.CreateParameter().Returns(parameter);
command.Parameters.Returns(Substitute.For<IDataParameterCollection>());
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<ArgumentNullException>(
() => command.AddParameter(null!, 0, DbType.Int32));

Assert.Equal("name", ex.ParamName);
}
}
96 changes: 96 additions & 0 deletions Tests/Open.Database.Extensions.Core.Tests/CanceledLookupTests.cs
Original file line number Diff line number Diff line change
@@ -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<Exception> 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<DataTable> 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<Exception> 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<OperationCanceledException>(
() => 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));
}
}
109 changes: 109 additions & 0 deletions Tests/Open.Database.Extensions.Core.Tests/CompletedTransactionTests.cs
Original file line number Diff line number Diff line change
@@ -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<string, bool> EntryPoints()
{
TheoryData<string, bool> 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<InvalidOperationException>(ex);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public static void Transaction_WithoutConnection_Throws()
var transaction = Substitute.For<IDbTransaction>();
transaction.Connection.Returns((IDbConnection)null!);

Assert.Throws<ArgumentNullException>(() => transaction.Command("UPDATE t SET x = 1"));
Assert.Throws<InvalidOperationException>(() => transaction.Command("UPDATE t SET x = 1"));
}

[Fact]
Expand Down
3 changes: 3 additions & 0 deletions docsite/articles/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()`, 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

Expand Down