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
21 changes: 4 additions & 17 deletions Source/Channel/ChannelPump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ IAsyncEnumerator<TItem> rows

return wait.Result
? new(rows)
: CloseAsync(rows);
: AsyncEnumerators.CloseAsync(rows);
}

static async ValueTask<IAsyncEnumerator<TItem>?> OpenAsync<TItem>(
Expand Down Expand Up @@ -118,18 +118,10 @@ await rows.DisposeAsync()

return room
? rows
: await CloseAsync(rows)
: await AsyncEnumerators.CloseAsync(rows)
.ConfigureAwait(false);
}

static async ValueTask<IAsyncEnumerator<TItem>?> CloseAsync<TItem>(
IAsyncEnumerator<TItem> rows)
{
await rows.DisposeAsync()
.ConfigureAwait(false);
return null;
}

/// <summary>
/// Writes rows from a position of a chunk until the writer has no room.
/// </summary>
Expand Down Expand Up @@ -237,11 +229,7 @@ public async ValueTask<long> WriteAsync(
// so it waits on the caller's token and creates nothing.
var signal = rows as IStallSignal;
using CancellationTokenSource? link
= signal?.Expired.CanBeCanceled is true
? CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
signal.Expired)
: null;
= StallSignal.Link(signal, cancellationToken);
CancellationToken wait = link?.Token ?? cancellationToken;

IAsyncEnumerator<T>? pulled
Expand Down Expand Up @@ -295,8 +283,7 @@ static async ValueTask<bool> WaitAsync(
// The stream expired while the target had no room, and
// the caller did not cancel: Core's own exception, Core's text.
catch (OperationCanceledException)
when (signal.Expired.IsCancellationRequested
&& !cancellationToken.IsCancellationRequested)
when (StallSignal.ExpiredWithoutCancel(signal, cancellationToken))
{
throw signal.ToException();
}
Expand Down
8 changes: 8 additions & 0 deletions Source/Core/ArrayLease.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ internal readonly struct ArrayLease<T>(
int used,
ChunkConfig<T> config,
ClearMode mode)
: IDisposable
{
/// <summary>The pooled array.</summary>
public T[] Array { get; } = array;
Expand Down Expand Up @@ -104,6 +105,13 @@ public void Release()
break;
}
}

/// <summary>
/// Releases the lease, as <see cref="Release"/> does, so that a
/// <c>using</c> gives the array back.
/// </summary>
public void Dispose()
=> Release();
}

/// <summary>The one runner of each row type.</summary>
Expand Down
17 changes: 17 additions & 0 deletions Source/Core/AsyncEnumerators.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Open.Database.Extensions.Core;

/// <summary>
/// What the Channel and Dataflow pumps share about the enumerators they take.
/// </summary>
internal static class AsyncEnumerators
{
// Disposes an enumerator that will not be read; the pumps' answer for
// "nothing to read" is null.
public static async ValueTask<IAsyncEnumerator<TItem>?> CloseAsync<TItem>(
IAsyncEnumerator<TItem> rows)
{
await rows.DisposeAsync()
.ConfigureAwait(false);
return null;
}
}
4 changes: 1 addition & 3 deletions Source/Core/ChunkChain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -298,14 +298,12 @@ public void Dispose()
T[][] chunks = _chunks;
ChunkConfig<T> config = _config!;
int count = _chunkCount;
int lastUsed = _index;
Exception? first = null;
for (int i = 0; i < count; ++i)
{
try
{
int used = i == count - 1 ? lastUsed : chunks[i].Length;
config.SealCopyOut(chunks[i], used).Release();
config.SealCopyOut(chunks[i], Used(i)).Release();
}
catch (Exception ex)
{
Expand Down
22 changes: 11 additions & 11 deletions Source/Core/ChunkSizing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,33 +65,33 @@ public ChunkSizes(
int collectShift = DefaultCollectShift,
int collectMaxRows = DefaultCollectMaxRows)
{
FirstRows = ChunkSizing.IsPowerOfTwo(firstRows) && firstRows <= 1 << 20
? firstRows
: DefaultFirstRows;
FirstRows = Fit(firstRows, 1 << 20, DefaultFirstRows);

StreamMaxRows = ChunkSizing.IsPowerOfTwo(streamMaxRows)
&& streamMaxRows >= FirstRows
&& streamMaxRows <= 1 << 26
? streamMaxRows
: Math.Max(DefaultStreamMaxRows, FirstRows);

CollectFirstRows = ChunkSizing.IsPowerOfTwo(collectFirstRows)
&& collectFirstRows <= 1 << 20
? collectFirstRows
: DefaultCollectFirstRows;
CollectFirstRows = Fit(
collectFirstRows, 1 << 20, DefaultCollectFirstRows);

CollectShift = (uint)(collectShift - 1) <= 3u
? collectShift
: DefaultCollectShift;

CollectMaxRows = ChunkSizing.IsPowerOfTwo(collectMaxRows)
&& collectMaxRows <= 1 << 26
? collectMaxRows
: DefaultCollectMaxRows;
CollectMaxRows = Fit(collectMaxRows, 1 << 26, DefaultCollectMaxRows);

LastStreamDoubling = ChunkSizing.Log2(StreamMaxRows / FirstRows);
}

// The value when it is a power of two no larger than the maximum;
// otherwise the default.
static int Fit(int value, int max, int fallback)
=> ChunkSizing.IsPowerOfTwo(value) && value <= max
? value
: fallback;

/// <summary>Gets the number of rows in the first chunk of a buffer or a stream.</summary>
public int FirstRows { get; }

Expand Down
4 changes: 2 additions & 2 deletions Source/Core/ChunkStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ async IAsyncEnumerator<ReadOnlyMemory<T>> Read(
&& reader.TryRead(out ArrayLease<T> chunk))
{
// The array goes back at the next step.
try { yield return chunk.Memory; }
finally { chunk.Release(); }
using (chunk)
yield return chunk.Memory;
}

cancellationToken.ThrowIfCancellationRequested();
Expand Down
15 changes: 10 additions & 5 deletions Source/Core/DbQueryBinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ public static string ResolveDerived(
if (last is null || !ReferenceEquals(last.Names, names))
{
string real = names!.Match(derived.Expression, definition.CommandText)
?? throw NoMatch(derived.Expression, names!, definition);
?? throw NoMatch(
derived.Expression, definition.CommandText,
"It declares", names!.Names);
last = new(names!, real, names!.Find(real));
derived.Last = last;
}
Expand Down Expand Up @@ -312,9 +314,12 @@ static InvalidOperationException Collision(
: "The parameter names are not known, so each argument is used under its last member as written.")
+ " Name one of them explicitly: AddParam(\"name\", value).");

static InvalidOperationException NoMatch(
// The one text of "matches none", for a command and for a query: the owner
// is the command text or procedure name, declares the words before the names.
public static InvalidOperationException NoMatch(
string expression,
NameSet names,
DbQuery definition)
=> new($"The argument '{expression}' matches none of the parameters of '{definition.CommandText}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). It declares: {string.Join(", ", names.Names)}. Name the parameter explicitly: AddParam(\"name\", value).");
string owner,
string declares,
ImmutableArray<string> declared)
=> new($"The argument '{expression}' matches none of the parameters of '{owner}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). {declares}: {string.Join(", ", declared)}. Name the parameter explicitly: AddParam(\"name\", value).");
}
8 changes: 2 additions & 6 deletions Source/Core/DirectStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,13 @@ public DirectStream(
internal bool HasTimer => Volatile.Read(ref _timer) is not null;

TimeoutException ToException()
=> new($"The consumer made no pull for {_stall} while the reader and the connection were held; the read was stopped.");
=> StallStream.TimeoutFor(_stall);

public IAsyncEnumerator<T> GetAsyncEnumerator(
CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _taken, 1) != 0)
{
throw new InvalidOperationException(
"This stream can be enumerated only once."
+ " Call ToListAsync() or ToPooledBuffer() to read the rows more than once.");
}
throw StallStream.EnumeratedTwice();

return Read(cancellationToken);
}
Expand Down
35 changes: 16 additions & 19 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -992,18 +992,18 @@ await ProcedureParameterMetadata.EnsureAsync(
return names;
}

NameSet? WrittenNames()
{
if (_params is not { Count: > 0 } || Type != CommandType.Text || Command is not { Length: > 0 } text) return null;
// The @names the text declares, when it declares any.
NameSet? TextNames()
=> Type == CommandType.Text && Command is { Length: > 0 } text && TextNameCache.Get(text) is { Names.Length: > 0 } names
? names
: null;

return TextNameCache.Get(text) is { Names.Length: > 0 } names ? names : null;
}
NameSet? WrittenNames()
=> _params is { Count: > 0 } ? TextNames() : null;

// The count of @names the text declares (one slot each), else the default growth.
int ScannedCount()
=> Type == CommandType.Text && Command is { Length: > 0 } text && TextNameCache.Get(text) is { Names.Length: > 0 } names
? names.Names.Length
: 0;
=> TextNames()?.Names.Length ?? 0;

TCommand PrepareWritten(TConnection connection)
=> WrittenNames() is { } text
Expand Down Expand Up @@ -1230,7 +1230,7 @@ InvalidOperationException Collision(string name, Param first, Param second, Immu
+ " Name one of them explicitly: AddParam(\"name\", value).");

InvalidOperationException NoMatch(string expression, ImmutableArray<string> real)
=> new($"The argument '{expression}' matches none of the parameters of '{Command}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). The procedure declares: {string.Join(", ", real)}. Name the parameter explicitly: AddParam(\"name\", value).");
=> DbQueryBinding.NoMatch(expression, Command, "The procedure declares", real);

#endregion

Expand Down Expand Up @@ -1537,6 +1537,11 @@ internal T Execute<T>(Func<TCommand, T> transform)
return ExecuteCore(transform, static (cmd, _, f) => f(cmd));
}

// The refusal of an ExecuteAsync that has captures: they are completed with it.
static Exception AsyncRefused(CaptureSet captures)
=> captures.Refuse(new InvalidOperationException(
CaptureMessages.ExecuteAsync(captures)));

/// <inheritdoc />
public virtual ValueTask ExecuteAsync(Func<TCommand, ValueTask> handler)
{
Expand All @@ -1545,11 +1550,7 @@ public virtual ValueTask ExecuteAsync(Func<TCommand, ValueTask> handler)

// Your code runs the command, so nothing can fill a capture: refused,
// and the capture completed with the refusal.
if (_captures is { } captures)
{
throw captures.Refuse(new InvalidOperationException(
CaptureMessages.ExecuteAsync(captures)));
}
if (_captures is { } captures) throw AsyncRefused(captures);

CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task.

Expand All @@ -1568,11 +1569,7 @@ public virtual ValueTask<T> ExecuteAsync<T>(Func<TCommand, ValueTask<T>> transfo
Contract.EndContractBlock();

// As above.
if (_captures is { } captures)
{
throw captures.Refuse(new InvalidOperationException(
CaptureMessages.ExecuteAsync(captures)));
}
if (_captures is { } captures) throw AsyncRefused(captures);

CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task.

Expand Down
2 changes: 1 addition & 1 deletion Source/Core/ExpressiveDbCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public ExpressiveDbCommand(
CommandType type,
string command,
IEnumerable<Param>? @params = null)
: base(connFactory.AsPool(), type, command, @params)
: base(connFactory, type, command, @params)
{
}

Expand Down
24 changes: 9 additions & 15 deletions Source/Core/MappedDbQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource<T> source)
/// <seealso cref="WithOptions(QueryOptions)"/>

public MappedDbQuery<T> SingleResult()
=> new(
Query, _source, _options | QueryOptions.SingleResult,
_pool, _clearOnReturn);
=> With(_options | QueryOptions.SingleResult);

/// <summary>
/// Cancels the command when a terminal stops before the last row, in every query made from this definition
Expand All @@ -78,9 +76,7 @@ public MappedDbQuery<T> SingleResult()
/// <returns>A definition whose queries cancel their command on an early stop.</returns>
/// <seealso cref="WithOptions(QueryOptions)"/>
public MappedDbQuery<T> CancelOnEarlyStop()
=> new(
Query, _source, _options | QueryOptions.CancelOnEarlyStop,
_pool, _clearOnReturn);
=> With(_options | QueryOptions.CancelOnEarlyStop);

/// <summary>
/// Reads the rows with the asynchronous read of the provider, in every query made from this definition
Expand All @@ -89,9 +85,7 @@ public MappedDbQuery<T> CancelOnEarlyStop()
/// <returns>A definition that reads asynchronously.</returns>
/// <seealso cref="WithOptions(QueryOptions)"/>
public MappedDbQuery<T> AsyncReads()
=> new(
Query, _source, _options | QueryOptions.AsyncReads,
_pool, _clearOnReturn);
=> With(_options | QueryOptions.AsyncReads);

/// <summary>
/// Asks the reader for sequential access, in every query made from this definition
Expand All @@ -100,9 +94,7 @@ public MappedDbQuery<T> AsyncReads()
/// <returns>A definition whose queries read with sequential access.</returns>
/// <seealso cref="WithOptions(QueryOptions)"/>
public MappedDbQuery<T> SequentialAccess()
=> new(
Query, _source, _options | QueryOptions.SequentialAccess,
_pool, _clearOnReturn);
=> With(_options | QueryOptions.SequentialAccess);

/// <summary>
/// Returns a definition whose switches, in every query made from it, are
Expand All @@ -111,9 +103,11 @@ public MappedDbQuery<T> SequentialAccess()
/// <include file="Mapped.docs.xml" path="docs/members[@name='options']/*" />
/// <returns>A definition with exactly these switches.</returns>
public MappedDbQuery<T> WithOptions(QueryOptions options)
=> new(
Query, _source, Views.CheckedOptions(options),
_pool, _clearOnReturn);
=> With(Views.CheckedOptions(options));

// The same definition with other switches.
MappedDbQuery<T> With(QueryOptions options)
=> new(Query, _source, options, _pool, _clearOnReturn);

/// <summary>
/// Takes the arrays that hold the rows from <paramref name="pool"/>, in every query made from this definition
Expand Down
Loading