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: 1 addition & 2 deletions Source/Core/Core/RowsSources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ namespace Open.Database.Extensions.Core;
/// <summary>
/// Reads a row without a model: one slot for each column, <see cref="DBNull"/> read as <see langword="null"/>.
/// </summary>
// GetValues reads each column once, in order, so a provider may stream the row
// (the read mode of a generated mapping applies: SequentialAccess).
// GetValues reads each column once, in order, so it also works with SequentialAccess().
static class ObjectRow
{
/// <summary>Reads the current row of a record.</summary>
Expand Down
43 changes: 41 additions & 2 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ private protected sealed class CommandOptions
public CancellationToken CancellationToken;
public ushort Timeout = CommandTimeout.DEFAULT_SECONDS;
public bool AsyncReads;
public bool SequentialAccess;
}

private protected CommandOptions? _options;
Expand Down Expand Up @@ -741,6 +742,44 @@ public TThis SetTimeout(ushort seconds)
return (TThis)this;
}

/// <summary>Opens this command's readers with <see cref="CommandBehavior.SequentialAccess"/>, for very large text or binary values.</summary>
/// <remarks>
/// <para>
/// The provider then streams each row instead of buffering it, and a column can be read once, in ascending order.
/// It applies to every reader this command opens from then on: a reader callback, the <c>Map</c> terminals (also of a view made before this call)
/// and the <see cref="DataTable"/> terminals. It stays on the command.
/// Without it the library reads with the default access mode.
/// </para>
/// <para>
/// The typical use is to copy one very large value as a stream: select the key columns first and the large column last,
/// and read it in a reader callback with <see cref="DbDataReader.GetStream(int)"/>.
/// A selector given to <c>Map</c> must read the columns in ascending order, or the provider throws.
/// </para>
/// </remarks>
/// <example>
/// Copy one large value from a command made on a <see cref="DbConnection"/> or a factory:
/// <code>
/// await command
/// .SequentialAccess()
/// .ExecuteReaderAsync(async ValueTask (reader) =>
/// {
/// if (!await reader.ReadAsync(cancellationToken)) return;
/// using Stream value = reader.GetStream(0);
/// await value.CopyToAsync(destination, cancellationToken);
/// }, cancellationToken: cancellationToken);
/// </code>
/// </example>
/// <returns>This instance for use in method chaining.</returns>
public TThis SequentialAccess()
{
EnsureOptions().SequentialAccess = true;
return (TThis)this;
}

// The behavior a reader of this command is asked for: the caller's, and sequential access when SequentialAccess() was called.
CommandBehavior WithAccess(CommandBehavior behavior)
=> _options is { SequentialAccess: true } ? behavior | CommandBehavior.SequentialAccess : behavior;

#region Derived parameter names

/// <summary>
Expand Down Expand Up @@ -1395,7 +1434,7 @@ internal TResult ExecuteReader<TState, TResult>(TState state, Func<IDataReader,
if (transform is null) throw new ArgumentNullException(nameof(transform));
Contract.EndContractBlock();

return ExecuteCore((state, transform, behavior), static (cmd, prior, s) =>
return ExecuteCore((state, transform, behavior: WithAccess(behavior)), static (cmd, prior, s) =>
{
ReaderAbandon.ArmFor(s.transform, cmd);
CommandBehavior b = ConnectionExtensions.ReaderBehavior(prior, s.behavior);
Expand Down Expand Up @@ -1498,7 +1537,7 @@ ValueTask<T> IExecuteReader<TReader>.ExecuteReaderAsync<T>(
=> ExecuteReaderAsync(handler, behavior, default);

ValueTask<TResult> ExecuteReaderCoreAsync<TState, TResult>(TState state, Func<IDataReader, TState, ValueTask<TResult>> transform, CommandBehavior behavior, CancellationToken cancellationToken)
=> ExecuteCoreAsync((state, transform, behavior, cancellationToken), static async (cmd, prior, s) =>
=> ExecuteCoreAsync((state, transform, behavior: WithAccess(behavior), cancellationToken), static async (cmd, prior, s) =>
{
ReaderAbandon.ArmFor(s.transform, cmd);
CommandBehavior b = ConnectionExtensions.ReaderBehavior(prior, s.behavior);
Expand Down
34 changes: 25 additions & 9 deletions Source/Core/MappedDbQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ namespace Open.Database.Extensions;
/// </para>
/// <para>
/// Set on the definition, for every query made from it: the map, <see cref="SingleResult"/>, <see cref="CancelOnEarlyStop"/>, <see cref="AsyncReads"/>,
/// <see cref="UsePool(ArrayPool{T}, bool)"/> and (on the <see cref="DbQuery"/> before <c>Map</c>)
/// <see cref="DbQuery.SetTimeout(ushort)"/>. A query made from it can still apply <c>SingleResult</c>, <c>CancelOnEarlyStop</c>, <c>AsyncReads</c> and
/// <c>UsePool</c> for one call. Chosen per call: the parameters, <c>Skip</c> and <c>Take</c>.
/// <see cref="SequentialAccess"/>, <see cref="UsePool(ArrayPool{T}, bool)"/> and (on the <see cref="DbQuery"/> before <c>Map</c>)
/// <see cref="DbQuery.SetTimeout(ushort)"/>. A query made from it can still apply <c>SingleResult</c>, <c>CancelOnEarlyStop</c>, <c>AsyncReads</c>,
/// <c>SequentialAccess</c> and <c>UsePool</c> for one call. Chosen per call: the parameters, <c>Skip</c> and <c>Take</c>.
/// </para>
/// </remarks>
/// <typeparam name="T">The type each row is mapped to.</typeparam>
Expand All @@ -35,9 +35,10 @@ public sealed class MappedDbQuery<T>
readonly ArrayPool<T>? _pool;
readonly bool _clearOnReturn;
readonly bool _cancelOnEarlyStop;
readonly bool _sequentialAccess;

internal MappedDbQuery(DbQuery definition, IRowSource<T> source)
: this(definition, source, false, false, null, false, false)
: this(definition, source, false, false, null, false, false, false)
{
}

Expand All @@ -48,7 +49,8 @@ internal MappedDbQuery(DbQuery definition, IRowSource<T> source)
bool asyncReads,
ArrayPool<T>? pool,
bool clearOnReturn,
bool cancelOnEarlyStop)
bool cancelOnEarlyStop,
bool sequentialAccess)
{
Debug.Assert(definition is not null);
Debug.Assert(source is not null);
Expand All @@ -60,6 +62,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource<T> source)
_pool = pool;
_clearOnReturn = clearOnReturn;
_cancelOnEarlyStop = cancelOnEarlyStop;
_sequentialAccess = sequentialAccess;
}

/// <summary>Gets the command definition under this mapped one.</summary>
Expand All @@ -72,23 +75,31 @@ internal MappedDbQuery(DbQuery definition, IRowSource<T> source)
/// <returns>A definition that reads only the first result set.</returns>

public MappedDbQuery<T> SingleResult()
=> new(Query, _source, true, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop);
=> new(Query, _source, true, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop, _sequentialAccess);

/// <summary>
/// Cancels the command when a terminal stops before the last row, in every query made from this definition
/// (see <see cref="MappedQuery{T}.CancelOnEarlyStop"/> for when to use it and what it costs).
/// </summary>
/// <returns>A definition whose queries cancel their command on an early stop.</returns>
public MappedDbQuery<T> CancelOnEarlyStop()
=> new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, true);
=> new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, true, _sequentialAccess);

/// <summary>
/// Reads the rows with the asynchronous read of the provider, in every query made from this definition
/// (see <see cref="MappedQuery{T}.AsyncReads"/>).
/// </summary>
/// <returns>A definition that reads asynchronously.</returns>
public MappedDbQuery<T> AsyncReads()
=> new(Query, _source, _singleResult, true, _pool, _clearOnReturn, _cancelOnEarlyStop);
=> new(Query, _source, _singleResult, true, _pool, _clearOnReturn, _cancelOnEarlyStop, _sequentialAccess);

/// <summary>
/// Asks the reader for sequential access, in every query made from this definition
/// (see <see cref="MappedQuery{T}.SequentialAccess"/> for when to use it).
/// </summary>
/// <returns>A definition whose queries read with sequential access.</returns>
public MappedDbQuery<T> SequentialAccess()
=> new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop, true);

/// <summary>
/// Takes the arrays that hold the rows from <paramref name="pool"/>, in every query made from this definition
Expand All @@ -103,7 +114,7 @@ public MappedDbQuery<T> UsePool(ArrayPool<T> pool, bool clearOnReturn)
if (pool is null) throw new ArgumentNullException(nameof(pool));
Contract.EndContractBlock();

return new(Query, _source, _singleResult, _asyncReads, pool, clearOnReturn, _cancelOnEarlyStop);
return new(Query, _source, _singleResult, _asyncReads, pool, clearOnReturn, _cancelOnEarlyStop, _sequentialAccess);
}

/// <inheritdoc cref="DbQuery.Params{TParams}"/>
Expand Down Expand Up @@ -194,6 +205,7 @@ internal MappedQuery<T> View(DbQueryCall call)
if (_singleResult) view = view.SingleResult();
if (_cancelOnEarlyStop) view = view.CancelOnEarlyStop();
if (_asyncReads) view = view.AsyncReads();
if (_sequentialAccess) view = view.SequentialAccess();
if (_pool is not null) view = view.UsePool(_pool, _clearOnReturn);
return view;
}
Expand Down Expand Up @@ -227,6 +239,10 @@ public MappedDbQuery<TParams, T> CancelOnEarlyStop()
public MappedDbQuery<TParams, T> AsyncReads()
=> new(_definition.AsyncReads());

/// <inheritdoc cref="MappedDbQuery{T}.SequentialAccess"/>
public MappedDbQuery<TParams, T> SequentialAccess()
=> new(_definition.SequentialAccess());

/// <inheritdoc cref="MappedDbQuery{T}.UsePool(ArrayPool{T}, bool)"/>
public MappedDbQuery<TParams, T> UsePool(ArrayPool<T> pool, bool clearOnReturn)
// The definition throws ArgumentNullException for a null pool.
Expand Down
59 changes: 36 additions & 23 deletions Source/Core/MappedQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ public static MappedQuery<T> Map<T>(
/// <param name="singleResult"><see langword="true"/> to stop after the first result set and not read through the later ones; otherwise, <see langword="false"/>.</param>
/// <param name="asyncReads"><see langword="true"/> to read the rows of an asynchronous terminal with <c>ReadAsync</c>; otherwise, <see langword="false"/>, which reads them with <c>Read</c>.</param>
/// <param name="cancelOnEarlyStop"><see langword="true"/> to cancel the command when a terminal stops before the last row; otherwise, <see langword="false"/>.</param>
/// <param name="sequentialAccess"><see langword="true"/> to ask the reader for <see cref="CommandBehavior.SequentialAccess"/>; otherwise, <see langword="false"/>.</param>
/// <param name="config">The pool, the clear rule, the chunk sizes and the bin the pooling terminals use.</param>
readonly struct MappedQueryCore<T>(
IExecuteReader? command,
Expand All @@ -158,22 +159,17 @@ readonly struct MappedQueryCore<T>(
bool singleResult,
bool asyncReads,
bool cancelOnEarlyStop,
bool sequentialAccess,
ChunkConfig<T> config)
: IEquatable<MappedQueryCore<T>>
{
/// <summary>
/// The reader behavior of a generated mapping.
/// </summary>
// Generated mappings read each column once, in order, so the provider may stream the row.
// A caller-supplied selector may read in any order, so it runs with the default access mode.
const CommandBehavior GeneratedMapping = CommandBehavior.SingleResult | CommandBehavior.SequentialAccess;

readonly IRowSource<T> _source = source;
readonly int _skip = skip;
readonly int _take = take; // -1 == unbounded.
readonly bool _singleResult = singleResult; // SingleResult() was called: stop after the first result set and do not read through the rest.
readonly bool _asyncReads = asyncReads; // AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read).
readonly bool _cancelOnEarlyStop = cancelOnEarlyStop; // CancelOnEarlyStop() was called: see ReaderAbandon.
readonly bool _sequentialAccess = sequentialAccess; // SequentialAccess() was called on the query.

/// <summary>
/// The command, or <see langword="null"/> for a default value.
Expand Down Expand Up @@ -248,6 +244,7 @@ public bool Equals(MappedQueryCore<T> other)
&& _singleResult == other._singleResult
&& _asyncReads == other._asyncReads
&& _cancelOnEarlyStop == other._cancelOnEarlyStop
&& _sequentialAccess == other._sequentialAccess
&& ReferenceEquals(Config, other.Config);

public override bool Equals(object? obj)
Expand All @@ -262,6 +259,7 @@ public override int GetHashCode()
h = h * 31 + _skip;
h = h * 31 + _take;
return h * 31
+ (_sequentialAccess ? 8 : 0)
+ (_cancelOnEarlyStop ? 4 : 0)
+ (_singleResult ? 2 : 0)
+ (_asyncReads ? 1 : 0)
Expand All @@ -273,15 +271,18 @@ public override int GetHashCode()
/// Gets the <see cref="CommandBehavior"/> the reader is asked for.
/// </summary>
// Without SingleResult() the reader is asked for every result set, because a terminal reads through the later ones to report their failures.
CommandBehavior Behavior => _singleResult
? (_source is SelectorSource<T> ? CommandBehavior.SingleResult : GeneratedMapping)
: (_source is SelectorSource<T> ? CommandBehavior.Default : CommandBehavior.SequentialAccess);
// SequentialAccess() called on the command is added by the command itself when it opens the reader.
CommandBehavior Behavior
=> (_singleResult ? CommandBehavior.SingleResult : CommandBehavior.Default)
| (_sequentialAccess ? CommandBehavior.SequentialAccess : CommandBehavior.Default);

public MappedQueryCore<T> WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, true, _asyncReads, _cancelOnEarlyStop, Config));
public MappedQueryCore<T> WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, true, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config));

public MappedQueryCore<T> WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, true, _cancelOnEarlyStop, Config));
public MappedQueryCore<T> WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, true, _cancelOnEarlyStop, _sequentialAccess, Config));

public MappedQueryCore<T> WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, true, Config));
public MappedQueryCore<T> WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, true, _sequentialAccess, Config));

public MappedQueryCore<T> WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, true, Config));

/// <summary>
/// Gets the configuration the query was given.
Expand Down Expand Up @@ -318,11 +319,11 @@ public MappedQueryCore<T> WithPool(ArrayPool<T> pool, bool clearOnReturn)
/// <param name="config">The configuration to use.</param>
/// <returns>A copy of the query that uses <paramref name="config"/>.</returns>
public MappedQueryCore<T> WithConfig(ChunkConfig<T> config)
=> Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, config));
=> Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, config));

/// <summary>Returns the same query over another call.</summary>
public MappedQueryCore<T> WithCall(DbQueryCall call)
=> new(null, call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, Config);
=> new(null, call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config);

public MappedQueryCore<T> WithSkip(int count)
=> count >= 0
Expand All @@ -335,6 +336,7 @@ public MappedQueryCore<T> WithSkip(int count)
_singleResult,
_asyncReads,
_cancelOnEarlyStop,
_sequentialAccess,
Config))
: throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative.");

Expand All @@ -357,6 +359,7 @@ public MappedQueryCore<T> WithTake(int count)
_singleResult,
_asyncReads,
_cancelOnEarlyStop,
_sequentialAccess,
Config))
: throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative.");

Expand Down Expand Up @@ -801,9 +804,6 @@ static async (reader, s) =>
return found ? row! : throw RowReader.NoRows(nameof(SingleAsync));
}

// AnyAsync and CountAsync map nothing and touch no column, so the provider may stream the row whatever the source is.
CommandBehavior NoColumnBehavior => _singleResult ? GeneratedMapping : CommandBehavior.SequentialAccess;

public ValueTask<bool> AnyAsync(CancellationToken cancellationToken)
{
ReaderAbandon? abandon = NewAbandon();
Expand All @@ -813,10 +813,7 @@ public ValueTask<bool> AnyAsync(CancellationToken cancellationToken)
(_skip, _take, _asyncReads, abandon, token),
static (reader, s) => RowReader.AnyAsync(
reader, s._skip, s._take, s._asyncReads, s.token, s.abandon),
// As FirstBehavior.
UseSingleRow
? NoColumnBehavior | CommandBehavior.SingleRow
: NoColumnBehavior,
FirstBehavior,
abandon, linked, token);
}

Expand All @@ -829,7 +826,7 @@ public ValueTask<int> CountAsync(CancellationToken cancellationToken)
(_skip, _take, _asyncReads, abandon, token),
static (reader, s) => RowReader.CountAsync(
reader, s._skip, s._take, s._asyncReads, s.token, s.abandon),
NoColumnBehavior, abandon, linked, token);
Behavior, abandon, linked, token);
}

public ImmutableArray<T> ToImmutableArray()
Expand Down Expand Up @@ -1213,6 +1210,16 @@ public readonly record struct MappedQuery<T>
// A selector map (Map(Func)) on one very large value reads slower and uses more memory with ReadAsync.
public MappedQuery<T> AsyncReads() => new(_core.WithAsyncReads());

/// <summary>Asks the reader for <see cref="CommandBehavior.SequentialAccess"/>, for very large text or binary values.</summary>
/// <remarks>
/// The provider then streams each row instead of buffering it, and a column can be read once, in ascending order:
/// a selector given to <c>Map</c> must read the columns in that order, or the provider throws.
/// Without it the library reads with the default access mode. It can be called in any order with <c>Skip</c>, <c>Take</c> and <c>SingleResult</c>.
/// To read one large value as a stream, call <c>SequentialAccess()</c> on the command and use <c>reader.GetStream</c> in a reader callback.
/// </remarks>
/// <returns>The same query, reading with sequential access.</returns>
public MappedQuery<T> SequentialAccess() => new(_core.WithSequentialAccess());

/// <summary>
/// Chooses the pool this query's pooled arrays are rented from, and
/// whether their rows are cleared when they go back.
Expand Down Expand Up @@ -1767,6 +1774,9 @@ public readonly record struct MappedQueryWithSkip<T>
/// <inheritdoc cref="MappedQuery{T}.AsyncReads"/>
public MappedQueryWithSkip<T> AsyncReads() => new(_core.WithAsyncReads());

/// <inheritdoc cref="MappedQuery{T}.SequentialAccess"/>
public MappedQueryWithSkip<T> SequentialAccess() => new(_core.WithSequentialAccess());

/// <inheritdoc cref="MappedQuery{T}.UsePool(ArrayPool{T}, bool)"/>
public MappedQueryWithSkip<T> UsePool(ArrayPool<T> pool, bool clearOnReturn)
=> new(_core.WithPool(pool, clearOnReturn));
Expand Down Expand Up @@ -1907,6 +1917,9 @@ public readonly record struct MappedQueryWithTake<T>
/// <inheritdoc cref="MappedQuery{T}.AsyncReads"/>
public MappedQueryWithTake<T> AsyncReads() => new(_core.WithAsyncReads());

/// <inheritdoc cref="MappedQuery{T}.SequentialAccess"/>
public MappedQueryWithTake<T> SequentialAccess() => new(_core.WithSequentialAccess());

/// <inheritdoc cref="MappedQuery{T}.UsePool(ArrayPool{T}, bool)"/>
public MappedQueryWithTake<T> UsePool(ArrayPool<T> pool, bool clearOnReturn)
=> new(_core.WithPool(pool, clearOnReturn));
Expand Down
5 changes: 5 additions & 0 deletions Source/Core/MappedViews.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ static MappedQueryCore<T> NewCore<T>(
singleResult,
asyncReads,
false,
false,
Defaults<T>.Config);

/// <summary>
Expand Down Expand Up @@ -885,6 +886,10 @@ public MappedCommand<T> CancelOnEarlyStop()
public MappedCommand<T> AsyncReads()
=> new(_core.WithAsyncReads());

/// <inheritdoc cref="MappedQuery{T}.SequentialAccess"/>
public MappedCommand<T> SequentialAccess()
=> new(_core.WithSequentialAccess());

/// <inheritdoc cref="MappedQuery{T}.UsePool(ArrayPool{T}, bool)"/>
public MappedCommand<T> UsePool(ArrayPool<T> pool, bool clearOnReturn)
=> new(_core.WithPool(pool, clearOnReturn));
Expand Down
Loading