From daf41ae9d203ae5dc1fab408c7e791d89d620d9d Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:32:17 -0800 Subject: [PATCH 1/6] Review fixes: keep ExpressiveDbCommand's formatting, wrap long lines, cut repeated comments Follow-up to the shared-code change, after the merge of master: - Views.CommandCore is back to its two-branch form: the command inside a SingleResultDbCommand is never null (the one place that makes it checks the argument), so a fallback for null was dead code. - ExpressiveDbCommand's `: base(` line keeps its original indentation; only the argument changed. - Lines that this change added are wrapped at about 80 columns (the text-name helper, the procedure lookup command, the schema table reads, the NoMatch call). - Comments that repeated what the next line says are removed (the bounds helper of ChunkSizes, the integer reader and the schema check of the procedure metadata, the chunk release in the stream). No behavior change, no public API change, no cost per call or per row. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ChunkSizing.cs | 2 -- Source/Core/ChunkStream.cs | 1 - Source/Core/ExpressiveCommandBase.cs | 7 +++++-- Source/Core/ExpressiveDbCommand.cs | 2 +- Source/Core/MappedViews.cs | 13 +++++++------ Source/Core/ProcedureParameterMetadata.cs | 6 ++---- Source/Core/ProcedureSchemaNames.cs | 15 ++++++++++++--- Source/MSSqlClient/ExpressiveSqlCommand.cs | 4 +++- 8 files changed, 30 insertions(+), 20 deletions(-) diff --git a/Source/Core/ChunkSizing.cs b/Source/Core/ChunkSizing.cs index 7ad7bcc4..4ca3019f 100644 --- a/Source/Core/ChunkSizing.cs +++ b/Source/Core/ChunkSizing.cs @@ -85,8 +85,6 @@ public ChunkSizes( 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 diff --git a/Source/Core/ChunkStream.cs b/Source/Core/ChunkStream.cs index 6dcbd085..a4b83da4 100644 --- a/Source/Core/ChunkStream.cs +++ b/Source/Core/ChunkStream.cs @@ -163,7 +163,6 @@ async IAsyncEnumerator> Read( !cancellationToken.IsCancellationRequested && reader.TryRead(out ArrayLease chunk)) { - // The array goes back at the next step. using (chunk) yield return chunk.Memory; } diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 03fd89e2..364baed9 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -994,7 +994,9 @@ await ProcedureParameterMetadata.EnsureAsync( // 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 + => Type == CommandType.Text + && Command is { Length: > 0 } text + && TextNameCache.Get(text) is { Names.Length: > 0 } names ? names : null; @@ -1230,7 +1232,8 @@ InvalidOperationException Collision(string name, Param first, Param second, Immu + " Name one of them explicitly: AddParam(\"name\", value)."); InvalidOperationException NoMatch(string expression, ImmutableArray real) - => DbQueryBinding.NoMatch(expression, Command, "The procedure declares", real); + => DbQueryBinding.NoMatch( + expression, Command, "The procedure declares", real); #endregion diff --git a/Source/Core/ExpressiveDbCommand.cs b/Source/Core/ExpressiveDbCommand.cs index bd9ce4f5..f21e1f44 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, type, command, @params) + : base(connFactory, type, command, @params) { } diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index e0dcde6e..16a7a2ff 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -371,12 +371,13 @@ internal static MappedQueryCore ReaderCore( internal static MappedQueryCore CommandCore( IDbCommand command, IRowSource source) - { - var single = command as SingleResultDbCommand; - return NewCore( - new CommandExecutor(single?.Command ?? command), default, source, - single is null ? QueryOptions.None : QueryOptions.SingleResult); - } + => command is SingleResultDbCommand single + ? NewCore( + new CommandExecutor(single.Command), default, source, + QueryOptions.SingleResult) + : NewCore( + new CommandExecutor(command), default, source, + QueryOptions.None); internal static MappedQueryCore TableCore( DataTable table, diff --git a/Source/Core/ProcedureParameterMetadata.cs b/Source/Core/ProcedureParameterMetadata.cs index 90db1bdc..c9a03bfe 100644 --- a/Source/Core/ProcedureParameterMetadata.cs +++ b/Source/Core/ProcedureParameterMetadata.cs @@ -91,7 +91,8 @@ public static async ValueTask EnsureAsync( { #if NET10_0_OR_GREATER using DataTable table = await db.GetSchemaAsync( - ProcedureSchemaNames.Collection, restrictions, cancellationToken) + ProcedureSchemaNames.Collection, restrictions, + cancellationToken) .ConfigureAwait(false); #else // DbConnection.GetSchemaAsync does not exist on the netstandard @@ -100,8 +101,6 @@ public static async ValueTask EnsureAsync( using DataTable table = db.GetSchema( ProcedureSchemaNames.Collection, restrictions); #endif - // 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)) @@ -203,7 +202,6 @@ static int ScaleOf(object value) ? scale : ParameterMetadata.NoScale; - // A value the database reports that is not a number is "not known". static bool TryInt(object value, out int result) { try diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index b88cce47..ebf1ed2b 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -34,7 +34,8 @@ internal static ImmutableArray Get(DbConnection connection, string proce try { - using DataTable table = connection.GetSchema(Collection, restrictions); + 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) @@ -78,7 +79,9 @@ internal static async ValueTask> GetAsync(DbConnection co try { - using 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) @@ -206,7 +209,13 @@ public static bool SpansSchemas(DataTable table) { string current = row["SPECIFIC_SCHEMA"] as string ?? ""; schema ??= current; - if (!string.Equals(schema, current, StringComparison.OrdinalIgnoreCase)) return true; + if (!string.Equals( + schema, + current, + StringComparison.OrdinalIgnoreCase)) + { + return true; + } } return false; diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index 05a411f4..506132c0 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -194,7 +194,9 @@ 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, ProcedureNameLength).Value = procedure; + command.Parameters + .Add("@procedure", SqlDbType.NVarChar, ProcedureNameLength) + .Value = procedure; if (Transaction is SqlTransaction transaction) command.Transaction = transaction; return command; } From 2e142485369dcbb3d81c878ed7a443e573fe6de1 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:44:54 -0800 Subject: [PATCH 2/6] Channel and Dataflow pumps: each keeps its own CloseAsync A six-line helper is not worth a shared Core internal that two packages call. The channel pump and the block pump each have their private CloseAsync again, with the body they had before the helper was shared; the shared class is gone. No other change. Co-Authored-By: Claude Sonnet 5.5 --- Source/Channel/ChannelPump.cs | 12 ++++++++++-- Source/Core/AsyncEnumerators.cs | 17 ----------------- Source/Dataflow/BlockPump.cs | 10 +++++++++- 3 files changed, 19 insertions(+), 20 deletions(-) delete mode 100644 Source/Core/AsyncEnumerators.cs diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index fee0b8a8..22bffedc 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -88,7 +88,7 @@ IAsyncEnumerator rows return wait.Result ? new(rows) - : AsyncEnumerators.CloseAsync(rows); + : CloseAsync(rows); } static async ValueTask?> OpenAsync( @@ -118,10 +118,18 @@ await rows.DisposeAsync() return room ? rows - : await AsyncEnumerators.CloseAsync(rows) + : await 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. /// diff --git a/Source/Core/AsyncEnumerators.cs b/Source/Core/AsyncEnumerators.cs deleted file mode 100644 index c19f7d30..00000000 --- a/Source/Core/AsyncEnumerators.cs +++ /dev/null @@ -1,17 +0,0 @@ -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/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index ce85c28c..9208248b 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -81,9 +81,17 @@ internal static async ValueTask Run( IAsyncEnumerator rows = stream.GetAsyncEnumerator(cancellationToken); return target.Completion.IsCompleted - ? AsyncEnumerators.CloseAsync(rows) + ? CloseAsync(rows) : new(rows); } + + static async ValueTask?> CloseAsync( + IAsyncEnumerator rows) + { + await rows.DisposeAsync() + .ConfigureAwait(false); + return null; + } } /// From 43441cb3b76c1f8789fb0c4fb8055881419d1326 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:52:20 -0800 Subject: [PATCH 3/6] Generator: put the one-line helpers' arrows on the next line, and one call on one line Layout fixes in the generator's own code, no change to its behavior or to the text it emits. The two Nullable helpers in ModelReader put their expression body's arrow on the next line, and the partial check in ModelReader keeps its single call chain on one line. The generated file of the generator tests (counters on and off) and of the generated benchmarks is byte-identical to the one the generator made before the previous change, so that change's two partial-model Bind sites are covered too: five models exercise one, two trusted models the other. Checks: whole solution Release build without warnings; generator tests in Release; dotnet format style and analyzers on the generator. Co-Authored-By: Claude Sonnet 5.5 --- Source/Generator/ModelReader.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index 88ccd1ac..bf4f4bdc 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -172,8 +172,7 @@ [.. properties.Where(static p => p.SetMethod is { DeclaredAccessibility: Accessi // Whether the model or a base type is declared partial in this compilation. A type from a referenced assembly is already whole. static bool IsPartial(INamedTypeSymbol t) - => TypeAndBaseTypes(t).Any(static c => c.DeclaringSyntaxReferences - .Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword))); + => TypeAndBaseTypes(t).Any(static c => c.DeclaringSyntaxReferences.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword))); // The type, then each base type up to object: the order reflection reads members in. static IEnumerable TypeAndBaseTypes(INamedTypeSymbol t) @@ -371,10 +370,12 @@ static bool IsNonNullableReference(IParameterSymbol p) return declared.NullableAnnotation == NullableAnnotation.NotAnnotated; } - static bool IsNullableValue(ITypeSymbol t) => t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; + static bool IsNullableValue(ITypeSymbol t) + => t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; // T of a Nullable, else the type itself. - static ITypeSymbol Underlying(ITypeSymbol t) => IsNullableValue(t) ? ((INamedTypeSymbol)t).TypeArguments[0] : t; + static ITypeSymbol Underlying(ITypeSymbol t) + => IsNullableValue(t) ? ((INamedTypeSymbol)t).TypeArguments[0] : t; static bool IsReference(ITypeSymbol t) => !t.IsValueType && t.TypeKind is not (TypeKind.TypeParameter or TypeKind.Pointer or TypeKind.FunctionPointer); From 9d4af742c91f1189518d19e039a344c5bd2b9634 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:13:20 -0800 Subject: [PATCH 4/6] Remove dead code and duplicated text; no public API change Internal removals and consolidation. No behavior change and no cost per call or per row: everything removed was never read, or is the same code written twice. - The source generator no longer emits the layout's `Ordinals` field and the `l.Ordinals = o;` store: nothing reads it. This changes the generated text, and only that: a before and after comparison of the generated files differs by exactly those lines (the field and its comment once, the store once per layout). No test compares the generated text. - The command-path cancellation token store on an output run is dropped from the two query-definition paths that never read it (the command path sets and reads its own). - The private `EnsureOpen` and `EnsureOpenAsync` command helpers, each with one caller, are inlined at that caller. - `IterateWhileAsyncInternal` no longer repeats the null checks that both of its callers already make. - The non-generic `ConnectionFactoryToPoolAdapter` is deleted. `AsPool` on a factory or a function now returns the generic adapter over `IDbConnection`, and the name-cache owner switch loses its second arm. A null factory still names `factory` in the exception. - `ArrayMapper` and its region are documented with their real callers (the output and capture reads), not "generated code" and the Channel and Dataflow pipelines. - A comment that said the same thing twice on the per-model-type statics of `RowMap` is folded into one. - The sentence about `DbQuery.Using` throwing for a null source is written once per type in the scalar and non-query definitions instead of on every overload. - The two `SingleResult` doc blocks share their common paragraphs through one include in `Mapped.docs.xml`. - An unused `using static` in the MSSqlClient synchronous transaction extensions is removed. - `DirectStream.HasTimer`, an `internal` member of an internal type, is `public`. Checks: solution Release build with no warnings on every target framework; Core and Generator tests in Release; `dotnet format` style and analyzers at info severity on the touched projects and their tests; the docs build. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Core/RowMap.cs | 6 +-- Source/Core/DbNonQuery.cs | 10 +---- Source/Core/DbQueryRunner.Output.cs | 6 +-- Source/Core/DirectStream.cs | 2 +- Source/Core/ExpressiveCommandBase.cs | 1 - Source/Core/Extensions/Command._.cs | 17 ++------ Source/Core/Extensions/DataReader.cs | 4 -- Source/Core/IDbConnectionFactory.cs | 43 ++----------------- Source/Core/Mapped.docs.xml | 18 ++++++++ Source/Core/ScalarDbQuery.cs | 10 +---- Source/Core/SingleResult.cs | 32 ++------------ Source/Generator/Emitter.cs | 5 --- .../SyncSqlTransactionExtensions.cs | 2 - 13 files changed, 35 insertions(+), 121 deletions(-) diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index bac1c832..b711bd7b 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -456,8 +456,6 @@ RowMap Converting( /// The number of layouts a map keeps readers for before its cache is cleared. const int MaxLayouts = 128; - // The statics below are one immutable copy per model type: see TypeShape. - // Never throws: an unmappable T holds its error, so no static initializer here can fail with it. // The per-model-type statics (TypeShape, MappedSlots, ModelSlotIndex, Default) are one immutable copy per T, built once. // Any cache of compiled readers keyed by model type lives as long and costs a lookup per call; a static on the generic type is the cheapest place for it. @@ -1277,7 +1275,7 @@ public bool Matches(IDataRecord r) } } - #region Array rows (the route generated mappers and the Channel and Dataflow pipelines use) + #region Array rows (the route the output and capture reads use) /// The layout of the object[] rows most recently used. /// @@ -1303,7 +1301,7 @@ public bool Matches(ImmutableArray candidate) } /// Returns the mapper from object[] rows whose columns are, in order, . - /// For generated code. + /// For the output and capture reads, whose caller owns the loop. /// The names of the columns, in order. /// The delegate that maps a row to a . /// A required property has no column among . diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs index bfeaaa07..f68ce72d 100644 --- a/Source/Core/DbNonQuery.cs +++ b/Source/Core/DbNonQuery.cs @@ -134,13 +134,12 @@ public OutputDbNonQuery Output( /// /// The write, bound. public BoundCall Using(DbConnection connection) - // DbQuery.Using throws ArgumentNullException for a null source. + // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection).ToCall()); /// /// The write, bound. public BoundCall Using(DbTransaction transaction) - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(transaction).ToCall()); /// @@ -148,7 +147,6 @@ public BoundCall Using(DbTransaction transaction) public BoundCall Using( IDbConnectionPool pool) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(pool).ToCall()); /// @@ -156,7 +154,6 @@ public BoundCall Using( public BoundCall Using( IDbConnectionFactory factory) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(factory).ToCall()); /// @@ -219,13 +216,12 @@ public PendingParams AddParams(TParams values) /// /// The write, bound. public BoundParams Using(DbConnection connection) - // DbQuery.Using throws ArgumentNullException for a null source. + // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection)); /// /// The write, bound. public BoundParams Using(DbTransaction transaction) - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(transaction)); /// @@ -233,7 +229,6 @@ public BoundParams Using(DbTransaction transaction) public BoundParams Using( IDbConnectionPool pool) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(pool)); /// @@ -241,7 +236,6 @@ public BoundParams Using( public BoundParams Using( IDbConnectionFactory factory) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(factory)); /// diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index 5f7f5e65..d93342cf 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -265,7 +265,6 @@ static async ValueTask ExecuteWithOutputAsync( { // Cancelled awaited tasks throw, so this does too. cancellationToken.ThrowIfCancellationRequested(); - output.Token = cancellationToken; TValue value; // The run is a block of its own, so everything is released at its end. @@ -348,10 +347,7 @@ public static async ValueTask RunCapturedAsync( { // Cancelled awaited tasks throw, so this does too. cancellationToken.ThrowIfCancellationRequested(); - var output = new OutputRun(run.Set.Layout) - { - Token = cancellationToken, - }; + var output = new OutputRun(run.Set.Layout); TResult result; { diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 41535cb1..82006a6a 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -92,7 +92,7 @@ public DirectStream( } // Whether the watchdog timer exists: it does not before the first row, nor after the stream is over. - internal bool HasTimer => Volatile.Read(ref _timer) is not null; + public bool HasTimer => Volatile.Read(ref _timer) is not null; TimeoutException ToException() => StallStream.TimeoutFor(_stall); diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 364baed9..5917e65b 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1066,7 +1066,6 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f object NameCacheOwner => _poolOrConnection switch { DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter typed => typed.Identity, - DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter untyped => untyped.Identity, _ => _poolOrConnection, }; diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 4113629d..479363ad 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -7,16 +7,6 @@ namespace Open.Database.Extensions; public static partial class CommandExtensions { - #region Connection.EnsureOpen Shortcuts. - // A command with no connection is refused by the connection extension: ArgumentNullException named "connection". - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ConnectionState EnsureOpen(this IDbCommand command) - => command.Connection!.EnsureOpen(); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ValueTask EnsureOpenAsync(this IDbCommand command, CancellationToken cancellationToken) - => command.Connection!.EnsureOpenAsync(cancellationToken); - /// /// Gets the scope of the command's own connection: /// it is opened if needed, and closed again if the scope opened it. @@ -60,7 +50,8 @@ internal static async ValueTask> EnsureOpenScopeA internal static TReader OpenAndExecuteReader(TCommand command, CommandBehavior behavior, Func execute) where TCommand : IDbCommand { - if (!ConnectionExtensions.NeedsOpen(command.EnsureOpen())) + // A command with no connection is refused by the connection extension: ArgumentNullException named "connection". + if (!ConnectionExtensions.NeedsOpen(command.Connection!.EnsureOpen())) return execute(command, behavior); // The connection this call opened is the one it closes if the execute fails. @@ -80,7 +71,7 @@ internal static TReader OpenAndExecuteReader(TCommand command internal static async ValueTask OpenAndExecuteReaderAsync(TCommand command, CommandBehavior behavior, Func> execute, CancellationToken cancellationToken) where TCommand : IDbCommand { - ConnectionState prior = await command.EnsureOpenAsync(cancellationToken).ConfigureAwait(false); + ConnectionState prior = await command.Connection!.EnsureOpenAsync(cancellationToken).ConfigureAwait(false); if (!ConnectionExtensions.NeedsOpen(prior)) return await execute(command, behavior, cancellationToken).ConfigureAwait(false); @@ -153,8 +144,6 @@ static async ValueTask ExecuteReaderCoreAsync( return await handle(reader, arg).ConfigureAwait(false); } - #endregion - /// public static ValueTask ExecuteReaderAsync(this IDbCommand command, CancellationToken cancellationToken = default) diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index d883f00e..1def227f 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -929,10 +929,6 @@ public static async ValueTask IterateWhileAsync(this DbDataReader reader, Func> predicate, CancellationToken cancellationToken) { - if (reader is null) throw new ArgumentNullException(nameof(reader)); - if (predicate is null) throw new ArgumentNullException(nameof(predicate)); - Contract.EndContractBlock(); - while (ReadNext(reader, cancellationToken)) { if (!await predicate(reader).ConfigureAwait(false)) break; diff --git a/Source/Core/IDbConnectionFactory.cs b/Source/Core/IDbConnectionFactory.cs index 94b25fba..8ac2a9dc 100644 --- a/Source/Core/IDbConnectionFactory.cs +++ b/Source/Core/IDbConnectionFactory.cs @@ -61,43 +61,6 @@ interface IConnectionIdentity /// public static class DbConnectionFactoryExtensions { - /// - /// Presents a connection factory function as an : taking a connection invokes the function and giving it back disposes it. - /// - /// - /// Nothing is pooled. This adapter lets code written against accept a plain factory. - /// - /// The function that creates a new connection each time one is taken. - /// is . - /// - internal readonly struct ConnectionFactoryToPoolAdapter(Func factory) : IDbConnectionPool, IConnectionIdentity - { - readonly Func _factory = factory ?? throw new ArgumentNullException(nameof(factory)); - - /// - /// Constructs a from a connection factory. - /// - /// The factory whose method creates each connection. - /// is . - public ConnectionFactoryToPoolAdapter(IDbConnectionFactory factory) - : this((factory ?? throw new ArgumentNullException(nameof(factory))).Create) { } - - /// - /// Creates a new connection by invoking the factory function. - public IDbConnection Take() - => _factory(); - - /// - public object Identity => _factory.Target ?? _factory; - - object IConnectionIdentity.Identity => Identity; - - /// - /// Disposes ; nothing is retained for reuse. - public void Give(IDbConnection connection) - => connection.Dispose(); - } - /// /// Presents a typed connection factory function as an : taking a connection invokes the function and giving it back disposes it. /// @@ -154,8 +117,8 @@ public void Give(IDbConnection connection) /// /// is . public static IDbConnectionPool AsPool(this IDbConnectionFactory connectionFactory) - // The adapter constructor throws ArgumentNullException for a null source. - => new ConnectionFactoryToPoolAdapter(connectionFactory); + // The adapter constructor throws ArgumentNullException for a null source: a null factory passes it a null function. + => new ConnectionFactoryToPoolAdapter(connectionFactory is null ? null! : connectionFactory.Create); /// /// Presents a connection factory function as a connection pool that invokes the function when a connection is taken and disposes the connection when it is given back. @@ -166,7 +129,7 @@ public static IDbConnectionPool AsPool(this IDbConnectionFactory connectionFacto /// is . public static IDbConnectionPool AsPool(this Func connectionFactory) // The adapter constructor throws ArgumentNullException for a null source. - => new ConnectionFactoryToPoolAdapter(connectionFactory); + => new ConnectionFactoryToPoolAdapter(connectionFactory); /// /// Presents a typed connection factory as a connection pool that creates a new connection when one is taken and disposes it when it is given back. diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index db7af9c2..7823bcaa 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -313,4 +313,22 @@ A cancel or a dispose stops the read promptly only as far as the provider honors the cancellation. + + + + A Map terminal returns the rows of the first result set + (a result here is one whole result set, what moves between; never a row) + and then reads through the later sets without reading their rows, + so a failure in a later statement is thrown as the provider raised it. + This is the one explicit opt-out of that. + It asserts nothing: it does not check that there is only one result set. + + + Call it before Map, as in command.SingleResult().Map<Post>().ToListAsync(cancellationToken). + + + A later failure can follow a write that already committed, + so a caller that retries can repeat it, and the opt-out hides that failure. + + diff --git a/Source/Core/ScalarDbQuery.cs b/Source/Core/ScalarDbQuery.cs index d478c440..7235bd31 100644 --- a/Source/Core/ScalarDbQuery.cs +++ b/Source/Core/ScalarDbQuery.cs @@ -41,26 +41,23 @@ public ScalarDbQuery Params() /// public BoundCall> Using(DbConnection connection) - // DbQuery.Using throws ArgumentNullException for a null source. + // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection).ToCall()); /// public BoundCall> Using(DbTransaction transaction) - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(transaction).ToCall()); /// public BoundCall> Using( IDbConnectionPool pool) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(pool).ToCall()); /// public BoundCall> Using( IDbConnectionFactory factory) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(factory).ToCall()); /// @@ -109,25 +106,22 @@ public PendingParams, TParams> AddParams(TParams values) /// public BoundParams, TParams> Using(DbConnection connection) - // DbQuery.Using throws ArgumentNullException for a null source. + // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection)); /// public BoundParams, TParams> Using(DbTransaction transaction) - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(transaction)); /// public BoundParams, TParams> Using( IDbConnectionPool pool) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(pool)); /// public BoundParams, TParams> Using( IDbConnectionFactory factory) where TConnection : DbConnection - // DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(factory)); } diff --git a/Source/Core/SingleResult.cs b/Source/Core/SingleResult.cs index c17bb998..ece1b943 100644 --- a/Source/Core/SingleResult.cs +++ b/Source/Core/SingleResult.cs @@ -8,19 +8,11 @@ public static partial class CoreExtensions /// Opts an expressive command out of the read-through, so that the query reads only the first result set. /// /// + /// /// - /// A Map terminal returns the rows of the first result set - /// (a result here is one whole result set, what moves between; never a row) - /// and then reads through the later sets without reading their rows, - /// so a failure in a later statement is thrown as the provider raised it. - /// This is the one explicit opt-out of that. - /// With it the reader is asked for + /// With the opt-out the reader is asked for /// (and too for First, FirstOrDefault and AnyAsync when nothing is skipped and CancelOnEarlyStop() was not called), /// which lets the provider stop early. - /// It asserts nothing: it does not check that there is only one result set. - /// - /// - /// Call it before Map, as in command.SingleResult().Map<Post>().ToListAsync(cancellationToken). /// /// /// command.SingleResult().Map<T>() is exactly @@ -30,10 +22,6 @@ public static partial class CoreExtensions /// The command is not changed, so it can be used again without the opt-out. /// /// - /// A later failure can follow a write that already committed, - /// so a caller that retries can repeat it, and the opt-out hides that failure. - /// - /// /// The result is a view of the command for Map. /// Used as an directly, /// it runs the command with added to each call. @@ -59,17 +47,7 @@ public static IExecuteReader SingleResult( /// Opts a command out of the read-through, so that the query reads only the first result set. /// /// - /// - /// A Map terminal returns the rows of the first result set - /// (a result here is one whole result set, what moves between; never a row) - /// and then reads through the later sets without reading their rows, - /// so a failure in a later statement is thrown as the provider raised it. - /// This is the one explicit opt-out of that. - /// It asserts nothing: it does not check that there is only one result set. - /// - /// - /// Call it before Map, as in command.SingleResult().Map<Post>().ToListAsync(cancellationToken). - /// + /// /// /// command.SingleResult().Map<T>() is exactly /// command.Map<T>().SingleResult(), which still works, @@ -80,10 +58,6 @@ public static IExecuteReader SingleResult( /// that disposing the view disposes the command, so dispose one or the other. /// /// - /// A later failure can follow a write that already committed, - /// so a caller that retries can repeat it, and the opt-out hides that failure. - /// - /// /// The result is a view of the command for Map: /// it is not a , so pass the command itself to anything else. /// Used as an directly, diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index c05cb1be..b3bb332a 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -217,10 +217,6 @@ file abstract class OdxLayout // reads like a hand-written selector. public int Mode; - // The column of each slot, -1 for none (in slot order); - // null when the runtime serves the layout. - public int[] Ordinals; - // The fed slots in column order: // the order a guarded read takes, as the runtime reads and sets // (and a SequentialAccess reader needs). @@ -561,7 +557,6 @@ static Layout Resolve({{DbReader}} r) // Every slot fed in ascending column order: constant ordinals when each sits at its declaration position (4, the identity: read in slot order, // which is column order), else the layout's (1). Anything else is guarded (2), read in column order. sb.AppendLine(""" - l.Ordinals = o; l.Mode = !full || !ascending ? 2 : literal ? 4 : 1; if (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots); // The row reader of the mode, chosen here once: diff --git a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs index c66f2cf6..d60cc905 100644 --- a/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs +++ b/Source/MSSqlClient/Synchronous/SyncSqlTransactionExtensions.cs @@ -1,5 +1,3 @@ -using static Open.Database.Extensions.SqlTransactionExtensions; - namespace Open.Database.Extensions.Synchronous; /// From f0ef04ee7e669eb9f672a33e9a76293fbe4af8b3 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:17:11 -0800 Subject: [PATCH 5/6] Review fixes: keep the connection-factory adapter, tidy chains and a comment The non-generic connection-factory adapter stays. Making AsPool return the generic adapter would change what the procedure-name cache shares between commands built from one factory function (it would share across them, where today each command has its own), which is a behavior change and not a refactor. Also: the first call of three chains stays on its receiver's line, the schema comparison's arguments are grouped, and the comment above the Using overloads says it covers every overload of the type. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbNonQuery.cs | 4 +- Source/Core/ExpressiveCommandBase.cs | 1 + Source/Core/IDbConnectionFactory.cs | 43 ++++++++++++++++++++-- Source/Core/ProcedureSchemaNames.cs | 7 ++-- Source/Core/ScalarDbQuery.cs | 4 +- Source/MSSqlClient/ExpressiveSqlCommand.cs | 4 +- 6 files changed, 50 insertions(+), 13 deletions(-) diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs index f68ce72d..1e36445a 100644 --- a/Source/Core/DbNonQuery.cs +++ b/Source/Core/DbNonQuery.cs @@ -134,7 +134,7 @@ public OutputDbNonQuery Output( /// /// The write, bound. public BoundCall Using(DbConnection connection) - // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. + // Every Using overload of this type: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection).ToCall()); /// @@ -216,7 +216,7 @@ public PendingParams AddParams(TParams values) /// /// The write, bound. public BoundParams Using(DbConnection connection) - // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. + // Every Using overload of this type: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection)); /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 5917e65b..364baed9 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1066,6 +1066,7 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f object NameCacheOwner => _poolOrConnection switch { DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter typed => typed.Identity, + DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter untyped => untyped.Identity, _ => _poolOrConnection, }; diff --git a/Source/Core/IDbConnectionFactory.cs b/Source/Core/IDbConnectionFactory.cs index 8ac2a9dc..94b25fba 100644 --- a/Source/Core/IDbConnectionFactory.cs +++ b/Source/Core/IDbConnectionFactory.cs @@ -61,6 +61,43 @@ interface IConnectionIdentity /// public static class DbConnectionFactoryExtensions { + /// + /// Presents a connection factory function as an : taking a connection invokes the function and giving it back disposes it. + /// + /// + /// Nothing is pooled. This adapter lets code written against accept a plain factory. + /// + /// The function that creates a new connection each time one is taken. + /// is . + /// + internal readonly struct ConnectionFactoryToPoolAdapter(Func factory) : IDbConnectionPool, IConnectionIdentity + { + readonly Func _factory = factory ?? throw new ArgumentNullException(nameof(factory)); + + /// + /// Constructs a from a connection factory. + /// + /// The factory whose method creates each connection. + /// is . + public ConnectionFactoryToPoolAdapter(IDbConnectionFactory factory) + : this((factory ?? throw new ArgumentNullException(nameof(factory))).Create) { } + + /// + /// Creates a new connection by invoking the factory function. + public IDbConnection Take() + => _factory(); + + /// + public object Identity => _factory.Target ?? _factory; + + object IConnectionIdentity.Identity => Identity; + + /// + /// Disposes ; nothing is retained for reuse. + public void Give(IDbConnection connection) + => connection.Dispose(); + } + /// /// Presents a typed connection factory function as an : taking a connection invokes the function and giving it back disposes it. /// @@ -117,8 +154,8 @@ public void Give(IDbConnection connection) /// /// is . public static IDbConnectionPool AsPool(this IDbConnectionFactory connectionFactory) - // The adapter constructor throws ArgumentNullException for a null source: a null factory passes it a null function. - => new ConnectionFactoryToPoolAdapter(connectionFactory is null ? null! : connectionFactory.Create); + // The adapter constructor throws ArgumentNullException for a null source. + => new ConnectionFactoryToPoolAdapter(connectionFactory); /// /// Presents a connection factory function as a connection pool that invokes the function when a connection is taken and disposes the connection when it is given back. @@ -129,7 +166,7 @@ public static IDbConnectionPool AsPool(this IDbConnectionFactory connectionFacto /// is . public static IDbConnectionPool AsPool(this Func connectionFactory) // The adapter constructor throws ArgumentNullException for a null source. - => new ConnectionFactoryToPoolAdapter(connectionFactory); + => new ConnectionFactoryToPoolAdapter(connectionFactory); /// /// Presents a typed connection factory as a connection pool that creates a new connection when one is taken and disposes it when it is given back. diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index ebf1ed2b..f7d5a856 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -79,8 +79,8 @@ internal static async ValueTask> GetAsync(DbConnection co try { - using DataTable table = await connection - .GetSchemaAsync(Collection, restrictions, cancellationToken) + using DataTable table = await connection.GetSchemaAsync( + Collection, restrictions, cancellationToken) .ConfigureAwait(false); return Names(table, schemaGiven: restrictions[1] is not null); } @@ -210,8 +210,7 @@ public static bool SpansSchemas(DataTable table) string current = row["SPECIFIC_SCHEMA"] as string ?? ""; schema ??= current; if (!string.Equals( - schema, - current, + schema, current, StringComparison.OrdinalIgnoreCase)) { return true; diff --git a/Source/Core/ScalarDbQuery.cs b/Source/Core/ScalarDbQuery.cs index 7235bd31..1e2c0b75 100644 --- a/Source/Core/ScalarDbQuery.cs +++ b/Source/Core/ScalarDbQuery.cs @@ -41,7 +41,7 @@ public ScalarDbQuery Params() /// public BoundCall> Using(DbConnection connection) - // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. + // Every Using overload of this type: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection).ToCall()); /// @@ -106,7 +106,7 @@ public PendingParams, TParams> AddParams(TParams values) /// public BoundParams, TParams> Using(DbConnection connection) - // Each Using overload: DbQuery.Using throws ArgumentNullException for a null source. + // Every Using overload of this type: DbQuery.Using throws ArgumentNullException for a null source. => new(_definition.Using(connection)); /// diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index 506132c0..51da18b1 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -194,8 +194,8 @@ 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, ProcedureNameLength) + command.Parameters.Add( + "@procedure", SqlDbType.NVarChar, ProcedureNameLength) .Value = procedure; if (Transaction is SqlTransaction transaction) command.Transaction = transaction; return command; From 5481ddd22a81f03c28d81f08902be1653890faa2 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:51:13 -0800 Subject: [PATCH 6/6] Channel and Dataflow pumps: use the shared CloseAsync again The shared helper in Core stays: both pumps call AsyncEnumerators.CloseAsync, as before the earlier commit of this branch, which removed it. Co-Authored-By: Claude Sonnet 5.5 --- Source/Channel/ChannelPump.cs | 12 ++---------- Source/Core/AsyncEnumerators.cs | 17 +++++++++++++++++ Source/Dataflow/BlockPump.cs | 10 +--------- 3 files changed, 20 insertions(+), 19 deletions(-) create mode 100644 Source/Core/AsyncEnumerators.cs diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index 22bffedc..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. /// 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/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index 9208248b..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; - } } ///