diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index d9436f7d..84bd3b07 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -195,9 +195,7 @@ public DbQuery SetTimeout(ushort seconds) // Any other type is read through RowMap.Default, shared, so its compiled // reader is built once. public MappedDbQuery Map() - => FirstColumn.Instance is { } firstColumn - ? new(this, firstColumn) - : new(this, RowMap.Default); + => new(this, Views.DefaultSource()); /// Maps each row to a with a map the caller declared, and returns the mapped definition. /// The type each row is mapped to. diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index a68495a5..96146631 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -84,14 +84,27 @@ public DbQueryCall AddParam( SourceCore, Params.AddDerived(Definition, CheckedExpression(expression), value)); - /// + /// + /// Maps each row to a by column name (a single + /// value such as is read from the first column), and + /// returns the mapped query. + /// + /// + /// The same as . + /// + /// + /// + /// // The query holds this call as it is; the value is not boxed. public MappedQuery Map() - => FirstColumn.Instance is { } firstColumn - ? new(Views.QueryCore(Bound(), firstColumn)) - : new(Views.QueryCore(Bound(), RowMap.Default)); + => new(Views.QueryCore(Bound(), Views.DefaultSource())); - /// + /// + /// Maps each row to a with a map the caller + /// declared, and returns the mapped query. + /// + /// + /// // A bare null does not compile here (it also fits the selector overload): // write (RowMap?)null. public MappedQuery Map(RowMap? map) @@ -100,11 +113,11 @@ public MappedQuery Map(RowMap? map) : new(Views.QueryCore(Bound(), map)); /// Maps each row with a selector, and returns the mapped query. - /// The type each row is mapped to. + /// /// Called for each row, from any thread and by overlapping calls, so it must be safe for concurrent use. - /// The mapped query, to be read with a terminal. + /// /// is . - /// This is a value, which is bound to nothing. + /// public MappedQuery Map(Func selector) { if (selector is null) throw new ArgumentNullException(nameof(selector)); @@ -113,11 +126,26 @@ public MappedQuery Map(Func selector) return new(Views.QueryCore(Bound(), new SelectorSource(selector))); } - /// + /// + /// Reads each row without a model, as an array of its values. + /// + /// + /// The same as . + /// + /// + /// public MappedQuery AsObjectArrays() => new(Views.QueryCore(Bound(), ObjectArraySource.Instance)); - /// + /// + /// Reads each row without a model, as a . + /// + /// + /// The same as + /// . + /// + /// + /// public MappedQuery AsDictionaryRows() => new(Views.QueryCore(Bound(), DictionaryRowSource.Instance)); diff --git a/Source/Core/DbQueryUsing.cs b/Source/Core/DbQueryUsing.cs index fdb309ea..7d88ce04 100644 --- a/Source/Core/DbQueryUsing.cs +++ b/Source/Core/DbQueryUsing.cs @@ -44,61 +44,36 @@ object SourceOrThrow /// This is a value, which is bound to nothing. public object Source => SourceOrThrow; - /// - /// Maps each row to a by column name (a single value such as - /// is read from the first column), and returns the mapped query. - /// - /// - /// The same as . - /// - /// The type each row is mapped to. - /// The mapped query, to be read with a terminal. - /// This is a value, which is bound to nothing. + /// // The query holds this value as it is; the value is not boxed. public MappedQuery Map() - => FirstColumn.Instance is { } firstColumn - ? new(Views.QueryCore(ToCall(), firstColumn)) - : new(Views.QueryCore(ToCall(), RowMap.Default)); - - /// Maps each row to a with a map the caller declared, and returns the mapped query. - /// The type each row is mapped to. - /// The map. A map reads as does. - /// The mapped query, to be read with a terminal. - /// This is a value, which is bound to nothing. + => ToCall().Map(); + + /// // A bare null does not compile here (it also fits the selector overload): // write (RowMap?)null. public MappedQuery Map(RowMap? map) - => map is null - ? Map() - : new(Views.QueryCore(ToCall(), map)); - - /// Maps each row with a selector, and returns the mapped query. - /// The type each row is mapped to. - /// Called for each row, from any thread and by overlapping calls, so it must be safe for concurrent use. - /// The mapped query, to be read with a terminal. - /// is . - /// This is a value, which is bound to nothing. + => ToCall().Map(map); + + /// public MappedQuery Map(Func selector) { if (selector is null) throw new ArgumentNullException(nameof(selector)); Contract.EndContractBlock(); - return new(Views.QueryCore(ToCall(), new SelectorSource(selector))); + // The selector is checked above, before ToCall() reads the value, so a + // default value with no selector reports the selector first, as it + // always did. + return ToCall().Map(selector); } - /// Reads each row without a model, as an array of its values. - /// The same as . - /// The mapped query, to be read with a terminal. - /// This is a value, which is bound to nothing. + /// public MappedQuery AsObjectArrays() - => new(Views.QueryCore(ToCall(), ObjectArraySource.Instance)); + => ToCall().AsObjectArrays(); - /// Reads each row without a model, as a . - /// The same as . - /// The mapped query, to be read with a terminal. - /// This is a value, which is bound to nothing. + /// public MappedQuery AsDictionaryRows() - => new(Views.QueryCore(ToCall(), DictionaryRowSource.Instance)); + => ToCall().AsDictionaryRows(); /// /// This is a value, which is bound to nothing. diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index 1a05f22d..2f6ca9e6 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -21,6 +21,45 @@ The query to execute. + + + + It replaces the switches, it does not combine them: any switch that is + not in is turned off, including one set + earlier in the chain or on the command before Map + (SingleResult(), AsyncReads()). + WithOptions(QueryOptions.None) clears all four, and is the only + way to turn a switch off. + To add one switch and keep the others, call its own method: + SingleResult(), AsyncReads(), CancelOnEarlyStop() + or SequentialAccess(). + The pool is not a switch: see UsePool. + + + + The switches the query is to have: any combination of the + values. + + + has a bit that is not one of the four + switches. + + + + + + + + + + This is a value, which is bound to nothing. + + + + + The mapped query, to be read with a terminal. + + is . diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index aa44bc4f..b55d4eda 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -30,39 +30,30 @@ namespace Open.Database.Extensions; public sealed class MappedDbQuery { readonly IRowSource _source; - readonly bool _singleResult; - readonly bool _asyncReads; + readonly QueryOptions _options; readonly ArrayPool? _pool; readonly bool _clearOnReturn; - readonly bool _cancelOnEarlyStop; - readonly bool _sequentialAccess; internal MappedDbQuery(DbQuery definition, IRowSource source) - : this(definition, source, false, false, null, false, false, false) + : this(definition, source, default, null, false) { } MappedDbQuery( DbQuery definition, IRowSource source, - bool singleResult, - bool asyncReads, + QueryOptions options, ArrayPool? pool, - bool clearOnReturn, - bool cancelOnEarlyStop, - bool sequentialAccess) + bool clearOnReturn) { Debug.Assert(definition is not null); Debug.Assert(source is not null); Query = definition; _source = source; - _singleResult = singleResult; - _asyncReads = asyncReads; + _options = options; _pool = pool; _clearOnReturn = clearOnReturn; - _cancelOnEarlyStop = cancelOnEarlyStop; - _sequentialAccess = sequentialAccess; } /// Gets the command definition under this mapped one. @@ -73,33 +64,71 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// (see ). /// /// A definition that reads only the first result set. + /// public MappedDbQuery SingleResult() - => new(Query, _source, true, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop, _sequentialAccess); + => new( + Query, + _source, + _options | QueryOptions.SingleResult, + _pool, + _clearOnReturn); /// /// Cancels the command when a terminal stops before the last row, in every query made from this definition /// (see for when to use it and what it costs). /// /// A definition whose queries cancel their command on an early stop. + /// public MappedDbQuery CancelOnEarlyStop() - => new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, true, _sequentialAccess); + => new( + Query, + _source, + _options | QueryOptions.CancelOnEarlyStop, + _pool, + _clearOnReturn); /// /// Reads the rows with the asynchronous read of the provider, in every query made from this definition /// (see ). /// /// A definition that reads asynchronously. + /// public MappedDbQuery AsyncReads() - => new(Query, _source, _singleResult, true, _pool, _clearOnReturn, _cancelOnEarlyStop, _sequentialAccess); + => new( + Query, + _source, + _options | QueryOptions.AsyncReads, + _pool, + _clearOnReturn); /// /// Asks the reader for sequential access, in every query made from this definition /// (see for when to use it). /// /// A definition whose queries read with sequential access. + /// public MappedDbQuery SequentialAccess() - => new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop, true); + => new( + Query, + _source, + _options | QueryOptions.SequentialAccess, + _pool, + _clearOnReturn); + + /// + /// Returns a definition whose switches, in every query made from it, are + /// exactly . + /// + /// + /// A definition with exactly these switches. + public MappedDbQuery WithOptions(QueryOptions options) + => new( + Query, + _source, + Views.CheckedOptions(options), + _pool, + _clearOnReturn); /// /// Takes the arrays that hold the rows from , in every query made from this definition @@ -114,7 +143,7 @@ public MappedDbQuery UsePool(ArrayPool pool, bool clearOnReturn) if (pool is null) throw new ArgumentNullException(nameof(pool)); Contract.EndContractBlock(); - return new(Query, _source, _singleResult, _asyncReads, pool, clearOnReturn, _cancelOnEarlyStop, _sequentialAccess); + return new(Query, _source, _options, pool, clearOnReturn); } /// @@ -201,13 +230,8 @@ public UnboundCall AddParams(TValues values) /// Makes the view over a command made from this definition, with the options of this definition. internal MappedQuery View(DbQueryCall call) { - MappedQuery view = new(Views.QueryCore(call, _source)); - 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; + MappedQuery view = new(Views.QueryCore(call, _source, _options)); + return _pool is null ? view : view.UsePool(_pool, _clearOnReturn); } } @@ -243,6 +267,11 @@ public MappedDbQuery AsyncReads() public MappedDbQuery SequentialAccess() => new(_definition.SequentialAccess()); + /// + public MappedDbQuery WithOptions(QueryOptions options) + // The definition throws ArgumentOutOfRangeException for a bad value. + => new(_definition.WithOptions(options)); + /// public MappedDbQuery UsePool(ArrayPool pool, bool clearOnReturn) // The definition throws ArgumentNullException for a null pool. diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index ad191eb8..2b6d7cfd 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -97,11 +97,8 @@ public static MappedQuery Map( if (command is null) throw new ArgumentNullException(nameof(command)); Contract.EndContractBlock(); - // A single value such as int is read from the first column; - // any other T maps by column name. - return FirstColumn.Instance is { } firstColumn - ? new MappedQuery(Views.QueryCore(command, firstColumn)) - : Map(command, RowMap.Default); + return new MappedQuery( + Views.QueryCore(command, Views.DefaultSource())); } /// @@ -145,10 +142,10 @@ public static MappedQuery Map( /// Reads and maps one row. /// The number of rows to skip before the first mapped row. /// The maximum number of rows to map, or -1 for no limit. -/// to stop after the first result set and not read through the later ones; otherwise, . -/// to read the rows of an asynchronous terminal with ReadAsync; otherwise, , which reads them with Read. -/// to cancel the command when a terminal stops before the last row; otherwise, . -/// to ask the reader for ; otherwise, . +/// +/// The switches of the query: SingleResult(), AsyncReads(), +/// CancelOnEarlyStop() and SequentialAccess(). +/// /// The pool, the clear rule, the chunk sizes and the bin the pooling terminals use. readonly struct MappedQueryCore( IExecuteReader? command, @@ -156,20 +153,27 @@ readonly struct MappedQueryCore( IRowSource source, int skip, int take, - bool singleResult, - bool asyncReads, - bool cancelOnEarlyStop, - bool sequentialAccess, + QueryOptions options, ChunkConfig config) : IEquatable> { readonly IRowSource _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. + /// Gets the switches of the query. + // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): + // see QueryOptions. + public QueryOptions Options { get; } = options; + + // A switch is read with a mask, never with HasFlag, which boxes on the + // older targets. + bool SingleResult => (Options & QueryOptions.SingleResult) != 0; + + bool AsyncReads => (Options & QueryOptions.AsyncReads) != 0; + + bool CancelOnEarlyStop => (Options & QueryOptions.CancelOnEarlyStop) != 0; + + bool SequentialAccess => (Options & QueryOptions.SequentialAccess) != 0; /// /// The command, or for a default value. @@ -241,10 +245,7 @@ public bool Equals(MappedQueryCore other) && Equals(_source, other._source) && _skip == other._skip && _take == other._take - && _singleResult == other._singleResult - && _asyncReads == other._asyncReads - && _cancelOnEarlyStop == other._cancelOnEarlyStop - && _sequentialAccess == other._sequentialAccess + && Options == other.Options && ReferenceEquals(Config, other.Config); public override bool Equals(object? obj) @@ -259,10 +260,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) + + (int)Options + RuntimeHelpers.GetHashCode(Config); // Reference equality, null for a default value. } } @@ -273,16 +271,35 @@ public override int GetHashCode() // Without SingleResult() the reader is asked for every result set, because a terminal reads through the later ones to report their failures. // 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 WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, true, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config)); - - public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, true, _cancelOnEarlyStop, _sequentialAccess, Config)); + => (SingleResult + ? CommandBehavior.SingleResult + : CommandBehavior.Default) + | (SequentialAccess + ? CommandBehavior.SequentialAccess + : CommandBehavior.Default); - public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, true, _sequentialAccess, Config)); + /// + /// Returns the query with these switches and no others, whatever it had. + /// + /// The switches the query is to have. + /// A copy of the query with . + public MappedQueryCore WithOptions(QueryOptions options) + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + options, + Config)); - public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, true, Config)); + /// + /// Returns the query with one more switch set, and the others as they were. + /// + /// The switch to set. + /// A copy of the query with the switch on. + public MappedQueryCore WithOption(QueryOptions option) + => WithOptions(Options | option); /// /// Gets the configuration the query was given. @@ -319,11 +336,18 @@ public MappedQueryCore WithPool(ArrayPool pool, bool clearOnReturn) /// The configuration to use. /// A copy of the query that uses . public MappedQueryCore WithConfig(ChunkConfig config) - => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, config)); + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + Options, + config)); /// Returns the same query over another call. public MappedQueryCore WithCall(DbQueryCall call) - => new(null, call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config); + => new(null, call, _source, _skip, _take, Options, Config); public MappedQueryCore WithSkip(int count) => count >= 0 @@ -333,10 +357,7 @@ public MappedQueryCore WithSkip(int count) _source, _skip + count, _take, - _singleResult, - _asyncReads, - _cancelOnEarlyStop, - _sequentialAccess, + Options, Config)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); @@ -356,10 +377,7 @@ public MappedQueryCore WithTake(int count) _source, _skip, count, - _singleResult, - _asyncReads, - _cancelOnEarlyStop, - _sequentialAccess, + Options, Config)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); @@ -429,8 +447,9 @@ static async ValueTask ExecuteLinkedAsync(MappedQueryC // With an abandon, its own method reads through, so the lambda here carries nothing for it. TResult Run(TState state, Func transform, CommandBehavior behavior, ReaderAbandon? abandon) => abandon is not null - ? ExecuteAbandonable(state, transform, behavior, abandon, !_singleResult) - : _singleResult + ? ExecuteAbandonable( + state, transform, behavior, abandon, !SingleResult) + : SingleResult ? ExecuteReader(state, transform, behavior) : ExecuteReader((state, transform), static (reader, s) => { @@ -441,8 +460,10 @@ TResult Run(TState state, Func tr ValueTask RunAsync(TState state, Func> transform, CommandBehavior behavior, ReaderAbandon? abandon, CancellationTokenSource? linked, CancellationToken token) => abandon is not null - ? ExecuteAbandonableAsync(state, transform, behavior, abandon, !_singleResult, linked, token) - : _singleResult + ? ExecuteAbandonableAsync( + state, transform, behavior, abandon, + !SingleResult, linked, token) + : SingleResult ? ExecuteAsync(state, transform, behavior, linked, token) : ExecuteAsync((state, transform, token), static async (reader, s) => { @@ -453,7 +474,7 @@ ValueTask RunAsync(TState state, Func _cancelOnEarlyStop ? new ReaderAbandon() : null; + => CancelOnEarlyStop ? new ReaderAbandon() : null; /// Runs the reader function of a terminal that reads through by itself, if at all. TResult ExecuteReader(TState state, Func transform, CommandBehavior behavior, ReaderAbandon? abandon) @@ -510,18 +531,37 @@ async ValueTask ExecuteAbandonableAsync(TState state, public void Read(Action> handler) { ReaderAbandon? abandon = NewAbandon(); - ExecuteReader((handler, _source, _skip, _take, _singleResult, abandon), static (reader, s) => - { - s.handler(RowReader.Stream(s._source, reader, s._skip, s._take, !s._singleResult, s.abandon)); - return false; - }, Behavior, abandon); + ExecuteReader( + (handler, _source, _skip, _take, SingleResult, abandon), + static (reader, s) => + { + s.handler(RowReader.Stream( + s._source, + reader, + s._skip, + s._take, + !s.SingleResult, + s.abandon)); + return false; + }, + Behavior, + abandon); } public TResult Read(Func, TResult> handler) { ReaderAbandon? abandon = NewAbandon(); - return ExecuteReader((handler, _source, _skip, _take, _singleResult, abandon), static (reader, s) - => s.handler(RowReader.Stream(s._source, reader, s._skip, s._take, !s._singleResult, s.abandon)), Behavior, abandon); + return ExecuteReader( + (handler, _source, _skip, _take, SingleResult, abandon), + static (reader, s) => s.handler(RowReader.Stream( + s._source, + reader, + s._skip, + s._take, + !s.SingleResult, + s.abandon)), + Behavior, + abandon); } public ValueTask ReadAsync(Func, CancellationToken, ValueTask> handler, CancellationToken cancellationToken) @@ -535,19 +575,52 @@ public ValueTask ReadAsync(Func, CancellationToken, ValueTas public ValueTask ReadAsync(Func, CancellationToken, ValueTask> handler, ReaderAbandon? abandon, CancellationToken cancellationToken) { CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return ValueTaskHelpers.Discard(ExecuteAsync((handler, _source, _skip, _take, _singleResult, _asyncReads, abandon, token), static async (reader, s) => - { - await s.handler(StreamAsync(s._source, reader, s._skip, s._take, s._singleResult, s._asyncReads, s.abandon, s.token), s.token).ConfigureAwait(false); - return false; - }, Behavior, abandon, linked, token)); + return ValueTaskHelpers.Discard(ExecuteAsync( + (handler, _source, _skip, _take, + SingleResult, AsyncReads, abandon, token), + static async (reader, s) => + { + await s.handler( + StreamAsync( + s._source, + reader, + s._skip, + s._take, + s.SingleResult, + s.AsyncReads, + s.abandon, + s.token), + s.token).ConfigureAwait(false); + return false; + }, + Behavior, + abandon, + linked, + token)); } public ValueTask ReadAsync(Func, CancellationToken, ValueTask> handler, CancellationToken cancellationToken) { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return ExecuteAsync((handler, _source, _skip, _take, _singleResult, _asyncReads, abandon, token), static (reader, s) - => s.handler(StreamAsync(s._source, reader, s._skip, s._take, s._singleResult, s._asyncReads, s.abandon, s.token), s.token), Behavior, abandon, linked, token); + return ExecuteAsync( + (handler, _source, _skip, _take, + SingleResult, AsyncReads, abandon, token), + static (reader, s) => s.handler( + StreamAsync( + s._source, + reader, + s._skip, + s._take, + s.SingleResult, + s.AsyncReads, + s.abandon, + s.token), + s.token), + Behavior, + abandon, + linked, + token); } /// @@ -614,7 +687,7 @@ public T[] ToArray() // which is the one that decides whether to cancel; it would read them all and report the end. CommandBehavior FirstBehavior => UseSingleRow ? Behavior | CommandBehavior.SingleRow : Behavior; - bool UseSingleRow => _skip == 0 && _singleResult && !_cancelOnEarlyStop; + bool UseSingleRow => _skip == 0 && SingleResult && !CancelOnEarlyStop; public T? SingleOrDefault() { @@ -690,10 +763,10 @@ public ValueTask CollectAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _asyncReads, Config, token, build, abandon), + (_source, _skip, _take, AsyncReads, Config, token, build, abandon), static (reader, s) => reader is DbDataReader db ? RowReader.CollectAsync( - s._source, db, s._skip, s._take, s._asyncReads, + s._source, db, s._skip, s._take, s.AsyncReads, s.build, s.Config, s.token, s.abandon) : new ValueTask(RowReader.Collect( s._source, reader, s._skip, s._take, s.build, @@ -724,32 +797,76 @@ public ValueTask ToArrayAsync(CancellationToken cancellationToken) { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return RunAsync((_source, _skip, _take, _asyncReads, abandon, token), static async (reader, s) => - { - if (reader is DbDataReader db) + return RunAsync( + (_source, _skip, _take, AsyncReads, abandon, token), + static async (reader, s) => { - (bool found, T? item) = await RowReader.TryFirstAsync(s._source, db, s._skip, s._take, s._asyncReads, s.token, s.abandon).ConfigureAwait(false); - return found ? item : default; - } + if (reader is DbDataReader db) + { + (bool found, T? item) = await RowReader.TryFirstAsync( + s._source, + db, + s._skip, + s._take, + s.AsyncReads, + s.token, + s.abandon).ConfigureAwait(false); + return found ? item : default; + } - return RowReader.TryFirst(s._source, reader, s._skip, s._take, out T? i, s.abandon, s.token) ? i : default; - }, FirstBehavior, abandon, linked, token); + return RowReader.TryFirst( + s._source, + reader, + s._skip, + s._take, + out T? i, + s.abandon, + s.token) + ? i + : default; + }, + FirstBehavior, + abandon, + linked, + token); } public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return RunAsync((_source, _skip, _take, _asyncReads, abandon, token), static async (reader, s) => - { - if (reader is DbDataReader db) + return RunAsync( + (_source, _skip, _take, AsyncReads, abandon, token), + static async (reader, s) => { - (bool found, T? item) = await RowReader.TrySingleAsync(s._source, db, s._skip, s._take, s._asyncReads, s.token, s.abandon).ConfigureAwait(false); - return found ? item : default; - } + if (reader is DbDataReader db) + { + (bool found, T? item) = await RowReader.TrySingleAsync( + s._source, + db, + s._skip, + s._take, + s.AsyncReads, + s.token, + s.abandon).ConfigureAwait(false); + return found ? item : default; + } - return RowReader.TrySingle(s._source, reader, s._skip, s._take, out T? i, s.abandon, s.token) ? i : default; - }, Behavior, abandon, linked, token); + return RowReader.TrySingle( + s._source, + reader, + s._skip, + s._take, + out T? i, + s.abandon, + s.token) + ? i + : default; + }, + Behavior, + abandon, + linked, + token); } public async ValueTask FirstAsync(CancellationToken cancellationToken) @@ -759,14 +876,14 @@ public async ValueTask FirstAsync(CancellationToken cancellationToken) cancellationToken, out CancellationTokenSource? linked); (bool found, T? row) = await RunAsync( - (_source, _skip, _take, _asyncReads, abandon, token), + (_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) { return await RowReader.TryFirstAsync( s._source, db, s._skip, s._take, - s._asyncReads, s.token, s.abandon).ConfigureAwait(false); + s.AsyncReads, s.token, s.abandon).ConfigureAwait(false); } bool has = RowReader.TryFirst( @@ -785,14 +902,14 @@ public async ValueTask SingleAsync(CancellationToken cancellationToken) cancellationToken, out CancellationTokenSource? linked); (bool found, T? row) = await RunAsync( - (_source, _skip, _take, _asyncReads, abandon, token), + (_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) { return await RowReader.TrySingleAsync( s._source, db, s._skip, s._take, - s._asyncReads, s.token, s.abandon).ConfigureAwait(false); + s.AsyncReads, s.token, s.abandon).ConfigureAwait(false); } bool has = RowReader.TrySingle( @@ -810,9 +927,9 @@ public ValueTask AnyAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _asyncReads, abandon, token), + (_skip, _take, AsyncReads, abandon, token), static (reader, s) => RowReader.AnyAsync( - reader, s._skip, s._take, s._asyncReads, s.token, s.abandon), + reader, s._skip, s._take, s.AsyncReads, s.token, s.abandon), FirstBehavior, abandon, linked, token); } @@ -823,9 +940,9 @@ public ValueTask CountAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _asyncReads, abandon, token), + (_skip, _take, AsyncReads, abandon, token), static (reader, s) => RowReader.CountAsync( - reader, s._skip, s._take, s._asyncReads, s.token, s.abandon), + reader, s._skip, s._take, s.AsyncReads, s.token, s.abandon), Behavior, abandon, linked, token); } @@ -955,14 +1072,14 @@ public ValueTask FillAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _asyncReads, token, sink, abandon), + (_source, _skip, _take, AsyncReads, token, sink, abandon), static async (reader, s) => { if (reader is DbDataReader db) { await RowReader.FillAsync( s._source, db, s._skip, s._take, - s._asyncReads, s.sink, s.token, s.abandon) + s.AsyncReads, s.sink, s.token, s.abandon) .ConfigureAwait(false); } else @@ -1145,7 +1262,9 @@ public readonly record struct MappedQuery /// command.SingleResult().Map<T>() (see ) is the same as command.Map<T>().SingleResult(). /// /// The same query, without the read-through. - public MappedQuery SingleResult() => new(_core.WithSingleResult()); + /// + public MappedQuery SingleResult() + => new(_core.WithOption(QueryOptions.SingleResult)); /// /// Cancels the command when a terminal stops before the last row, so the rows nobody asked for are discarded instead of being read off the wire. Off by default. @@ -1197,7 +1316,9 @@ public readonly record struct MappedQuery /// /// /// The same query, canceling its command on an early stop. - public MappedQuery CancelOnEarlyStop() => new(_core.WithCancelOnEarlyStop()); + /// + public MappedQuery CancelOnEarlyStop() + => new(_core.WithOption(QueryOptions.CancelOnEarlyStop)); /// Reads the rows of an async terminal with ReadAsync instead of Read. /// @@ -1207,8 +1328,10 @@ public readonly record struct MappedQuery /// It changes nothing on a synchronous terminal. It can be called in any order with Skip, Take and SingleResult. /// /// The same query, reading its rows asynchronously. + /// // A selector map (Map(Func)) on one very large value reads slower and uses more memory with ReadAsync. - public MappedQuery AsyncReads() => new(_core.WithAsyncReads()); + public MappedQuery AsyncReads() + => new(_core.WithOption(QueryOptions.AsyncReads)); /// Asks the reader for , for very large text or binary values. /// @@ -1218,7 +1341,17 @@ public readonly record struct MappedQuery /// To read one large value as a stream, call SequentialAccess() on the command and use reader.GetStream in a reader callback. /// /// The same query, reading with sequential access. - public MappedQuery SequentialAccess() => new(_core.WithSequentialAccess()); + /// + public MappedQuery SequentialAccess() + => new(_core.WithOption(QueryOptions.SequentialAccess)); + + /// + /// Returns a query whose switches are exactly . + /// + /// + /// The same query, with exactly these switches. + public MappedQuery WithOptions(QueryOptions options) + => new(_core.WithOptions(Views.CheckedOptions(options))); /// /// Chooses the pool this query's pooled arrays are rented from, and @@ -1759,16 +1892,24 @@ public readonly record struct MappedQueryWithSkip public MappedQueryWithTake Take(int count) => new(_core.WithTake(count)); /// - public MappedQueryWithSkip SingleResult() => new(_core.WithSingleResult()); + public MappedQueryWithSkip SingleResult() + => new(_core.WithOption(QueryOptions.SingleResult)); /// - public MappedQueryWithSkip CancelOnEarlyStop() => new(_core.WithCancelOnEarlyStop()); + public MappedQueryWithSkip CancelOnEarlyStop() + => new(_core.WithOption(QueryOptions.CancelOnEarlyStop)); /// - public MappedQueryWithSkip AsyncReads() => new(_core.WithAsyncReads()); + public MappedQueryWithSkip AsyncReads() + => new(_core.WithOption(QueryOptions.AsyncReads)); /// - public MappedQueryWithSkip SequentialAccess() => new(_core.WithSequentialAccess()); + public MappedQueryWithSkip SequentialAccess() + => new(_core.WithOption(QueryOptions.SequentialAccess)); + + /// + public MappedQueryWithSkip WithOptions(QueryOptions options) + => new(_core.WithOptions(Views.CheckedOptions(options))); /// public MappedQueryWithSkip UsePool(ArrayPool pool, bool clearOnReturn) @@ -1898,16 +2039,24 @@ public readonly record struct MappedQueryWithTake public IExecuteReader Command => _core.Command; /// - public MappedQueryWithTake SingleResult() => new(_core.WithSingleResult()); + public MappedQueryWithTake SingleResult() + => new(_core.WithOption(QueryOptions.SingleResult)); /// - public MappedQueryWithTake CancelOnEarlyStop() => new(_core.WithCancelOnEarlyStop()); + public MappedQueryWithTake CancelOnEarlyStop() + => new(_core.WithOption(QueryOptions.CancelOnEarlyStop)); /// - public MappedQueryWithTake AsyncReads() => new(_core.WithAsyncReads()); + public MappedQueryWithTake AsyncReads() + => new(_core.WithOption(QueryOptions.AsyncReads)); /// - public MappedQueryWithTake SequentialAccess() => new(_core.WithSequentialAccess()); + public MappedQueryWithTake SequentialAccess() + => new(_core.WithOption(QueryOptions.SequentialAccess)); + + /// + public MappedQueryWithTake WithOptions(QueryOptions options) + => new(_core.WithOptions(Views.CheckedOptions(options))); /// public MappedQueryWithTake UsePool(ArrayPool pool, bool clearOnReturn) diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 805e1fd4..4008afdd 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -49,11 +49,8 @@ public static MappedReader Map( if (reader is null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); - // A single value such as int is read from the first column; - // any other T maps by column name. - return FirstColumn.Instance is { } firstColumn - ? new MappedReader(Views.ReaderCore(reader, firstColumn)) - : Map(reader, RowMap.Default); + return new MappedReader( + Views.ReaderCore(reader, Views.DefaultSource())); } /// @@ -132,11 +129,8 @@ public static MappedCommand Map( if (command is null) throw new ArgumentNullException(nameof(command)); Contract.EndContractBlock(); - // A single value such as int is read from the first column; - // any other T maps by column name. - return FirstColumn.Instance is { } firstColumn - ? new MappedCommand(Views.CommandCore(command, firstColumn)) - : Map(command, RowMap.Default); + return new MappedCommand( + Views.CommandCore(command, Views.DefaultSource())); } /// @@ -218,11 +212,8 @@ public static MappedTable Map( if (table is null) throw new ArgumentNullException(nameof(table)); Contract.EndContractBlock(); - // A single value such as int is read from the first column; - // any other T maps by column name. - return FirstColumn.Instance is { } firstColumn - ? new MappedTable(Views.TableCore(table, firstColumn)) - : Map(table, RowMap.Default); + return new MappedTable( + Views.TableCore(table, Views.DefaultSource())); } /// @@ -268,6 +259,43 @@ public static MappedTable Map( // against the command itself with the core's singleResult flag set. static class Views { + /// + /// Refuses a value that has a bit which is none of the four switches. + /// + /// The value a caller gave to Options. + /// . + /// + /// has a bit that is not one of the switches. + /// + internal static QueryOptions CheckedOptions(QueryOptions options) + => (options & ~AllOptions) == QueryOptions.None + ? options + : throw new ArgumentOutOfRangeException( + nameof(options), + (int)options, + "QueryOptions has a bit that is none of its switches. " + + "Use AsyncReads (1), SingleResult (2), CancelOnEarlyStop (4) " + + "and SequentialAccess (8), alone or added together with |, " + + "or None (0)."); + + const QueryOptions AllOptions + = QueryOptions.AsyncReads + | QueryOptions.SingleResult + | QueryOptions.CancelOnEarlyStop + | QueryOptions.SequentialAccess; + + /// + /// Gets the source of a plain Map<T>(): a single value such as + /// is read from the first column, any other type maps by + /// column name through the shared default map. + /// + /// The type each row is mapped to. + /// The source that reads and maps one row. + internal static IRowSource DefaultSource() + => FirstColumn.Instance is { } firstColumn + ? firstColumn + : RowMap.Default; + internal static MappedQueryCore QueryCore( IExecuteReader command, IRowSource source) @@ -285,7 +313,25 @@ internal static MappedQueryCore QueryCore( internal static MappedQueryCore QueryCore( DbQueryCall call, IRowSource source) - => NewCore(null, call, source, false, false); + => NewCore(null, call, source, QueryOptions.None); + + /// + /// Makes the query core of a call made from a + /// definition, with the options the definition holds. + /// + /// The type each row is mapped to. + /// The call. + /// Reads and maps one row. + /// The switches of the definition. + /// The new query core. + internal static MappedQueryCore QueryCore( + DbQueryCall call, + IRowSource source, + QueryOptions options) + => NewCore(null, call, source, options); + + static QueryOptions Single(bool singleResult) + => singleResult ? QueryOptions.SingleResult : QueryOptions.None; // A call made from a definition is held as it is, even when it reaches here as an IExecuteReader. static MappedQueryCore FromCommand( @@ -294,9 +340,18 @@ static MappedQueryCore FromCommand( bool singleResult) => command switch { - DbQueryCall call => NewCore(null, call, source, singleResult, false), - DbQueryUsing bound => NewCore(null, bound.ToCall(), source, singleResult, false), - _ => NewCore(command, default, source, singleResult, AsyncReads(command)), + DbQueryCall call + => NewCore(null, call, source, Single(singleResult)), + DbQueryUsing bound + => NewCore(null, bound.ToCall(), source, Single(singleResult)), + _ => NewCore( + command, + default, + source, + Single(singleResult) + | (AsyncReads(command) + ? QueryOptions.AsyncReads + : QueryOptions.None)), }; /// @@ -311,19 +366,35 @@ static bool AsyncReads(IExecuteReader command) internal static MappedQueryCore ReaderCore( IDataReader reader, IRowSource source) - => NewCore(new ReaderExecutor(reader), default, source, true, false); + => NewCore( + new ReaderExecutor(reader), + default, + source, + QueryOptions.SingleResult); internal static MappedQueryCore CommandCore( IDbCommand command, IRowSource source) => command is SingleResultDbCommand single - ? NewCore(new CommandExecutor(single.Command), default, source, true, false) - : NewCore(new CommandExecutor(command), default, source, false, false); + ? NewCore( + new CommandExecutor(single.Command), + default, + source, + QueryOptions.SingleResult) + : NewCore( + new CommandExecutor(command), + default, + source, + QueryOptions.None); internal static MappedQueryCore TableCore( DataTable table, IRowSource source) - => NewCore(new TableExecutor(table), default, source, true, false); + => NewCore( + new TableExecutor(table), + default, + source, + QueryOptions.SingleResult); /// /// Makes a query core: the one door every query is made through. @@ -332,8 +403,10 @@ internal static MappedQueryCore TableCore( /// The command the rows are read from. /// The call, when the query is made from a definition; then is . /// Reads and maps one row. - /// to stop after the first result set and not read through the later ones; otherwise, . - /// to read the rows of an asynchronous terminal with ReadAsync; otherwise, . + /// + /// The switches of the query (SingleResult() and the others), the + /// ones a command or a definition chose before Map. + /// /// The new query core, with the default configuration for . // The one place a default pool configuration is chosen: when the query is made, before any terminal runs. // Everything after this (a terminal, UsePool, a collector) uses the query's own configuration and never picks one. @@ -341,18 +414,14 @@ static MappedQueryCore NewCore( IExecuteReader? command, DbQueryCall call, IRowSource source, - bool singleResult, - bool asyncReads) + QueryOptions options) => new( command, call, source, 0, -1, - singleResult, - asyncReads, - false, - false, + options, Defaults.Config); /// @@ -876,19 +945,23 @@ public MappedQueryWithTake Take(int count) /// public MappedCommand SingleResult() - => new(_core.WithSingleResult()); + => new(_core.WithOption(QueryOptions.SingleResult)); /// public MappedCommand CancelOnEarlyStop() - => new(_core.WithCancelOnEarlyStop()); + => new(_core.WithOption(QueryOptions.CancelOnEarlyStop)); /// public MappedCommand AsyncReads() - => new(_core.WithAsyncReads()); + => new(_core.WithOption(QueryOptions.AsyncReads)); /// public MappedCommand SequentialAccess() - => new(_core.WithSequentialAccess()); + => new(_core.WithOption(QueryOptions.SequentialAccess)); + + /// + public MappedCommand WithOptions(QueryOptions options) + => new(_core.WithOptions(Views.CheckedOptions(options))); /// public MappedCommand UsePool(ArrayPool pool, bool clearOnReturn) diff --git a/Source/Core/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index 107b9b62..58b80039 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -15,3 +15,15 @@ static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTable(th static Open.Database.Extensions.Synchronous.SyncCommandExtensions.ToDataTables(this System.Data.IDbCommand! command, System.Data.CommandBehavior behavior = System.Data.CommandBehavior.Default) -> System.Collections.Generic.List! static Open.Database.Extensions.DataReaderExtensions.ToArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static Open.Database.Extensions.DataReaderExtensions.ToImmutableArrayAsync(this System.Data.Common.DbDataReader! reader, System.Func>! transform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask> +Open.Database.Extensions.QueryOptions +Open.Database.Extensions.QueryOptions.AsyncReads = 1 -> Open.Database.Extensions.QueryOptions +Open.Database.Extensions.QueryOptions.CancelOnEarlyStop = 4 -> Open.Database.Extensions.QueryOptions +Open.Database.Extensions.QueryOptions.None = 0 -> Open.Database.Extensions.QueryOptions +Open.Database.Extensions.QueryOptions.SequentialAccess = 8 -> Open.Database.Extensions.QueryOptions +Open.Database.Extensions.QueryOptions.SingleResult = 2 -> Open.Database.Extensions.QueryOptions +Open.Database.Extensions.MappedQuery.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedQuery +Open.Database.Extensions.MappedQueryWithSkip.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedQueryWithSkip +Open.Database.Extensions.MappedQueryWithTake.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedQueryWithTake +Open.Database.Extensions.MappedCommand.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedCommand +Open.Database.Extensions.MappedDbQuery.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedDbQuery! +Open.Database.Extensions.MappedDbQuery.WithOptions(Open.Database.Extensions.QueryOptions options) -> Open.Database.Extensions.MappedDbQuery! diff --git a/Source/Core/QueryOptions.cs b/Source/Core/QueryOptions.cs new file mode 100644 index 00000000..ab5bbe36 --- /dev/null +++ b/Source/Core/QueryOptions.cs @@ -0,0 +1,45 @@ +namespace Open.Database.Extensions; + +/// +/// How a mapped query executes its command and reads its rows: the switches of +/// SingleResult(), AsyncReads(), CancelOnEarlyStop() and +/// SequentialAccess() as one value for +/// . +/// +/// +/// Each value is what the method of the same name sets: +/// , +/// , +/// and +/// , which are the usual way to +/// set one and keep the others. +/// WithOptions sets all four at once: a switch that is not in the value +/// is off, whatever was set before. +/// The pool is not one of them (see UsePool). +/// They apply to the terminals that read rows from a command: a terminal that +/// reads no rows does not use them, and a Map over a reader or a table +/// you already have has no command to execute, so it has no switches to set. +/// +// One byte: the layout is smaller than the four bool fields it replaces. +// The values are the bits the query's hash code has always mixed in +// (8, 4, 2 and 1). +// A switch is read with a mask, never with HasFlag, which boxes on the older +// targets. +[Flags] +public enum QueryOptions : byte +{ + /// No switch is set. + None = 0, + + /// + AsyncReads = 1, + + /// + SingleResult = 2, + + /// + CancelOnEarlyStop = 4, + + /// + SequentialAccess = 8, +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs new file mode 100644 index 00000000..50ddf584 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs @@ -0,0 +1,294 @@ +using static Open.Database.Extensions.QueryOptions; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// The parameters of the typed definitions below. +internal readonly record struct AuthorParams(int Author); + +// Options(x) sets the four switches as one value: it is the same query as the +// calls that set them one by one, it replaces what was set before (also what a +// command chose before Map), it keeps skip and take, and it refuses a value +// that has a bit which is no switch. +[ExcludeFromCodeCoverage] +public static class OptionsSetterTests +{ + // Every combination of the four switches: 0 to 15. + public static TheoryData Masks => [.. Enumerable.Range(0, 16)]; + + static bool Has(QueryOptions options, QueryOptions flag) + => (options & flag) != 0; + + // ---- the same query as the calls, for every combination ---------------- + + static MappedCommand View() + => new FakeDbCommand( + new FakeDbConnection(), + () => new ChannelTestReader(3)) + .Map(); + + static MappedCommand ByCalls(MappedCommand view, QueryOptions o) + { + if (Has(o, SingleResult)) view = view.SingleResult(); + if (Has(o, AsyncReads)) view = view.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) view = view.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) view = view.SequentialAccess(); + return view; + } + + static MappedQuery ByCalls(MappedQuery query, QueryOptions o) + { + if (Has(o, SingleResult)) query = query.SingleResult(); + if (Has(o, AsyncReads)) query = query.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) query = query.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) query = query.SequentialAccess(); + return query; + } + + static MappedDbQuery ByCalls(MappedDbQuery d, QueryOptions o) + { + if (Has(o, SingleResult)) d = d.SingleResult(); + if (Has(o, AsyncReads)) d = d.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) d = d.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) d = d.SequentialAccess(); + return d; + } + + static MappedDbQuery ByCalls( + MappedDbQuery d, + QueryOptions o) + { + if (Has(o, SingleResult)) d = d.SingleResult(); + if (Has(o, AsyncReads)) d = d.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) d = d.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) d = d.SequentialAccess(); + return d; + } + + [Theory, MemberData(nameof(Masks))] + public static void ACommandView_WithOptions_IsTheChainedCalls(int mask) + { + var options = (QueryOptions)mask; + MappedCommand plain = View(); + + MappedCommand set = plain.WithOptions(options); + MappedCommand chained = ByCalls(plain, options); + + Assert.Equal(chained, set); + Assert.Equal(chained.GetHashCode(), set.GetHashCode()); + } + + [Theory, MemberData(nameof(Masks))] + public static void AMappedQuery_WithOptions_IsTheChainedCalls(int mask) + { + var options = (QueryOptions)mask; + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + MappedQuery plain = definition.Map().Using(connection); + + MappedQuery set = plain.WithOptions(options); + MappedQuery chained = ByCalls(plain, options); + + Assert.Equal(chained, set); + Assert.Equal(chained.GetHashCode(), set.GetHashCode()); + } + + [Theory, MemberData(nameof(Masks))] + public static void ASkippedOrTakenQuery_WithOptions_IsTheChainedCalls( + int mask) + { + var options = (QueryOptions)mask; + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + MappedQuery plain = definition.Map().Using(connection); + + MappedQueryWithSkip skipped = plain.Skip(2); + MappedQueryWithSkip skippedSet = skipped.WithOptions(options); + MappedQueryWithSkip skippedChained = ByCalls(skipped, options); + MappedQueryWithTake taken = plain.Take(3); + MappedQueryWithTake takenSet = taken.WithOptions(options); + MappedQueryWithTake takenChained = ByCalls(taken, options); + + Assert.Equal(skippedChained, skippedSet); + Assert.Equal(skippedChained.GetHashCode(), skippedSet.GetHashCode()); + Assert.Equal(takenChained, takenSet); + Assert.Equal(takenChained.GetHashCode(), takenSet.GetHashCode()); + } + + static MappedQueryWithSkip ByCalls( + MappedQueryWithSkip query, + QueryOptions o) + { + if (Has(o, SingleResult)) query = query.SingleResult(); + if (Has(o, AsyncReads)) query = query.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) query = query.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) query = query.SequentialAccess(); + return query; + } + + static MappedQueryWithTake ByCalls( + MappedQueryWithTake query, + QueryOptions o) + { + if (Has(o, SingleResult)) query = query.SingleResult(); + if (Has(o, AsyncReads)) query = query.AsyncReads(); + if (Has(o, CancelOnEarlyStop)) query = query.CancelOnEarlyStop(); + if (Has(o, SequentialAccess)) query = query.SequentialAccess(); + return query; + } + + [Theory, MemberData(nameof(Masks))] + public static void ADefinition_WithOptions_IsChained_AndReachesTheQuery( + int mask) + { + var options = (QueryOptions)mask; + DbQuery query = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + + MappedDbQuery plain = query.Map(); + MappedQuery set = plain.WithOptions(options).Using(connection); + MappedQuery chained = ByCalls(plain, options).Using(connection); + MappedQuery byHand = ByCalls(plain.Using(connection), options); + + Assert.Equal(chained, set); + Assert.Equal(chained.GetHashCode(), set.GetHashCode()); + Assert.Equal(byHand, set); + } + + [Theory, MemberData(nameof(Masks))] + public static void ATypedDefinition_WithOptions_IsTheChainedCalls( + int mask) + { + var options = (QueryOptions)mask; + using FakeDbConnection connection = new(); + AuthorParams values = new(7); + + MappedDbQuery plain = DbQuery.Text("select 1") + .Params() + .Map(); + MappedQuery set = plain + .WithOptions(options) + .Using(connection) + .AddParams(values); + MappedQuery chained = ByCalls(plain, options) + .Using(connection) + .AddParams(values); + MappedQuery byHand = ByCalls( + plain.Using(connection).AddParams(values), + options); + + Assert.Equal(chained, set); + Assert.Equal(chained.GetHashCode(), set.GetHashCode()); + Assert.Equal(byHand, set); + } + + // ---- it sets: it does not add ----------------------------------------- + + [Fact] + public static void WithOptions_ReplacesTheSwitchesSetBefore() + { + MappedCommand plain = View(); + MappedCommand view = plain.SingleResult().AsyncReads(); + + MappedCommand only = view.WithOptions(SequentialAccess); + + Assert.Equal(plain.SequentialAccess(), only); + Assert.NotEqual(view, only); + Assert.Equal(plain, view.WithOptions(None)); + } + + // What a command chose before Map is replaced too. + [Fact] + public static void WithOptions_ReplacesWhatTheCommandChoseBeforeMap() + { + ExpressiveDbCommand command = new( + new FakeDbConnection(), + CommandType.Text, + "select 1"); + + MappedQuery async = command.AsyncReads().Map(); + MappedQuery single = command.SingleResult().Map(); + + // The switch the command chose is off after Options, as any other is. + Assert.NotEqual(async, async.WithOptions(None)); + Assert.NotEqual(single, single.WithOptions(None)); + } + + [Fact] + public static void WithOptions_KeepsSkipAndTake() + { + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + MappedQuery plain = definition.Map().Using(connection); + + MappedQueryWithTake before = plain + .Skip(2) + .Take(3) + .WithOptions(QueryOptions.SingleResult); + MappedQueryWithTake after = plain + .WithOptions(QueryOptions.SingleResult) + .Skip(2) + .Take(3); + MappedQueryWithTake otherSkip = plain + .Skip(1) + .Take(3) + .WithOptions(QueryOptions.SingleResult); + + Assert.Equal(after, before); + Assert.NotEqual(otherSkip, before); + } + + // ---- a value with a bit that is no switch ------------------------- + + public static TheoryData BadValues => [16, 17, 32, 128, 255]; + + [Theory, MemberData(nameof(BadValues))] + public static void ABitThatIsNoSwitch_IsRefused_WithTheValidValues( + int value) + { + var options = (QueryOptions)value; + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + MappedQuery query = definition.Map().Using(connection); + + Action[] calls = + [ + () => View().WithOptions(options), + () => query.WithOptions(options), + () => query.Skip(1).WithOptions(options), + () => query.Take(1).WithOptions(options), + () => definition.Map().WithOptions(options), + () => definition + .Params() + .Map() + .WithOptions(options), + ]; + + foreach (Action call in calls) + { + ArgumentOutOfRangeException thrown + = Assert.Throws(call); + + Assert.Equal("options", thrown.ParamName); + Assert.Equal(value, thrown.ActualValue); + Assert.Contains("none of its switches", thrown.Message); + Assert.Contains("AsyncReads (1)", thrown.Message); + Assert.Contains("SingleResult (2)", thrown.Message); + Assert.Contains("CancelOnEarlyStop (4)", thrown.Message); + Assert.Contains("SequentialAccess (8)", thrown.Message); + Assert.Contains("None (0)", thrown.Message); + } + } + + [Fact] + public static void TheValueIsRefusedBeforeADefaultValueIsLookedAt() + { + MappedQuery unbound = default; + + Assert.Throws( + () => unbound.WithOptions((QueryOptions)16)); + Assert.Throws( + () => unbound.WithOptions(None)); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs new file mode 100644 index 00000000..52d05b63 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs @@ -0,0 +1,173 @@ +using System.Buffers; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// The four switches of a mapped query (SingleResult, AsyncReads, +// CancelOnEarlyStop, SequentialAccess) are one value; a copy with one changed +// is one query, whichever order they are set in, and a definition hands its +// switches and its pool to every query made from it. +[ExcludeFromCodeCoverage] +public static class QueryOptionsTests +{ + static MappedCommand View() + => new FakeDbCommand( + new FakeDbConnection(), + () => new ChannelTestReader(3)) + .Map(); + + static readonly ( + string Name, + Func, MappedCommand> Set)[] Switches = + [ + ("SingleResult", static q => q.SingleResult()), + ("AsyncReads", static q => q.AsyncReads()), + ("CancelOnEarlyStop", static q => q.CancelOnEarlyStop()), + ("SequentialAccess", static q => q.SequentialAccess()), + ]; + + [Fact] + public static void EachSwitch_MakesAnotherQuery_ThatNoOtherSwitchStandsFor() + { + MappedCommand plain = View(); + + for (int i = 0; i < Switches.Length; i++) + { + MappedCommand one = Switches[i].Set(plain); + Assert.NotEqual(plain, one); + Assert.Equal(one, Switches[i].Set(plain)); + Assert.Equal( + one.GetHashCode(), + Switches[i].Set(plain).GetHashCode()); + + for (int j = 0; j < Switches.Length; j++) + { + if (i != j) Assert.NotEqual(one, Switches[j].Set(plain)); + } + } + } + + [Fact] + public static void TheSwitches_InAnyOrder_AreTheSameQuery() + { + MappedCommand plain = View(); + MappedCommand forward = Switches + .Aggregate(plain, static (q, s) => s.Set(q)); + MappedCommand backward = Switches + .Reverse() + .Aggregate(plain, static (q, s) => s.Set(q)); + + Assert.Equal(forward, backward); + Assert.Equal(forward.GetHashCode(), backward.GetHashCode()); + Assert.NotEqual(plain, forward); + } + + [Fact] + public static void ASwitchSetTwice_IsTheSameAsOnce() + { + MappedCommand plain = View(); + + foreach ((string name, var set) in Switches) + Assert.True(set(plain).Equals(set(set(plain))), name); + } + + // The values are the bits the query's hash code has always mixed in, one + // bit each. + [Fact] + public static void TheOptions_AreOneBitEach_AndCombineWithOr() + { + Assert.Equal(0, (int)QueryOptions.None); + Assert.Equal(1, (int)QueryOptions.AsyncReads); + Assert.Equal(2, (int)QueryOptions.SingleResult); + Assert.Equal(4, (int)QueryOptions.CancelOnEarlyStop); + Assert.Equal(8, (int)QueryOptions.SequentialAccess); + + const QueryOptions all + = QueryOptions.AsyncReads + | QueryOptions.SingleResult + | QueryOptions.CancelOnEarlyStop + | QueryOptions.SequentialAccess; + Assert.Equal(15, (int)all); + Assert.Equal( + QueryOptions.SingleResult, + all & QueryOptions.SingleResult); + } + + // A definition holds the switches before there is a source, and every query + // made from it has them. + [Fact] + public static void ADefinitionsSwitches_ReachTheQueryMadeFromIt() + { + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + + MappedQuery fromDefinition = definition.Map() + .SingleResult().AsyncReads().CancelOnEarlyStop().SequentialAccess() + .Using(connection); + MappedQuery afterwards = definition.Map() + .Using(connection) + .SingleResult().AsyncReads().CancelOnEarlyStop().SequentialAccess(); + + Assert.Equal(afterwards, fromDefinition); + Assert.NotEqual( + definition.Map().Using(connection), + fromDefinition); + } + + [Fact] + public static void ADefinitionsSwitches_AreEachOne_NotAllOrNone() + { + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + + var definitions = new ( + string Name, + Func, MappedDbQuery> Set, + Func, MappedQuery> Apply)[] + { + ( + "SingleResult", + static d => d.SingleResult(), + static q => q.SingleResult()), + ( + "AsyncReads", + static d => d.AsyncReads(), + static q => q.AsyncReads()), + ( + "CancelOnEarlyStop", + static d => d.CancelOnEarlyStop(), + static q => q.CancelOnEarlyStop()), + ( + "SequentialAccess", + static d => d.SequentialAccess(), + static q => q.SequentialAccess()), + }; + + foreach ((string name, var set, var apply) in definitions) + { + MappedQuery fromDefinition + = set(definition.Map()).Using(connection); + MappedQuery byHand + = apply(definition.Map().Using(connection)); + Assert.True(fromDefinition.Equals(byHand), name); + } + } + + [Fact] + public static void ADefinitionsPool_ReachesTheQueryMadeFromIt() + { + DbQuery definition = DbQuery.Text("select 1"); + using FakeDbConnection connection = new(); + ArrayPool pool = ArrayPool.Create(); + + MappedQuery plain = definition.Map().Using(connection); + MappedQuery pooled = definition.Map() + .UsePool(pool, clearOnReturn: true) + .Using(connection); + + // The configuration is part of what a query is, and a pool of its own + // is another one. + Assert.NotEqual(plain, pooled); + } +} diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 32caac8f..cd571a80 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -12,6 +12,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. - **Changed: the synchronous `ToList()` reads into pooled chunks, as `ToListAsync` does.** On a view or a reader it grew a list of its own, and so allocated the growth as well as the result and rented no pooled array; it now reads into the chain of pooled arrays and copies the rows once into a list of exactly their number, so the copy-out clearing above applies to it too. The growth is gone: 100,000 `int` rows allocate about 400 KB instead of about 1.05 MB, and 1,000 rows about 28.8 KB instead of 33.2 KB. +- **New: `WithOptions(QueryOptions)` sets the four switches of a mapped query at once.** `QueryOptions` is a flags enum (`None`, `AsyncReads`, `SingleResult`, `CancelOnEarlyStop`, `SequentialAccess`), and `WithOptions(x)` on `MappedQuery` (also after `Skip` or `Take`), `MappedCommand`, `MappedDbQuery` and `MappedDbQuery` is the same query as the calls that set those switches one by one. It sets, it does not add: a switch that is not in the value is off, also one a command chose before `Map` (`SingleResult()`, `AsyncReads()`), so `WithOptions(QueryOptions.None)` turns all of them off. A value with a bit that is no switch throws `ArgumentOutOfRangeException` that names the valid ones. The four methods keep working as before. ### Changes since rc.15