From c70052e65eb230b074a715705bace21451f0d865 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:49:47 -0800 Subject: [PATCH 1/6] MappedQuery dedupe: one options value, one default source, forwarding on the bound query No behavior change and no public API change (the public member list and order are the same). - The four switches of a mapped query (`SingleResult`, `AsyncReads`, `CancelOnEarlyStop`, `SequentialAccess`) are one internal readonly struct, `QueryOptions` (a plain struct with `With*` copies, as the netstandard targets have no `init` accessors). The query core takes it in place of four bools (seven constructor arguments, not ten), each `With*` is one copy call, and its equality compares the value; the hash code mixes the same bits as before. `MappedDbQuery` holds the value in place of four bool fields (five constructor arguments, not eight), its setters are copies of it, and `View()` makes the core with its options in one call instead of re-applying four, then the pool. - `Views.DefaultSource()` is the first-column-or-default-map choice of a plain `Map()`, written seven times before (`DbQuery`, `DbQueryCall`, `DbQueryUsing`, and the four view factories). - `DbQueryUsing.Map()`, `Map(RowMap)`, `Map(Func)`, `AsObjectArrays()` and `AsDictionaryRows()` forward to the call they hold (`ToCall().Map()` and so on), as its `AnyAsync` and `CountAsync` already did, instead of repeating the call's bodies. `Map(Func)` keeps its own selector check first, so a default value with no selector reports the selector, as it always did. Tests: `QueryOptionsTests` pins what the refactor must keep: each switch makes another query that no other switch stands for, any order of the switches is the same query, a switch set twice is the same as once, and a definition's switches and pool reach the query made from it. They pass on the code before this change as well. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQuery.cs | 4 +- Source/Core/DbQueryCall.cs | 4 +- Source/Core/DbQueryUsing.cs | 15 +-- Source/Core/MappedDbQuery.cs | 38 ++---- Source/Core/MappedQuery.cs | 120 +++++++----------- Source/Core/MappedViews.cs | 70 +++++----- Source/Core/QueryOptions.cs | 90 +++++++++++++ .../QueryOptionsTests.cs | 116 +++++++++++++++++ 8 files changed, 314 insertions(+), 143 deletions(-) create mode 100644 Source/Core/QueryOptions.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs 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..7835d75e 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -87,9 +87,7 @@ public DbQueryCall AddParam( /// // 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())); /// // A bare null does not compile here (it also fits the selector overload): diff --git a/Source/Core/DbQueryUsing.cs b/Source/Core/DbQueryUsing.cs index fdb309ea..03fc3356 100644 --- a/Source/Core/DbQueryUsing.cs +++ b/Source/Core/DbQueryUsing.cs @@ -56,9 +56,7 @@ object SourceOrThrow /// 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)); + => ToCall().Map(); /// Maps each row to a with a map the caller declared, and returns the mapped query. /// The type each row is mapped to. @@ -68,9 +66,7 @@ public MappedQuery 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)); + => ToCall().Map(map); /// Maps each row with a selector, and returns the mapped query. /// The type each row is mapped to. @@ -83,7 +79,8 @@ 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. @@ -91,14 +88,14 @@ public MappedQuery Map(Func selector) /// 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/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index aa44bc4f..3f8f7421 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. @@ -75,7 +66,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// 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.WithSingleResult(), _pool, _clearOnReturn); /// /// Cancels the command when a terminal stops before the last row, in every query made from this definition @@ -83,7 +74,7 @@ public MappedDbQuery SingleResult() /// /// 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.WithCancelOnEarlyStop(), _pool, _clearOnReturn); /// /// Reads the rows with the asynchronous read of the provider, in every query made from this definition @@ -91,7 +82,7 @@ public MappedDbQuery CancelOnEarlyStop() /// /// A definition that reads asynchronously. public MappedDbQuery AsyncReads() - => new(Query, _source, _singleResult, true, _pool, _clearOnReturn, _cancelOnEarlyStop, _sequentialAccess); + => new(Query, _source, _options.WithAsyncReads(), _pool, _clearOnReturn); /// /// Asks the reader for sequential access, in every query made from this definition @@ -99,7 +90,7 @@ public MappedDbQuery AsyncReads() /// /// A definition whose queries read with sequential access. public MappedDbQuery SequentialAccess() - => new(Query, _source, _singleResult, _asyncReads, _pool, _clearOnReturn, _cancelOnEarlyStop, true); + => new(Query, _source, _options.WithSequentialAccess(), _pool, _clearOnReturn); /// /// Takes the arrays that hold the rows from , in every query made from this definition @@ -114,7 +105,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 +192,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); } } diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index ad191eb8..89eeafc6 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -97,11 +97,7 @@ 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 +141,7 @@ 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 +149,14 @@ 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. + readonly QueryOptions _options = options; // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): see QueryOptions. /// /// The command, or for a default value. @@ -241,10 +228,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 +243,10 @@ 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) + + (_options.SequentialAccess ? 8 : 0) + + (_options.CancelOnEarlyStop ? 4 : 0) + + (_options.SingleResult ? 2 : 0) + + (_options.AsyncReads ? 1 : 0) + RuntimeHelpers.GetHashCode(Config); // Reference equality, null for a default value. } } @@ -273,16 +257,16 @@ 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); + => (_options.SingleResult ? CommandBehavior.SingleResult : CommandBehavior.Default) + | (_options.SequentialAccess ? CommandBehavior.SequentialAccess : CommandBehavior.Default); - public MappedQueryCore WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, true, _asyncReads, _cancelOnEarlyStop, _sequentialAccess, Config)); + public MappedQueryCore WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, _options.WithSingleResult(), Config)); - public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, true, _cancelOnEarlyStop, _sequentialAccess, Config)); + public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _options.WithAsyncReads(), Config)); - public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, true, _sequentialAccess, Config)); + public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _options.WithCancelOnEarlyStop(), Config)); - public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _singleResult, _asyncReads, _cancelOnEarlyStop, true, Config)); + public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _options.WithSequentialAccess(), Config)); /// /// Gets the configuration the query was given. @@ -319,11 +303,11 @@ 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 +317,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 +337,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 +407,8 @@ 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, !_options.SingleResult) + : _options.SingleResult ? ExecuteReader(state, transform, behavior) : ExecuteReader((state, transform), static (reader, s) => { @@ -441,8 +419,8 @@ 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, !_options.SingleResult, linked, token) + : _options.SingleResult ? ExecuteAsync(state, transform, behavior, linked, token) : ExecuteAsync((state, transform, token), static async (reader, s) => { @@ -453,7 +431,7 @@ ValueTask RunAsync(TState state, Func _cancelOnEarlyStop ? new ReaderAbandon() : null; + => _options.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,9 +488,9 @@ async ValueTask ExecuteAbandonableAsync(TState state, public void Read(Action> handler) { ReaderAbandon? abandon = NewAbandon(); - ExecuteReader((handler, _source, _skip, _take, _singleResult, abandon), static (reader, s) => + ExecuteReader((handler, _source, _skip, _take, _options.SingleResult, abandon), static (reader, s) => { - s.handler(RowReader.Stream(s._source, reader, s._skip, s._take, !s._singleResult, s.abandon)); + s.handler(RowReader.Stream(s._source, reader, s._skip, s._take, !s.SingleResult, s.abandon)); return false; }, Behavior, abandon); } @@ -520,8 +498,8 @@ public void Read(Action> handler) 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, _options.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,9 +513,9 @@ 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) => + return ValueTaskHelpers.Discard(ExecuteAsync((handler, _source, _skip, _take, _options.SingleResult, _options.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); + 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)); } @@ -546,8 +524,8 @@ public ValueTask ReadAsync(Func, Cancellat { 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, _options.SingleResult, _options.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 +592,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 && _options.SingleResult && !_options.CancelOnEarlyStop; public T? SingleOrDefault() { @@ -690,10 +668,10 @@ public ValueTask CollectAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _asyncReads, Config, token, build, abandon), + (_source, _skip, _take, _options.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,11 +702,11 @@ 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) => + return RunAsync((_source, _skip, _take, _options.AsyncReads, abandon, token), static async (reader, s) => { 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); + (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; } @@ -740,11 +718,11 @@ 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) => + return RunAsync((_source, _skip, _take, _options.AsyncReads, abandon, token), static async (reader, s) => { 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); + (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; } @@ -759,14 +737,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, _options.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 +763,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, _options.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 +788,9 @@ public ValueTask AnyAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _asyncReads, abandon, token), + (_skip, _take, _options.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 +801,9 @@ public ValueTask CountAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _asyncReads, abandon, token), + (_skip, _take, _options.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 +933,14 @@ public ValueTask FillAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _asyncReads, token, sink, abandon), + (_source, _skip, _take, _options.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 diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 805e1fd4..3477062e 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -49,11 +49,7 @@ 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 +128,7 @@ 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 +210,7 @@ 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 +256,17 @@ public static MappedTable Map( // against the command itself with the core's singleResult flag set. static class Views { + /// + /// 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 +284,21 @@ internal static MappedQueryCore QueryCore( internal static MappedQueryCore QueryCore( DbQueryCall call, IRowSource source) - => NewCore(null, call, source, false, false); + => NewCore(null, call, source, default); + + /// + /// 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); // A call made from a definition is held as it is, even when it reaches here as an IExecuteReader. static MappedQueryCore FromCommand( @@ -294,9 +307,9 @@ 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, new(singleResult)), + DbQueryUsing bound => NewCore(null, bound.ToCall(), source, new(singleResult)), + _ => NewCore(command, default, source, new(singleResult, AsyncReads(command))), }; /// @@ -311,19 +324,19 @@ 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, new(true)); 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, new(true)) + : NewCore(new CommandExecutor(command), default, source, default); internal static MappedQueryCore TableCore( DataTable table, IRowSource source) - => NewCore(new TableExecutor(table), default, source, true, false); + => NewCore(new TableExecutor(table), default, source, new(true)); /// /// Makes a query core: the one door every query is made through. @@ -332,8 +345,7 @@ 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 +353,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); /// diff --git a/Source/Core/QueryOptions.cs b/Source/Core/QueryOptions.cs new file mode 100644 index 00000000..623edca0 --- /dev/null +++ b/Source/Core/QueryOptions.cs @@ -0,0 +1,90 @@ +namespace Open.Database.Extensions.Core; + +/// +/// The four switches a mapped query carries, as one value, so that a copy with one of them changed is one call. +/// +/// +/// What the pool and its clear rule are is not here: they belong to the configuration of the query +/// (), and a definition holds them beside these. +/// +// Four bools: the layout of the struct is that of the four fields it replaces. +// A plain struct, not a record with init members: the netstandard targets have no init accessors. +internal readonly struct QueryOptions( + bool singleResult = false, + bool asyncReads = false, + bool cancelOnEarlyStop = false, + bool sequentialAccess = false) + : IEquatable +{ + /// + /// Gets whether SingleResult() was called: stop after the first result set and do not read through the rest. + /// + public bool SingleResult { get; } = singleResult; + + /// + /// Gets whether AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read). + /// + public bool AsyncReads { get; } = asyncReads; + + /// + /// Gets whether CancelOnEarlyStop() was called: see . + /// + public bool CancelOnEarlyStop { get; } = cancelOnEarlyStop; + + /// + /// Gets whether SequentialAccess() was called on the query. + /// + public bool SequentialAccess { get; } = sequentialAccess; + + /// Returns the options with SingleResult() set. + /// A copy with the switch on. + public QueryOptions WithSingleResult() + => new(true, AsyncReads, CancelOnEarlyStop, SequentialAccess); + + /// Returns the options with AsyncReads() set. + /// A copy with the switch on. + public QueryOptions WithAsyncReads() + => new(SingleResult, true, CancelOnEarlyStop, SequentialAccess); + + /// Returns the options with CancelOnEarlyStop() set. + /// A copy with the switch on. + public QueryOptions WithCancelOnEarlyStop() + => new(SingleResult, AsyncReads, true, SequentialAccess); + + /// Returns the options with SequentialAccess() set. + /// A copy with the switch on. + public QueryOptions WithSequentialAccess() + => new(SingleResult, AsyncReads, CancelOnEarlyStop, true); + + /// + public bool Equals(QueryOptions other) + => SingleResult == other.SingleResult + && AsyncReads == other.AsyncReads + && CancelOnEarlyStop == other.CancelOnEarlyStop + && SequentialAccess == other.SequentialAccess; + + /// + public override bool Equals(object? obj) + => obj is QueryOptions other && Equals(other); + + /// + public override int GetHashCode() + => (SequentialAccess ? 8 : 0) + + (CancelOnEarlyStop ? 4 : 0) + + (SingleResult ? 2 : 0) + + (AsyncReads ? 1 : 0); + + /// Determines whether two sets of options are the same. + /// The first. + /// The second. + /// if they are the same; otherwise, . + public static bool operator ==(QueryOptions left, QueryOptions right) + => left.Equals(right); + + /// Determines whether two sets of options differ. + /// The first. + /// The second. + /// if they differ; otherwise, . + public static bool operator !=(QueryOptions left, QueryOptions right) + => !left.Equals(right); +} 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..33bb87eb --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs @@ -0,0 +1,116 @@ +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); + } + + // 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); + } +} From 9eb4516d64caba1870045421d115754ec5490220 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:17:26 -0800 Subject: [PATCH 2/6] MappedQuery dedupe: QueryOptions is a flags enum The four switches of a mapped query are `[Flags] internal enum QueryOptions : byte` (`None`, `AsyncReads` 1, `SingleResult` 2, `CancelOnEarlyStop` 4, `SequentialAccess` 8), in place of the plain struct: the values are the bits the query's hash code has always mixed in, so the hash part is `(int)_options`, equality is `==`, a copy with a switch set is `_options | QueryOptions.X`, and a switch is read with a mask (`(_options & QueryOptions.X) != 0`, never `HasFlag`, which boxes on the older targets). The core reads them through four private properties of that mask, so the capture tuples of its terminals still pass bools, computed where they are captured, at no cost per row. `Views.NewCore`, `QueryCore` and `FromCommand` pass flag values. No behavior change; the previous tests pass, and a new one pins the flag values. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/MappedDbQuery.cs | 8 +- Source/Core/MappedQuery.cs | 62 +++++++------ Source/Core/MappedViews.cs | 19 ++-- Source/Core/QueryOptions.cs | 86 ++++--------------- .../QueryOptionsTests.cs | 15 ++++ 5 files changed, 81 insertions(+), 109 deletions(-) diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 3f8f7421..6cfc8aa0 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -66,7 +66,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// A definition that reads only the first result set. public MappedDbQuery SingleResult() - => new(Query, _source, _options.WithSingleResult(), _pool, _clearOnReturn); + => 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 @@ -74,7 +74,7 @@ public MappedDbQuery SingleResult() /// /// A definition whose queries cancel their command on an early stop. public MappedDbQuery CancelOnEarlyStop() - => new(Query, _source, _options.WithCancelOnEarlyStop(), _pool, _clearOnReturn); + => 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 @@ -82,7 +82,7 @@ public MappedDbQuery CancelOnEarlyStop() /// /// A definition that reads asynchronously. public MappedDbQuery AsyncReads() - => new(Query, _source, _options.WithAsyncReads(), _pool, _clearOnReturn); + => new(Query, _source, _options | QueryOptions.AsyncReads, _pool, _clearOnReturn); /// /// Asks the reader for sequential access, in every query made from this definition @@ -90,7 +90,7 @@ public MappedDbQuery AsyncReads() /// /// A definition whose queries read with sequential access. public MappedDbQuery SequentialAccess() - => new(Query, _source, _options.WithSequentialAccess(), _pool, _clearOnReturn); + => new(Query, _source, _options | QueryOptions.SequentialAccess, _pool, _clearOnReturn); /// /// Takes the arrays that hold the rows from , in every query made from this definition diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 89eeafc6..bce7d7d2 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -158,6 +158,15 @@ readonly struct MappedQueryCore( readonly int _take = take; // -1 == unbounded. readonly QueryOptions _options = options; // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): see QueryOptions. + // 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. /// @@ -243,10 +252,7 @@ public override int GetHashCode() h = h * 31 + _skip; h = h * 31 + _take; return h * 31 - + (_options.SequentialAccess ? 8 : 0) - + (_options.CancelOnEarlyStop ? 4 : 0) - + (_options.SingleResult ? 2 : 0) - + (_options.AsyncReads ? 1 : 0) + + (int)_options + RuntimeHelpers.GetHashCode(Config); // Reference equality, null for a default value. } } @@ -257,16 +263,16 @@ 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 - => (_options.SingleResult ? CommandBehavior.SingleResult : CommandBehavior.Default) - | (_options.SequentialAccess ? CommandBehavior.SequentialAccess : CommandBehavior.Default); + => (SingleResult ? CommandBehavior.SingleResult : CommandBehavior.Default) + | (SequentialAccess ? CommandBehavior.SequentialAccess : CommandBehavior.Default); - public MappedQueryCore WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, _options.WithSingleResult(), Config)); + public MappedQueryCore WithSingleResult() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.SingleResult, Config)); - public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _options.WithAsyncReads(), Config)); + public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.AsyncReads, Config)); - public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _options.WithCancelOnEarlyStop(), Config)); + public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.CancelOnEarlyStop, Config)); - public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _options.WithSequentialAccess(), Config)); + public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.SequentialAccess, Config)); /// /// Gets the configuration the query was given. @@ -407,8 +413,8 @@ 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, !_options.SingleResult) - : _options.SingleResult + ? ExecuteAbandonable(state, transform, behavior, abandon, !SingleResult) + : SingleResult ? ExecuteReader(state, transform, behavior) : ExecuteReader((state, transform), static (reader, s) => { @@ -419,8 +425,8 @@ 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, !_options.SingleResult, linked, token) - : _options.SingleResult + ? ExecuteAbandonableAsync(state, transform, behavior, abandon, !SingleResult, linked, token) + : SingleResult ? ExecuteAsync(state, transform, behavior, linked, token) : ExecuteAsync((state, transform, token), static async (reader, s) => { @@ -431,7 +437,7 @@ ValueTask RunAsync(TState state, Func _options.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) @@ -488,7 +494,7 @@ async ValueTask ExecuteAbandonableAsync(TState state, public void Read(Action> handler) { ReaderAbandon? abandon = NewAbandon(); - ExecuteReader((handler, _source, _skip, _take, _options.SingleResult, abandon), static (reader, s) => + 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; @@ -498,7 +504,7 @@ public void Read(Action> handler) public TResult Read(Func, TResult> handler) { ReaderAbandon? abandon = NewAbandon(); - return ExecuteReader((handler, _source, _skip, _take, _options.SingleResult, abandon), static (reader, s) + 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); } @@ -513,7 +519,7 @@ 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, _options.SingleResult, _options.AsyncReads, abandon, token), static async (reader, s) => + 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; @@ -524,7 +530,7 @@ public ValueTask ReadAsync(Func, Cancellat { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return ExecuteAsync((handler, _source, _skip, _take, _options.SingleResult, _options.AsyncReads, abandon, token), static (reader, s) + 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); } @@ -592,7 +598,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 && _options.SingleResult && !_options.CancelOnEarlyStop; + bool UseSingleRow => _skip == 0 && SingleResult && !CancelOnEarlyStop; public T? SingleOrDefault() { @@ -668,7 +674,7 @@ public ValueTask CollectAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _options.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, @@ -702,7 +708,7 @@ public ValueTask ToArrayAsync(CancellationToken cancellationToken) { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return RunAsync((_source, _skip, _take, _options.AsyncReads, abandon, token), static async (reader, s) => + return RunAsync((_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) { @@ -718,7 +724,7 @@ public ValueTask ToArrayAsync(CancellationToken cancellationToken) { ReaderAbandon? abandon = NewAbandon(); CancellationToken token = Combine(cancellationToken, out CancellationTokenSource? linked); - return RunAsync((_source, _skip, _take, _options.AsyncReads, abandon, token), static async (reader, s) => + return RunAsync((_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) { @@ -737,7 +743,7 @@ public async ValueTask FirstAsync(CancellationToken cancellationToken) cancellationToken, out CancellationTokenSource? linked); (bool found, T? row) = await RunAsync( - (_source, _skip, _take, _options.AsyncReads, abandon, token), + (_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) @@ -763,7 +769,7 @@ public async ValueTask SingleAsync(CancellationToken cancellationToken) cancellationToken, out CancellationTokenSource? linked); (bool found, T? row) = await RunAsync( - (_source, _skip, _take, _options.AsyncReads, abandon, token), + (_source, _skip, _take, AsyncReads, abandon, token), static async (reader, s) => { if (reader is DbDataReader db) @@ -788,7 +794,7 @@ public ValueTask AnyAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _options.AsyncReads, abandon, token), + (_skip, _take, AsyncReads, abandon, token), static (reader, s) => RowReader.AnyAsync( reader, s._skip, s._take, s.AsyncReads, s.token, s.abandon), FirstBehavior, @@ -801,7 +807,7 @@ public ValueTask CountAsync(CancellationToken cancellationToken) CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_skip, _take, _options.AsyncReads, abandon, token), + (_skip, _take, AsyncReads, abandon, token), static (reader, s) => RowReader.CountAsync( reader, s._skip, s._take, s.AsyncReads, s.token, s.abandon), Behavior, abandon, linked, token); @@ -933,7 +939,7 @@ public ValueTask FillAsync( CancellationToken token = Combine( cancellationToken, out CancellationTokenSource? linked); return RunAsync( - (_source, _skip, _take, _options.AsyncReads, token, sink, abandon), + (_source, _skip, _take, AsyncReads, token, sink, abandon), static async (reader, s) => { if (reader is DbDataReader db) diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 3477062e..29e61bb5 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -284,7 +284,7 @@ internal static MappedQueryCore QueryCore( internal static MappedQueryCore QueryCore( DbQueryCall call, IRowSource source) - => NewCore(null, call, source, default); + => NewCore(null, call, source, QueryOptions.None); /// /// Makes the query core of a call made from a definition, with the options the definition holds. @@ -300,6 +300,9 @@ internal static MappedQueryCore QueryCore( 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( IExecuteReader command, @@ -307,9 +310,9 @@ static MappedQueryCore FromCommand( bool singleResult) => command switch { - DbQueryCall call => NewCore(null, call, source, new(singleResult)), - DbQueryUsing bound => NewCore(null, bound.ToCall(), source, new(singleResult)), - _ => NewCore(command, default, source, new(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)), }; /// @@ -324,19 +327,19 @@ static bool AsyncReads(IExecuteReader command) internal static MappedQueryCore ReaderCore( IDataReader reader, IRowSource source) - => NewCore(new ReaderExecutor(reader), default, source, new(true)); + => 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, new(true)) - : NewCore(new CommandExecutor(command), default, source, default); + ? 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, new(true)); + => NewCore(new TableExecutor(table), default, source, QueryOptions.SingleResult); /// /// Makes a query core: the one door every query is made through. diff --git a/Source/Core/QueryOptions.cs b/Source/Core/QueryOptions.cs index 623edca0..3b4a0525 100644 --- a/Source/Core/QueryOptions.cs +++ b/Source/Core/QueryOptions.cs @@ -1,90 +1,38 @@ namespace Open.Database.Extensions.Core; /// -/// The four switches a mapped query carries, as one value, so that a copy with one of them changed is one call. +/// The four switches a mapped query carries, as one value, so that a copy with one of them changed is one |. /// /// /// What the pool and its clear rule are is not here: they belong to the configuration of the query /// (), and a definition holds them beside these. +/// A switch is read with (options & QueryOptions.X) != 0, never with , which boxes on the older targets. /// -// Four bools: the layout of the struct is that of the four fields it replaces. -// A plain struct, not a record with init members: the netstandard targets have no init accessors. -internal readonly struct QueryOptions( - bool singleResult = false, - bool asyncReads = false, - bool cancelOnEarlyStop = false, - bool sequentialAccess = false) - : IEquatable +// 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). +[Flags] +internal enum QueryOptions : byte { + /// No switch is set. + None = 0, + /// - /// Gets whether SingleResult() was called: stop after the first result set and do not read through the rest. + /// AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read). /// - public bool SingleResult { get; } = singleResult; + AsyncReads = 1, /// - /// Gets whether AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read). + /// SingleResult() was called: stop after the first result set and do not read through the rest. /// - public bool AsyncReads { get; } = asyncReads; + SingleResult = 2, /// - /// Gets whether CancelOnEarlyStop() was called: see . + /// CancelOnEarlyStop() was called: see . /// - public bool CancelOnEarlyStop { get; } = cancelOnEarlyStop; + CancelOnEarlyStop = 4, /// - /// Gets whether SequentialAccess() was called on the query. + /// SequentialAccess() was called on the query. /// - public bool SequentialAccess { get; } = sequentialAccess; - - /// Returns the options with SingleResult() set. - /// A copy with the switch on. - public QueryOptions WithSingleResult() - => new(true, AsyncReads, CancelOnEarlyStop, SequentialAccess); - - /// Returns the options with AsyncReads() set. - /// A copy with the switch on. - public QueryOptions WithAsyncReads() - => new(SingleResult, true, CancelOnEarlyStop, SequentialAccess); - - /// Returns the options with CancelOnEarlyStop() set. - /// A copy with the switch on. - public QueryOptions WithCancelOnEarlyStop() - => new(SingleResult, AsyncReads, true, SequentialAccess); - - /// Returns the options with SequentialAccess() set. - /// A copy with the switch on. - public QueryOptions WithSequentialAccess() - => new(SingleResult, AsyncReads, CancelOnEarlyStop, true); - - /// - public bool Equals(QueryOptions other) - => SingleResult == other.SingleResult - && AsyncReads == other.AsyncReads - && CancelOnEarlyStop == other.CancelOnEarlyStop - && SequentialAccess == other.SequentialAccess; - - /// - public override bool Equals(object? obj) - => obj is QueryOptions other && Equals(other); - - /// - public override int GetHashCode() - => (SequentialAccess ? 8 : 0) - + (CancelOnEarlyStop ? 4 : 0) - + (SingleResult ? 2 : 0) - + (AsyncReads ? 1 : 0); - - /// Determines whether two sets of options are the same. - /// The first. - /// The second. - /// if they are the same; otherwise, . - public static bool operator ==(QueryOptions left, QueryOptions right) - => left.Equals(right); - - /// Determines whether two sets of options differ. - /// The first. - /// The second. - /// if they differ; otherwise, . - public static bool operator !=(QueryOptions left, QueryOptions right) - => !left.Equals(right); + SequentialAccess = 8, } diff --git a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs index 33bb87eb..0a613cb6 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs @@ -60,6 +60,21 @@ public static void ASwitchSetTwice_IsTheSameAsOnce() 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)Core.QueryOptions.None); + Assert.Equal(1, (int)Core.QueryOptions.AsyncReads); + Assert.Equal(2, (int)Core.QueryOptions.SingleResult); + Assert.Equal(4, (int)Core.QueryOptions.CancelOnEarlyStop); + Assert.Equal(8, (int)Core.QueryOptions.SequentialAccess); + + const Core.QueryOptions all = Core.QueryOptions.AsyncReads | Core.QueryOptions.SingleResult | Core.QueryOptions.CancelOnEarlyStop | Core.QueryOptions.SequentialAccess; + Assert.Equal(15, (int)all); + Assert.Equal(Core.QueryOptions.SingleResult, all & Core.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() From 14796de76943e4d44e2f83614e27a753430a3d77 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:27:15 -0800 Subject: [PATCH 3/6] MappedQuery dedupe: one wording for the Map members' docs The doc comments of the members this change touches reuse text instead of repeating it: - `DbQueryCall.Map()`, `Map(RowMap)`, `Map(Func)`, `AsObjectArrays()` and `AsDictionaryRows()` now hold the text, built from the shared members of `Mapped.docs.xml` (`row-type`, `map-overload`, plus two new ones, `default-bound` for the "default value" exception and `returns-mapped-query` for the one returns line they all repeated). They inherited it from `DbQueryUsing` before. - The same five members of `DbQueryUsing`, which forward to those, are `` of them, instead of their own copies of the summary, type parameter, returns and exceptions. (The two types were each other's source: the direction is turned round, as a cycle would resolve nothing.) - The selector parameter keeps its text that the selector is called from any thread and by overlapping calls, so the shared `map-selector` text, which lacks it, is not used there. No code change. The members of the internal `QueryOptions` keep one-line docs. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQueryCall.cs | 31 ++++++++++++++++++++++++------- Source/Core/DbQueryUsing.cs | 34 +++++----------------------------- Source/Core/Mapped.docs.xml | 10 ++++++++++ 3 files changed, 39 insertions(+), 36 deletions(-) diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index 7835d75e..d8abe7c1 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -84,12 +84,23 @@ 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() => 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) @@ -98,11 +109,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)); @@ -111,11 +122,17 @@ 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 03fc3356..9657390e 100644 --- a/Source/Core/DbQueryUsing.cs +++ b/Source/Core/DbQueryUsing.cs @@ -44,36 +44,18 @@ 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() => ToCall().Map(); - /// 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. + /// // A bare null does not compile here (it also fits the selector overload): // write (RowMap?)null. public MappedQuery Map(RowMap? map) => ToCall().Map(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)); @@ -83,17 +65,11 @@ public MappedQuery Map(Func selector) 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() => 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() => ToCall().AsDictionaryRows(); diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index 1a05f22d..6b2de4b2 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -21,6 +21,16 @@ The query to execute. + + + This is a value, which is bound to nothing. + + + + + The mapped query, to be read with a terminal. + + is . From f4f142ec68a845c50b8eb26fd3e1122bd5c8e016 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:39:59 -0800 Subject: [PATCH 4/6] MappedQuery dedupe: wrap the lines this change adds or touches Style only, no change to what the code does: every line this change adds or touches (the query core's `With*` one-liners, the `QueryOptions` call sites in `Views` and `MappedDbQuery`, the `ExecuteReader`, `ExecuteAsync` and `RunAsync` calls whose captured switches were renamed, the touched comments and doc comments, and the new tests) is within about 80 columns: an expression body starts on its own line, a long argument list is one argument per line or in natural groups under it, a long ternary is broken at its `?` and `:`, and a comment is wrapped at its phrase breaks. The `` lines of the doc comments stay on one line, as everywhere in the repo. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQueryCall.cs | 27 +- Source/Core/DbQueryUsing.cs | 4 +- Source/Core/MappedDbQuery.cs | 28 +- Source/Core/MappedQuery.cs | 243 ++++++++++++++---- Source/Core/MappedViews.cs | 61 ++++- Source/Core/QueryOptions.cs | 20 +- .../QueryOptionsTests.cs | 86 +++++-- 7 files changed, 367 insertions(+), 102 deletions(-) diff --git a/Source/Core/DbQueryCall.cs b/Source/Core/DbQueryCall.cs index d8abe7c1..96146631 100644 --- a/Source/Core/DbQueryCall.cs +++ b/Source/Core/DbQueryCall.cs @@ -85,8 +85,9 @@ public DbQueryCall AddParam( 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. + /// 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 . @@ -98,7 +99,10 @@ public DbQueryCall AddParam( public MappedQuery Map() => new(Views.QueryCore(Bound(), Views.DefaultSource())); - /// Maps each row to a with a map the caller declared, and returns the mapped query. + /// + /// 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): @@ -122,15 +126,24 @@ 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 . + /// + /// 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 . + /// + /// Reads each row without a model, as a . + /// + /// + /// The same as + /// . + /// /// /// public MappedQuery AsDictionaryRows() diff --git a/Source/Core/DbQueryUsing.cs b/Source/Core/DbQueryUsing.cs index 9657390e..7d88ce04 100644 --- a/Source/Core/DbQueryUsing.cs +++ b/Source/Core/DbQueryUsing.cs @@ -61,7 +61,9 @@ public MappedQuery Map(Func selector) if (selector is null) throw new ArgumentNullException(nameof(selector)); Contract.EndContractBlock(); - // 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. + // 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); } diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 6cfc8aa0..592b5363 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -66,7 +66,12 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// A definition that reads only the first result set. public MappedDbQuery SingleResult() - => new(Query, _source, _options | QueryOptions.SingleResult, _pool, _clearOnReturn); + => 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 @@ -74,7 +79,12 @@ public MappedDbQuery SingleResult() /// /// A definition whose queries cancel their command on an early stop. public MappedDbQuery CancelOnEarlyStop() - => new(Query, _source, _options | QueryOptions.CancelOnEarlyStop, _pool, _clearOnReturn); + => 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 @@ -82,7 +92,12 @@ public MappedDbQuery CancelOnEarlyStop() /// /// A definition that reads asynchronously. public MappedDbQuery AsyncReads() - => new(Query, _source, _options | QueryOptions.AsyncReads, _pool, _clearOnReturn); + => new( + Query, + _source, + _options | QueryOptions.AsyncReads, + _pool, + _clearOnReturn); /// /// Asks the reader for sequential access, in every query made from this definition @@ -90,7 +105,12 @@ public MappedDbQuery AsyncReads() /// /// A definition whose queries read with sequential access. public MappedDbQuery SequentialAccess() - => new(Query, _source, _options | QueryOptions.SequentialAccess, _pool, _clearOnReturn); + => new( + Query, + _source, + _options | QueryOptions.SequentialAccess, + _pool, + _clearOnReturn); /// /// Takes the arrays that hold the rows from , in every query made from this definition diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index bce7d7d2..20c6c94b 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -97,7 +97,8 @@ public static MappedQuery Map( if (command is null) throw new ArgumentNullException(nameof(command)); Contract.EndContractBlock(); - return new MappedQuery(Views.QueryCore(command, Views.DefaultSource())); + return new MappedQuery( + Views.QueryCore(command, Views.DefaultSource())); } /// @@ -141,7 +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. -/// The switches of the query: SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(). +/// +/// 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,9 +160,12 @@ readonly struct MappedQueryCore( readonly IRowSource _source = source; readonly int _skip = skip; readonly int _take = take; // -1 == unbounded. - readonly QueryOptions _options = options; // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): see QueryOptions. + // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): + // see QueryOptions. + readonly QueryOptions _options = options; - // A switch is read with a mask, never with HasFlag, which boxes on the older targets. + // 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; @@ -263,16 +270,52 @@ 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, _options | QueryOptions.SingleResult, Config)); - - public MappedQueryCore WithAsyncReads() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.AsyncReads, Config)); - - public MappedQueryCore WithCancelOnEarlyStop() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.CancelOnEarlyStop, Config)); - - public MappedQueryCore WithSequentialAccess() => Checked(new(_command, _call, _source, _skip, _take, _options | QueryOptions.SequentialAccess, Config)); + => (SingleResult + ? CommandBehavior.SingleResult + : CommandBehavior.Default) + | (SequentialAccess + ? CommandBehavior.SequentialAccess + : CommandBehavior.Default); + + public MappedQueryCore WithSingleResult() + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + _options | QueryOptions.SingleResult, + Config)); + + public MappedQueryCore WithAsyncReads() + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + _options | QueryOptions.AsyncReads, + Config)); + + public MappedQueryCore WithCancelOnEarlyStop() + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + _options | QueryOptions.CancelOnEarlyStop, + Config)); + + public MappedQueryCore WithSequentialAccess() + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + _options | QueryOptions.SequentialAccess, + Config)); /// /// Gets the configuration the query was given. @@ -309,7 +352,14 @@ 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, _options, config)); + => Checked(new( + _command, + _call, + _source, + _skip, + _take, + _options, + config)); /// Returns the same query over another call. public MappedQueryCore WithCall(DbQueryCall call) @@ -413,7 +463,8 @@ 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) + ? ExecuteAbandonable( + state, transform, behavior, abandon, !SingleResult) : SingleResult ? ExecuteReader(state, transform, behavior) : ExecuteReader((state, transform), static (reader, s) => @@ -425,7 +476,9 @@ 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) + ? ExecuteAbandonableAsync( + state, transform, behavior, abandon, + !SingleResult, linked, token) : SingleResult ? ExecuteAsync(state, transform, behavior, linked, token) : ExecuteAsync((state, transform, token), static async (reader, s) => @@ -494,18 +547,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) @@ -519,19 +591,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); } /// @@ -708,32 +813,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) diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 29e61bb5..7afc0e74 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -49,7 +49,8 @@ public static MappedReader Map( if (reader is null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); - return new MappedReader(Views.ReaderCore(reader, Views.DefaultSource())); + return new MappedReader( + Views.ReaderCore(reader, Views.DefaultSource())); } /// @@ -128,7 +129,8 @@ public static MappedCommand Map( if (command is null) throw new ArgumentNullException(nameof(command)); Contract.EndContractBlock(); - return new MappedCommand(Views.CommandCore(command, Views.DefaultSource())); + return new MappedCommand( + Views.CommandCore(command, Views.DefaultSource())); } /// @@ -210,7 +212,8 @@ public static MappedTable Map( if (table is null) throw new ArgumentNullException(nameof(table)); Contract.EndContractBlock(); - return new MappedTable(Views.TableCore(table, Views.DefaultSource())); + return new MappedTable( + Views.TableCore(table, Views.DefaultSource())); } /// @@ -257,8 +260,9 @@ public static MappedTable Map( static class Views { /// - /// 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. + /// 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. @@ -287,7 +291,8 @@ internal static MappedQueryCore QueryCore( => NewCore(null, call, source, QueryOptions.None); /// - /// Makes the query core of a call made from a definition, with the options the definition holds. + /// 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. @@ -310,9 +315,18 @@ static MappedQueryCore FromCommand( bool singleResult) => command switch { - 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)), + 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)), }; /// @@ -327,19 +341,35 @@ static bool AsyncReads(IExecuteReader command) internal static MappedQueryCore ReaderCore( IDataReader reader, IRowSource source) - => NewCore(new ReaderExecutor(reader), default, source, QueryOptions.SingleResult); + => 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, QueryOptions.SingleResult) - : NewCore(new CommandExecutor(command), default, source, QueryOptions.None); + ? 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, QueryOptions.SingleResult); + => NewCore( + new TableExecutor(table), + default, + source, + QueryOptions.SingleResult); /// /// Makes a query core: the one door every query is made through. @@ -348,7 +378,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. - /// The switches of the query (SingleResult() and the others), the ones a command or a definition chose before Map. + /// + /// 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. diff --git a/Source/Core/QueryOptions.cs b/Source/Core/QueryOptions.cs index 3b4a0525..1ce47e8c 100644 --- a/Source/Core/QueryOptions.cs +++ b/Source/Core/QueryOptions.cs @@ -1,15 +1,19 @@ namespace Open.Database.Extensions.Core; /// -/// The four switches a mapped query carries, as one value, so that a copy with one of them changed is one |. +/// The four switches a mapped query carries, as one value, so that a copy +/// with one of them changed is one |. /// /// -/// What the pool and its clear rule are is not here: they belong to the configuration of the query -/// (), and a definition holds them beside these. -/// A switch is read with (options & QueryOptions.X) != 0, never with , which boxes on the older targets. +/// The pool and its clear rule are not here: they belong to the configuration +/// of the query (), and a definition holds them +/// beside these. +/// A switch is read with (options & QueryOptions.X) != 0, never with +/// , which boxes on the older targets. /// // 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). +// The values are the bits the query's hash code has always mixed in +// (8, 4, 2 and 1). [Flags] internal enum QueryOptions : byte { @@ -17,12 +21,14 @@ internal enum QueryOptions : byte None = 0, /// - /// AsyncReads() was called: the rows of an async terminal are read with ReadAsync (the default is Read). + /// AsyncReads() was called: the rows of an async terminal are read + /// with ReadAsync (the default is Read). /// AsyncReads = 1, /// - /// SingleResult() was called: stop after the first result set and do not read through the rest. + /// SingleResult() was called: stop after the first result set and do + /// not read through the rest. /// SingleResult = 2, diff --git a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs index 0a613cb6..c9625c8e 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs @@ -4,15 +4,22 @@ 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. +// 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 = + => 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()), @@ -30,7 +37,9 @@ public static void EachSwitch_MakesAnotherQuery_ThatNoOtherSwitchStandsFor() 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()); + Assert.Equal( + one.GetHashCode(), + Switches[i].Set(plain).GetHashCode()); for (int j = 0; j < Switches.Length; j++) { @@ -43,8 +52,11 @@ public static void EachSwitch_MakesAnotherQuery_ThatNoOtherSwitchStandsFor() 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)); + 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()); @@ -60,7 +72,8 @@ public static void ASwitchSetTwice_IsTheSameAsOnce() 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. + // The values are the bits the query's hash code has always mixed in, one + // bit each. [Fact] public static void TheOptions_AreOneBitEach_AndCombineWithOr() { @@ -70,12 +83,19 @@ public static void TheOptions_AreOneBitEach_AndCombineWithOr() Assert.Equal(4, (int)Core.QueryOptions.CancelOnEarlyStop); Assert.Equal(8, (int)Core.QueryOptions.SequentialAccess); - const Core.QueryOptions all = Core.QueryOptions.AsyncReads | Core.QueryOptions.SingleResult | Core.QueryOptions.CancelOnEarlyStop | Core.QueryOptions.SequentialAccess; + const Core.QueryOptions all + = Core.QueryOptions.AsyncReads + | Core.QueryOptions.SingleResult + | Core.QueryOptions.CancelOnEarlyStop + | Core.QueryOptions.SequentialAccess; Assert.Equal(15, (int)all); - Assert.Equal(Core.QueryOptions.SingleResult, all & Core.QueryOptions.SingleResult); + Assert.Equal( + Core.QueryOptions.SingleResult, + all & Core.QueryOptions.SingleResult); } - // A definition holds the switches before there is a source, and every query made from it has them. + // A definition holds the switches before there is a source, and every query + // made from it has them. [Fact] public static void ADefinitionsSwitches_ReachTheQueryMadeFromIt() { @@ -90,7 +110,9 @@ public static void ADefinitionsSwitches_ReachTheQueryMadeFromIt() .SingleResult().AsyncReads().CancelOnEarlyStop().SequentialAccess(); Assert.Equal(afterwards, fromDefinition); - Assert.NotEqual(definition.Map().Using(connection), fromDefinition); + Assert.NotEqual( + definition.Map().Using(connection), + fromDefinition); } [Fact] @@ -99,18 +121,35 @@ 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)[] + 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()), + ( + "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)); + MappedQuery fromDefinition + = set(definition.Map()).Using(connection); + MappedQuery byHand + = apply(definition.Map().Using(connection)); Assert.True(fromDefinition.Equals(byHand), name); } } @@ -123,9 +162,12 @@ public static void ADefinitionsPool_ReachesTheQueryMadeFromIt() ArrayPool pool = ArrayPool.Create(); MappedQuery plain = definition.Map().Using(connection); - MappedQuery pooled = definition.Map().UsePool(pool, clearOnReturn: true).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. + // The configuration is part of what a query is, and a pool of its own + // is another one. Assert.NotEqual(plain, pooled); } } From 024ee0ddc8359d8df75cfc28ba4cd6393d54e267 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:04:22 -0800 Subject: [PATCH 5/6] MappedQuery dedupe: QueryOptions is public, with WithOptions(QueryOptions) to set it `QueryOptions` (`None`, `AsyncReads` 1, `SingleResult` 2, `CancelOnEarlyStop` 4, `SequentialAccess` 8) is a public flags enum in the `Open.Database.Extensions` namespace: how a mapped query executes its command and reads its rows. The summary of each value is inherited from the method of the same name, and the remarks say it applies to the terminals that read rows from a command (a `Map` over a reader or a table you already have has no command to execute, so it has no switches). `WithOptions(QueryOptions options)` on `MappedQuery`, `MappedQueryWithSkip`, `MappedQueryWithTake`, `MappedCommand` and `MappedDbQuery` returns a query whose switches are exactly `options`. It replaces, it does not combine: any switch not in the value is turned off, including one set earlier in the chain or on the command before `Map` (`SingleResult()`, `AsyncReads()`), so `WithOptions(QueryOptions.None)` clears all four and is the only way to turn a switch off; to add one switch, the named method is the call. Skip and take are kept. A value with a bit that is none of the switches throws `ArgumentOutOfRangeException` (parameter `options`, the value as the actual value) whose message names the valid values, before a default value is looked at. The text that says so is one shared member of `Mapped.docs.xml`, and each named switch method (and the enum) points to `WithOptions` with a `seealso`. Inside, the query core's four `With*` are one `WithOptions` (set) and one `WithOption` (add one switch); the four public switch methods call `WithOption` and are unchanged for callers. The core's switches are an auto-property (`Options`), read by mask, never with `HasFlag`. `PublicAPI.Unshipped.txt` lists the enum, its values and the five methods; the release notes have a bullet. Tests: for all 16 combinations, `WithOptions(x)` is the same query (equal, same hash) as the chained calls on a command view, a mapped query, a skipped and a taken query, and a definition (and the definition's query); it replaces earlier switches, and `WithOptions(None)` turns off what a command chose before `Map`, giving the plain query of that command; it keeps skip and take; and a bit that is no switch is refused with the message, on all five types, before a default value is looked at. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Mapped.docs.xml | 29 ++ Source/Core/MappedDbQuery.cs | 18 ++ Source/Core/MappedQuery.cs | 124 +++++---- Source/Core/MappedViews.cs | 37 ++- Source/Core/PublicAPI.Unshipped.txt | 11 + Source/Core/QueryOptions.cs | 47 ++-- .../OptionsSetterTests.cs | 248 ++++++++++++++++++ .../QueryOptionsTests.cs | 26 +- docsite/articles/release-notes.md | 1 + 9 files changed, 447 insertions(+), 94 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index 6b2de4b2..2f6ca9e6 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -21,6 +21,35 @@ 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. diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 592b5363..81552c2e 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -64,6 +64,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// (see ). /// /// A definition that reads only the first result set. + /// public MappedDbQuery SingleResult() => new( @@ -78,6 +79,7 @@ public MappedDbQuery SingleResult() /// (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, @@ -91,6 +93,7 @@ public MappedDbQuery CancelOnEarlyStop() /// (see ). /// /// A definition that reads asynchronously. + /// public MappedDbQuery AsyncReads() => new( Query, @@ -104,6 +107,7 @@ public MappedDbQuery AsyncReads() /// (see for when to use it). /// /// A definition whose queries read with sequential access. + /// public MappedDbQuery SequentialAccess() => new( Query, @@ -112,6 +116,20 @@ public MappedDbQuery 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 /// (see ). diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 20c6c94b..2b6d7cfd 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -160,19 +160,20 @@ readonly struct MappedQueryCore( readonly IRowSource _source = source; readonly int _skip = skip; readonly int _take = take; // -1 == unbounded. + /// Gets the switches of the query. // SingleResult(), AsyncReads(), CancelOnEarlyStop() and SequentialAccess(): // see QueryOptions. - readonly QueryOptions _options = options; + 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 SingleResult => (Options & QueryOptions.SingleResult) != 0; - bool AsyncReads => (_options & QueryOptions.AsyncReads) != 0; + bool AsyncReads => (Options & QueryOptions.AsyncReads) != 0; - bool CancelOnEarlyStop => (_options & QueryOptions.CancelOnEarlyStop) != 0; + bool CancelOnEarlyStop => (Options & QueryOptions.CancelOnEarlyStop) != 0; - bool SequentialAccess => (_options & QueryOptions.SequentialAccess) != 0; + bool SequentialAccess => (Options & QueryOptions.SequentialAccess) != 0; /// /// The command, or for a default value. @@ -244,7 +245,7 @@ public bool Equals(MappedQueryCore other) && Equals(_source, other._source) && _skip == other._skip && _take == other._take - && _options == other._options + && Options == other.Options && ReferenceEquals(Config, other.Config); public override bool Equals(object? obj) @@ -259,7 +260,7 @@ public override int GetHashCode() h = h * 31 + _skip; h = h * 31 + _take; return h * 31 - + (int)_options + + (int)Options + RuntimeHelpers.GetHashCode(Config); // Reference equality, null for a default value. } } @@ -277,45 +278,28 @@ CommandBehavior Behavior ? CommandBehavior.SequentialAccess : CommandBehavior.Default); - public MappedQueryCore WithSingleResult() - => Checked(new( - _command, - _call, - _source, - _skip, - _take, - _options | QueryOptions.SingleResult, - Config)); - - public MappedQueryCore WithAsyncReads() - => Checked(new( - _command, - _call, - _source, - _skip, - _take, - _options | QueryOptions.AsyncReads, - Config)); - - public MappedQueryCore WithCancelOnEarlyStop() + /// + /// 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 | QueryOptions.CancelOnEarlyStop, + options, Config)); - public MappedQueryCore WithSequentialAccess() - => Checked(new( - _command, - _call, - _source, - _skip, - _take, - _options | QueryOptions.SequentialAccess, - 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. @@ -358,12 +342,12 @@ public MappedQueryCore WithConfig(ChunkConfig config) _source, _skip, _take, - _options, + Options, config)); /// Returns the same query over another call. public MappedQueryCore WithCall(DbQueryCall call) - => new(null, call, _source, _skip, _take, _options, Config); + => new(null, call, _source, _skip, _take, Options, Config); public MappedQueryCore WithSkip(int count) => count >= 0 @@ -373,7 +357,7 @@ public MappedQueryCore WithSkip(int count) _source, _skip + count, _take, - _options, + Options, Config)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); @@ -393,7 +377,7 @@ public MappedQueryCore WithTake(int count) _source, _skip, count, - _options, + Options, Config)) : throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be negative."); @@ -1278,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. @@ -1330,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. /// @@ -1340,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. /// @@ -1351,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 @@ -1892,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) @@ -2031,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 7afc0e74..4008afdd 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -259,6 +259,31 @@ 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 @@ -920,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..c0b0986b 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -15,3 +15,14 @@ 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! diff --git a/Source/Core/QueryOptions.cs b/Source/Core/QueryOptions.cs index 1ce47e8c..ab5bbe36 100644 --- a/Source/Core/QueryOptions.cs +++ b/Source/Core/QueryOptions.cs @@ -1,44 +1,45 @@ -namespace Open.Database.Extensions.Core; +namespace Open.Database.Extensions; /// -/// The four switches a mapped query carries, as one value, so that a copy -/// with one of them changed is one |. +/// How a mapped query executes its command and reads its rows: the switches of +/// SingleResult(), AsyncReads(), CancelOnEarlyStop() and +/// SequentialAccess() as one value for +/// . /// /// -/// The pool and its clear rule are not here: they belong to the configuration -/// of the query (), and a definition holds them -/// beside these. -/// A switch is read with (options & QueryOptions.X) != 0, never with -/// , which boxes on the older targets. +/// 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] -internal enum QueryOptions : byte +public enum QueryOptions : byte { /// No switch is set. None = 0, - /// - /// AsyncReads() was called: the rows of an async terminal are read - /// with ReadAsync (the default is Read). - /// + /// AsyncReads = 1, - /// - /// SingleResult() was called: stop after the first result set and do - /// not read through the rest. - /// + /// SingleResult = 2, - /// - /// CancelOnEarlyStop() was called: see . - /// + /// CancelOnEarlyStop = 4, - /// - /// SequentialAccess() was called on the query. - /// + /// 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..82229188 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs @@ -0,0 +1,248 @@ +using static Open.Database.Extensions.QueryOptions; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// 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; + } + + [Theory, MemberData(nameof(Masks))] + public static void ACommandView_Options_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_Options_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_Options_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_Options_IsTheChainedCalls_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); + } + + // ---- it sets: it does not add ----------------------------------------- + + [Fact] + public static void Options_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 Options_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 Options_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), + ]; + + 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 index c9625c8e..52d05b63 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/QueryOptionsTests.cs @@ -77,21 +77,21 @@ public static void ASwitchSetTwice_IsTheSameAsOnce() [Fact] public static void TheOptions_AreOneBitEach_AndCombineWithOr() { - Assert.Equal(0, (int)Core.QueryOptions.None); - Assert.Equal(1, (int)Core.QueryOptions.AsyncReads); - Assert.Equal(2, (int)Core.QueryOptions.SingleResult); - Assert.Equal(4, (int)Core.QueryOptions.CancelOnEarlyStop); - Assert.Equal(8, (int)Core.QueryOptions.SequentialAccess); - - const Core.QueryOptions all - = Core.QueryOptions.AsyncReads - | Core.QueryOptions.SingleResult - | Core.QueryOptions.CancelOnEarlyStop - | Core.QueryOptions.SequentialAccess; + 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( - Core.QueryOptions.SingleResult, - all & Core.QueryOptions.SingleResult); + QueryOptions.SingleResult, + all & QueryOptions.SingleResult); } // A definition holds the switches before there is a source, and every query diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 32caac8f..ee6f9827 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` 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 From 730c77c7d7ca5f047e8c3222081255c8072ccd11 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:21:21 -0800 Subject: [PATCH 6/6] MappedDbQuery gets WithOptions too Every type that has the four named switches has `WithOptions(QueryOptions options)`: the typed definition `MappedDbQuery` had them and not the setter. It forwards to the untyped definition, which checks the value (`ArgumentOutOfRangeException` for a bit that is no switch), and its docs are the untyped one's (inherited), so the four named methods' `seealso` reach it too. `PublicAPI.Unshipped.txt` and the release note list it. Tests: for all 16 combinations the typed definition's `WithOptions(x)` gives the same query (equal, same hash) as the chained calls, and as the chained calls on the query made from it with `AddParams`; the typed definition refuses a bit that is no switch like the others. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/MappedDbQuery.cs | 5 ++ Source/Core/PublicAPI.Unshipped.txt | 1 + .../OptionsSetterTests.cs | 60 ++++++++++++++++--- docsite/articles/release-notes.md | 2 +- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 81552c2e..b55d4eda 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -267,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/PublicAPI.Unshipped.txt b/Source/Core/PublicAPI.Unshipped.txt index c0b0986b..58b80039 100644 --- a/Source/Core/PublicAPI.Unshipped.txt +++ b/Source/Core/PublicAPI.Unshipped.txt @@ -26,3 +26,4 @@ Open.Database.Extensions.MappedQueryWithSkip.WithOptions(Open.Database.Extens 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/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs index 82229188..50ddf584 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OptionsSetterTests.cs @@ -4,6 +4,9 @@ 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 @@ -52,8 +55,19 @@ static MappedDbQuery ByCalls(MappedDbQuery d, QueryOptions o) 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_Options_IsTheChainedCalls(int mask) + public static void ACommandView_WithOptions_IsTheChainedCalls(int mask) { var options = (QueryOptions)mask; MappedCommand plain = View(); @@ -66,7 +80,7 @@ public static void ACommandView_Options_IsTheChainedCalls(int mask) } [Theory, MemberData(nameof(Masks))] - public static void AMappedQuery_Options_IsTheChainedCalls(int mask) + public static void AMappedQuery_WithOptions_IsTheChainedCalls(int mask) { var options = (QueryOptions)mask; DbQuery definition = DbQuery.Text("select 1"); @@ -81,7 +95,8 @@ public static void AMappedQuery_Options_IsTheChainedCalls(int mask) } [Theory, MemberData(nameof(Masks))] - public static void ASkippedOrTakenQuery_Options_IsTheChainedCalls(int mask) + public static void ASkippedOrTakenQuery_WithOptions_IsTheChainedCalls( + int mask) { var options = (QueryOptions)mask; DbQuery definition = DbQuery.Text("select 1"); @@ -124,7 +139,7 @@ static MappedQueryWithTake ByCalls( } [Theory, MemberData(nameof(Masks))] - public static void ADefinition_Options_IsTheChainedCalls_AndReachesTheQuery( + public static void ADefinition_WithOptions_IsChained_AndReachesTheQuery( int mask) { var options = (QueryOptions)mask; @@ -141,10 +156,37 @@ public static void ADefinition_Options_IsTheChainedCalls_AndReachesTheQuery( 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 Options_ReplacesTheSwitchesSetBefore() + public static void WithOptions_ReplacesTheSwitchesSetBefore() { MappedCommand plain = View(); MappedCommand view = plain.SingleResult().AsyncReads(); @@ -158,7 +200,7 @@ public static void Options_ReplacesTheSwitchesSetBefore() // What a command chose before Map is replaced too. [Fact] - public static void Options_ReplacesWhatTheCommandChoseBeforeMap() + public static void WithOptions_ReplacesWhatTheCommandChoseBeforeMap() { ExpressiveDbCommand command = new( new FakeDbConnection(), @@ -174,7 +216,7 @@ public static void Options_ReplacesWhatTheCommandChoseBeforeMap() } [Fact] - public static void Options_KeepsSkipAndTake() + public static void WithOptions_KeepsSkipAndTake() { DbQuery definition = DbQuery.Text("select 1"); using FakeDbConnection connection = new(); @@ -217,6 +259,10 @@ public static void ABitThatIsNoSwitch_IsRefused_WithTheValidValues( () => query.Skip(1).WithOptions(options), () => query.Take(1).WithOptions(options), () => definition.Map().WithOptions(options), + () => definition + .Params() + .Map() + .WithOptions(options), ]; foreach (Action call in calls) diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index ee6f9827..cd571a80 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -12,7 +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` 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. +- **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