From 31d84bd724e26f5907d458b6f845116a9f8031bb Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:14:45 -0800 Subject: [PATCH 1/3] Share code the Core internals wrote twice, and replace flag parameters with named methods No public API change and no change to generated code. The cost is none per call or per row: every change is on a declaration, chain-building or error path, or is a property read or a call that inlines. - A capture's task is read by two methods, one that only needs the terminal to have started (AsTask) and one that also refuses an open stream (await), instead of one method taking a bool. A capture marks its stream open and closed with two methods, not a bool. - A set of captures is extended with WithOnCommand or WithOnQuery instead of a bool; the word the messages use ("command" or "query") now comes from the set's own Noun, in one place. A capture of the return code beside a call that reads it is refused by one method on the set, which the command and the bound call both use. - The capture of an output model builds its display text once, and the return-code capture of a captured ExecuteReturnAsync now shows the typed form of the call in its messages, like the uncaptured one. - The eight capture overloads of a bound call share one helper that adds the capture and hands back its handle. - A definition's call that reads outputs builds its command through the same method as a plain call, then adds the outputs, instead of repeating its ten lines. The test for a procedure whose metadata is still to be read is one property on the name set, used by the command and the definition runner. - The declared type name of an output member is read by the same attribute reader the row map uses (Decoration), instead of a second walk over the attributes. The decimal call texts in the "no output matches" message come from the same two helpers the argument checks use, with the same wording. - The output definitions share one place that names the definition in a refusal, one place that checks a decimal's precision and scale, and the model's refusal no longer repeats its own catch block. - ReturnCode keeps the type check and the message in a non-generic class, and the generic one only what depends on the type. - CaptureNames: the redundant null-forgiving operators after the white-space check are removed. - The documentation samples read SAMPLES_BLOG_CONNECTION with string.IsNullOrWhiteSpace, so an empty value falls back to LocalDB as an unset one does. Checks: solution Release build with 0 warnings on every target framework; Core.Tests Release 16151 passed; Generator.Tests Release 189 passed; dotnet format style and analyzers at info severity on Core, Core.Tests and the samples: 0 findings; docfx build with 0 warnings and 0 errors; style scan clean. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/BoundCall.cs | 87 +++++------- Source/Core/Capture.cs | 135 +++++++++++++------ Source/Core/CaptureNames.cs | 6 +- Source/Core/CapturedStream.cs | 6 +- Source/Core/Core/RowMap.cs | 30 +++-- Source/Core/DbCapture.cs | 10 +- Source/Core/DbQueryRunner.Output.cs | 35 ++--- Source/Core/ExpressiveCommandBase.Capture.cs | 5 +- Source/Core/ExpressiveCommandBase.cs | 17 +-- Source/Core/MappedQuery.Capture.cs | 4 +- Source/Core/NameSet.cs | 6 + Source/Core/OutputBinding.cs | 21 +-- Source/Core/OutputDbNonQuery.cs | 83 ++++++------ Source/Core/OutputLayout.cs | 91 +++++++------ docsite/samples/OutputParameters.cs | 7 +- 15 files changed, 284 insertions(+), 259 deletions(-) diff --git a/Source/Core/BoundCall.cs b/Source/Core/BoundCall.cs index 47044b1b..a7f62eb5 100644 --- a/Source/Core/BoundCall.cs +++ b/Source/Core/BoundCall.cs @@ -366,13 +366,7 @@ public static ValueTask ExecuteReturnAsync( } // A capture of the return code and this would read it twice. - if (call.Captures?.ReturnReader is { } returnReader) - { - throw call.Captures.Refuse( - new InvalidOperationException( - CaptureMessages.ReturnBeside(returnReader)), - cancellationToken); - } + call.Captures?.ThrowIfReturnBeside(cancellationToken); return DbQueryRunner.ReturnAsync( definition, @@ -394,6 +388,17 @@ static BoundCall WithCapture( CaptureSet.WithOnDefinition( call.Captures, source, call.Call.Definition.Kind)); + // The call with the capture, and the capture's handle for the caller. + static BoundCall WithCapture( + BoundCall call, + CaptureSource source, + out DbCapture capture) + { + BoundCall captured = WithCapture(call, source); + capture = new(source); + return captured; + } + /// /// Reads the output parameters into a when the /// write runs: a model by its members, or one value by the name of the @@ -407,12 +412,7 @@ public static BoundCall CaptureOutput( this BoundCall call, out DbCapture output, [CallerArgumentExpression(nameof(output))] string? name = null) - { - CaptureSource source = Captures.Output(name); - BoundCall captured = WithCapture(call, source); - output = new(source); - return captured; - } + => WithCapture(call, Captures.Output(name), out output); /// /// Reads one output parameter of the given precision @@ -429,12 +429,10 @@ public static BoundCall CaptureOutput( byte precision, byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) - { - CaptureSource source = Captures.Shaped(name, precision, scale); - BoundCall captured = WithCapture(call, source); - value = new(source); - return captured; - } + => WithCapture( + call, + Captures.Shaped(name, precision, scale), + out value); /// /// Reads one output parameter of the given precision @@ -450,12 +448,10 @@ public static BoundCall CaptureOutputDecimal( byte precision, byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) - { - CaptureSource source = Captures.Decimal(name, precision, scale); - BoundCall captured = WithCapture(call, source); - value = new(source); - return captured; - } + => WithCapture( + call, + Captures.Decimal(name, precision, scale), + out value); /// /// Reads the stored procedure's return code, converted to @@ -467,12 +463,7 @@ public static BoundCall CaptureOutputDecimal( public static BoundCall CaptureReturn( this BoundCall call, out DbCapture returnCode) - { - CaptureSource source = Captures.Return(); - BoundCall captured = WithCapture(call, source); - returnCode = new(source); - return captured; - } + => WithCapture(call, Captures.Return(), out returnCode); /// /// Reads the output parameters into a when the @@ -488,12 +479,7 @@ public static BoundCall> CaptureOutput( this BoundCall> call, out DbCapture output, [CallerArgumentExpression(nameof(output))] string? name = null) - { - CaptureSource source = Captures.Output(name); - BoundCall> captured = WithCapture(call, source); - output = new(source); - return captured; - } + => WithCapture(call, Captures.Output(name), out output); /// /// Reads one output parameter of the given precision @@ -511,12 +497,10 @@ public static BoundCall> CaptureOutput( byte precision, byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) - { - CaptureSource source = Captures.Shaped(name, precision, scale); - BoundCall> captured = WithCapture(call, source); - value = new(source); - return captured; - } + => WithCapture( + call, + Captures.Shaped(name, precision, scale), + out value); /// /// Reads one output parameter of the given precision @@ -533,12 +517,10 @@ public static BoundCall> CaptureOutputDecimal( byte precision, byte scale, [CallerArgumentExpression(nameof(value))] string? name = null) - { - CaptureSource source = Captures.Decimal(name, precision, scale); - BoundCall> captured = WithCapture(call, source); - value = new(source); - return captured; - } + => WithCapture( + call, + Captures.Decimal(name, precision, scale), + out value); /// /// Reads the stored procedure's return code, converted to @@ -551,10 +533,5 @@ public static BoundCall> CaptureOutputDecimal( public static BoundCall> CaptureReturn( this BoundCall> call, out DbCapture returnCode) - { - CaptureSource source = Captures.Return(); - BoundCall> captured = WithCapture(call, source); - returnCode = new(source); - return captured; - } + => WithCapture(call, Captures.Return(), out returnCode); } diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 2f6e0c07..4e401374 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -83,10 +83,11 @@ interface ICaptureSource void Arm(); /// Marks the capture as belonging to a stream whose enumerator is - /// open, or no longer. - /// while the enumerator is - /// open. - void SetStreamOpen(bool open); + /// open. + void BeginStream(); + + /// Marks the capture's stream as no longer open. + void EndStream(); /// Completes the capture from the values of the call, once the /// response is complete. @@ -150,8 +151,11 @@ public bool TryArm() public void Arm() => Interlocked.CompareExchange(ref _state, Armed, NotStarted); - public void SetStreamOpen(bool open) - => Volatile.Write(ref _state, open ? StreamOpen : Armed); + public void BeginStream() + => Volatile.Write(ref _state, StreamOpen); + + public void EndStream() + => Volatile.Write(ref _state, Armed); public void Observe() => _ = Task.Exception; @@ -181,27 +185,35 @@ public void Deliver(OutputRun call, int start) protected abstract T Read(OutputRun call, int start); /// - /// Gets the task of a capture that may be awaited now: refuses one whose - /// terminal was not called, and, when it is awaited, - /// one whose stream is still open. + /// Gets the task of a capture whose terminal was called, for + /// AsTask, which a stream's loop may hand on. /// - /// for GetAwaiter and - /// ConfigureAwait; for AsTask, which - /// a stream's loop may hand on. /// The task. - /// The terminal was not called, - /// or the stream is still open. - public Task Started(bool awaiting) + /// The terminal was not + /// called. + public Task Started() { - int state = Volatile.Read(ref _state); - if (state == NotStarted) + if (Volatile.Read(ref _state) == NotStarted) { throw new InvalidOperationException( CaptureMessages.NotStarted(Display)); } - Task task = Task; - if (awaiting && state == StreamOpen && !task.IsCompleted) + return Task; + } + + /// + /// Gets the task of a capture that may be awaited now, for + /// GetAwaiter and ConfigureAwait: refuses one whose terminal + /// was not called, and one whose stream is still open. + /// + /// The task. + /// The terminal was not called, + /// or the stream is still open. + public Task Awaited() + { + Task task = Started(); + if (!task.IsCompleted && Volatile.Read(ref _state) == StreamOpen) { throw new InvalidOperationException( CaptureMessages.StreamOpen(Display)); @@ -218,10 +230,11 @@ public Task Started(bool awaiting) /// The model's layout. /// The name the capture was given, which a model does not use, or . sealed class ModelCapture(OutputLayout layout, string? receivedName) - : CaptureSource( - $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)", - CaptureKind.Model) + : CaptureSource(CaptureCall(), CaptureKind.Model) { + static string CaptureCall() + => $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)"; + // The members named for the messages as members of this capture. public override ImmutableArray Members { get; } = Named(layout, receivedName); @@ -232,7 +245,7 @@ static ImmutableArray Named( OutputLayout layout, string? receivedName) { - string capture = $"CaptureOutput(out DbCapture<{Shape.TypeName(typeof(TOut))}>)"; + string capture = CaptureCall(); var members = ImmutableArray.CreateBuilder( layout.Members.Length); foreach (OutputMember member in layout.Members) @@ -405,34 +418,48 @@ sealed class CaptureSet : CaptureHolder public string Noun => OnQuery ? "query" : "command"; /// - /// Returns the captures with one more, after checking that it reads nothing - /// another one reads. + /// Returns the captures of a command with one more, after checking that it + /// reads nothing another one reads. /// /// The captures so far, or /// . /// The new capture. - /// when it is attached on a - /// mapped query. /// The new set. /// The capture reads what /// another capture reads. - public static CaptureSet With( + public static CaptureSet WithOnCommand( CaptureSet? set, - ICaptureSource source, - bool onQuery) - { - if (set is null) return new([source], onQuery); + ICaptureSource source) + => set?.Added(source) ?? new([source], onQuery: false); - string noun = onQuery ? "query" : "command"; - foreach (ICaptureSource other in set.Sources) - ThrowIfSameOwner(other, source, noun); + /// + /// Returns the captures of a mapped query with one more, as + /// does. + /// + /// The captures so far, or + /// . + /// The new capture. + /// The new set. + /// The capture reads what + /// another capture reads. + public static CaptureSet WithOnQuery( + CaptureSet? set, + ICaptureSource source) + => set?.Added(source) ?? new([source], onQuery: true); - return new([.. set.Sources, source], onQuery || set.OnQuery); + // The set is on a command or on a query for good: the new one is as well, + // and the messages say which. + CaptureSet Added(ICaptureSource source) + { + foreach (ICaptureSource other in Sources) + ThrowIfSameOwner(other, source, Noun); + + return new([.. Sources, source], OnQuery); } /// /// Returns the captures of a definition's call with one more, as - /// does. + /// does. /// /// /// A definition's kind never changes, so a capture of the return code is @@ -458,7 +485,7 @@ public static CaptureSet WithOnDefinition( CaptureMessages.NotProcedure(source)); } - return With(set, source, onQuery: true); + return WithOnQuery(set, source); } /// @@ -595,6 +622,21 @@ public override Exception Refuse( public InvalidOperationException NotProcedure() => new(CaptureMessages.NotProcedure(ReturnReader!)); + /// Refuses a call that reads the return code itself when a capture + /// reads it too: the capture is completed with the refusal. + /// The token that governs the call. + /// A capture reads the return + /// code. + public void ThrowIfReturnBeside(CancellationToken cancellationToken) + { + if (ReturnReader is not { } returnReader) return; + + throw Refuse( + new InvalidOperationException( + CaptureMessages.ReturnBeside(returnReader)), + cancellationToken); + } + /// Gets the capture that reads the return code, or /// . public ICaptureSource? ReturnReader @@ -716,14 +758,21 @@ public override Exception Refuse( } /// Marks every capture as belonging to a stream whose enumerator - /// is open, or no longer. - /// while the enumerator is - /// open. - public void SetStreamOpen(bool open) + /// is open. + public void BeginStream() + { + foreach (ICaptureSource source in set.Sources) + { + source.BeginStream(); + } + } + + /// Marks every capture's stream as no longer open. + public void EndStream() { foreach (ICaptureSource source in set.Sources) { - source.SetStreamOpen(open); + source.EndStream(); } } diff --git a/Source/Core/CaptureNames.cs b/Source/Core/CaptureNames.cs index 19913c62..474bb091 100644 --- a/Source/Core/CaptureNames.cs +++ b/Source/Core/CaptureNames.cs @@ -68,18 +68,18 @@ public static CaptureName From(string? text) { if (string.IsNullOrWhiteSpace(text)) return null; - if (IsPlain(text!)) + if (IsPlain(text)) { // A typed value: "$", "#" and the like are part of the name; one // leading @ or : is dropped. - string plain = text![0] is '@' or ':' ? text[1..] : text; + string plain = text[0] is '@' or ':' ? text[1..] : text; return plain.Length == 0 || plain == "_" ? null : new CaptureName(plain); } return Cache - .GetValue(text!, static t => new Parsed(Derive(t))) + .GetValue(text, static t => new Parsed(Derive(t))) .Name; } diff --git a/Source/Core/CapturedStream.cs b/Source/Core/CapturedStream.cs index c13e3004..58f124fc 100644 --- a/Source/Core/CapturedStream.cs +++ b/Source/Core/CapturedStream.cs @@ -50,14 +50,14 @@ public IAsyncEnumerator GetAsyncEnumerator( run.Claim(); run.Enumerating(cancellationToken); - run.SetStreamOpen(true); + run.BeginStream(); try { _inner = inner.GetAsyncEnumerator(cancellationToken); } catch (Exception ex) { - run.SetStreamOpen(false); + run.EndStream(); run.Settle(ex); throw; } @@ -123,7 +123,7 @@ public async ValueTask DisposeAsync() } finally { - run.SetStreamOpen(false); + run.EndStream(); run.Settle(_error); } } diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index b711bd7b..f1e46875 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -2529,14 +2529,15 @@ static bool Has(IList attributes, string attributeName) /// /// /// The declarations are [Column(Name)] and [Column(Order = n)] -/// (System.ComponentModel.DataAnnotations.Schema.ColumnAttribute; TypeName is ignored) and [NotMapped]. +/// (System.ComponentModel.DataAnnotations.Schema.ColumnAttribute) and [NotMapped]; the map ignores the TypeName that [Column] carries, and the output parameters read it. /// /// The name the column attribute gives, or for none. /// The ordinal the column attribute gives, or -1 for none. /// if a column attribute is there at all; otherwise, . /// if the property is [NotMapped]; otherwise, . /// Why a declaration is not valid, or . -readonly struct Decoration(string? column, int order, bool hasColumnAttribute, bool notMapped, string? invalid) +/// The TypeName the column attribute gives, or for none. +readonly struct Decoration(string? column, int order, bool hasColumnAttribute, bool notMapped, string? invalid, string? typeName) { const string ColumnAttributeName = "System.ComponentModel.DataAnnotations.Schema.ColumnAttribute"; const string NotMappedAttributeName = "System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute"; @@ -2562,9 +2563,12 @@ readonly struct Decoration(string? column, int order, bool hasColumnAttribute, b /// public string? Invalid => invalid; + /// Gets the TypeName the column attribute gives, or for none. + public string? TypeName => typeName; + // The default value of the struct is not this one: it would claim ordinal 0. /// Gets a that declares nothing. - public static Decoration None => new(null, -1, false, false, null); + public static Decoration None => new(null, -1, false, false, null, null); /// /// Reads what a property declares. @@ -2578,6 +2582,7 @@ public static Decoration Of(PropertyInfo property) bool hasColumn = false; bool notMapped = false; string? invalid = null; + string? typeName = null; foreach (CustomAttributeData attribute in CustomAttributeData.GetCustomAttributes(property)) { string? name = attribute.AttributeType.FullName; @@ -2598,17 +2603,22 @@ public static Decoration Of(PropertyInfo property) foreach (CustomAttributeNamedArgument named in attribute.NamedArguments) { - if (named.MemberName != "Order" || named.TypedValue.Value is not int value) continue; - - if (value >= 0) - order = value; - else - invalid ??= $"a negative [Column(Order = {value})]"; + if (named.MemberName == "TypeName") + { + if (named.TypedValue.Value is string declared) typeName = declared; + } + else if (named.MemberName == "Order" && named.TypedValue.Value is int value) + { + if (value >= 0) + order = value; + else + invalid ??= $"a negative [Column(Order = {value})]"; + } } } } - return new(column, order, hasColumn, notMapped, invalid); + return new(column, order, hasColumn, notMapped, invalid, typeName); } } diff --git a/Source/Core/DbCapture.cs b/Source/Core/DbCapture.cs index 5383433b..708c8f02 100644 --- a/Source/Core/DbCapture.cs +++ b/Source/Core/DbCapture.cs @@ -25,10 +25,10 @@ internal DbCapture(CaptureSource source) CaptureSource Source => field ?? throw Unassigned(); - CaptureSource Started(bool awaiting) + CaptureSource Awaited() { CaptureSource source = Source; - _ = source.Started(awaiting); + _ = source.Awaited(); return source; } @@ -48,7 +48,7 @@ static InvalidOperationException Unassigned() /// path="docs/members[@name='capture-stream-await']/*" /> /// public Awaiter GetAwaiter() - => new(Started(awaiting: true)); + => new(Awaited()); /// /// Configures how an of the capture continues. @@ -66,7 +66,7 @@ public Awaiter GetAwaiter() /// path="docs/members[@name='capture-stream-await']/*" /> /// public ConfiguredAwaitable ConfigureAwait(bool continueOnCapturedContext) - => new(Started(awaiting: true), continueOnCapturedContext); + => new(Awaited(), continueOnCapturedContext); /// /// Gets the capture as a task, to hand on to code that awaits it later. @@ -86,7 +86,7 @@ public ConfiguredAwaitable ConfigureAwait(bool continueOnCapturedContext) /// path="docs/members[@name='capture-before-terminal']/*" /> /// public Task AsTask() - => Source.Started(awaiting: false); + => Source.Started(); /// /// The awaiter of a capture. diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index d93342cf..f49a1b30 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -13,8 +13,10 @@ static partial class DbQueryRunner /// The type of the return code. static class ReturnOutput { - public static readonly OutputLayout Layout = ReturnLayout( - $"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>()"); + public static readonly string Display + = $"ExecuteReturnAsync<{Shape.TypeName(typeof(T))}>()"; + + public static readonly OutputLayout Layout = ReturnLayout(Display); } static OutputLayout ReturnLayout(string display) @@ -25,16 +27,16 @@ [new OutputMember(OutputLayout.ReturnValue, display, named: true)], [OutputLayout.ReturnValue]); // The captures' values one after another, then the return code. - static OutputLayout WithReturn(OutputLayout layout) - { - string display = "ExecuteReturnAsync<>()"; - return new( + static OutputLayout WithReturn(OutputLayout layout) + => new( layout.Model, layout.Members.Add( - new OutputMember(OutputLayout.ReturnValue, display, named: true)), + new OutputMember( + OutputLayout.ReturnValue, + ReturnOutput.Display, + named: true)), new int[layout.Members.Length + 1], []); - } // A call that reads an output parameter of a procedure is checked against // the procedure's parameter metadata, as a command's call is: read once for @@ -46,7 +48,7 @@ static ValueTask EnsureMetadataAsync( OutputRun output, CancellationToken cancellationToken) => output.Layout.HasOutputParameter - && names is { Home: not null, Names.Length: > 0, Metadata: null } + && names is { NeedsMetadata: true } ? ProcedureParameterMetadata.EnsureAsync( connection, definition.CommandText, @@ -64,15 +66,14 @@ static DbCommand MakeWithOutput( NameSet? names, OutputRun output) { - DbCommand command = connection.CreateCommand(); + DbCommand command = Make( + connection, + transaction, + definition, + call, + names); try { - command.Transaction = transaction; - command.CommandText = definition.CommandText; - command.CommandType = definition.Kind; - if (definition.Timeout >= 0) - command.CommandTimeout = definition.Timeout; - call.BindAll(command, definition, names); OutputBinding.Resolve( output, names, @@ -157,7 +158,7 @@ public static ValueTask ReturnAsync( cancellationToken) : CapturedAsync( definition, source, call, - captures, WithReturn, + captures, WithReturn, static (command, token) => command.ExecuteNonQueryAsync(token), static (_, run) => RowMap.ConvertScalar( run.Value(run.Layout.Members.Length - 1)), diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 5dae398c..272c7e93 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -160,10 +160,7 @@ public TThis CaptureReturn(out DbCapture returnCode) } void Attach(ICaptureSource source) - => _captures = CaptureSet.With( - _captures, - source, - onQuery: false); + => _captures = CaptureSet.WithOnCommand(_captures, source); CaptureSet? ICaptureRunner.Captures => _captures; diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 364baed9..149d3318 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -930,7 +930,7 @@ await GetProcedureParameterNamesAsync( { ProcedureKey key = ProcedureKey(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept - ? NeedsMetadata(kept) + ? kept.NeedsMetadata ? NamesWithMetadataAsync(connection, kept, cancellationToken) : new(kept) : ReadNamesAndMetadataAsync(connection, key, cancellationToken); @@ -969,17 +969,12 @@ await GetProcedureParameterNamesAsync( NameSet? names = await ReadNamesAsync(connection, key, cancellationToken) .ConfigureAwait(false); - return names is not null && NeedsMetadata(names) + return names is { NeedsMetadata: true } ? await NamesWithMetadataAsync(connection, names, cancellationToken) .ConfigureAwait(false) : names; } - // Only a procedure's own set (a text's markers never have metadata), with - // names, that has not been asked yet. - static bool NeedsMetadata(NameSet names) - => names is { Home: not null, Names.Length: > 0, Metadata: null }; - async ValueTask NamesWithMetadataAsync( TConnection connection, NameSet names, @@ -1998,13 +1993,7 @@ ValueTask IExecuteReader.ExecuteReaderAsync(Func { // A capture of the return code and this would read it twice: refused, // and the capture completed with the refusal. - if (_captures?.ReturnReader is { } returnReader) - { - throw _captures.Refuse( - new InvalidOperationException( - CaptureMessages.ReturnBeside(returnReader)), - cancellationToken); - } + _captures?.ThrowIfReturnBeside(cancellationToken); // Thrown synchronously, not through the returned task: // both tokens are checked before anything is linked (a capture on the diff --git a/Source/Core/MappedQuery.Capture.cs b/Source/Core/MappedQuery.Capture.cs index f7be7da2..be6a27df 100644 --- a/Source/Core/MappedQuery.Capture.cs +++ b/Source/Core/MappedQuery.Capture.cs @@ -93,9 +93,9 @@ public MappedQueryCore WithCapture(ICaptureSource source) CaptureSet.ThrowIfSameOwner(other, source, "query"); } - CaptureSet captures = CaptureSet.With( + CaptureSet captures = CaptureSet.WithOnQuery( _captures as CaptureSet, - source, onQuery: true); + source); return new( _command, _call, _source, _skip, _take, Options, Config, captures); diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index be335481..49a2cca7 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -103,6 +103,12 @@ public int GetHashCode(string obj) public ParameterMetadata? Metadata => Volatile.Read(ref _metadata); + /// + /// Gets whether the set is a procedure's own (a text's markers never have metadata), with names, and has not been asked for its metadata yet. + /// + public bool NeedsMetadata + => this is { Home: not null, Names.Length: > 0, Metadata: null }; + /// /// Keeps what the database said about each parameter, unless another call has kept its answer first. /// diff --git a/Source/Core/OutputBinding.cs b/Source/Core/OutputBinding.cs index 01a2d630..03ca4cea 100644 --- a/Source/Core/OutputBinding.cs +++ b/Source/Core/OutputBinding.cs @@ -265,21 +265,12 @@ static InvalidOperationException NoOutputMatch( // A decimal reaches here through the form that takes a precision and // scale; any other type through the plain named form. string call = member.Wire!.Type == DbType.Decimal - ? member.Form switch - { - OutputForm.Capture - => "Pass one of those names last to " - + "CaptureOutput(out DbCapture x, precision, scale, name) " - + "or CaptureOutputDecimal(out DbCapture x, precision, " - + "scale, name)", - OutputForm.Definition - => "Pass one of those names to Output(name, " - + "precision, scale) or OutputDecimal(name, precision, " - + "scale)", - _ => "Pass one of those names to " - + "ExecuteOutputAsync(name, precision, scale) " - + "or ExecuteOutputDecimalAsync(name, precision, scale)", - } + ? (member.Form == OutputForm.Capture + ? "Pass one of those names last to " + : "Pass one of those names to ") + + OutputArguments.ShapedCall(member.Form, "name", "precision, scale") + + " or " + + OutputArguments.DecimalCall(member.Form, "name", "precision, scale") : $"Pass one of those names to {OutputArguments.NamedCall(member.Form, "T", "name")}"; return new( diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs index 0b510539..b441d465 100644 --- a/Source/Core/OutputDbNonQuery.cs +++ b/Source/Core/OutputDbNonQuery.cs @@ -34,17 +34,10 @@ public static string Describe(DbQuery definition) public static DbQuery Model(DbQuery definition) { string model = Shape.TypeName(typeof(TOut)); - OutputLayout layout; - try - { - layout = OutputLayout.Get(OutputForm.Definition); - } - catch (InvalidOperationException ex) - { - throw new InvalidOperationException( - $"Output<{model}>() on {Describe(definition)} cannot be declared: {ex.Message}", - ex); - } + OutputLayout layout = Wrap( + definition, + $"Output<{model}>()", + static () => OutputLayout.Get(OutputForm.Definition)); if (layout.HasReturnValue && definition.Kind != CommandType.StoredProcedure) { @@ -60,10 +53,10 @@ public static DbQuery Model(DbQuery definition) public static DbQuery Named(DbQuery definition, string name) { OutputArguments.ThrowIfNoName(name, OutputForm.Definition); - return definition.WithOutput(Wrap( + return definition.WithOutput(Wrap( definition, - name, - static (n) => OutputValue.Get(n, OutputForm.Definition))); + $"Output<{Shape.TypeName(typeof(T))}>(\"{name}\")", + () => OutputValue.Get(name, OutputForm.Definition))); } public static DbQuery Shaped( @@ -73,19 +66,19 @@ public static DbQuery Shaped( byte scale) { OutputArguments.ThrowIfNoName(name, OutputForm.Definition); - Check( + string type = Shape.TypeName(typeof(T)); + return definition.WithOutput(Wrap( definition, - name, - static n => OutputValue.ThrowUnlessDecimal( - n, - OutputForm.Definition)); - OutputArguments.ThrowIfBadShape(name, precision, scale, OutputForm.Definition); - return definition.WithOutput(OutputValue.Shaped( - name, - precision, - scale, - $"Output<{Shape.TypeName(typeof(T))}>(\"{name}\", {precision}, {scale})", - OutputForm.Definition)); + $"Output<{type}>(\"{name}\")", + () => + { + OutputValue.ThrowUnlessDecimal(name, OutputForm.Definition); + return DecimalLayout( + name, + precision, + scale, + $"Output<{type}>(\"{name}\", {precision}, {scale})"); + })); } public static DbQuery Decimal( @@ -95,40 +88,42 @@ public static DbQuery Decimal( byte scale) { OutputArguments.ThrowIfNoName(name, OutputForm.Definition); - OutputArguments.ThrowIfBadShape(name, precision, scale, OutputForm.Definition); - return definition.WithOutput(OutputValue.Shaped( + return definition.WithOutput(DecimalLayout( name, precision, scale, - $"OutputDecimal(\"{name}\", {precision}, {scale})", - OutputForm.Definition)); + $"OutputDecimal(\"{name}\", {precision}, {scale})")); } - // The same, for a check that returns nothing. - static void Check(DbQuery definition, string name, Action check) - => Wrap( - definition, + static OutputLayout DecimalLayout( + string name, + byte precision, + byte scale, + string display) + { + OutputArguments.ThrowIfBadShape(name, precision, scale, OutputForm.Definition); + return OutputValue.Shaped( name, - n => - { - check(n); - return null!; - }); + precision, + scale, + display, + OutputForm.Definition); + } // Names the definition in the message of a refusal. - static OutputLayout Wrap( + static OutputLayout Wrap( DbQuery definition, - string name, - Func check) + string call, + Func declare) { try { - return check(name); + return declare(); } catch (InvalidOperationException ex) { throw new InvalidOperationException( - $"Output<{Shape.TypeName(typeof(T))}>(\"{name}\") on {Describe(definition)} cannot be declared: {ex.Message}", + $"{call} on {Describe(definition)} cannot be declared: {ex.Message}", ex); } } diff --git a/Source/Core/OutputLayout.cs b/Source/Core/OutputLayout.cs index 9d63dfdd..8b62ac77 100644 --- a/Source/Core/OutputLayout.cs +++ b/Source/Core/OutputLayout.cs @@ -534,7 +534,7 @@ static string Refusal(OutputForm form) string display = $"{model}.{slot.Name}"; if (slot.ColumnName is null && slot.Name.Equals(OutputLayout.ReturnValue, StringComparison.OrdinalIgnoreCase)) { - if (ReturnCode.Holds(slot.Type)) return new OutputMember(label, display); + if (ReturnCode.Holds(slot.Type)) return new OutputMember(label, display); error = $"{display} reads the return code, which is one integer, so {Shape.TypeName(slot.Type)} cannot hold it. Change {display} to int (or int?, long, an enum)."; return null; @@ -561,7 +561,6 @@ static string Refusal(OutputForm form) return null; } - // Read by full name, as RowMap reads [Column]: a consumer's own copy of the attribute counts. A positional record declares it with [property: Column(...)]. /// /// Returns the TypeName the member's property declares with [Column], or . /// @@ -571,22 +570,11 @@ static string Refusal(OutputForm form) { if (!slot.IsProperty) return null; - // The first property of the name, as the slots take it. + // The first property of the name, as the slots take it. A positional + // record declares the attribute with [property: Column(...)]. foreach (PropertyInfo property in typeof(TOut).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { - if (property.Name != slot.Name) continue; - - foreach (CustomAttributeData attribute in CustomAttributeData.GetCustomAttributes(property)) - { - if (attribute.AttributeType.FullName != "System.ComponentModel.DataAnnotations.Schema.ColumnAttribute") continue; - - foreach (CustomAttributeNamedArgument named in attribute.NamedArguments) - { - if (named.MemberName == "TypeName" && named.TypedValue.Value is string typeName) return typeName; - } - } - - return null; + if (property.Name == slot.Name) return Decoration.Of(property).TypeName; } return null; @@ -883,15 +871,10 @@ public TOut Map() } /// -/// Whether a type can hold a return code, worked out once per type. +/// Whether a type can hold a return code, and the message when it cannot. /// -/// The type. -static class ReturnCode +static class ReturnCode { - /// Whether can hold the return code: a - /// single value, or . - public static bool IsValue { get; } = Holds(typeof(T)); - /// /// Whether a type can hold the return code: a single value, or . /// @@ -900,6 +883,25 @@ static class ReturnCode public static bool Holds(Type type) => type == typeof(object) || Shape.IsScalar(type); + /// + /// Says that a type cannot hold the return code, and what can. + /// + /// The type, or the member, as the message names it. + /// The message. + public static string Message(string shown) + => $"The return code is one integer, so {shown} cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."; +} + +/// +/// Whether a type can hold a return code, worked out once per type. +/// +/// The type. +static class ReturnCode +{ + /// Whether can hold the return code: a + /// single value, or . + public static bool IsValue { get; } = ReturnCode.Holds(typeof(T)); + /// /// Throws when is a model, which cannot hold the return code. /// @@ -908,16 +910,9 @@ public static void ThrowUnlessScalar() { if (IsValue) return; - throw new InvalidOperationException(Message(Shape.TypeName(typeof(T)))); + throw new InvalidOperationException( + ReturnCode.Message(Shape.TypeName(typeof(T)))); } - - /// - /// Says that a type cannot hold the return code, and what can. - /// - /// The type, or the member, as the message names it. - /// The message. - public static string Message(string shown) - => $"The return code is one integer, so {shown} cannot hold it. Use int (or int?, long, an enum), or a ReturnValue member on the output model."; } /// @@ -984,14 +979,20 @@ public static string NamedCall( /// /// The members the call comes from. /// The name as the call writes it. - /// The call, written for decimal(19,4). - public static string ShapedCall(OutputForm form, string argument) + /// The precision and scale as the call writes + /// them. + /// The call, written for decimal(19,4) unless + /// says otherwise. + public static string ShapedCall( + OutputForm form, + string argument, + string shape = "19, 4") => form switch { OutputForm.Capture - => $"CaptureOutput(out DbCapture x, 19, 4, {argument})", - OutputForm.Definition => $"Output({argument}, 19, 4)", - _ => $"ExecuteOutputAsync({argument}, 19, 4)", + => $"CaptureOutput(out DbCapture x, {shape}, {argument})", + OutputForm.Definition => $"Output({argument}, {shape})", + _ => $"ExecuteOutputAsync({argument}, {shape})", }; /// @@ -1000,14 +1001,20 @@ public static string ShapedCall(OutputForm form, string argument) /// /// The members the call comes from. /// The name as the call writes it. - /// The call, written for decimal(19,4). - public static string DecimalCall(OutputForm form, string argument) + /// The precision and scale as the call writes + /// them. + /// The call, written for decimal(19,4) unless + /// says otherwise. + public static string DecimalCall( + OutputForm form, + string argument, + string shape = "19, 4") => form switch { OutputForm.Capture - => $"CaptureOutputDecimal(out DbCapture x, 19, 4, {argument})", - OutputForm.Definition => $"OutputDecimal({argument}, 19, 4)", - _ => $"ExecuteOutputDecimalAsync({argument}, 19, 4)", + => $"CaptureOutputDecimal(out DbCapture x, {shape}, {argument})", + OutputForm.Definition => $"OutputDecimal({argument}, {shape})", + _ => $"ExecuteOutputDecimalAsync({argument}, {shape})", }; /// diff --git a/docsite/samples/OutputParameters.cs b/docsite/samples/OutputParameters.cs index 459a01f6..bfaa0cb7 100644 --- a/docsite/samples/OutputParameters.cs +++ b/docsite/samples/OutputParameters.cs @@ -11,9 +11,12 @@ public static class OutputParameters { public const string ConnectionVariable = "SAMPLES_BLOG_CONNECTION"; + // An empty variable counts as none. static readonly SqlConnectionFactory Blog = new( - Environment.GetEnvironmentVariable(ConnectionVariable) - ?? @"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); + Environment.GetEnvironmentVariable(ConnectionVariable) is { } connection + && !string.IsNullOrWhiteSpace(connection) + ? connection + : @"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); #region sql_server_output_def_model // The procedure declares @id and @created_utc as OUTPUT and ends with a RETURN code. From 942a2cc0cbeb3cc5d475651bf08cc24ad23e310f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:15:41 -0800 Subject: [PATCH 2/3] Comments, names and rules: no behavior change, no public API change Members of internal types are public or private, not internal (the channel and dataflow pumps, the parameter-name caches and sets, the schema-name reader, the view builders, the row reader, and the row-map helper types). ProcedureKey becomes a primary-constructor struct, as the analyzer asks once its constructor is public. The tests and benchmarks that reach these members by reflection look for public members now. Messages that said what is wrong now also say what to do: a blank command, a command whose type does not match the connection's provider, concurrent use of a single connection, a reader of the wrong type, and a transaction with no connection (the SQL Server package test that pins the transaction text and the blank-command test follow the new text). Names and comments: - the ExpressiveCommandBase method that built the procedure key is called KeyOf, and the producer's count of rows already handed on is _handedOn, so neither shares a word with a type or with the one-shot flag of the streams; - the generator's styleB flag is buildsAfterReading, and the Slot calls name their bool arguments; - the RowReader stream flag that meant "rows still to map" is reading. Comments only: a comment about DbQuery no longer sits above ExpressiveCommandBase; the long comments there are wrapped and placed over the members they describe; the no-timeout dispose rationale is written once, in the ChunkProducer header, and the buffer and the stream point to it; comments that cited a spike or a proof now say the record is not kept in the repository, or drop the citation; the CapturedStream header is shorter and states why ToException may cast; a dangling comment in RowMap is gone; the TextNameCache note moved into its remarks; two RowReader doc blocks are indented, and the second ToArray path says why its sink is disposed by hand; the Emitter header no longer cites a missing file and is wrapped at 80 columns; the three sentences that Stream and StreamBuffered repeat in IMappedQuery are one include. Cost: none (no per-call or per-row code changed). Co-Authored-By: Claude Sonnet 5.5 --- .../TextNameScanBenchmarks.cs | 8 +- Source/Channel/ChannelPump.cs | 6 +- Source/Core/CapturedStream.cs | 17 ++-- Source/Core/ChunkConfig.cs | 3 +- Source/Core/ChunkProducer.cs | 19 ++++- Source/Core/ChunkStream.cs | 15 +--- Source/Core/Core/RowMap.cs | 8 +- Source/Core/Core/RowReader.cs | 56 +++++++------ Source/Core/DbQueryBinding.cs | 2 +- Source/Core/DirectStream.cs | 2 +- Source/Core/ExpressiveCommandBase.cs | 30 ++++--- .../Extensions/Transaction.CreateCommand.cs | 6 +- Source/Core/IMappedQuery.cs | 8 +- Source/Core/Mapped.docs.xml | 7 ++ Source/Core/MappedViews.cs | 16 ++-- Source/Core/NameSet.cs | 12 +-- Source/Core/PooledBuffer.cs | 18 +--- Source/Core/ProcedureParameterNames.cs | 32 +++---- Source/Core/ProcedureSchemaNames.cs | 6 +- Source/Core/RecycleBin.cs | 2 +- Source/Core/TextNameCache.cs | 9 +- Source/Dataflow/BlockPump.cs | 4 +- Source/Generator/Emitter.cs | 84 ++++++++++++------- Source/Generator/ModelReader.cs | 10 ++- .../Extensions/Transaction.CreateCommand.cs | 4 +- .../DbQueryChecksTests.cs | 2 +- .../DerivedNameCostTests.cs | 4 +- .../SqlServerPackageTests.cs | 2 +- 28 files changed, 207 insertions(+), 185 deletions(-) diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/TextNameScanBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/TextNameScanBenchmarks.cs index bcfbb722..8c82c486 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/TextNameScanBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/TextNameScanBenchmarks.cs @@ -33,11 +33,11 @@ public class TextNameScanBenchmarks static readonly Type NameSet = Core.GetType("Open.Database.Extensions.NameSet", throwOnError: true)!; static readonly Func Scan - = Cache.GetMethod("Scan", BindingFlags.Static | BindingFlags.NonPublic)!.CreateDelegate>(); + = Cache.GetMethod("Scan", BindingFlags.Static | BindingFlags.Public)!.CreateDelegate>(); // The new path's lookup: null for a text that is not interned (the text is then scanned). static readonly Func Get - = Cache.GetMethod("Get", BindingFlags.Static | BindingFlags.NonPublic)!.CreateDelegate>(); + = Cache.GetMethod("Get", BindingFlags.Static | BindingFlags.Public)!.CreateDelegate>(); // The parsed way: read the text into a set of names and match each argument in it, as the set of a remembered text does. static readonly Func Parse @@ -55,7 +55,7 @@ static readonly Func> Tokens static Func, object> BuildMakeSet() { ParameterExpression names = Expression.Parameter(typeof(ImmutableArray)); - ConstructorInfo constructor = NameSet.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0]; + ConstructorInfo constructor = NameSet.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; NewExpression made = constructor.GetParameters().Length == 1 ? Expression.New(constructor, names) : Expression.New(constructor, names, Expression.Constant(false)); @@ -67,7 +67,7 @@ static Func, object> BuildMakeSet() ParameterExpression set = Expression.Parameter(typeof(object)); ParameterExpression expression = Expression.Parameter(typeof(string)); ParameterExpression procedure = Expression.Parameter(typeof(string)); - MethodInfo match = NameSet.GetMethod("Match", BindingFlags.Instance | BindingFlags.NonPublic)!; + MethodInfo match = NameSet.GetMethod("Match", BindingFlags.Instance | BindingFlags.Public)!; return Expression.Lambda>( Expression.Call(Expression.Convert(set, NameSet), match, expression, procedure), set, diff --git a/Source/Channel/ChannelPump.cs b/Source/Channel/ChannelPump.cs index fee0b8a8..3f379f34 100644 --- a/Source/Channel/ChannelPump.cs +++ b/Source/Channel/ChannelPump.cs @@ -20,7 +20,7 @@ internal static class ChannelPump /// /// /// The number of rows handed to the writer. - internal static async ValueTask Run( + public static async ValueTask Run( TFeed feed, ChannelWriter writer, bool complete, @@ -67,7 +67,7 @@ internal static async ValueTask Run( /// // Not async: with room now, it returns the enumerator with no frame and // nothing allocated. Only a wait, a closed writer or a failure goes on. - internal static ValueTask?> Open( + public static ValueTask?> Open( IAsyncEnumerable stream, ChannelWriter writer, CancellationToken cancellationToken) @@ -127,7 +127,7 @@ await rows.DisposeAsync() /// /// The position of the first row not written. // The only code that holds a span: nothing can await while it lives. - internal static int TryWriteFrom( + public static int TryWriteFrom( ChannelWriter writer, ReadOnlyMemory chunk, int start) diff --git a/Source/Core/CapturedStream.cs b/Source/Core/CapturedStream.cs index 58f124fc..001e3620 100644 --- a/Source/Core/CapturedStream.cs +++ b/Source/Core/CapturedStream.cs @@ -1,15 +1,12 @@ namespace Open.Database.Extensions; // A stream that fills captures (see Capture.cs). -// Its GetAsyncEnumerator is the claim (the arm), so a second enumeration, or -// a run of the command by another route, gets the second-run message. -// While its enumerator is open the captures may not be awaited: the loop -// that reads the stream would wait on itself. -// -// A consumer that stops early (a break, or a dispose before the last row) -// is told apart from a cancel of the caller: the read is not cancelled, the -// reader is closed, and closing it reads the rest of the response, the -// output parameters included, so the run delivers the captures. +// Its GetAsyncEnumerator is the claim, so a second enumeration, or a run of +// the command by another route, gets the second-run message; while the +// enumerator is open the captures may not be awaited (the loop that reads the +// stream would wait on itself). +// A consumer that stops early does not cancel the read: the reader is closed, +// which reads the rest of the response, the output parameters included. // The inner stream's dispose waits for its read, so the captures are // complete when this dispose returns. /// @@ -38,6 +35,8 @@ public TItem Current public CancellationToken Expired => (inner as IStallSignal)?.Expired ?? default; + // Called only after Expired fired, and it fires only for an inner stream that + // is an IStallSignal: without one it is default, which never fires. public TimeoutException ToException() => ((IStallSignal)inner).ToException(); diff --git a/Source/Core/ChunkConfig.cs b/Source/Core/ChunkConfig.cs index 6f087092..b6d2c544 100644 --- a/Source/Core/ChunkConfig.cs +++ b/Source/Core/ChunkConfig.cs @@ -48,7 +48,8 @@ internal sealed class ChunkConfig( /// rows of a chunk are cleared in the recycle bin instead of where the chunk /// is released. /// - // Measured (the recycle bin proof, paced so the bin never fills, .NET 10). + // Measured on .NET 10 with the bin paced so it never fills (a one-off probe; + // its record is not kept in this repository). // Clearing where the chunk is released costs the releasing thread about 8 to // 20 ns per KB (int rows: 154 ns at 16 KB, 526 ns at 64 KB, 1.8 microseconds // at 256 KB; rows of 80 bytes without references: 21 microseconds at 1.3 MB, diff --git a/Source/Core/ChunkProducer.cs b/Source/Core/ChunkProducer.cs index f4064937..09e2ec3b 100644 --- a/Source/Core/ChunkProducer.cs +++ b/Source/Core/ChunkProducer.cs @@ -71,6 +71,19 @@ namespace Open.Database.Extensions.Core; // - The rows read before a failure or a cancel are delivered first: the // buffer that is still being filled is handed over (sealed) before // IChunkTarget.Finish. +// - The owner's dispose waits for the producer, and the wait has no timeout, +// on purpose: correctness (no array goes back while the producer might +// still write) comes before promptness. +// So a dispose waits for the provider call in progress (the execute, or a +// read) to return; a provider that ignores the cancel token delays it by +// that call. +// After that the producer stops at the next chunk boundary at the latest: +// the read loop checks the token per row in the default read mode, the +// provider does in the async read mode, and the producer checks once per +// chunk. +// So with AsyncReads() and a provider that ignores the token, a dispose or +// a cancel is seen at the next chunk (a buffer's chunks double: up to the +// rows of the current chunk; a stream's are by default 16 to 4,096 rows). // // Invariants. // @@ -141,12 +154,12 @@ readonly CancellationTokenSource _linked /// The rows in the buffers already handed on. /// Moves once per buffer, in , never per row. - int _taken; + int _handedOn; /// Gets the number of rows stored so far. // Read when a row fails to map, to name the row. public int Count - => _taken + _next; + => _handedOn + _next; /// /// Starts the producer, once. A token that is already cancelled @@ -356,7 +369,7 @@ void Advance() ArrayLease Take() { ArrayLease lease = config.Seal(_array!, _next); - _taken += _next; + _handedOn += _next; _array = null; _next = 0; _limit = 0; diff --git a/Source/Core/ChunkStream.cs b/Source/Core/ChunkStream.cs index a4b83da4..8cfd0d22 100644 --- a/Source/Core/ChunkStream.cs +++ b/Source/Core/ChunkStream.cs @@ -50,17 +50,10 @@ namespace Open.Database.Extensions.Core; // producer (so nothing can write any more), and only then releases every // array still in the channel. // -// The wait has no timeout, on purpose (an await in a -// finally is legal; only a yield is -// not): correctness, meaning no array goes back while the producer might -// still write, comes before promptness. -// So a break or a dispose waits for the provider call in progress (the -// execute, or a read) to return. -// A provider that ignores the cancel token delays it by that call. -// After that the producer stops at the next chunk boundary at the latest: -// the read loop checks the token per row in the default read mode, the -// provider does in the async read mode, and the producer checks once per -// chunk (a stream's chunks are by default 16 to 4,096 rows). +// The wait has no timeout, on purpose (an await in a finally is legal; only a +// yield is not), so a break or a dispose waits for the provider call in +// progress to return; why, and where the producer stops, is in the header of +// ChunkProducer. // // A pool whose Return throws surfaces at the release (the next step, // or the dispose) and replaces what the consumer was already about to see; diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index f1e46875..376d0d59 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -449,8 +449,6 @@ RowMap Converting( return new RowMap(_slots, _slotIndex, _factory, columns, named, converters); } - // The compiled, cached readers of a layout are described on Layout. - // The per-layout reader cache is bounded so dynamically generated column lists cannot grow memory forever. // Real applications use a handful of layouts; when the bound is hit the cache is simply cleared and refills. /// The number of layouts a map keeps readers for before its cache is cleared. @@ -2098,7 +2096,7 @@ static object GetConverted(object value, Type u) /// static class TypedGetters { - internal static readonly FrozenDictionary ByType = new Dictionary() + public static readonly FrozenDictionary ByType = new Dictionary() { [typeof(bool)] = nameof(IDataRecord.GetBoolean), [typeof(byte)] = nameof(IDataRecord.GetByte), @@ -2128,7 +2126,7 @@ static class TypedGetters /// The type of the single value. internal sealed class FirstColumn : IRowSource { - internal static readonly FirstColumn? Instance + public static readonly FirstColumn? Instance = Shape.IsScalar(typeof(T)) ? new() : null; sealed class Entry(Type columnType) @@ -2785,7 +2783,7 @@ public void ThrowIfUnmappable() /// /// of these is one too. /// - internal static bool IsScalar(Type type) + public static bool IsScalar(Type type) { type = Nullable.GetUnderlyingType(type) ?? type; // DateOnly and TimeOnly are matched by name, so every target framework agrees (the netstandard builds cannot name them). diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index 4d391b73..e97b3e63 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -257,6 +257,8 @@ public static T[] ToArray( if (!SkipRows(db, skip) || !db.Read()) return []; Func map = source.Mapper(db); + + // A mutable struct again, so it is disposed by hand, as above. var buffer = new ArraySink(config); try { @@ -368,20 +370,20 @@ public static bool TrySingle(IRowSource source, IDataReader reader, int sk public static IEnumerable Stream(IRowSource source, IDataReader reader, int skip, int take, bool readThrough = false, ReaderAbandon? abandon = null, CancellationToken token = default) { int first = skip; // The row number of the first row mapped: skip counts down below. - bool skipped = !TakesNone(take, abandon, reader); + bool reading = !TakesNone(take, abandon, reader); - if (skipped) + if (reading) { for (; skip > 0; skip--) { token.ThrowIfCancellationRequested(); if (reader.Read()) continue; - skipped = false; + reading = false; break; } } - if (skipped) + if (reading) { int n = 0; if (reader is DbDataReader db) @@ -449,18 +451,18 @@ public static IEnumerable Stream(IRowSource source, IDataReader reader, if (readThrough && live) ReadThrough(reader, token); } -/// -/// Moves past every later result set without reading its rows. -/// -/// -/// The provider raises a failure in one of them here. -/// A canceled token throws before each NextResult; -/// once one returns the read is done. -/// -/// The reader positioned on a result set. -/// The token that cancels the read. -/// is canceled. - internal static void ReadThrough( + /// + /// Moves past every later result set without reading its rows. + /// + /// + /// The provider raises a failure in one of them here. + /// A canceled token throws before each NextResult; + /// once one returns the read is done. + /// + /// The reader positioned on a result set. + /// The token that cancels the read. + /// is canceled. + public static void ReadThrough( IDataReader reader, CancellationToken token = default) { @@ -512,15 +514,15 @@ static T MapAt(IRowSource source, Func map, TReader r static InvalidOperationException MoreThanOne() => new("Sequence contains more than one element."); -/// -/// Creates the exception the throwing terminals (First, Single) raise when the query returned no row. -/// -/// -/// It is thrown after the reader is cleaned up. -/// -/// The name of the terminal that needs a row. -/// The exception to throw. - internal static InvalidOperationException NoRows(string terminal) + /// + /// Creates the exception the throwing terminals (First, Single) raise when the query returned no row. + /// + /// + /// It is thrown after the reader is cleaned up. + /// + /// The name of the terminal that needs a row. + /// The exception to throw. + public static InvalidOperationException NoRows(string terminal) => new($"Sequence contains no elements: the query returned no rows, and {terminal} needs one."); #endregion @@ -739,7 +741,7 @@ public static async ValueTask CountAsync( } // For the loops that map nothing, so one loop serves every reader: a bare IDataReader has only Read. - internal static ValueTask NextRowAsync(IDataReader reader, bool useReadAsync, CancellationToken cancellationToken) + public static ValueTask NextRowAsync(IDataReader reader, bool useReadAsync, CancellationToken cancellationToken) { if (reader is DbDataReader db) return ReadRowAsync(db, useReadAsync, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); @@ -801,7 +803,7 @@ public static async IAsyncEnumerable StreamAsync( if (readThrough && live) await ReadThroughAsync(reader, cancellationToken).ConfigureAwait(false); } - internal static ValueTask ReadThroughAsync(IDataReader reader, CancellationToken token) + public static ValueTask ReadThroughAsync(IDataReader reader, CancellationToken token) { if (reader is not DbDataReader db) { diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index bcf5afb5..31c88180 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -299,7 +299,7 @@ static bool Has(DbCommand command, string name) public static bool SameName(string a, string b) => Bare(a).Equals(Bare(b), StringComparison.OrdinalIgnoreCase); - internal static ReadOnlySpan Bare(string name) + public static ReadOnlySpan Bare(string name) => name.Length > 0 && name[0] == '@' ? name.AsSpan(1) : name.AsSpan(); diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 82006a6a..9ac0e054 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -16,7 +16,7 @@ namespace Open.Database.Extensions.Core; // // Why a periodic timer and not one CancellationTokenSource armed with CancelAfter at each hand-over: // - Cost. Here a hand-over costs one clock read. CancelAfter changes a timer twice per row (armed at the hand-over, disarmed at the pull). In a -// comparison with an in-memory reader (2026-11-29, ratios for comparison only; absolute times vary by machine) that took 27 to 30 % longer for +// comparison with an in-memory reader (2026-11-29, record not kept in this repository; ratios only, absolute times vary by machine) that took 27 to 30 % longer for // streams of 1,000 and 100,000 rows, about 20 ns more per row. // - Correctness (from reading the code and how .NET timers behave; not reproduced). A CancelAfter timer that has fired cannot be taken back by // disarming it. A callback that runs late (a starved thread pool) can expire a consumer that did not stall, or be used up just before a hand-over diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 149d3318..ca11e6a9 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -3,7 +3,6 @@ namespace Open.Database.Extensions; -// DbQuery scans its text once and holds its parameters in one array. A literal is interned text, which is what lets the written-name spelling be resolved once. /// /// Represents the base class of the expressive commands, for use with /// and types. @@ -110,7 +109,7 @@ private protected sealed class CommandOptions static string CheckedCommand(string command) { if (command is null) throw new ArgumentNullException(nameof(command)); - if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException("Cannot be null or whitespace.", nameof(command)); + if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException("The command cannot be empty or white space. Pass the SQL text or the name of the stored procedure.", nameof(command)); Contract.EndContractBlock(); return command; @@ -315,7 +314,7 @@ TCommand PrepareCommand(TConnection connection, OutputRun? output) try { if (cmd is not TCommand c) - throw new InvalidCastException($"Actual command type ({cmd.GetType()}) is not compatible with expected command type ({typeof(TCommand)})."); + throw new InvalidCastException($"Actual command type ({cmd.GetType()}) is not compatible with expected command type ({typeof(TCommand)}). Use a connection whose provider creates {typeof(TCommand).Name} commands."); if (Transaction != null) c.Transaction = Transaction; if ((ActiveSendList ?? _params) is { Count: > 0 }) AddParams(c); @@ -859,7 +858,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs { if (Type == CommandType.StoredProcedure) { - ProcedureKey key = ProcedureKey(connection); + ProcedureKey key = KeyOf(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) ?? ProcedureParameterNames.Remember(NameCacheOwner, key, GetProcedureParameterNames(connection, Command)); } @@ -886,7 +885,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs { if (Type == CommandType.StoredProcedure) { - ProcedureKey key = ProcedureKey(connection); + ProcedureKey key = KeyOf(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept ? new(kept) : ReadNamesAsync(connection, key, cancellationToken); @@ -928,7 +927,7 @@ await GetProcedureParameterNamesAsync( { if (Type == CommandType.StoredProcedure) { - ProcedureKey key = ProcedureKey(connection); + ProcedureKey key = KeyOf(connection); return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept ? kept.NeedsMetadata ? NamesWithMetadataAsync(connection, kept, cancellationToken) @@ -1065,13 +1064,18 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f _ => _poolOrConnection, }; - // The server and the database are part of the key: one connection can be switched to another database, and one factory can hand out connections to different servers, where the same procedure name may be a different procedure. IDbConnection has no server name, so a connection that is not a DbConnection contributes none. The key is a struct of the three parts, so no string is built. /// /// Makes the key a procedure's names are remembered under. /// /// The connection the procedure is looked up on. /// The key of on that connection. - ProcedureKey ProcedureKey(TConnection connection) => new((connection as DbConnection)?.DataSource, connection.Database, Command); + // The server and the database are part of the key: one connection can be + // switched to another database, and one factory can hand out connections to + // different servers, where the same procedure name may be a different + // procedure. IDbConnection has no server name, so a connection that is not + // a DbConnection contributes none. The key is a struct of the three parts, + // so no string is built. + ProcedureKey KeyOf(TConnection connection) => new((connection as DbConnection)?.DataSource, connection.Database, Command); /// /// Builds, in , what one run of a command with written names sends: each name that the text declares @@ -1234,7 +1238,6 @@ InvalidOperationException NoMatch(string expression, ImmutableArray real #region Execution core - // Every execution path funnels through this method and ExecuteCoreAsync. The caller's inputs travel in TState (a value type for the typed paths) and the functions are static lambdas, so a call allocates no closures or delegates of its own. The connection is opened before the command is created, as some IDbCommand implementations require it. /// /// Runs a function on a command built on a connection from the source, /// synchronously. @@ -1250,6 +1253,11 @@ InvalidOperationException NoMatch(string expression, ImmutableArray real /// before it was opened, and . /// /// The result of . + // Every execution path funnels through this method and ExecuteCoreAsync. + // The caller's inputs travel in TState (a value type for the typed paths) + // and the functions are static lambdas, so a call allocates no closures or + // delegates of its own. The connection is opened before the command is + // created, as some IDbCommand implementations require it. private protected TResult ExecuteCore(TState state, Func func) { // Captures are async only: refused before anything runs, and nothing is @@ -1499,7 +1507,7 @@ TResult ExecuteDirect(TConnection single, TState state, Func IExecuteCommand.ExecuteAsync(Func> tran /// The reader is not a . protected static TReader EnsureReaderType(TActual reader) where TActual : IDataReader - => reader is TReader r ? r : throw new InvalidCastException($"Expected reader type of ({typeof(TReader)}). Actual: ({reader.GetType()})"); + => reader is TReader r ? r : throw new InvalidCastException($"Expected reader type of ({typeof(TReader)}). Actual: ({reader.GetType()}). Use a connection whose provider returns {typeof(TReader).Name} readers, or read through the IDataReader overloads."); /// internal TResult ExecuteReader(TState state, Func transform, CommandBehavior behavior = CommandBehavior.Default) diff --git a/Source/Core/Extensions/Transaction.CreateCommand.cs b/Source/Core/Extensions/Transaction.CreateCommand.cs index a06fc46e..b426f496 100644 --- a/Source/Core/Extensions/Transaction.CreateCommand.cs +++ b/Source/Core/Extensions/Transaction.CreateCommand.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; /// /// Extension methods for database transactions that do not depend on a specific database provider. @@ -19,7 +19,7 @@ public static IDbCommand CreateCommand(this IDbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); IDbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); @@ -72,7 +72,7 @@ public static DbCommand CreateCommand(this DbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); DbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); diff --git a/Source/Core/IMappedQuery.cs b/Source/Core/IMappedQuery.cs index 200546c9..1db7520d 100644 --- a/Source/Core/IMappedQuery.cs +++ b/Source/Core/IMappedQuery.cs @@ -29,9 +29,7 @@ IAsyncEnumerable> ToPooledBufferStream( /// To read while the query runs, use , which releases it when the read ends. /// If you go without pulling the next row, the read stops, the command is cancelled, /// the connection this library opened is closed, and your next pull throws . - /// Dispose the enumeration (await foreach does). - /// The rows are read with Read() on your thread unless the query asked for AsyncReads(), so a slow database read blocks your thread for its wait; a cancel cannot interrupt a read the provider is blocked in, so the command's CommandTimeout bounds it, and a cancel while you hold a row is seen at your next pull. - /// A timer checks the stall timeout, so an expiry is found up to about a quarter of the timeout (at least 10 ms) after the timeout has passed, never before it. + /// /// /// /// @@ -55,9 +53,7 @@ IAsyncEnumerable Stream( /// If the buffer is full and you go without pulling the next row, the read stops, the command is cancelled, /// the connection this library opened is closed, and your next pull throws . /// Rows still waiting in the buffer when the stall trips are discarded, not delivered. - /// Dispose the enumeration (await foreach does). - /// The rows are read with Read() on your thread unless the query asked for AsyncReads(), so a slow database read blocks your thread for its wait; a cancel cannot interrupt a read the provider is blocked in, so the command's CommandTimeout bounds it, and a cancel while you hold a row is seen at your next pull. - /// A timer checks the stall timeout, so an expiry is found up to about a quarter of the timeout (at least 10 ms) after the timeout has passed, never before it. + /// /// /// /// diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index 7823bcaa..4be64684 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -281,6 +281,13 @@ The state to pass to the transform. The function that processes the data reader. + + + Dispose the enumeration (await foreach does). + The rows are read with Read() on your thread unless the query asked for AsyncReads(), so a slow database read blocks your thread for its wait; a cancel cannot interrupt a read the provider is blocked in, so the command's CommandTimeout bounds it, and a cancel while you hold a row is seen at your next pull. + A timer checks the stall timeout, so an expiry is found up to about a quarter of the timeout (at least 10 ms) after the timeout has passed, never before it. + + Three ways to read the rows as they arrive; pick by what the connection and your loop need: diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index 16a7a2ff..b1817441 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -267,7 +267,7 @@ static class Views /// /// has a bit that is not one of the switches. /// - internal static QueryOptions CheckedOptions(QueryOptions options) + public static QueryOptions CheckedOptions(QueryOptions options) => (options & ~AllOptions) == QueryOptions.None ? options : throw new ArgumentOutOfRangeException( @@ -291,12 +291,12 @@ const QueryOptions AllOptions /// /// The type each row is mapped to. /// The source that reads and maps one row. - internal static IRowSource DefaultSource() + public static IRowSource DefaultSource() => FirstColumn.Instance is { } firstColumn ? firstColumn : RowMap.Default; - internal static MappedQueryCore QueryCore( + public static MappedQueryCore QueryCore( IExecuteReader command, IRowSource source) => command is SingleResultReader single @@ -310,7 +310,7 @@ internal static MappedQueryCore QueryCore( /// The call. /// Reads and maps one row. /// The new query core. - internal static MappedQueryCore QueryCore( + public static MappedQueryCore QueryCore( DbQueryCall call, IRowSource source) => NewCore(null, call, source, QueryOptions.None); @@ -324,7 +324,7 @@ internal static MappedQueryCore QueryCore( /// Reads and maps one row. /// The switches of the definition. /// The new query core. - internal static MappedQueryCore QueryCore( + public static MappedQueryCore QueryCore( DbQueryCall call, IRowSource source, QueryOptions options) @@ -361,14 +361,14 @@ DbQueryUsing bound static bool AsyncReads(IExecuteReader command) => command is IExecuteReaderAsync { UseAsyncRead: true }; - internal static MappedQueryCore ReaderCore( + public static MappedQueryCore ReaderCore( IDataReader reader, IRowSource source) => NewCore( new ReaderExecutor(reader), default, source, QueryOptions.SingleResult); - internal static MappedQueryCore CommandCore( + public static MappedQueryCore CommandCore( IDbCommand command, IRowSource source) => command is SingleResultDbCommand single @@ -379,7 +379,7 @@ internal static MappedQueryCore CommandCore( new CommandExecutor(command), default, source, QueryOptions.None); - internal static MappedQueryCore TableCore( + public static MappedQueryCore TableCore( DataTable table, IRowSource source) => NewCore( diff --git a/Source/Core/NameSet.cs b/Source/Core/NameSet.cs index 49a2cca7..35ac64b3 100644 --- a/Source/Core/NameSet.cs +++ b/Source/Core/NameSet.cs @@ -34,7 +34,7 @@ sealed class NameSet /// What it is kept under. // The names are set here, before the set is published, and never change; // the only field written afterwards is the metadata (once). - internal NameSet(ImmutableArray names, WeakReference? home = null, ProcedureKey key = default) + public NameSet(ImmutableArray names, WeakReference? home = null, ProcedureKey key = default) { Debug.Assert(!names.IsDefault, "A set is made from names, not from 'not known'."); Home = home; @@ -51,16 +51,16 @@ internal NameSet(ImmutableArray names, WeakReferenceThe names as the provider reported them. - internal ImmutableArray Names { get; } + public ImmutableArray Names { get; } /// The same names without a leading @. - internal ImmutableArray BareNames { get; } + public ImmutableArray BareNames { get; } /// One name of the set, with its place in it. /// The name as the set holds it, with its @ when it has one. /// The place of the name in . // Held once per set: a call that stores it allocates nothing, and a call that binds it knows its place without looking the name up. - internal sealed class Entry(string real, int index) + public sealed class Entry(string real, int index) { /// Gets the name as the set holds it. public string Real { get; } = real; @@ -74,7 +74,7 @@ internal sealed class Entry(string real, int index) /// sealed class BareComparer : IEqualityComparer { - internal static readonly BareComparer Instance = new(); + public static readonly BareComparer Instance = new(); public bool Equals(string? x, string? y) => DbQueryBinding.Bare(x!).Equals(DbQueryBinding.Bare(y!), StringComparison.OrdinalIgnoreCase); @@ -188,7 +188,7 @@ Dictionary BuildEntries() /// The real name, or when the expression matches none. /// The expression is not derivable. /// The expression fits more than one name equally well. - internal string? Match(string expression, string procedure, string? subject = null) + public string? Match(string expression, string procedure, string? subject = null) { if (_matches.TryGetValue(expression, out string? remembered)) return remembered; diff --git a/Source/Core/PooledBuffer.cs b/Source/Core/PooledBuffer.cs index aaa8404e..1773c55f 100644 --- a/Source/Core/PooledBuffer.cs +++ b/Source/Core/PooledBuffer.cs @@ -518,21 +518,9 @@ Task DisposeCore() // // DisposeAsync additionally awaits the producer, so its // arrays are back when it returns; Dispose does not wait. - // The await has no timeout, on purpose: correctness (no array goes back - // while the producer might still write) comes before promptness. - // So a dispose waits for the provider call in progress (the execute, or a - // read) to return; a provider that ignores the cancel token delays it by - // that call. - // After that the producer stops at the next chunk boundary at the latest: - // the read loop checks the token per row in the default read mode, the - // provider does in the async read mode, and the producer itself checks - // once per chunk. - // So with AsyncReads() and a provider that ignores the token, a - // dispose or a cancel is seen at the next chunk (a buffer's chunks double: - // up to the rows of the current chunk). - // A caller's own cancel is the opposite: it is not swallowed. - // Finish stores it, and Items is cancelled with the - // caller's token. + // Why the await has no timeout, and where the producer stops: see + // the header of ChunkProducer. A caller's own cancel is not swallowed: + // Finish stores it, and Items is cancelled with the caller's token. // The dispose-once guard (a full fence: see the comment above this method). if (Interlocked.Exchange(ref _disposed, 1) != 0) diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs index 85937eb0..75dc9229 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -9,27 +9,19 @@ namespace Open.Database.Extensions; /// The server and the database are compared ignoring case, the procedure exactly: a case-sensitive database can hold two procedures that differ only /// in case, and an extra entry for one procedure written two ways costs only a second read. A part that is is the empty string. /// +/// The server, or when it is not known. +/// The database, or when it is not known. +/// The procedure name. // A small struct compared part by part, so looking a procedure up builds no string. -readonly struct ProcedureKey : IEquatable +// StringComparer.GetHashCode(null) throws, and a missing server or database is the same key as an empty one. +readonly struct ProcedureKey(string? server, string? database, string? procedure) : IEquatable { - /// Initializes a new instance. - /// The server, or when it is not known. - /// The database, or when it is not known. - /// The procedure name. - internal ProcedureKey(string? server, string? database, string? procedure) - { - // StringComparer.GetHashCode(null) throws, and a missing server or database is the same key as an empty one. - Server = server ?? string.Empty; - Database = database ?? string.Empty; - Procedure = procedure ?? string.Empty; - } - /// Gets the server; empty when it is not known. - internal string Server { get; } + public string Server { get; } = server ?? string.Empty; /// Gets the database; empty when it is not known. - internal string Database { get; } + public string Database { get; } = database ?? string.Empty; /// Gets the procedure name. - internal string Procedure { get; } + public string Procedure { get; } = procedure ?? string.Empty; /// public bool Equals(ProcedureKey other) @@ -99,7 +91,7 @@ public sealed class Entries /// The object commands take their connections from. /// The server, database and procedure. /// The set, or when none is kept. - internal static NameSet? Find(object source, ProcedureKey key) + public static NameSet? Find(object source, ProcedureKey key) => Sources.TryGetValue(source, out Entries? entries) && entries.ByProcedure.TryGetValue(key, out NameSet? names) ? names : null; @@ -109,7 +101,7 @@ public sealed class Entries /// The server, database and procedure the names belong to. /// The names as the database reported them; empty or the default array when it reported none. /// The set kept for the procedure: this one, or the one another call kept first. - internal static NameSet Remember(object source, ProcedureKey key, ImmutableArray names) + public static NameSet Remember(object source, ProcedureKey key, ImmutableArray names) { Entries entries = Sources.GetValue(source, static _ => new Entries()); // Only here, where a lookup was just paid for, is the bound checked. @@ -126,7 +118,7 @@ internal static NameSet Remember(object source, ProcedureKey key, ImmutableArray /// /// The set the failed call used, or . /// . - internal static bool Forget(NameSet? names) + public static bool Forget(NameSet? names) { if (names?.Home is { } home && home.TryGetTarget(out Entries? entries)) { @@ -143,6 +135,6 @@ internal static bool Forget(NameSet? names) /// The set the call used, or . /// The failure. /// . - internal static bool ForgetUnlessCanceled(NameSet? names, Exception exception) + public static bool ForgetUnlessCanceled(NameSet? names, Exception exception) => exception is not OperationCanceledException && Forget(names); } diff --git a/Source/Core/ProcedureSchemaNames.cs b/Source/Core/ProcedureSchemaNames.cs index f7d5a856..64f01f68 100644 --- a/Source/Core/ProcedureSchemaNames.cs +++ b/Source/Core/ProcedureSchemaNames.cs @@ -28,7 +28,7 @@ static class ProcedureSchemaNames /// An open connection to run the lookup on. /// The procedure name as given to the command. /// The names in ordinal order, or an empty or default array when they are not known. - internal static ImmutableArray Get(DbConnection connection, string procedure) + public static ImmutableArray Get(DbConnection connection, string procedure) { if (Restrictions(procedure) is not { } restrictions) return default; @@ -59,7 +59,7 @@ internal static ImmutableArray Get(DbConnection connection, string proce /// The procedure name as given to the command. /// /// A task that represents the asynchronous operation; its result is the names in ordinal order, or an empty or default array when they are not known. - internal static ValueTask> GetAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) + public static ValueTask> GetAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return new(Get(connection, procedure)); @@ -73,7 +73,7 @@ internal static ValueTask> GetAsync(DbConnection connecti /// The procedure name as given to the command. /// /// A task that represents the asynchronous operation; its result is the names in ordinal order, or an empty or default array when they are not known. - internal static async ValueTask> GetAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) + public static async ValueTask> GetAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) { if (Restrictions(procedure) is not { } restrictions) return default; diff --git a/Source/Core/RecycleBin.cs b/Source/Core/RecycleBin.cs index 6e7df5e4..3b31dd10 100644 --- a/Source/Core/RecycleBin.cs +++ b/Source/Core/RecycleBin.cs @@ -2,7 +2,7 @@ namespace Open.Database.Extensions.Core; -// Threshold: a chunk of 128 KB or more of rows (value rows included) is cleared here (spike 4e); a smaller one is cleared where it is released. +// Threshold: a chunk of 128 KB or more of rows (value rows included) is cleared here; a smaller one is cleared where it is released. // The only work the bin ever runs is ours and bounded (clear the rows of one array, then give it back). The default path with no clearing, and small chunks, never touch it. // How it works: // - One Channel of struct work items (a runner, an array, the number of rows, the configuration), bounded by the capacity, with one reader. diff --git a/Source/Core/TextNameCache.cs b/Source/Core/TextNameCache.cs index 2cefca8b..8f20e6d7 100644 --- a/Source/Core/TextNameCache.cs +++ b/Source/Core/TextNameCache.cs @@ -1,7 +1,5 @@ namespace Open.Database.Extensions; -// An interned text is the same object on every call, and there are as many as the code has literals; a run-time text is a new string with the same characters on every call. -// The scan allocates nothing, so such a text costs no more than a literal one, and no table gains an entry per call or holds a text. /// /// Finds the real names of the derived arguments of a text command in the @name markers of its SQL text. /// @@ -9,6 +7,7 @@ namespace Open.Database.Extensions; /// A text that is an interned string (a literal or a ) is read once into a /// remembered by the text object (weakly: the entry goes when the string is released). /// Any other text, such as one put together at run time, is scanned for each argument on every run and nothing about it is remembered. +/// There are as many interned texts as the code has literals, while a run-time text is a new string on every call; the scan allocates nothing, so such a text costs no more than a literal one, and no table gains an entry per call or holds a text. /// static class TextNameCache { @@ -27,7 +26,7 @@ static class TextNameCache /// /// The SQL text. /// The set of its markers, or when the text is not interned. - internal static NameSet? Get(string text) + public static NameSet? Get(string text) => ByReference.TryGetValue(text, out NameSet? known) ? known : ReferenceEquals(string.IsInterned(text), text) @@ -37,7 +36,7 @@ static class TextNameCache /// Determines whether the text has at least one marker (otherwise its parameter names are not known). /// The SQL text. /// if the text has a marker; otherwise, . - internal static bool HasMarkers(string text) + public static bool HasMarkers(string text) { int position = 0; return SqlTextParameters.NextMarker(text, ref position, out _, out _); @@ -50,7 +49,7 @@ internal static bool HasMarkers(string text) /// The text of the argument. /// The marker, or when none fits. /// The expression fits more than one marker equally well. - internal static string? Scan(string text, string expression) + public static string? Scan(string text, string expression) { // The answer is the one NameSet.Match gives over the parsed tokens, found without parsing. // It allocates nothing once the expression has been seen and its marker was found before. diff --git a/Source/Dataflow/BlockPump.cs b/Source/Dataflow/BlockPump.cs index ce85c28c..71b6f2a9 100644 --- a/Source/Dataflow/BlockPump.cs +++ b/Source/Dataflow/BlockPump.cs @@ -22,7 +22,7 @@ internal static class BlockPump /// /// /// The number of rows the target accepted. - internal static async ValueTask Run( + public static async ValueTask Run( TFeed feed, ITargetBlock target, bool complete, @@ -73,7 +73,7 @@ internal static async ValueTask Run( /// // Not async: an open block gets the enumerator with no frame and nothing // allocated. Only a finished block goes on, to dispose the enumerator. - internal static ValueTask?> Open( + public static ValueTask?> Open( IAsyncEnumerable stream, ITargetBlock target, CancellationToken cancellationToken) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index b3bb332a..c0051119 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -2,27 +2,47 @@ namespace Open.Database.Extensions.Generator; -// Writes the one generated file. Shape (SG.md section 2), through Core's one hidden entry, GeneratedRowMap.Create: -// - per call site, an interceptor that passes M_T.Map to the receiver's existing Map(RowMap?) overload: CoreExtensions.Map(x, M_T.Map) -// for a reader or command, x.Map(M_T.Map) for a query type (see Interceptor); -// - every member is read by its own type, as a hand-written reader reads it (ModelReader.MemberReadOf): the column's type is not looked at, and the -// provider converts or throws. -// - a model that declares every column's ordinal ([Column(Order = n)] on every mapped member) is trusted: Bind returns the literal reader and -// looks at nothing in the result (EmitTrusted). What follows about layouts is for every other model. -// - per model type, one class M_T holding one RowMap made by GeneratedRowMap.Create(Bind). Core's read loop calls Bind once per result -// set, after its first row is read and before it is mapped (a set with no row to map calls nothing): Bind compares the reader's column count and names with the layouts met lately (a small static cache of immutable layouts, -// swapped atomically) or resolves a new one, and returns that layout's row reader, or null for a layout it does not serve (the runtime map then -// serves it, exactly as the default map: its rows, its exceptions). A next result set is bound again, so it is always read at its own ordinals. -// - the row reader is the reads and nothing else: typed getters, a NULL test only on a nullable member, the model built and set. No try region, -// no row counter, no layout check, no mode switch: Bind chose the reader for the mode once per result set. -// * identity layouts (mode 4) and trusted models: a static lambda reading literal ordinals (a closed delegate on the compiler's +// Writes the one generated file, through Core's one hidden entry, +// GeneratedRowMap.Create: +// - per call site, an interceptor that passes M_T.Map to the receiver's +// existing Map(RowMap?) overload: CoreExtensions.Map(x, M_T.Map) +// for a reader or command, x.Map(M_T.Map) for a query type (see +// Interceptor); +// - every member is read by its own type, as a hand-written reader reads +// it (ModelReader.MemberReadOf): the column's type is not looked at, and +// the provider converts or throws. +// - a model that declares every column's ordinal ([Column(Order = n)] on +// every mapped member) is trusted: Bind returns the literal reader and +// looks at nothing in the result (EmitTrusted). What follows about +// layouts is for every other model. +// - per model type, one class M_T holding one RowMap made by +// GeneratedRowMap.Create(Bind). Core's read loop calls Bind once per +// result set, after its first row is read and before it is mapped (a set +// with no row to map calls nothing): Bind compares the reader's column +// count and names with the layouts met lately (a small static cache of +// immutable layouts, swapped atomically) or resolves a new one, and +// returns that layout's row reader, or null for a layout it does not +// serve (the runtime map then serves it, exactly as the default map: its +// rows, its exceptions). A next result set is bound again, so it is +// always read at its own ordinals. +// - the row reader is the reads and nothing else: typed getters, a NULL +// test only on a nullable member, the model built and set. No try +// region, no row counter, no layout check, no mode switch: Bind chose +// the reader for the mode once per result set. +// * identity layouts (mode 4) and trusted models: a static lambda +// reading literal ordinals (a closed delegate on the compiler's // singleton: no state, no argument-shuffling thunk); -// * the other modes (full 1, guarded 2): an instance method of the layout (a delegate closed over it, no thunk), reading the +// * the other modes (full 1, guarded 2): an instance method of the +// layout (a delegate closed over it, no thunk), reading the // layout's ordinals from it. -// - errors: Core's loop catches around its call of the row reader alone and reports what the reader throws as it reports a failure of the runtime's -// typed read: a ValueMappingException naming the model type and the 0-based row (skipped rows counted), the exception inside; a DbException or a -// cancellation passes through. Nothing is read from the reader after a failure. -// - NULL is handled by the member's type (see Statement). A model that declares NullPolicy or NullValue is not intercepted (ModelReader): the +// - errors: Core's loop catches around its call of the row reader alone +// and reports what the reader throws as it reports a failure of the +// runtime's typed read: a ValueMappingException naming the model type +// and the 0-based row (skipped rows counted), the exception inside; a +// DbException or a cancellation passes through. Nothing is read from the +// reader after a failure. +// - NULL is handled by the member's type (see Statement). A model that +// declares NullPolicy or NullValue is not intercepted (ModelReader): the // runtime map applies the policy. static class Emitter { @@ -407,7 +427,7 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) { string T = m.Type; var slots = m.Slots.Items; - bool styleB = m.UseConstructor || slots.Any(s => s.InitBound && !s.NotMapped); + bool buildsAfterReading = m.UseConstructor || slots.Any(s => s.InitBound && !s.NotMapped); int[] literal = LiteralOrdinals(m); string reader = $"global::System.Func<{DbReader}, {T}>"; @@ -441,7 +461,7 @@ file sealed class {{id}} if (m.AllOrdered) { - EmitTrusted(sb, m, options, styleB, literal, reader); + EmitTrusted(sb, m, options, buildsAfterReading, literal, reader); sb.AppendLine(""" } @@ -573,7 +593,7 @@ static Layout Resolve({{DbReader}} r) """); - EmitLiteralReader(sb, m, styleB, literal, reader); + EmitLiteralReader(sb, m, buildsAfterReading, literal, reader); // ---- the layout and its row readers ---- // The ordinal fields are a line of their own with its indent and line end, or nothing for a model with no slot. @@ -599,8 +619,8 @@ public Layout({{DbReader}} r) : base(r) { } """); - EmitMethod(sb, m, "ReadFull", styleB, ReadMode.Full, literal); - EmitMethod(sb, m, "ReadGuarded", styleB, ReadMode.Guarded, literal); + EmitMethod(sb, m, "ReadFull", buildsAfterReading, ReadMode.Full, literal); + EmitMethod(sb, m, "ReadGuarded", buildsAfterReading, ReadMode.Guarded, literal); sb.AppendLine(""" } } @@ -609,7 +629,7 @@ public Layout({{DbReader}} r) : base(r) { } } // The literal row reader: a static lambda over the reader alone. - static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] literal, string reader) + static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool buildsAfterReading, int[] literal, string reader) { sb.AppendLine($$""" // Every member at its constant ordinal: the reads, and nothing else. @@ -617,7 +637,7 @@ static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] { """); - EmitRead(sb, m, styleB, ReadMode.Literal, literal, 3); + EmitRead(sb, m, buildsAfterReading, ReadMode.Literal, literal, 3); sb.AppendLine(""" }; @@ -627,7 +647,7 @@ static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] // Every mapped member declares its ordinal ([Column(Order = n)]): the declaration is trusted, as a hand-written reader trusts its ordinals. // Nothing about the result set is checked (no name, type or count), so there is one reader and Bind has nothing to choose. A result that does // not match gives what the member's getter gives: the provider's conversion or its exception, or, where the types agree, the value at that position. - static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool styleB, int[] literal, string reader) + static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool buildsAfterReading, int[] literal, string reader) { sb.AppendLine(""" // Every member declares its column ordinal: @@ -656,7 +676,7 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty } sb.AppendLine(); - EmitLiteralReader(sb, m, styleB, literal, reader); + EmitLiteralReader(sb, m, buildsAfterReading, literal, reader); } // The first line of a partial model's Bind, with its indent and line end (appended as it is, before the rest of the body), or nothing for a @@ -710,14 +730,14 @@ static string Code(string name) => Microsoft.CodeAnalysis.CSharp.SyntaxFacts.GetKeywordKind(name) != Microsoft.CodeAnalysis.CSharp.SyntaxKind.None ? "@" + name : name; // A row reader of the layout: an instance method (the delegate is closed over the layout, so no thunk), reading the layout's ordinals. - static void EmitMethod(StringBuilder sb, ModelSpec m, string name, bool styleB, ReadMode mode, int[] literal) + static void EmitMethod(StringBuilder sb, ModelSpec m, string name, bool buildsAfterReading, ReadMode mode, int[] literal) { sb.AppendLine($$""" public {{m.Type}} {{name}}({{DbReader}} r) { """); - EmitRead(sb, m, styleB, mode, literal, 4); + EmitRead(sb, m, buildsAfterReading, mode, literal, 4); sb.AppendLine(""" } @@ -725,13 +745,13 @@ static void EmitMethod(StringBuilder sb, ModelSpec m, string name, bool styleB, } // The body of a row reader: the reads, the construction, the sets, and return. No try region: Core's loop reports a failure. - static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, int[] literal, int depth) + static void EmitRead(StringBuilder sb, ModelSpec m, bool buildsAfterReading, ReadMode mode, int[] literal, int depth) { string I = Tabs(depth); string T = m.Type; var slots = m.Slots.Items; - if (!styleB) + if (!buildsAfterReading) { // RowMap.CreateThenSet: new T(), then each fed cell read and set in column order (ascending: slot order). sb.AppendLine($"{I}var item = {m.Create};"); diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index bf4f4bdc..380f5b7c 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -128,7 +128,10 @@ static class ModelReader if (!CanName(parameter.Type, compilation)) return null; - SlotSpec? slot = Slot(name, i, parameter.Type, IsNonNullableReference(parameter), false, false, declared, fallback, dbNull); + SlotSpec? slot = Slot( + name, i, parameter.Type, IsNonNullableReference(parameter), + initBound: false, required: false, + declared, fallback, dbNull); if (slot is null) return null; slots.Add(slot); } @@ -145,7 +148,10 @@ static class ModelReader // What generated code names: the member (its setter included) and its type. if (!declared.NotMapped && (IsRetired(p) || IsRetired(setter) || !SyntaxFacts.IsValidIdentifier(p.Name) || !CanName(p.Type, compilation))) return null; - SlotSpec? slot = Slot(p.Name, -1, p.Type, IsNonNullableReference(p), setter.IsInitOnly || required, required, declared, null, dbNull); + SlotSpec? slot = Slot( + p.Name, -1, p.Type, IsNonNullableReference(p), + initBound: setter.IsInitOnly || required, required: required, + declared, null, dbNull); if (slot is null) return null; slots.Add(slot); } diff --git a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs index 5486cbb6..7e5e55b9 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; public static partial class SqlTransactionExtensions { @@ -16,7 +16,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs index 3d2f2c0e..8463050d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DbQueryChecksTests.cs @@ -13,7 +13,7 @@ public static class DbQueryChecksTests { const string BlankName = "Parameter names cannot be empty or white space."; const string BlankCommand = "The command cannot be empty or white space."; - const string BlankCommandOfACommand = "Cannot be null or whitespace."; + const string BlankCommandOfACommand = "The command cannot be empty or white space. Pass the SQL text or the name of the stored procedure."; static CancellationToken Token => TestContext.Current.CancellationToken; diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 34db3d88..d6d595bd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -395,8 +395,8 @@ public static void AnInternedText_IsRememberedOnce_ByItsObject() public static void TheScanPath_AllocatesNothing() { Type cache = typeof(DataRecordExtensions).Assembly.GetType("Open.Database.Extensions.TextNameCache", throwOnError: true)!; - var get = cache.GetMethod("Get", BindingFlags.Static | BindingFlags.NonPublic)!.CreateDelegate>(); - var scan = cache.GetMethod("Scan", BindingFlags.Static | BindingFlags.NonPublic)!.CreateDelegate>(); + var get = cache.GetMethod("Get", BindingFlags.Static | BindingFlags.Public)!.CreateDelegate>(); + var scan = cache.GetMethod("Scan", BindingFlags.Static | BindingFlags.Public)!.CreateDelegate>(); string built = new("select * from orders where order_id = @order_id and customer_id = @customer_id and start_date >= @start_date".AsSpan()); const string expression = "customerId"; diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs index 835049af..40743278 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs @@ -479,7 +479,7 @@ public static void CreateCommand_OnATransactionWithNoConnection_Throws() var transaction = (SqlTransaction)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(SqlTransaction)); Assert.Null(transaction.Connection); - Assert.Equal("Transaction has no connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); + Assert.Equal("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); Assert.Throws(() => SqlTx.CreateTextCommand(transaction, "select 1")); Assert.Throws(() => SqlTx.CreateStoredProcedureCommand(transaction, "dbo.p")); } From c7e113d248aa93a8ae5e1af02623bd811af84e8c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:26:59 -0800 Subject: [PATCH 3/3] Apply review fixes: argument grouping, one shared doc include, a Debug assert Group the arguments of the decimal layout calls and of the output command build, put the `=>` of the procedure key on its own line, and rename the chunk producer's count of handed-over rows to match its comment. Drop a comment in the row reader that repeated an earlier one. Restore the UTF-8 byte order mark on the two `Transaction.CreateCommand.cs` files. The message for a transaction without a connection now says it can happen after the transaction completed, not only the one way; the test that pins it and the release note are updated, and the note no longer quotes the text. The mapped query's `Stream` and `StreamBuffered` now take the three sentences on the read thread from the `stream-your-thread` include that the interface already uses, so the two cannot drift. `CaptureSet.WithOnQuery` and `WithOnCommand` assert, in Debug builds, that the set they extend was made for the same kind of caller. No change in Release. No behavior change in Release. Checks: Release and Debug builds of the solution with 0 warnings; Core tests in Release (16151 passed) and Debug (16130 passed, 16 skipped); generator tests (189 passed); `dotnet format` style and analyzers at info severity, 0 findings on Core, MSSqlClient and Core.Tests; docs build with 0 warnings. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Capture.cs | 12 ++++++++++-- Source/Core/ChunkProducer.cs | 8 ++++---- Source/Core/Core/RowReader.cs | 1 - Source/Core/DbQueryRunner.Output.cs | 7 ++----- Source/Core/ExpressiveCommandBase.cs | 5 ++++- Source/Core/Extensions/Transaction.CreateCommand.cs | 6 +++--- Source/Core/MappedQuery.cs | 8 ++------ Source/Core/OutputDbNonQuery.cs | 8 ++------ .../Extensions/Transaction.CreateCommand.cs | 4 ++-- .../SqlServerPackageTests.cs | 2 +- docsite/articles/release-notes.md | 2 +- 11 files changed, 31 insertions(+), 32 deletions(-) diff --git a/Source/Core/Capture.cs b/Source/Core/Capture.cs index 4e401374..cc7c2a7a 100644 --- a/Source/Core/Capture.cs +++ b/Source/Core/Capture.cs @@ -1,3 +1,5 @@ +using System.Diagnostics; + namespace Open.Database.Extensions; // The captures (CaptureOutput, CaptureOutputDecimal, CaptureReturn) of a @@ -430,7 +432,10 @@ sealed class CaptureSet : CaptureHolder public static CaptureSet WithOnCommand( CaptureSet? set, ICaptureSource source) - => set?.Added(source) ?? new([source], onQuery: false); + { + Debug.Assert(set is null || !set.OnQuery); + return set?.Added(source) ?? new([source], onQuery: false); + } /// /// Returns the captures of a mapped query with one more, as @@ -445,7 +450,10 @@ public static CaptureSet WithOnCommand( public static CaptureSet WithOnQuery( CaptureSet? set, ICaptureSource source) - => set?.Added(source) ?? new([source], onQuery: true); + { + Debug.Assert(set is null || set.OnQuery); + return set?.Added(source) ?? new([source], onQuery: true); + } // The set is on a command or on a query for good: the new one is as well, // and the messages say which. diff --git a/Source/Core/ChunkProducer.cs b/Source/Core/ChunkProducer.cs index 09e2ec3b..c9824f34 100644 --- a/Source/Core/ChunkProducer.cs +++ b/Source/Core/ChunkProducer.cs @@ -152,14 +152,14 @@ readonly CancellationTokenSource _linked // Made in Start, on the caller's thread (see ReaderAbandon); null without CancelOnEarlyStop(). ReaderAbandon? _abandon; - /// The rows in the buffers already handed on. + /// The rows in the buffers already handed over. /// Moves once per buffer, in , never per row. - int _handedOn; + int _handedOver; /// Gets the number of rows stored so far. // Read when a row fails to map, to name the row. public int Count - => _handedOn + _next; + => _handedOver + _next; /// /// Starts the producer, once. A token that is already cancelled @@ -369,7 +369,7 @@ void Advance() ArrayLease Take() { ArrayLease lease = config.Seal(_array!, _next); - _handedOn += _next; + _handedOver += _next; _array = null; _next = 0; _limit = 0; diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index e97b3e63..7aabca02 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -258,7 +258,6 @@ public static T[] ToArray( Func map = source.Mapper(db); - // A mutable struct again, so it is disposed by hand, as above. var buffer = new ArraySink(config); try { diff --git a/Source/Core/DbQueryRunner.Output.cs b/Source/Core/DbQueryRunner.Output.cs index f49a1b30..64280ed3 100644 --- a/Source/Core/DbQueryRunner.Output.cs +++ b/Source/Core/DbQueryRunner.Output.cs @@ -67,11 +67,8 @@ static DbCommand MakeWithOutput( OutputRun output) { DbCommand command = Make( - connection, - transaction, - definition, - call, - names); + connection, transaction, definition, + call, names); try { OutputBinding.Resolve( diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index ca11e6a9..17ba5edb 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1075,7 +1075,10 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f // procedure. IDbConnection has no server name, so a connection that is not // a DbConnection contributes none. The key is a struct of the three parts, // so no string is built. - ProcedureKey KeyOf(TConnection connection) => new((connection as DbConnection)?.DataSource, connection.Database, Command); + ProcedureKey KeyOf(TConnection connection) + => new( + (connection as DbConnection)?.DataSource, + connection.Database, Command); /// /// Builds, in , what one run of a command with written names sends: each name that the text declares diff --git a/Source/Core/Extensions/Transaction.CreateCommand.cs b/Source/Core/Extensions/Transaction.CreateCommand.cs index b426f496..f61cd4e6 100644 --- a/Source/Core/Extensions/Transaction.CreateCommand.cs +++ b/Source/Core/Extensions/Transaction.CreateCommand.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; /// /// Extension methods for database transactions that do not depend on a specific database provider. @@ -19,7 +19,7 @@ public static IDbCommand CreateCommand(this IDbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); IDbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); @@ -72,7 +72,7 @@ public static DbCommand CreateCommand(this DbTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); DbCommand command = transaction.Connection.CreateCommand(type, commandText, secondsTimeout); diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 9220cd04..47056923 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -1821,9 +1821,7 @@ public IAsyncEnumerable> ToPooledBufferStream( /// To read while the query runs, use , which releases it when the read ends. /// If you go without pulling the next row, the read stops, the command is cancelled, /// the connection this library opened is closed, and your next pull throws . - /// Dispose the enumeration (await foreach does). - /// The rows are read with Read() on your thread unless the query asked for AsyncReads(), so a slow database read blocks your thread for its wait; a cancel cannot interrupt a read the provider is blocked in, so the command's CommandTimeout bounds it, and a cancel while you hold a row is seen at your next pull. - /// A timer checks the stall timeout, so an expiry is found up to about a quarter of the timeout (at least 10 ms) after the timeout has passed, never before it. + /// /// /// /// @@ -1852,9 +1850,7 @@ public IAsyncEnumerable Stream( /// If the buffer is full and you go without pulling the next row, the read stops, the command is cancelled, /// the connection this library opened is closed, and your next pull throws . /// Rows still waiting in the buffer when the stall trips are discarded, not delivered. - /// Dispose the enumeration (await foreach does). - /// The rows are read with Read() on your thread unless the query asked for AsyncReads(), so a slow database read blocks your thread for its wait; a cancel cannot interrupt a read the provider is blocked in, so the command's CommandTimeout bounds it, and a cancel while you hold a row is seen at your next pull. - /// A timer checks the stall timeout, so an expiry is found up to about a quarter of the timeout (at least 10 ms) after the timeout has passed, never before it. + /// /// /// /// diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs index b441d465..0938757f 100644 --- a/Source/Core/OutputDbNonQuery.cs +++ b/Source/Core/OutputDbNonQuery.cs @@ -74,9 +74,7 @@ public static DbQuery Shaped( { OutputValue.ThrowUnlessDecimal(name, OutputForm.Definition); return DecimalLayout( - name, - precision, - scale, + name, precision, scale, $"Output<{type}>(\"{name}\", {precision}, {scale})"); })); } @@ -89,9 +87,7 @@ public static DbQuery Decimal( { OutputArguments.ThrowIfNoName(name, OutputForm.Definition); return definition.WithOutput(DecimalLayout( - name, - precision, - scale, + name, precision, scale, $"OutputDecimal(\"{name}\", {precision}, {scale})")); } diff --git a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs index 7e5e55b9..35d2d994 100644 --- a/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs +++ b/Source/MSSqlClient/Extensions/Transaction.CreateCommand.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; public static partial class SqlTransactionExtensions { @@ -16,7 +16,7 @@ public static SqlCommand CreateCommand(this SqlTransaction transaction, { if (transaction is null) throw new ArgumentNullException(nameof(transaction)); ConnectionExtensions.CheckCommandText(commandText); - if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); + if (transaction.Connection is null) throw new InvalidOperationException("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection."); Contract.EndContractBlock(); SqlCommand command = transaction diff --git a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs index 40743278..1ff7a8fb 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/SqlServerPackageTests.cs @@ -479,7 +479,7 @@ public static void CreateCommand_OnATransactionWithNoConnection_Throws() var transaction = (SqlTransaction)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(SqlTransaction)); Assert.Null(transaction.Connection); - Assert.Equal("Transaction has no connection. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); + Assert.Equal("Transaction has no connection, for example after it completed. Create the command before the transaction commits or rolls back, from a transaction that was begun on a connection.", Assert.Throws(() => SqlTx.CreateCommand(transaction, CommandType.Text, "select 1")).Message); Assert.Throws(() => SqlTx.CreateTextCommand(transaction, "select 1")); Assert.Throws(() => SqlTx.CreateStoredProcedureCommand(transaction, "dbo.p")); } diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 58ee72c2..25ee630e 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -9,7 +9,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch. - **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter whose mode is `IN` (an input parameter), or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an `IN` parameter). See [Output parameters](expressive-commands.md#output-parameters). - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. -- **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. +- **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; both packages now throw `InvalidOperationException`, with a message that says the cause and the fix. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(out DbCapture value, name)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). - **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows).