From 1a1c642709947b53e174a34fa74e5cd588319432 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:30:25 -0800 Subject: [PATCH] Share code that two places wrote twice, in the Core internals and the two pumps No public API changes. Every change is internal, or a message or a name that no caller reads. - The Channel and Dataflow pumps share two helpers in Core: the one that disposes an enumerator that will not be read, and the ones that link a caller's token to a stream's stall expiry and recognize an expiry that the caller did not cancel. Each pump keeps its own try/catch and its per-row loops. - DirectStream and StallStream take the stall timeout exception and the "enumerated only once" exception from one place, with the same texts. - A chunk of a stream is released with a using: the lease is IDisposable (Dispose releases it, as Release does). - ChunkChain.Dispose asks Used for the rows of a chunk, as the copy out does. ChunkSizes checks its power-of-two bounds with one helper. PooledBuffer.From builds its config in one place. - The "matches none of the parameters" exception has one text for a command and for a query (the words before the declared names stay as they were). - ExpressiveCommandBase asks for the declared text names in one place, and builds the refusal of ExecuteAsync with captures in one place. - ExpressiveDbCommand passes a connection function straight to its base, as its siblings do. A null function now names the parameter connFactory in the ArgumentNullException (it named the adapter's parameter, factory). - The procedure schema code: the table that GetSchema returns is disposed, the "rows from more than one schema" scan and the collection name are shared by the names and the metadata, the two one-line wrappers around the row reader are gone, one helper reads an integer that may not be one, and the exception filter that mixes `is` and `&&` is parenthesized. - MappedDbQuery builds its changed copies in one method; the two view executors share the canceled-token answer; the command view makes one query core instead of two. - The 776 of the SQL Server procedure lookup is a named constant with the arithmetic. Cost: nothing per row or per call. The new shared calls sit on the setup of a pass (the link), on a throw path (the exceptions) or on a dispose. The stream iterator that releases a chunk with a using may carry one more struct in its state machine (once per stream, not per chunk). Co-Authored-By: Claude Sonnet 5.5 --- Source/Channel/ChannelPump.cs | 21 +---- Source/Core/ArrayLease.cs | 8 ++ Source/Core/AsyncEnumerators.cs | 17 ++++ Source/Core/ChunkChain.cs | 4 +- Source/Core/ChunkSizing.cs | 22 ++--- Source/Core/ChunkStream.cs | 4 +- Source/Core/DbQueryBinding.cs | 15 ++- Source/Core/DirectStream.cs | 8 +- Source/Core/ExpressiveCommandBase.cs | 35 ++++--- Source/Core/ExpressiveDbCommand.cs | 2 +- Source/Core/MappedDbQuery.cs | 24 ++--- Source/Core/MappedViews.cs | 30 +++--- Source/Core/PooledBuffer.cs | 26 ++++-- Source/Core/ProcedureParameterMetadata.cs | 102 ++++++--------------- Source/Core/ProcedureSchemaNames.cs | 35 ++++--- Source/Core/StallStream.cs | 43 +++++++-- Source/Dataflow/BlockPump.cs | 19 +--- Source/MSSqlClient/ExpressiveSqlCommand.cs | 6 +- 18 files changed, 204 insertions(+), 217 deletions(-) create mode 100644 Source/Core/AsyncEnumerators.cs diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index ccd78bf7..fee0b8a8 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -88,7 +88,7 @@ IAsyncEnumerator rows return wait.Result ? new(rows) - : CloseAsync(rows); + : AsyncEnumerators.CloseAsync(rows); } static async ValueTask?> OpenAsync( @@ -118,18 +118,10 @@ await rows.DisposeAsync() return room ? rows - : await CloseAsync(rows) + : await AsyncEnumerators.CloseAsync(rows) .ConfigureAwait(false); } - static async ValueTask?> CloseAsync( - IAsyncEnumerator rows) - { - await rows.DisposeAsync() - .ConfigureAwait(false); - return null; - } - /// /// Writes rows from a position of a chunk until the writer has no room. /// @@ -237,11 +229,7 @@ public async ValueTask WriteAsync( // so it waits on the caller's token and creates nothing. var signal = rows as IStallSignal; using CancellationTokenSource? link - = signal?.Expired.CanBeCanceled is true - ? CancellationTokenSource.CreateLinkedTokenSource( - cancellationToken, - signal.Expired) - : null; + = StallSignal.Link(signal, cancellationToken); CancellationToken wait = link?.Token ?? cancellationToken; IAsyncEnumerator? pulled @@ -295,8 +283,7 @@ static async ValueTask WaitAsync( // The stream expired while the target had no room, and // the caller did not cancel: Core's own exception, Core's text. catch (OperationCanceledException) - when (signal.Expired.IsCancellationRequested - && !cancellationToken.IsCancellationRequested) + when (StallSignal.ExpiredWithoutCancel(signal, cancellationToken)) { throw signal.ToException(); } diff --git a/Source/Core/ArrayLease.cs b/Source/Core/ArrayLease.cs index 0cd6f138..a3fd2266 100644 --- a/Source/Core/ArrayLease.cs +++ b/Source/Core/ArrayLease.cs @@ -52,6 +52,7 @@ internal readonly struct ArrayLease( int used, ChunkConfig config, ClearMode mode) + : IDisposable { /// The pooled array. public T[] Array { get; } = array; @@ -104,6 +105,13 @@ public void Release() break; } } + + /// + /// Releases the lease, as does, so that a + /// using gives the array back. + /// + public void Dispose() + => Release(); } /// The one runner of each row type. diff --git a/Source/Core/AsyncEnumerators.cs b/Source/Core/AsyncEnumerators.cs new file mode 100644 index 00000000..c19f7d30 --- /dev/null +++ b/Source/Core/AsyncEnumerators.cs @@ -0,0 +1,17 @@ +namespace Open.Database.Extensions.Core; + +/// +/// What the Channel and Dataflow pumps share about the enumerators they take. +/// +internal static class AsyncEnumerators +{ + // Disposes an enumerator that will not be read; the pumps' answer for + // "nothing to read" is null. + public static async ValueTask?> CloseAsync( + IAsyncEnumerator rows) + { + await rows.DisposeAsync() + .ConfigureAwait(false); + return null; + } +} diff --git a/Source/Core/ChunkChain.cs b/Source/Core/ChunkChain.cs index aa9fb4da..8c236dec 100644 --- a/Source/Core/ChunkChain.cs +++ b/Source/Core/ChunkChain.cs @@ -298,14 +298,12 @@ public void Dispose() T[][] chunks = _chunks; ChunkConfig config = _config!; int count = _chunkCount; - int lastUsed = _index; Exception? first = null; for (int i = 0; i < count; ++i) { try { - int used = i == count - 1 ? lastUsed : chunks[i].Length; - config.SealCopyOut(chunks[i], used).Release(); + config.SealCopyOut(chunks[i], Used(i)).Release(); } catch (Exception ex) { diff --git a/Source/Core/ChunkSizing.cs b/Source/Core/ChunkSizing.cs index 7167dec5..7ad7bcc4 100644 --- a/Source/Core/ChunkSizing.cs +++ b/Source/Core/ChunkSizing.cs @@ -65,9 +65,7 @@ public ChunkSizes( int collectShift = DefaultCollectShift, int collectMaxRows = DefaultCollectMaxRows) { - FirstRows = ChunkSizing.IsPowerOfTwo(firstRows) && firstRows <= 1 << 20 - ? firstRows - : DefaultFirstRows; + FirstRows = Fit(firstRows, 1 << 20, DefaultFirstRows); StreamMaxRows = ChunkSizing.IsPowerOfTwo(streamMaxRows) && streamMaxRows >= FirstRows @@ -75,23 +73,25 @@ public ChunkSizes( ? streamMaxRows : Math.Max(DefaultStreamMaxRows, FirstRows); - CollectFirstRows = ChunkSizing.IsPowerOfTwo(collectFirstRows) - && collectFirstRows <= 1 << 20 - ? collectFirstRows - : DefaultCollectFirstRows; + CollectFirstRows = Fit( + collectFirstRows, 1 << 20, DefaultCollectFirstRows); CollectShift = (uint)(collectShift - 1) <= 3u ? collectShift : DefaultCollectShift; - CollectMaxRows = ChunkSizing.IsPowerOfTwo(collectMaxRows) - && collectMaxRows <= 1 << 26 - ? collectMaxRows - : DefaultCollectMaxRows; + CollectMaxRows = Fit(collectMaxRows, 1 << 26, DefaultCollectMaxRows); LastStreamDoubling = ChunkSizing.Log2(StreamMaxRows / FirstRows); } + // The value when it is a power of two no larger than the maximum; + // otherwise the default. + static int Fit(int value, int max, int fallback) + => ChunkSizing.IsPowerOfTwo(value) && value <= max + ? value + : fallback; + /// Gets the number of rows in the first chunk of a buffer or a stream. public int FirstRows { get; } diff --git a/Source/Core/ChunkStream.cs b/Source/Core/ChunkStream.cs index 6492a930..6dcbd085 100644 --- a/Source/Core/ChunkStream.cs +++ b/Source/Core/ChunkStream.cs @@ -164,8 +164,8 @@ async IAsyncEnumerator> Read( && reader.TryRead(out ArrayLease chunk)) { // The array goes back at the next step. - try { yield return chunk.Memory; } - finally { chunk.Release(); } + using (chunk) + yield return chunk.Memory; } cancellationToken.ThrowIfCancellationRequested(); diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index 6ecf1c79..bcf5afb5 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -59,7 +59,9 @@ public static string ResolveDerived( if (last is null || !ReferenceEquals(last.Names, names)) { string real = names!.Match(derived.Expression, definition.CommandText) - ?? throw NoMatch(derived.Expression, names!, definition); + ?? throw NoMatch( + derived.Expression, definition.CommandText, + "It declares", names!.Names); last = new(names!, real, names!.Find(real)); derived.Last = last; } @@ -312,9 +314,12 @@ static InvalidOperationException Collision( : "The parameter names are not known, so each argument is used under its last member as written.") + " Name one of them explicitly: AddParam(\"name\", value)."); - static InvalidOperationException NoMatch( + // The one text of "matches none", for a command and for a query: the owner + // is the command text or procedure name, declares the words before the names. + public static InvalidOperationException NoMatch( string expression, - NameSet names, - DbQuery definition) - => new($"The argument '{expression}' matches none of the parameters of '{definition.CommandText}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). It declares: {string.Join(", ", names.Names)}. Name the parameter explicitly: AddParam(\"name\", value)."); + string owner, + string declares, + ImmutableArray declared) + => new($"The argument '{expression}' matches none of the parameters of '{owner}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). {declares}: {string.Join(", ", declared)}. Name the parameter explicitly: AddParam(\"name\", value)."); } diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 154ce8b2..41535cb1 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -95,17 +95,13 @@ public DirectStream( internal bool HasTimer => Volatile.Read(ref _timer) is not null; TimeoutException ToException() - => new($"The consumer made no pull for {_stall} while the reader and the connection were held; the read was stopped."); + => StallStream.TimeoutFor(_stall); public IAsyncEnumerator GetAsyncEnumerator( CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _taken, 1) != 0) - { - throw new InvalidOperationException( - "This stream can be enumerated only once." - + " Call ToListAsync() or ToPooledBuffer() to read the rows more than once."); - } + throw StallStream.EnumeratedTwice(); return Read(cancellationToken); } diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index cd3cc2b3..03fd89e2 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -992,18 +992,18 @@ await ProcedureParameterMetadata.EnsureAsync( return names; } - NameSet? WrittenNames() - { - if (_params is not { Count: > 0 } || Type != CommandType.Text || Command is not { Length: > 0 } text) return null; + // The @names the text declares, when it declares any. + NameSet? TextNames() + => Type == CommandType.Text && Command is { Length: > 0 } text && TextNameCache.Get(text) is { Names.Length: > 0 } names + ? names + : null; - return TextNameCache.Get(text) is { Names.Length: > 0 } names ? names : null; - } + NameSet? WrittenNames() + => _params is { Count: > 0 } ? TextNames() : null; // The count of @names the text declares (one slot each), else the default growth. int ScannedCount() - => Type == CommandType.Text && Command is { Length: > 0 } text && TextNameCache.Get(text) is { Names.Length: > 0 } names - ? names.Names.Length - : 0; + => TextNames()?.Names.Length ?? 0; TCommand PrepareWritten(TConnection connection) => WrittenNames() is { } text @@ -1230,7 +1230,7 @@ InvalidOperationException Collision(string name, Param first, Param second, Immu + " Name one of them explicitly: AddParam(\"name\", value)."); InvalidOperationException NoMatch(string expression, ImmutableArray real) - => new($"The argument '{expression}' matches none of the parameters of '{Command}' (tried {string.Join(", ", ParameterNames.Candidates(expression))}). The procedure declares: {string.Join(", ", real)}. Name the parameter explicitly: AddParam(\"name\", value)."); + => DbQueryBinding.NoMatch(expression, Command, "The procedure declares", real); #endregion @@ -1537,6 +1537,11 @@ internal T Execute(Func transform) return ExecuteCore(transform, static (cmd, _, f) => f(cmd)); } + // The refusal of an ExecuteAsync that has captures: they are completed with it. + static Exception AsyncRefused(CaptureSet captures) + => captures.Refuse(new InvalidOperationException( + CaptureMessages.ExecuteAsync(captures))); + /// public virtual ValueTask ExecuteAsync(Func handler) { @@ -1545,11 +1550,7 @@ public virtual ValueTask ExecuteAsync(Func handler) // Your code runs the command, so nothing can fill a capture: refused, // and the capture completed with the refusal. - if (_captures is { } captures) - { - throw captures.Refuse(new InvalidOperationException( - CaptureMessages.ExecuteAsync(captures))); - } + if (_captures is { } captures) throw AsyncRefused(captures); CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task. @@ -1568,11 +1569,7 @@ public virtual ValueTask ExecuteAsync(Func> transfo Contract.EndContractBlock(); // As above. - if (_captures is { } captures) - { - throw captures.Refuse(new InvalidOperationException( - CaptureMessages.ExecuteAsync(captures))); - } + if (_captures is { } captures) throw AsyncRefused(captures); CancellationToken.ThrowIfCancellationRequested(); // Thrown synchronously, not through the returned task. diff --git a/Source/Core/ExpressiveDbCommand.cs b/Source/Core/ExpressiveDbCommand.cs index 07ff69c9..bd9ce4f5 100644 --- a/Source/Core/ExpressiveDbCommand.cs +++ b/Source/Core/ExpressiveDbCommand.cs @@ -63,7 +63,7 @@ public ExpressiveDbCommand( CommandType type, string command, IEnumerable? @params = null) - : base(connFactory.AsPool(), type, command, @params) + : base(connFactory, type, command, @params) { } diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index ecd0a21f..957e8f36 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -67,9 +67,7 @@ internal MappedDbQuery(DbQuery definition, IRowSource source) /// public MappedDbQuery SingleResult() - => new( - Query, _source, _options | QueryOptions.SingleResult, - _pool, _clearOnReturn); + => With(_options | QueryOptions.SingleResult); /// /// Cancels the command when a terminal stops before the last row, in every query made from this definition @@ -78,9 +76,7 @@ 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); + => With(_options | QueryOptions.CancelOnEarlyStop); /// /// Reads the rows with the asynchronous read of the provider, in every query made from this definition @@ -89,9 +85,7 @@ public MappedDbQuery CancelOnEarlyStop() /// A definition that reads asynchronously. /// public MappedDbQuery AsyncReads() - => new( - Query, _source, _options | QueryOptions.AsyncReads, - _pool, _clearOnReturn); + => With(_options | QueryOptions.AsyncReads); /// /// Asks the reader for sequential access, in every query made from this definition @@ -100,9 +94,7 @@ public MappedDbQuery AsyncReads() /// A definition whose queries read with sequential access. /// public MappedDbQuery SequentialAccess() - => new( - Query, _source, _options | QueryOptions.SequentialAccess, - _pool, _clearOnReturn); + => With(_options | QueryOptions.SequentialAccess); /// /// Returns a definition whose switches, in every query made from it, are @@ -111,9 +103,11 @@ public MappedDbQuery SequentialAccess() /// /// A definition with exactly these switches. public MappedDbQuery WithOptions(QueryOptions options) - => new( - Query, _source, Views.CheckedOptions(options), - _pool, _clearOnReturn); + => With(Views.CheckedOptions(options)); + + // The same definition with other switches. + MappedDbQuery With(QueryOptions options) + => new(Query, _source, options, _pool, _clearOnReturn); /// /// Takes the arrays that hold the rows from , in every query made from this definition diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index e3dcdf48..e0dcde6e 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -371,13 +371,12 @@ internal static MappedQueryCore ReaderCore( 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); + { + var single = command as SingleResultDbCommand; + return NewCore( + new CommandExecutor(single?.Command ?? command), default, source, + single is null ? QueryOptions.None : QueryOptions.SingleResult); + } internal static MappedQueryCore TableCore( DataTable table, @@ -460,6 +459,11 @@ public abstract ValueTask ExecuteReaderAsync( CommandBehavior behavior, CancellationToken cancellationToken); + // A canceled token gives a canceled task, not an exception at the call. + protected static ValueTask Canceled( + CancellationToken cancellationToken) + => new(Task.FromCanceled(cancellationToken)); + public void ExecuteReader( Action handler, CommandBehavior behavior = CommandBehavior.Default) @@ -539,12 +543,8 @@ public override ValueTask ExecuteReaderAsync( CommandBehavior behavior, CancellationToken cancellationToken) { - // A cancelled token gives a cancelled task, not an exception at the call. if (cancellationToken.IsCancellationRequested) - { - return new ValueTask( - Task.FromCanceled(cancellationToken)); - } + return Canceled(cancellationToken); return transform(reader, state); } @@ -642,12 +642,8 @@ public override ValueTask ExecuteReaderAsync( CommandBehavior behavior, CancellationToken cancellationToken) { - // A cancelled token gives a cancelled task, not an exception at the call. if (cancellationToken.IsCancellationRequested) - { - return new ValueTask( - Task.FromCanceled(cancellationToken)); - } + return Canceled(cancellationToken); return ReadAsync(state, transform); } diff --git a/Source/Core/PooledBuffer.cs b/Source/Core/PooledBuffer.cs index 42a04522..aaa8404e 100644 --- a/Source/Core/PooledBuffer.cs +++ b/Source/Core/PooledBuffer.cs @@ -208,16 +208,9 @@ internal static PooledBuffer CreateEmptyOwner() /// The finished buffer. /// There are more than 2^30 rows. public static PooledBuffer From(ReadOnlySpan rows) - { - if (rows.Length > MaxFromRows) throw TooManyRows(rows.Length); - Contract.EndContractBlock(); - // A test can use this to fake the code that returns a buffer. An array of 128 KB or more of rows that must be cleared goes back through the recycle bin, so it reaches the pool shortly after. // This entry picks the pool and the clearing: the shared pool, and the app-wide default. - return Create( - rows, - new(ArrayPool.Shared, null, ChunkSizes.Default, RecycleBin.Default, ChunkConfig.DefaultDeferFromClearedBytes)); - } + => FromPool(rows, ArrayPool.Shared, null); /// Makes a finished buffer from rows you already have, with an array from a pool you choose. /// @@ -235,12 +228,25 @@ public static PooledBuffer From(ReadOnlySpan rows) public static PooledBuffer From(ReadOnlySpan rows, ArrayPool pool, bool clearOnReturn) { if (pool is null) throw new ArgumentNullException(nameof(pool)); - if (rows.Length > MaxFromRows) throw TooManyRows(rows.Length); Contract.EndContractBlock(); + return FromPool(rows, pool, clearOnReturn); + } + + // A null clearOnReturn leaves the clearing to the app-wide default (see PoolClearing). + static PooledBuffer FromPool( + ReadOnlySpan rows, + ArrayPool pool, + bool? clearOnReturn) + { + if (rows.Length > MaxFromRows) throw TooManyRows(rows.Length); + return Create( rows, - new(pool, clearOnReturn, ChunkSizes.Default, RecycleBin.Default, ChunkConfig.DefaultDeferFromClearedBytes)); + new( + pool, clearOnReturn, + ChunkSizes.Default, RecycleBin.Default, + ChunkConfig.DefaultDeferFromClearedBytes)); } /// The most rows From takes: its one array is a first chunk, which a buffer holds as a power of two. diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index 295ff417..90db1bdc 100644 --- a/Source/Core/ProcedureParameterMetadata.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -57,8 +57,6 @@ public int Scale(int index) /// static class ProcedureParameterMetadata { - const string Collection = "ProcedureParameters"; - /// /// Reads the metadata of a procedure's parameters into its set, unless the set /// already holds them. @@ -93,22 +91,27 @@ public static async ValueTask EnsureAsync( { #if NET10_0_OR_GREATER using DataTable table = await db.GetSchemaAsync( - Collection, restrictions, cancellationToken) + ProcedureSchemaNames.Collection, restrictions, cancellationToken) .ConfigureAwait(false); #else // DbConnection.GetSchemaAsync does not exist on the netstandard // targets. cancellationToken.ThrowIfCancellationRequested(); - using DataTable table = db.GetSchema(Collection, restrictions); + using DataTable table = db.GetSchema( + ProcedureSchemaNames.Collection, restrictions); #endif - metadata = restrictions[1] is not null - ? ReadForSchema(table, names) - : ReadForAnySchema(table, names); + // A table that tells nothing usable, or that spans schemas for a + // name given without one (ambiguous), leaves nothing known. + bool schemaGiven = restrictions[1] is not null; + metadata = table is null + || (!schemaGiven && ProcedureSchemaNames.SpansSchemas(table)) + ? ParameterMetadata.Unknown + : ReadRows(table, names); } catch (Exception ex) when ( - ex is NotSupportedException + (ex is NotSupportedException or NotImplementedException - or ArgumentException + or ArgumentException) && !cancellationToken.IsCancellationRequested) { // Not while the call is canceled: a cancellation surfaced as one of @@ -132,52 +135,6 @@ or ArgumentException names.KeepMetadata(metadata); } - /// - /// Works out the metadata of the set's parameters from the schema table of a - /// procedure whose name included its schema. - /// - /// The schema table. - /// The procedure's set. - /// The metadata; when the table tells nothing usable. - static ParameterMetadata ReadForSchema(DataTable? table, NameSet names) - => table is null - ? ParameterMetadata.Unknown - : ReadRows(table, names); - - /// - /// Works out the metadata of the set's parameters from the schema table of a - /// procedure whose name had no schema: rows from more than one schema are - /// ambiguous, and nothing is known. - /// - /// The schema table. - /// The procedure's set. - /// The metadata; when the table tells nothing usable or spans schemas. - static ParameterMetadata ReadForAnySchema(DataTable? table, NameSet names) - => table is null || SpansSchemas(table) - ? ParameterMetadata.Unknown - : ReadRows(table, names); - - static bool SpansSchemas(DataTable table) - { - if (!table.Columns.Contains("SPECIFIC_SCHEMA")) return false; - - string? schema = null; - foreach (DataRow row in table.Rows) - { - string current = row["SPECIFIC_SCHEMA"] as string ?? ""; - schema ??= current; - if (!string.Equals( - schema, - current, - StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; - } - /// /// Reads the rows of a schema table into the metadata of the set's parameters. /// @@ -235,37 +192,32 @@ static ParameterMetadata ReadRows(DataTable table, NameSet names) } static bool IsReturnRow(object ordinal) - { - if (ordinal is DBNull) return false; - - try - { - return Convert.ToInt32(ordinal, CultureInfo.InvariantCulture) == 0; - } - catch (Exception ex) when ( - ex is FormatException - or InvalidCastException - or OverflowException) - { - return false; - } - } + => ordinal is not DBNull + && TryInt(ordinal, out int position) + && position == 0; static int ScaleOf(object value) + => value is not DBNull + && TryInt(value, out int scale) + && scale >= 0 + ? scale + : ParameterMetadata.NoScale; + + // A value the database reports that is not a number is "not known". + static bool TryInt(object value, out int result) { - if (value is DBNull) return ParameterMetadata.NoScale; - try { - int scale = Convert.ToInt32(value, CultureInfo.InvariantCulture); - return scale < 0 ? ParameterMetadata.NoScale : scale; + result = Convert.ToInt32(value, CultureInfo.InvariantCulture); + return true; } catch (Exception ex) when ( ex is FormatException or InvalidCastException or OverflowException) { - return ParameterMetadata.NoScale; + result = 0; + return false; } } } diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index 6be61660..b88cce47 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -15,7 +15,7 @@ static class ProcedureSchemaNames /// /// The name of the ADO.NET schema collection. /// - const string Collection = "ProcedureParameters"; + public const string Collection = "ProcedureParameters"; /// /// Gets the names of the parameters a stored procedure declares. @@ -34,7 +34,8 @@ internal static ImmutableArray Get(DbConnection connection, string proce try { - return Names(connection.GetSchema(Collection, restrictions), schemaGiven: restrictions[1] is not null); + using DataTable table = connection.GetSchema(Collection, restrictions); + return Names(table, schemaGiven: restrictions[1] is not null); } catch (Exception ex) when (ex is NotSupportedException or NotImplementedException or ArgumentException) { @@ -77,7 +78,7 @@ internal static async ValueTask> GetAsync(DbConnection co try { - DataTable table = await connection.GetSchemaAsync(Collection, restrictions, cancellationToken).ConfigureAwait(false); + using DataTable table = await connection.GetSchemaAsync(Collection, restrictions, cancellationToken).ConfigureAwait(false); return Names(table, schemaGiven: restrictions[1] is not null); } catch (Exception ex) when (ex is NotSupportedException or NotImplementedException or ArgumentException) @@ -175,18 +176,11 @@ static ImmutableArray Names(DataTable? table, bool schemaGiven) DataColumnCollection columns = table.Columns; if (!columns.Contains("PARAMETER_NAME") || !columns.Contains("ORDINAL_POSITION")) return default; - bool checkSchema = !schemaGiven && columns.Contains("SPECIFIC_SCHEMA"); - string? schema = null; + if (!schemaGiven && SpansSchemas(table)) return default; + List> found = []; foreach (DataRow row in table.Rows) { - if (checkSchema) - { - string current = row["SPECIFIC_SCHEMA"] as string ?? ""; - schema ??= current; - if (!string.Equals(schema, current, StringComparison.OrdinalIgnoreCase)) return default; - } - if (row["PARAMETER_NAME"] is not string { Length: > 0 } name || row["ORDINAL_POSITION"] is DBNull) continue; int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"], CultureInfo.InvariantCulture); @@ -200,4 +194,21 @@ static ImmutableArray Names(DataTable? table, bool schemaGiven) foreach (KeyValuePair pair in found) names.Add(pair.Value); return names.MoveToImmutable(); } + + // Rows from more than one schema make a name given without a schema + // ambiguous. + public static bool SpansSchemas(DataTable table) + { + if (!table.Columns.Contains("SPECIFIC_SCHEMA")) return false; + + string? schema = null; + foreach (DataRow row in table.Rows) + { + string current = row["SPECIFIC_SCHEMA"] as string ?? ""; + schema ??= current; + if (!string.Equals(schema, current, StringComparison.OrdinalIgnoreCase)) return true; + } + + return false; + } } diff --git a/Source/Core/StallStream.cs b/Source/Core/StallStream.cs index d1ac3502..9d783903 100644 --- a/Source/Core/StallStream.cs +++ b/Source/Core/StallStream.cs @@ -23,10 +23,43 @@ internal interface IStallSignal } /// -/// The sizes of the stream buffer, kept out of the generic so they are one value for every row type. +/// What a write loop does with the of the stream it reads. +/// +internal static class StallSignal +{ + // A token that ends a wait when the caller cancels or the stream expires; + // null when no expiry can fire (the plain wait needs nothing created). + public static CancellationTokenSource? Link( + IStallSignal? signal, + CancellationToken cancellationToken) + => signal?.Expired.CanBeCanceled is true + ? CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + signal.Expired) + : null; + + // A canceled wait that was the expiry, not the caller: the stream's own + // exception is the one to throw. + public static bool ExpiredWithoutCancel( + IStallSignal signal, + CancellationToken cancellationToken) + => signal.Expired.IsCancellationRequested + && !cancellationToken.IsCancellationRequested; +} + +/// +/// The sizes of the stream buffer and the exceptions of a stream with a stall timeout (this one and ), kept out of the generic so they are one value for every row type. /// internal static class StallStream { + public static TimeoutException TimeoutFor(TimeSpan stall) + => new($"The consumer made no pull for {stall} while the reader and the connection were held; the read was stopped."); + + public static InvalidOperationException EnumeratedTwice() + => new( + "This stream can be enumerated only once." + + " Call ToListAsync() or ToPooledBuffer() to read the rows more than once."); + /// /// Gets the buffer size, in rows, unless the caller asks for another one. /// @@ -97,17 +130,13 @@ public CancellationToken Expired => _expiredSource?.Token ?? default; public TimeoutException ToException() - => new($"The consumer made no pull for {_stall} while the reader and the connection were held; the read was stopped."); + => StallStream.TimeoutFor(_stall); public IAsyncEnumerator GetAsyncEnumerator( CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _taken, 1) != 0) - { - throw new InvalidOperationException( - "This stream can be enumerated only once." - + " Call ToListAsync() or ToPooledBuffer() to read the rows more than once."); - } + throw StallStream.EnumeratedTwice(); return Read(cancellationToken); } diff --git a/Source/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index a17a0e4b..ce85c28c 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -81,17 +81,9 @@ internal static async ValueTask Run( IAsyncEnumerator rows = stream.GetAsyncEnumerator(cancellationToken); return target.Completion.IsCompleted - ? CloseAsync(rows) + ? AsyncEnumerators.CloseAsync(rows) : new(rows); } - - static async ValueTask?> CloseAsync( - IAsyncEnumerator rows) - { - await rows.DisposeAsync() - .ConfigureAwait(false); - return null; - } } /// @@ -179,11 +171,7 @@ public async ValueTask WriteAsync( // so it waits on the caller's token and creates nothing. var signal = rows as IStallSignal; using CancellationTokenSource? link - = signal?.Expired.CanBeCanceled is true - ? CancellationTokenSource.CreateLinkedTokenSource( - cancellationToken, - signal.Expired) - : null; + = StallSignal.Link(signal, cancellationToken); CancellationToken wait = link?.Token ?? cancellationToken; IAsyncEnumerator? pulled @@ -233,8 +221,7 @@ static async ValueTask SendAsync( // The stream expired while the target had no room, and // the caller did not cancel: Core's own exception, Core's text. catch (OperationCanceledException) - when (signal.Expired.IsCancellationRequested - && !cancellationToken.IsCancellationRequested) + when (StallSignal.ExpiredWithoutCancel(signal, cancellationToken)) { throw signal.ToException(); } diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index d358747c..05a411f4 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -179,6 +179,10 @@ protected override async ValueTask> GetProcedureParameter } } + // Three bracket-quoted parts of 258 characters (128 doubled, plus the + // brackets) and two dots: the longest procedure name the lookup takes. + const int ProcedureNameLength = 776; + /// /// Creates the command that looks up a procedure's parameter names, in the command's own transaction when it has one. /// @@ -190,7 +194,7 @@ SqlCommand ProcedureNamesCommand(SqlConnection connection, string procedure) SqlCommand command = connection.CreateCommand(); command.CommandText = "select name from sys.all_parameters where object_id = object_id(@procedure) and parsename(@procedure, 3) is null and parameter_id > 0 order by parameter_id"; command.CommandTimeout = Timeout; // the command's own timeout (SetTimeout), not the provider's default - command.Parameters.Add("@procedure", SqlDbType.NVarChar, 776).Value = procedure; + command.Parameters.Add("@procedure", SqlDbType.NVarChar, ProcedureNameLength).Value = procedure; if (Transaction is SqlTransaction transaction) command.Transaction = transaction; return command; }