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
1 change: 1 addition & 0 deletions Source/Channel/ToChannel.Target.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public static ValueTask<long> ToChannel<T>(
bool complete,
CancellationToken cancellationToken = default)
{
// The source is guarded by the ChannelWriter overload.
if (channel is null) throw new ArgumentNullException(nameof(channel));
Contract.EndContractBlock();

Expand Down
6 changes: 1 addition & 5 deletions Source/Core/ChunkStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,7 @@ public IAsyncEnumerator<ReadOnlyMemory<T>> GetAsyncEnumerator(
// The one-shot guard is here, not in the iterator: an iterator body runs
// at the first step, and the second call must throw at the call.
if (Interlocked.Exchange(ref _taken, 1) != 0)
{
throw new InvalidOperationException(
"This stream can be enumerated only once."
+ " Call ToPooledBuffer() to read it many times.");
}
throw StallStream.EnumeratedTwice();

return Read(cancellationToken);
}
Expand Down
6 changes: 3 additions & 3 deletions Source/Core/Core/RowMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -849,8 +849,8 @@ internal static void ThrowIfUnmappable()
// A column a member declares by ordinal ([Column(Order = n)]) is its before any tier runs, so none gives it away; a column that is not its throws.
int claimed = HasDecorators ? ClaimOrdinals(names, feeds, filled) : 0;

int unmatched = names.Length - claimed - Feed(ColumnIndex(StringComparer.Ordinal), names, feeds, filled);
if (unmatched > 0) unmatched -= Feed(ColumnIndex(StringComparer.OrdinalIgnoreCase), names, feeds, filled);
int unmatched = names.Length - claimed - Feed(OrdinalsByName(StringComparer.Ordinal), names, feeds, filled);
if (unmatched > 0) unmatched -= Feed(OrdinalsByName(StringComparer.OrdinalIgnoreCase), names, feeds, filled);
if (unmatched > 0 && NameIndex(filled) is { } byName) Feed(byName, names, feeds, filled);

return feeds;
Expand Down Expand Up @@ -884,7 +884,7 @@ int Feed(Dictionary<string, int> index, string[] names, Slot?[] feeds, bool[] fi
/// <remarks>
/// A member that declares its column (<c>[Column(Name)]</c>) is asked first: another member reading the same name does not take it.
/// </remarks>
Dictionary<string, int> ColumnIndex(StringComparer comparer)
Dictionary<string, int> OrdinalsByName(StringComparer comparer)
{
var index = new Dictionary<string, int>(_columns.Length, comparer);

Expand Down
8 changes: 5 additions & 3 deletions Source/Core/Extensions/Command.AddParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,15 +185,17 @@ public static IDbDataParameter AddParameterType(
/// </summary>
/// <include file="Readers.docs.xml" path="docs/members[@name='param-target']/*" />
/// <include file="Readers.docs.xml" path="docs/members[@name='param-type']/*" />
/// <param name="name">The optional name of the parameter.</param>
/// <param name="name">The optional name of the parameter. It is ignored if it is <see langword="null"/>, empty, or white space.</param>
/// <returns>The created parameter, which has already been added to the command's parameter collection. Read its value after the command has executed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="target"/> is <see langword="null"/>.</exception>
/// <include file="Readers.docs.xml" path="docs/members[@name='blank-name']/*" />
public static IDbDataParameter AddReturnParameter(
this IDbCommand target,
DbType type,
string? name = null)
=> target.AddParameterType(name, type, ParameterDirection.ReturnValue);
=> target.AddParameterType(
string.IsNullOrWhiteSpace(name) ? null : name,
type,
ParameterDirection.ReturnValue);

/// <summary>
/// Adds a return-value parameter to the command, leaving the provider to determine its type.
Expand Down
30 changes: 18 additions & 12 deletions Source/Core/Extensions/ConnectionProvider.Using.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,9 @@ public static async ValueTask<T> UsingAsync<T>(this IDbConnectionFactory connect
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using IDbConnection conn = connectionFactory.Create();
return await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory.Create(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
return await action(lease.Connection).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -203,8 +204,9 @@ public static async ValueTask UsingAsync(this IDbConnectionFactory connectionFac
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using IDbConnection conn = connectionFactory.Create();
await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory.Create(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
await action(lease.Connection).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -222,8 +224,9 @@ public static async ValueTask<T> UsingAsync<TConnection, T>(this IDbConnectionFa
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using TConnection conn = connectionFactory.Create();
return await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory.Create(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
return await action(lease.Connection).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -240,8 +243,9 @@ public static async ValueTask UsingAsync<TConnection>(this IDbConnectionFactory<
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using TConnection conn = connectionFactory.Create();
await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory.Create(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
await action(lease.Connection).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -333,8 +337,9 @@ public static async ValueTask<T> UsingAsync<TConnection, T>(this Func<TConnectio
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using TConnection conn = connectionFactory();
return await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
return await action(lease.Connection).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -351,7 +356,8 @@ public static async ValueTask UsingAsync<TConnection>(this Func<TConnection> con
if (action is null) throw new ArgumentNullException(nameof(action));
Contract.EndContractBlock();

using TConnection conn = connectionFactory();
await action(conn).ConfigureAwait(false);
var lease = Seal(connectionFactory(), default, null);
await using var leaseDisposal = lease.ConfigureAwait(false);
await action(lease.Connection).ConfigureAwait(false);
}
}
27 changes: 21 additions & 6 deletions Source/Core/IDbConnectionPool.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics;

namespace Open.Database.Extensions;

/// <summary>
Expand Down Expand Up @@ -69,12 +71,20 @@ public static class ConnectionPoolExtensions
/// <summary>
/// Presents a non-generic pool as an <see cref="IDbConnectionPool{TConnection}"/> of <see cref="IDbConnection"/> by forwarding to it.
/// </summary>
/// <param name="source">The pool to forward to.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
class GenericPool(IDbConnectionPool source) : IDbConnectionPool<IDbConnection>, IConnectionIdentity
class GenericPool : IDbConnectionPool<IDbConnection>, IConnectionIdentity
{
private readonly IDbConnectionPool _source
= source ?? throw new ArgumentNullException(nameof(source));
private readonly IDbConnectionPool _source;

/// <summary>
/// Initializes a new instance that forwards to the pool.
/// </summary>
/// <param name="source">The pool to forward to.</param>
public GenericPool(IDbConnectionPool source)
{
// Guarded by AsGeneric, the only place that makes one.
Debug.Assert(source is not null);
_source = source;
}

/// <inheritdoc />
public IDbConnection Take()
Expand All @@ -100,5 +110,10 @@ object IConnectionIdentity.Identity
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="connectionPool"/> is <see langword="null"/>.</exception>
public static IDbConnectionPool<IDbConnection> AsGeneric(this IDbConnectionPool connectionPool)
=> connectionPool is IDbConnectionPool<IDbConnection> p ? p : new GenericPool(connectionPool);
{
if (connectionPool is null) throw new ArgumentNullException(nameof(connectionPool));
Contract.EndContractBlock();

return connectionPool is IDbConnectionPool<IDbConnection> p ? p : new GenericPool(connectionPool);
}
}
9 changes: 6 additions & 3 deletions Source/Core/StallStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,13 @@ internal static class StallStream
public static TimeoutException TimeoutFor(TimeSpan stall)
=> new($"The consumer made no pull for {stall} while the reader and the connection were held; the read was stopped.");

/// <summary>A stream is enumerated a second time.</summary>
public const string EnumeratedTwiceMessage
= "This stream can be enumerated only once. "
+ "Call ToListAsync() or ToPooledBuffer() to read the rows more than once.";

public static InvalidOperationException EnumeratedTwice()
=> new(
"This stream can be enumerated only once."
+ " Call ToListAsync() or ToPooledBuffer() to read the rows more than once.");
=> new(EnumeratedTwiceMessage);

/// <summary>
/// Gets the buffer size, in rows, unless the caller asks for another one.
Expand Down
9 changes: 6 additions & 3 deletions Source/MSSqlClient/Extensions/Command.AddParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,14 @@ public static SqlParameter AddParameterType(
/// </summary>
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='param-target']/*" />
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='param-type']/*" />
/// <param name="name">The optional name of the parameter.</param>
/// <param name="name">The optional name of the parameter. It is ignored if it is <see langword="null"/>, empty, or white space.</param>
/// <returns>The created parameter, which has already been added to the command's parameter collection. Read its value after the command has executed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="target"/> is <see langword="null"/>.</exception>
/// <include file="MSSqlClient.docs.xml" path="docs/members[@name='blank-name']/*" />
public static SqlParameter AddReturnParameter(this SqlCommand target,
SqlDbType type, string? name = null)
=> AddParameterType(target, name, type, ParameterDirection.ReturnValue);
=> AddParameterType(
target,
string.IsNullOrWhiteSpace(name) ? null : name,
type,
ParameterDirection.ReturnValue);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Threading.Tasks.Dataflow;
using Open.Database.Extensions.Core;

#nullable enable

Expand Down Expand Up @@ -154,7 +155,7 @@ public static async Task ASecondEnumeration_IsRefused_AndLeavesTheFirstRun()
Contains(
Assert.Throws<InvalidOperationException>(
() => rows.GetAsyncEnumerator(Token)),
"can be enumerated only once");
StallStream.EnumeratedTwiceMessage);
Assert.Equal(3, count);
Assert.Equal(9, await total);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,43 @@ public static void AddReturnParameter_SetsReturnDirection()
Assert.Equal(ParameterDirection.ReturnValue, param.Direction);
}

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public static void AddReturnParameter_NullOrBlankName_AddsAnUnnamedParameter(
string? name)
{
(IDbCommand command, IDbDataParameter param, IDataParameterCollection parameters)
= NewCommand();
param.ParameterName = "unset";

command.AddReturnParameter(DbType.Int32, name);

Assert.Equal("unset", param.ParameterName);
Assert.Equal(DbType.Int32, param.DbType);
Assert.Equal(ParameterDirection.ReturnValue, param.Direction);
parameters.Received(1).Add(param);
}

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public static void AddReturnParameter_Untyped_NullOrBlankName_AddsAnUnnamedParameter(
string? name)
{
(IDbCommand command, IDbDataParameter param, IDataParameterCollection parameters)
= NewCommand();
param.ParameterName = "unset";

command.AddReturnParameter(name);

Assert.Equal("unset", param.ParameterName);
Assert.Equal(ParameterDirection.ReturnValue, param.Direction);
parameters.Received(1).Add(param);
}

[Fact]
public static void AddParameter_BlankName_Throws()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,39 @@ await Assert.ThrowsAsync<InvalidOperationException>(async () =>
Assert.Equal("Create,DisposeConnection", probe.Log);
}

[Fact]
public static async Task FactoryUsingAsync_AsyncDisposableConnection_IsDisposedAsynchronously()
{
int synchronous = 0;
int asynchronous = 0;
var connection = Substitute.For<IDbConnection, IAsyncDisposable>();
connection.When(c => c.Dispose()).Do(_ => ++synchronous);
#pragma warning disable CA2012 // NSubstitute is told what the call returns here; nothing consumes the ValueTask.
((IAsyncDisposable)connection).DisposeAsync().Returns(_ =>
{
++asynchronous;
return default;
});
#pragma warning restore CA2012

var factory = Substitute.For<IDbConnectionFactory>();
factory.Create().Returns(connection);
var generic = Substitute.For<IDbConnectionFactory<IDbConnection>>();
generic.Create().Returns(connection);
Func<IDbConnection> function = () => connection;

await factory.UsingAsync(_ => ValueTask.CompletedTask);
await factory.UsingAsync(_ => new ValueTask<int>(1));
await generic.UsingAsync(_ => ValueTask.CompletedTask);
await generic.UsingAsync(_ => new ValueTask<int>(1));
await function.UsingAsync(_ => ValueTask.CompletedTask);
await function.UsingAsync(_ => new ValueTask<int>(1));

// One asynchronous disposal for each of the six calls, and no other.
Assert.Equal(6, asynchronous);
Assert.Equal(0, synchronous);
}

#endregion

#region Argument validation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ static string Refusal(Action act)
public static void ANullSource_IsRefused_ByNamingTheParameter()
{
Assert.Equal("ArgumentNullException:connectionFactory", Refusal(() => _ = new ExpressiveCommand((IDbConnectionFactory)null!, CommandType.StoredProcedure, "proc")));
Assert.Equal("ArgumentNullException:source", Refusal(() => _ = new ExpressiveCommand((IDbConnectionPool)null!, CommandType.StoredProcedure, "proc")));
Assert.Equal("ArgumentNullException:connectionPool", Refusal(() => _ = new ExpressiveCommand((IDbConnectionPool)null!, CommandType.StoredProcedure, "proc")));
Assert.Equal("ArgumentNullException:connFactory", Refusal(() => _ = new ExpressiveCommand((Func<IDbConnection>)null!, CommandType.StoredProcedure, "proc")));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ public static void AsPool_NullSource_NamesTheSource(string call)
Assert.Equal("factory", ex.ParamName);
}

[Fact]
public static void AsGeneric_NullPool_NamesTheConnectionPool()
{
Assert.Equal("connectionPool", Assert.Throws<ArgumentNullException>(
() => ((IDbConnectionPool)null!).AsGeneric()).ParamName);
Assert.Equal("connectionFactory", Assert.Throws<ArgumentNullException>(
() => ((IDbConnectionFactory)null!).AsGeneric()).ParamName);
}

[Fact]
public static void AsPool_NullFactory_NamesTheFactory()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,17 @@ public static async Task Async_FindsTheSameNames()

// ---- the procedure name: which restrictions are asked ----

// These names are not ones ParameterNameHarness.NewProcedure hands out (dbo.namesN): a qualified name
// is remembered for every connection of this kind, so one that another test has used is not read again.
[Theory]
[InlineData("names1", null, "names1")]
[InlineData("dbo.names1", "dbo", "names1")]
[InlineData("[dbo].[names1]", "dbo", "names1")]
[InlineData("\"dbo\".\"names1\"", "dbo", "names1")]
[InlineData("split1", null, "split1")]
[InlineData("dbo.split1", "dbo", "split1")]
[InlineData("[dbo].[split1]", "dbo", "split1")]
[InlineData("\"dbo\".\"split1\"", "dbo", "split1")]
[InlineData("[my.schema].[my proc]", "my.schema", "my proc")]
[InlineData("\"dbo\".\"my.proc\"", "dbo", "my.proc")]
[InlineData("[sales].[a]]b]", "sales", "a]b")]
[InlineData("names1;1", null, "names1;1")] // nothing is stripped that the provider could still resolve
[InlineData("split1;1", null, "split1;1")] // nothing is stripped that the provider could still resolve
public static void TheProcedureName_IsSplitIntoSchemaAndName_ForTheRestrictions(string procedure, string? schema, string name)
{
const int orderId = 5;
Expand Down
26 changes: 26 additions & 0 deletions Tests/Open.Database.Extensions.Core.Tests/PumpStreamOpenTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,32 @@ IAsyncEnumerable<ChannelRow> stream
await TakeAndDispose(stream, tally);
}

[Fact]
public static void ChunkStream_ASecondEnumeration_SaysWhatToCallInstead()
{
IAsyncEnumerable<ReadOnlyMemory<ChannelRow>> stream
= Read(Tally(3)).ToPooledBufferStream(Ct);
stream.GetAsyncEnumerator(Ct);

var ex = Assert.Throws<InvalidOperationException>(
() => stream.GetAsyncEnumerator(Ct));

Assert.Equal(StallStream.EnumeratedTwiceMessage, ex.Message);
}

[Fact]
public static void StallStream_ASecondEnumeration_SaysWhatToCallInstead()
{
IAsyncEnumerable<ChannelRow> stream
= Read(Tally(3)).StreamBuffered(Long, 1, Ct);
stream.GetAsyncEnumerator(Ct);

var ex = Assert.Throws<InvalidOperationException>(
() => stream.GetAsyncEnumerator(Ct));

Assert.Equal(StallStream.EnumeratedTwiceMessage, ex.Message);
}

[Fact]
public static async Task CapturedStream_OverChunks_StartsNothing_UntilTheFirstPull()
{
Expand Down
Loading