diff --git a/Source/Channel/ToChannel.Produce.cs b/Source/Channel/ToChannel.Produce.cs index 03064709..2b9d76f6 100644 --- a/Source/Channel/ToChannel.Produce.cs +++ b/Source/Channel/ToChannel.Produce.cs @@ -21,6 +21,7 @@ public static partial class ChannelDbExtensions /// The channel is always completed: /// without an error after the last row, or with the exception that /// ended the read, a cancel included. + /// Channels. /// /// /// The type of each row. @@ -140,8 +141,8 @@ public static Channel ToChannel( /// /// /// The bound limits the channel, not memory: - /// the query is still read at full speed, and the rows the channel has - /// no room for wait in an internal queue. + /// the query is still read at full speed, and the rows that do not fit + /// wait in memory. /// /// /// The mapped query to read. diff --git a/Source/Channel/ToChannel.Streaming.cs b/Source/Channel/ToChannel.Streaming.cs index fed6b85e..451929f0 100644 --- a/Source/Channel/ToChannel.Streaming.cs +++ b/Source/Channel/ToChannel.Streaming.cs @@ -10,18 +10,18 @@ public static partial class ChannelDbExtensions /// /// /// Holds the reader and the connection open for each row: while the channel is full, - /// the next row is not pulled and the connection stays open until + /// the read waits and the connection stays open until /// expires (never, with ). /// Use , /// which frees the connection first, unless the rows must be pulled one at a time; - /// otherwise it behaves as that member. - /// See (with a buffer of one row) for the stall rules. + /// otherwise it behaves the same, apart from the stall timeout. + /// See Terminals for the stall rules. /// /// The type of each row. /// The mapped query to read. /// The channel to write to. /// - /// The longest the channel may make no room while the reader is held. Required; passed to Stream. + /// The longest the channel may make no room while the reader is held. Required; passed to with a buffer of one row. /// The wait for room before the command runs is not timed. /// /// @@ -42,7 +42,11 @@ public static ValueTask ToChannelHoldingConnection( false, cancellationToken); - /// + /// + /// Reads the query one row at a time and writes each row to a channel + /// you own, completing the channel when the pass ends if + /// is . + /// /// /// /// @@ -53,7 +57,7 @@ public static ValueTask ToChannelHoldingConnection( /// /// The mapped query to read. /// The channel to write to. - /// The longest the channel may make no room while the reader is held. Required; passed to Stream. + /// The longest the channel may make no room while the reader is held. Required; passed to with a buffer of one row. /// The wait for room before the command runs is not timed. /// public static ValueTask ToChannelHoldingConnection( @@ -85,7 +89,7 @@ public static ValueTask ToChannelHoldingConnection( /// /// The writer to write to. /// The mapped query to read. - /// The longest the writer may make no room while the reader is held. Required; passed to Stream. + /// The longest the writer may make no room while the reader is held. Required; passed to with a buffer of one row. /// The wait for room before the command runs is not timed. /// public static ValueTask ToChannelHoldingConnection( @@ -107,7 +111,7 @@ public static ValueTask ToChannelHoldingConnection( /// /// The writer to write to. /// The mapped query to read. - /// The longest the writer may make no room while the reader is held. Required; passed to Stream. + /// The longest the writer may make no room while the reader is held. Required; passed to with a buffer of one row. /// The wait for room before the command runs is not timed. /// /// to complete the writer when the pass ends, diff --git a/Source/Channel/ToChannel.Target.cs b/Source/Channel/ToChannel.Target.cs index c7629a37..8f387502 100644 --- a/Source/Channel/ToChannel.Target.cs +++ b/Source/Channel/ToChannel.Target.cs @@ -10,9 +10,9 @@ public static partial class ChannelDbExtensions /// /// /// - /// The task is the done signal: it completes with the number of rows - /// handed to the channel after the last result set was read through. - /// A failure or a cancel comes back through the task, and the channel + /// The returned ValueTask<long> completes with the number of + /// rows written after the last result set was read through. + /// A failure or a cancel is thrown by the await, and the channel /// is left as it was. /// /// @@ -20,14 +20,13 @@ public static partial class ChannelDbExtensions /// Pass complete: true to complete it when the pass ends. /// /// - /// The query is read at full speed and the connection is closed when the - /// read ends. When the channel is full, the write waits for room, - /// before the command runs and then between rows, while the rows wait in - /// an internal queue: the connection is free, but your channel does not - /// limit memory. - /// When the channel is closed, the pass stops without an exception and - /// returns the rows written so far. - /// A channel completed with an error throws that error. + /// The connection is closed when the read ends. + /// A full channel makes the write wait, before the command runs and then + /// between rows; the rows wait in memory meanwhile, so the channel does + /// not limit memory. + /// A closed channel ends the pass without an exception and returns the + /// rows written so far; a channel completed with an error throws that error. + /// A channel you own. /// /// /// The type of each row. @@ -47,8 +46,17 @@ public static ValueTask ToChannel( false, cancellationToken); - /// - /// + /// + /// Reads the query and writes each row to a channel you own, + /// completing the channel when the pass ends if is + /// . + /// + /// + /// With complete: false it is + /// . + /// With complete: true the channel is completed when the pass ends, + /// or completed with the exception that ended it, a cancel included. + /// /// /// /// diff --git a/Source/Core/Commands.docs.xml b/Source/Core/Commands.docs.xml index 73f317f0..f69dad88 100644 --- a/Source/Core/Commands.docs.xml +++ b/Source/Core/Commands.docs.xml @@ -70,6 +70,7 @@ The pool to take connections from. Each execution takes one and gives it back when finished. + The pool must return a connection; is not supported. or is @@ -82,6 +83,7 @@ The factory that creates the connections. Each execution creates a connection, opens it if needed, and disposes it when finished. + The factory must return a connection; is not supported. or is @@ -94,6 +96,7 @@ The function that creates the connections. Each execution invokes it, opens the connection if needed, and disposes it when finished. + The function must return a connection; is not supported. or is diff --git a/Source/Core/ConnectionScope.cs b/Source/Core/ConnectionScope.cs index 9608fb4f..a1cbda58 100644 --- a/Source/Core/ConnectionScope.cs +++ b/Source/Core/ConnectionScope.cs @@ -27,69 +27,15 @@ enum ScopeEnd : byte /// to do with it when the scope is disposed. /// /// -/// -/// One type for every source of a connection: the scope carries how it ends. What -/// disposing does depends on what made it: -/// -/// -/// -/// Made by -/// The connection came from; disposing the scope -/// -/// -/// / -/// -/// You already hold it; closes it if the scope opened it, and leaves it open if it was already open. -/// Never disposes it. -/// -/// -/// / -/// (on a factory) -/// The factory created it, so it is yours; disposes it: Dispose, as -/// factory.Open(...) does, and DisposeAsync from when the connection has one. -/// -/// -/// / -/// (on a pool) -/// The pool leased it; gives it back with , as -/// pool.Open(...) does. What giving back means (close it, keep it, dispose it) is the pool's. -/// +/// What disposing the scope does depends on where the connection came from: +/// +/// From EnsureOpenScope on a connection: closes it if the scope opened it; never disposes it. +/// From EnsureOpenScope on a factory: disposes it (DisposeAsync when it has one). +/// From EnsureOpenScope on a pool: gives it back with ; what that means is the pool's. /// -/// -/// When you already hold the connection the scope is usually only there to be disposed: -/// -/// -/// await using var _ = await connection.EnsureOpenScopeAsync(cancellationToken); -/// // ... use the connection you already hold. -/// -/// -/// When the connection came from a factory or a pool the scope is how you get it: -/// -/// -/// await using var scope = await factory.EnsureOpenScopeAsync(cancellationToken); -/// var connection = scope.Connection; -/// -/// -/// The scope keeps the type of the connection (a SqlConnection stays a -/// SqlConnection), and deconstructs into the connection and the state it was found in: -/// var (sql, was) = scope;. -/// -/// -/// A connection that was broken is closed and opened again, so a scope that closes it closes it -/// again afterwards; the broken state is not restored. -/// -/// -/// Dispose the value you were given exactly once, and do not copy it: a second dispose of a copy -/// disposes a factory's connection again, gives a pool's connection back again, or closes a connection -/// that someone opened in between. Deconstruct a scope you hold, never the call itself: -/// var (c, s) = connection.EnsureOpenScope(); drops the scope, and the connection it opened -/// stays open. -/// -/// -/// A scope holds nothing: disposing it does nothing, and -/// reading (or deconstructing it) throws -/// . -/// +/// Dispose the value exactly once; a copy disposes again. +/// Deconstruct a scope you hold, never the call itself, which drops the scope and leaves a connection it opened open. +/// Connection scopes. /// /// The type of the connection, as the caller holds it. public readonly struct ConnectionScope : IDisposable, IAsyncDisposable @@ -169,7 +115,7 @@ public void Deconstruct(out TConnection connection, out ConnectionState priorSta /// /// Lets go of the connection the way its source calls for: closes it if the scope opened it /// (a connection the caller held), disposes it (a factory's), or gives it back to the pool - /// (a pool's). See the table in the remarks of the type. + /// (a pool's). See the remarks of the type. /// public void Dispose() { @@ -264,11 +210,6 @@ public CommandBehavior ReaderBehavior(CommandBehavior behavior = CommandBehavior /// Configures how awaits the disposal of this scope. /// /// - /// Library code takes the scope first, then hands it to on its own line: - /// - /// var scope = await connection.EnsureOpenScopeAsync(cancellationToken).ConfigureAwait(false); - /// await using var disposal = scope.ConfigureAwait(false); - /// /// The library never returns to a caller's context; whether to is the caller's choice at their own call site, /// as with . /// diff --git a/Source/Core/Core/NullPolicy.cs b/Source/Core/Core/NullPolicy.cs index 58cbf4fc..09efe04c 100644 --- a/Source/Core/Core/NullPolicy.cs +++ b/Source/Core/Core/NullPolicy.cs @@ -16,7 +16,7 @@ public enum NullAction /// /// The same as no policy. On a member it overrides the type's policy, so one hot member can opt out. /// A NULL into a nullable member is ; - /// into a non-nullable one it surfaces as the provider's own exception inside a that names the model type and, when the row is known, the row (the member and the column are not known). + /// into a non-nullable one it throws naming the model type and the row, not the member or the column. /// To find which member and column, use . /// /// @@ -50,21 +50,11 @@ public enum NullAction /// Declares what a NULL does to a member when a row is mapped: on the model type for every member, or on one member. /// /// -/// /// A policy always applies, nullable members included. -/// On the type it covers every member, and a member's own policy overrides it ( included). -/// A on a member overrides any policy, the member's own included. -/// A positional record's parameter takes the policy on the parameter or on its property. -/// A pair or a converter of a that names the member is explicit and overrides the member's own declarations in that map (the type's policy still covers it); -/// a converter whose column type is a receives the NULL itself, and no policy applies. -/// A converter whose column type is a reference type () is not called for a NULL; the member then follows the NULL rules and the type's policy. -/// A policy on a base type covers a derived model's members. The nearest declaration wins: the derived type's own policy, then its base type's; -/// a member's own policy beats both, and a beats all. -/// The declarations are read once per type, when its slots are built. -/// -/// -/// Every check costs one NULL test per covered member per row. A member with no policy is not checked (). -/// +/// On the type it covers every member, and a policy on a base type covers a derived model's members. +/// A member's own policy overrides the type's, and a on a member overrides any policy. +/// A member with no policy is not checked (). +/// See Null policy. /// /// /// diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index 08958118..52dfe7da 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -12,81 +12,21 @@ namespace Open.Database.Extensions; /// /// /// Use a map when the columns are named differently from the members. -/// Declare it once and pass it as the map argument of the query methods (Map<T>, ToChannel<T>, …). -/// A map is immutable and thread-safe, and caches its compiled row readers. One built at a call site is rebuilt on every call, so declare it once. -/// Declare it with the collection syntax, RowMap<Post> map = [new(nameof(Post.Id), "post_id")];, or with the constructor, from one pair or several; a map enumerates the pairs it was declared with. +/// Pass it as the map argument of the query methods (Map<T>, ToChannel<T>, …). +/// A map is immutable and thread-safe, and caches its compiled row readers. One built in a call is rebuilt on every call, so declare it once. +/// Declare it with the collection syntax, RowMap<Post> map = [new(nameof(Post.Id), "post_id")];, or with the constructor. /// /// -/// Properties the map does not mention still map by name: a column feeds the property of that name exactly, else ignoring case, else ignoring case and underscores (q_type feeds QType). -/// A property with a pair is only matched by its column, exactly or ignoring case; a column means "do not map this property". +/// The pairs are validated when the map is constructed, and a type that cannot be mapped throws when the map is constructed or is read. +/// A NULL into a member the C# type declares non-nullable throws , and a property no column feeds throws it too. /// /// -/// A type with no public parameterless constructor is built through its one public constructor (a positional record, a record struct, a class with one constructor), and each parameter is fed like a property. -/// A parameter and a public property whose names differ only in case are one member, fed once, through the constructor, and a pair names it by the property's name (exactly) or by the parameter's name (ignoring case). -/// A parameter no column feeds, or a column ignores, receives its declared default value, else ; a parameter a column feeds receives the column's value, under the NULL rules below. -/// -/// -/// A property must be fed by a column in every result shape, and a constructor parameter's default never feeds it: -/// when none does, building the row reader throws ( is the column looked for), -/// which happens when the first row of that shape is mapped, so a query with no rows never reports it -/// (the buffered routes and the Channel and Dataflow methods know the columns before any row, and report it as soon as they have them). -/// A constructor marked SetsRequiredMembers promises to set them: nothing is enforced then, and they map like any other property. -/// -/// -/// The pairs are validated when the map is constructed: an unknown or unsettable property or constructor parameter, a member named twice, an empty column name, a column for a required property, -/// or two members reading one column throw . -/// -/// -/// A type that cannot be mapped throws when the map is constructed or is read, which every query method does at the call, even when the result is empty: -/// -/// -/// an interface, an abstract class or a delegate; -/// a single value such as or (use Map<T>() on a command to read one column); -/// a dictionary or a dynamic object (Dictionary<string, object?>, : they have no properties to set, so use AsDictionaryRows() or Map(selector)); -/// a type with two or more public constructors and none without parameters; -/// a class with no public constructor; -/// a type with a public field (a field is never mapped, so it cannot be set), unless the constructor it is built through is marked [SetsRequiredMembers]; -/// a type whose [Column] and [NotMapped] declarations cannot all be honoured (see below). -/// -/// -/// A NULL into a member the C# type declares non-nullable is an error: a value type other than (an enum counts), or a reference type with nullable annotations on (string, not string?). -/// The row throws naming the model type and the 0-based row, with the provider's error, if it raised one, as the inner exception. -/// A member that takes NULL receives : , a reference type declared nullable (string?, or [AllowNull] on a property), a reference type in code with nullable annotations off, and a member declared as a type parameter. -/// A on a member or on says what a NULL does instead, whatever the member's type, -/// and a on a member replaces a NULL with its value, over any policy; -/// a pair or a converter of this map that names a member overrides the member's own declarations (the type's policy still covers it). -/// -/// -/// A member that declares its column is a hard instruction, and a result that does not say the same throws. -/// The attributes are those of System.ComponentModel.DataAnnotations.Schema, read by full name: -/// -/// -/// [Column("name")] reads that column (exactly, else ignoring case; never inferred), and none in the result throws ; -/// [Column(Order = n)] says column n is the member's (its declared name, else its own name, exactly or ignoring case, never ignoring underscores), and another column there, or too few columns, throws naming the member, the ordinal and what is there; -/// [NotMapped] leaves the member out: no column feeds it, whatever its name, unless a pair names it. -/// -/// -/// These are checked once per result set, when the row reader is built, and a result set that fails is checked again the next time it comes back. -/// A [NotMapped] member that is also [Column], required, or set by a constructor parameter, two members that declare the same ordinal or name, and a declaration with an empty name or a negative ordinal are a type error (). -/// A pair that names a declared member overrides its declarations for that map: -/// it reads the pair's column, a column leaves it unread, and a [NotMapped] member it names is mapped; its own Name and Order checks do not apply. -/// A type error above still throws whatever the map says, and the other members keep their declarations. -/// A NULL follows the NULL rules above, declared or not. -/// -/// -/// A column that needs a trim, a parse or a format on its way to a member has a converter: -/// map.Convert<long, string>(nameof(Order.Number), n => n.ToString("D6")) returns a new map (this one is unchanged) -/// in which the member receives what the delegate makes of its column, and every other member still maps by name. -/// The delegate receives the column's own value when the column is a TColumn, -/// else the value read the way Map<int>() reads a single value: an integer converts only within the range of TColumn, else the row throws . -/// -/// -/// A converter is not called for a NULL cell, and the member follows the NULL rules above: -/// for a nullable member, for a non-nullable one. -/// A converter that must see NULL names a as TColumn (int?, DateTime?): it is called with , -/// and what it returns is the member's value, a non-nullable member's included. -/// A converter of a reference-type column (text included) is never called with , whatever its parameter is annotated as. -/// A converter is not a pair: a map enumerates the pairs it was declared with and the columns Convert was given, never the delegates. +/// See Records and constructors, +/// Columns named differently, +/// Null policy, +/// NULL in a non-nullable column, +/// Converting a column +/// and Errors. /// /// /// @@ -326,16 +266,15 @@ public static RowMap From(Delegate factory, params ReadOnlySpan /// /// The column is the one the map already names for the member (a pair), - /// else the one the member matches by name - /// (exactly, ignoring case, then ignoring case and underscores). + /// else the one the member matches by name. /// To name the column here, use /// . - /// The delegate is not called for a NULL cell, - /// unless is a - /// (see ). + /// The delegate runs once per row; a NULL cell is not passed to it, + /// unless is a . /// A lambda does not say what the column is read as: /// name the types, Convert<long, string>(...), /// or type the parameter of the lambda. + /// See Converting a column. /// /// The type the column is read as and the delegate receives: the column's own type, else any type a single value can be read as (Map<TColumn>()); an integer converts only within its range. /// The type the delegate returns: the member's type, or one assignable to it. diff --git a/Source/Core/Core/RowMapping.docs.xml b/Source/Core/Core/RowMapping.docs.xml index 13153b75..89bc2f04 100644 --- a/Source/Core/Core/RowMapping.docs.xml +++ b/Source/Core/Core/RowMapping.docs.xml @@ -6,29 +6,11 @@ (the file path is relative to the source file). A key may carry several elements; an include inside brings paragraphs. - map The optional "map" parameter of the query methods. - map-declare-once The paragraph that says to declare a map once. - declare-once The same, for a member that builds a map. + declare-once The paragraph that says to declare a map once. mappings The "mappings" parameter of the members that build a map. mapping-exceptions The two exceptions every member that builds a map raises. - obsolete-12 The paragraph of every member obsolete in 11.0. --> - - - An optional prebuilt ; - reads by column name. - - - - - - Declare the once and pass it: a map built in the - call (a new RowMap<T>(...) or a collection expression in - the argument) is rebuilt, and its row reader compiled, on every call. - - - Declare the map once: a map built in a call is rebuilt, and its row diff --git a/Source/Core/DbConnectionFactory.cs b/Source/Core/DbConnectionFactory.cs index 901badf6..a70dab15 100644 --- a/Source/Core/DbConnectionFactory.cs +++ b/Source/Core/DbConnectionFactory.cs @@ -30,6 +30,7 @@ protected DbConnectionFactory(Func factory) /// The connection returned by the factory function. The caller owns it and is responsible for disposing it. /// /// Exceptions thrown by the factory function propagate unchanged. + /// The function must return a connection; is not supported. /// public IDbConnection Create() => _factory(); diff --git a/Source/Core/DbNonQuery.cs b/Source/Core/DbNonQuery.cs index 1e36445a..8a02d02e 100644 --- a/Source/Core/DbNonQuery.cs +++ b/Source/Core/DbNonQuery.cs @@ -105,7 +105,7 @@ public OutputDbNonQuery Output(string name) /// The scale, up to the precision. /// The definition, to be run with ExecuteOutputAsync. /// is not a . - /// The precision or the scale is not a decimal's. + /// is 0 or more than 38, or is more than . public OutputDbNonQuery Output( string name, byte precision, @@ -124,7 +124,7 @@ public OutputDbNonQuery Output( /// The precision, from 1 to 38. /// The scale, up to the precision. /// The definition, to be run with ExecuteOutputAsync; NULL reads as . - /// The precision or the scale is not a decimal's. + /// is 0 or more than 38, or is more than . public OutputDbNonQuery OutputDecimal( string name, byte precision, @@ -282,7 +282,7 @@ public OutputDbNonQuery Output(string name) /// The scale, up to the precision. /// The definition, to be run with ExecuteOutputAsync. /// is not a . - /// The precision or the scale is not a decimal's. + /// is 0 or more than 38, or is more than . public OutputDbNonQuery Output( string name, byte precision, @@ -301,7 +301,7 @@ public OutputDbNonQuery Output( /// The precision, from 1 to 38. /// The scale, up to the precision. /// The definition, to be run with ExecuteOutputAsync; NULL reads as . - /// The precision or the scale is not a decimal's. + /// is 0 or more than 38, or is more than . public OutputDbNonQuery OutputDecimal( string name, byte precision, diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index ccb50f72..d8e97fc3 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -193,8 +193,11 @@ internal static string Checked(string text, string paramName) /// /// Returns a new definition with the command timeout set; - /// this one is not changed. + /// this one is not changed. Without it the provider's default timeout applies. /// + /// + /// The lookup of a stored procedure's parameter names is not bounded by this timeout. + /// /// /// The number of seconds to wait for the command. /// @@ -280,6 +283,7 @@ public ScalarDbQuery Scalar() /// The values are then given in one call, which the compiler checks: /// .Using(db).AddParams(new(AuthorId: authorId, Day: day)). /// A class object that already exists (for example a deserialized request) is added with AddParams on the untyped definition. + /// For the lightest call, use a . /// /// The type of the values. /// The typed definition. diff --git a/Source/Core/DbQueryUsing.cs b/Source/Core/DbQueryUsing.cs index e76c707e..c1a26ed9 100644 --- a/Source/Core/DbQueryUsing.cs +++ b/Source/Core/DbQueryUsing.cs @@ -98,7 +98,8 @@ internal DbQueryCall WithParams(ParamList values) /// /// Adds the public properties and fields of - /// as parameters, each under its own name. + /// as parameters, matched to the names the procedure or the text declares + /// (each under its own name where those are not known). /// /// The type of the values. /// The object to read the values from. @@ -108,16 +109,13 @@ internal DbQueryCall WithParams(ParamList values) /// /// Declare the type with /// to have it checked at compile time. - /// For the lightest call, use a typed definition with a . + /// The members are read when the query runs, not when this is called. /// public DbQueryCall AddParams(T values) where T : notnull => ToCall().AddParams(values); /// Adds an input parameter named as you write it. - /// - /// For the lightest call, declare the values with and a . - /// /// The type of the value. /// The name of the parameter. /// @@ -284,7 +282,8 @@ internal DbQueryUsing(DbQuery definition, object source) /// /// Adds the public properties and fields of - /// as parameters, each under its own name. + /// as parameters, matched to the names the procedure or the text declares + /// (each under its own name where those are not known). /// /// The values. /// diff --git a/Source/Core/ExpressiveCommand.cs b/Source/Core/ExpressiveCommand.cs index 7e6e9aed..7879513f 100644 --- a/Source/Core/ExpressiveCommand.cs +++ b/Source/Core/ExpressiveCommand.cs @@ -8,7 +8,7 @@ /// Create one with the Command and StoredProcedure extension methods in , add parameters with AddParam, optionally set a timeout and cancellation token, then run it with one of the execute methods (for example ExecuteNonQuery, ExecuteScalar, ExecuteReader, or Map<T>()). /// /// -/// Connections follow a "get in, get out" model. Each execution takes a connection, opens it only if it is not already open, builds the database command, runs it, and releases the connection. A connection supplied directly is closed again only if this execution opened it and is never disposed. A connection that comes from a factory is disposed after the execution, and one that comes from a pool is given back to the pool. +/// Each execution takes a connection, opens it only if it is not already open, builds the database command, runs it, and releases the connection. A connection supplied directly is closed again only if this execution opened it and is never disposed. A connection that comes from a factory is disposed after the execution, and one that comes from a pool is given back to the pool. /// /// /// A command built on a single connection supports one execution at a time; overlapping executions throw . Commands built on a factory or pool use a separate connection for each execution. @@ -133,19 +133,13 @@ protected override ImmutableArray GetProcedureParameterNames(IDbConnecti => connection is DbConnection db ? ProcedureSchemaNames.Get(db, procedure) : default; /// - /// Asynchronously gets the parameter names a stored procedure declares - /// through the ADO.NET schema collection ProcedureParameters when the - /// connection is a . The lookup is asynchronous - /// on net10.0 and later (GetSchemaAsync). The netstandard targets have - /// no such method: there the lookup blocks the calling thread and returns a - /// task that is already complete. + /// Asynchronously gets the parameter names a stored procedure declares through the ProcedureParameters schema collection. /// /// An open connection to run the lookup on. /// The procedure name as given to the command. /// - /// On net10.0 and later the token is passed to GetSchemaAsync and can - /// cancel the lookup; on the netstandard targets it is only checked before - /// the lookup starts. + /// The token that cancels the lookup. + /// On the netstandard targets the lookup is synchronous and the token is only checked before it starts. /// /// /// is canceled. diff --git a/Source/Core/ExpressiveCommandBase.Capture.cs b/Source/Core/ExpressiveCommandBase.Capture.cs index 623ad968..1178d741 100644 --- a/Source/Core/ExpressiveCommandBase.Capture.cs +++ b/Source/Core/ExpressiveCommandBase.Capture.cs @@ -123,7 +123,8 @@ public TThis CaptureOutput( /// /// Reads one output parameter of the given precision - /// and scale when the next terminal runs the command. + /// and scale, as when it is NULL, when the next + /// terminal runs the command. /// /// diff --git a/Source/Core/ExpressiveCommandBase.Output.cs b/Source/Core/ExpressiveCommandBase.Output.cs index 293c64d1..74fbd863 100644 --- a/Source/Core/ExpressiveCommandBase.Output.cs +++ b/Source/Core/ExpressiveCommandBase.Output.cs @@ -20,9 +20,7 @@ public abstract partial class ExpressiveCommandBase /// Each member Map<TOut>() would read is an output parameter, built by the same rules (constructors, records, /// required, conversion, [NullPolicy], [NullValue], [NotMapped]). - /// A member is matched to the parameter the way AddParam(value) is: when the names are known (a procedure's, or the - /// @name markers of a text) by the same tiers (exact, ignoring case, ignoring case and underscores, then after a common prefix such as p_ is removed from the parameter's name), and a member that matches none throws; otherwise it is sent under its own name. - /// [Column("name")] names the parameter exactly. + /// A member is matched to a parameter the way AddParam(value) is; [Column("name")] names it exactly. /// /// /// A member whose parameter was given a value (AddParam, AddParams) is sent as @@ -34,16 +32,11 @@ public abstract partial class ExpressiveCommandBaseReturnValue reads a stored procedure's return code. /// /// - /// - /// - /// A or array is sent with size -1 (the whole value). - /// - /// /// /// /// To read one value instead of a model, name it: . + /// Output parameters. /// - /// /// /// The model the output parameters are read into. /// @@ -143,7 +136,7 @@ public ValueTask ExecuteOutputAsync( /// decimal total = await connection /// .StoredProcedure("dbo.OrderTotal") /// .AddParam(orderId) - /// .ExecuteOutputAsync<decimal>("total", 19, 4); + /// .ExecuteOutputAsync<decimal>("total", 19, 4, cancellationToken); /// /// /// , or a of it. @@ -232,7 +225,7 @@ static async ValueTask NotNullAsync(string name, ValueTask va /// decimal? total = await connection /// .StoredProcedure("dbo.OrderTotal") /// .AddParam(orderId) - /// .ExecuteOutputDecimalAsync("total", 19, 4); + /// .ExecuteOutputDecimalAsync("total", 19, 4, cancellationToken); /// /// /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 92934243..e11fdf15 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -9,7 +9,7 @@ namespace Open.Database.Extensions; /// /// /// For a command you run more than once, use . This builder is for a command you build and run once. -/// A command whose text is a string literal sends an input parameter's name written without its @ under the text's own spelling; a parameter that is not an input keeps the name it was added with, as the caller reads it back by that name. +/// A command whose text is a string literal sends an input parameter's name written without its @ under the text's own spelling; a parameter that is not an input keeps the name it was added with. /// /// The type of the connection to be used. /// The type of the commands generated by the connection. @@ -335,7 +335,7 @@ public CancellationToken CancellationToken CancellationToken IExecuteReader.CancellationToken => CancellationToken; /// - /// Sets the cancellation token. + /// Sets the token that cancels the command's calls; a terminal's own token also cancels them (either one cancels). /// /// The token to use. /// This instance for use in method chaining. @@ -476,51 +476,10 @@ public TThis AddParam(string name, string? value) /// /// The argument must be a variable or a chain of member accesses (properties and fields alike): startDate, filter.AuthorId, post.Author.Id. /// Anything else (a call, an index, an operator, a literal) throws : use and name the parameter. - /// The name is settled when the command executes. The real parameter names are: - /// - /// for a stored procedure, the names the provider reports for the procedure; - /// - /// for a text command, the @name markers found in its SQL text - /// (not those inside a string, a quoted identifier or a comment, - /// and not @@system variables). - /// - /// - /// The argument is matched to one of them, trying in turn: - /// - /// exactly; - /// ignoring case; - /// ignoring case and underscores, so AuthorId finds @author_id; - /// - /// failing those, for the same argument, after removing one common - /// parameter prefix from the real name - /// (p_, in_, i_, prm_, par_, v_, - /// or a lone p before a capital letter), - /// so Author finds @p_author and @pAuthor. - /// - /// - /// - /// A field prefix on the last member (m_, s_ or _) is - /// also tried without. - /// A chain tries its more specific endings first: - /// post.Author.Id tries postAuthorId, AuthorId, then Id. - /// A name that matches nothing, matches two parameters at one tier, - /// or is claimed by two arguments throws - /// that says what you wrote and, - /// when the names are known, what the procedure declares. - /// - /// - /// A stored procedure's names are read once per server and database when its name has a - /// schema (dbo.get_author), the connection is a that - /// reports its server and its database, and this is one of the library's own command - /// types; otherwise once per connection factory, pool or connection. They are read again - /// after a call that cannot be built (other than by cancellation) or that the database - /// rejects. - /// - /// - /// Where the real names are not available (a text command with no - /// @name marker, or a provider that does not supply them) the last - /// member is used as written. - /// + /// The name is the last member of the argument as written. When the command executes, it is matched to the procedure's or the text's parameter names (exact, then ignoring case, then ignoring case and underscores, then after a common prefix such as p_). + /// A name that matches nothing, or two parameters, throws when the command executes. + /// Where the real names are not available, the name is used as written. + /// Name a parameter from its argument. /// /// The type of the value. /// The value of the parameter. A is sent as a database null. @@ -552,7 +511,7 @@ public TThis AddParamIf(bool condition, T value, [CallerArgumentExpression(na /// Adds the public properties and fields of as parameters, under the real names the stored procedure declares for them (AuthorId as @author_id). /// /// - /// Each member is matched to the stored procedure's real parameter names the same way as . + /// Members are matched as is. /// When the real names are known, a member that the procedure does not declare is not sent, so one object can serve several procedures; parameters the procedure declares that no member matches are left to default values or to explicit AddParam calls. /// Where the real names are not known (a text command with no @name marker, or a provider that does not supply them) every member is sent under its own name. /// A parameter you add with AddParam, by name or from an argument, wins over a member that resolves to the same name. @@ -753,6 +712,9 @@ public TThis AddParamIf(bool condition, string name, TDbType type) /// /// Sets the command timeout. /// + /// + /// The lookup of a stored procedure's parameter names also runs with this timeout on a command made by the MSSqlClient package; on any other command that lookup is not bounded by it. + /// /// The command timeout, in seconds. /// This instance for use in method chaining. public TThis SetTimeout(ushort seconds) @@ -767,12 +729,8 @@ public TThis SetTimeout(ushort seconds) /// The provider then streams each row instead of buffering it, and a column can be read once, in ascending order. /// It applies to every reader this command opens from then on: a reader callback, the Map terminals (also of a view made before this call) /// and the terminals. It stays on the command. - /// Without it the library reads with the default access mode. - /// - /// - /// The typical use is to copy one very large value as a stream: select the key columns first and the large column last, - /// and read it in a reader callback with . /// A selector given to Map must read the columns in ascending order, or the provider throws. + /// Sequential access, for very large values. /// /// /// diff --git a/Source/Core/Extensions/Command.AddParameter.cs b/Source/Core/Extensions/Command.AddParameter.cs index e0767fe3..093a70f9 100644 --- a/Source/Core/Extensions/Command.AddParameter.cs +++ b/Source/Core/Extensions/Command.AddParameter.cs @@ -127,6 +127,10 @@ public static IDbDataParameter AddParameter( /// /// Adds a typed parameter with the given name, value, and direction to the command. /// + /// + /// A parameter needs no name. + /// To add an unnamed return value, use . + /// /// /// The name of the parameter. It can be only when is . /// The value of the parameter. It is assigned as given: a is not converted to , so pass to send a database null. diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 76a145ec..b01fbef7 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -159,7 +159,7 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, /// it must already be open, and the caller owns and disposes the reader. /// /// - /// + /// /// /// /// A task that represents the asynchronous operation. @@ -192,7 +192,7 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// /// /// - /// + /// /// /// A task that represents the asynchronous operation. /// @@ -222,7 +222,7 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, /// /// /// - /// + /// /// /// A task that represents the asynchronous operation. /// @@ -263,7 +263,7 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// /// /// - /// + /// /// /// A task that represents the asynchronous operation. /// @@ -290,7 +290,7 @@ public static ValueTask ExecuteReaderAsync(this DbCommand command, /// /// /// - /// + /// /// /// /// A task that represents the asynchronous operation. @@ -313,7 +313,7 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, /// /// - /// + /// /// /// public static ValueTask ExecuteReaderAsync(this IDbCommand command, diff --git a/Source/Core/Extensions/Connections.docs.xml b/Source/Core/Extensions/Connections.docs.xml index 8f1c7cdf..93c05455 100644 --- a/Source/Core/Extensions/Connections.docs.xml +++ b/Source/Core/Extensions/Connections.docs.xml @@ -52,11 +52,6 @@ on rolling back. tx-async-para The paragraph that applies to the asynchronous forms. - Obsolete overloads - configure-await-ignored - The summary and the configureAwait parameter of the - obsolete overloads that ignore it. - Factories as-pool-remarks The remarks of the AsPool methods. --> @@ -125,7 +120,10 @@ - The function that creates the connection. + + The function that creates the connection. It must return a connection; + is not supported. + The action to execute. It receives the connection. or is @@ -134,7 +132,10 @@ - The function that creates the connection. + + The function that creates the connection. It must return a connection; + is not supported. + The asynchronous action to execute. It receives the connection. or is @@ -189,7 +190,6 @@ - Useful for single-line operations. Exceptions thrown by the action propagate after the connection has been disposed. If opening the connection throws, it is disposed before the exception @@ -199,7 +199,6 @@ - Useful for single-line operations. Exceptions thrown by the action propagate after the connection has been given back to the pool. If opening the connection throws, it is given back before the exception @@ -210,7 +209,6 @@ The connection is not opened by this method. - Useful for single-line operations. Exceptions thrown by the action propagate after the connection has been disposed. @@ -219,7 +217,6 @@ The connection is not opened by this method. - Useful for single-line operations. Exceptions thrown by the action propagate after the connection has been given back to the pool. @@ -386,63 +383,40 @@ If the connection is not open, it is opened first and closed (not - disposed) when the transaction completes, even if it fails. - A connection that was broken is closed and opened again, so it is closed - afterwards too. + disposed) when the transaction completes, even if it fails; + a broken connection is closed and opened again. A connection that was already open is left open. - A failure while closing is ignored, as by then the transaction has - already been committed or rolled back. + A failure while closing is ignored. To keep a connection open across several operations, open it before calling. - An exception thrown by the action, or a cancellation, rolls the - transaction back and propagates. - A transaction that is not committed is rolled back by disposing it, - which is the standard ADO.NET pattern; the .NET documentation for - notes that this is provider - specific. - The transaction is always disposed before the connection is closed, as - some providers (for example Microsoft.Data.Sqlite and MySqlConnector) - only roll back an uncommitted transaction on dispose while the - connection is still open. - The action should not commit or roll back the transaction itself; - completion is handled here. - When no isolation level is given, + The transaction is disposed before the connection is closed. + An exception or a cancellation rolls back and propagates. + The action must not commit or roll back the transaction itself. + With no isolation level given, is used. + Transactions. - The transaction is disposed with DisposeAsync, and the connection - closed with CloseAsync, where the target has them (not - netstandard2.0, which does both synchronously). - The token is checked just before the commit, and the commit itself is not - canceled once it has begun: cancelling part-way through would leave the - outcome unknown. + The transaction is committed with CommitAsync, disposed with + DisposeAsync, and the connection closed with CloseAsync. + The token is checked just before the commit; the commit is not + canceled once it has begun. - - - - - The argument is ignored: the library - always uses ConfigureAwait(false). - - - Ignored. The library always uses ConfigureAwait(false). - - - - This is the "get in, get out" model: every command execution creates its - own connection, opens it only if needed, and disposes it when the command - is finished. + Each execution creates a connection from the factory, opens it only if + needed, and disposes it when the command is finished. + The factory must return a connection; is not + supported. diff --git a/Source/Core/Extensions/DataReader.cs b/Source/Core/Extensions/DataReader.cs index 1a1f9d60..3429fee1 100644 --- a/Source/Core/Extensions/DataReader.cs +++ b/Source/Core/Extensions/DataReader.cs @@ -20,13 +20,8 @@ public static class DataReaderExtensions /// /// /// - /// The token is checked before each read: - /// a cancel throws, and the read is not made. - /// A cancel during the handler of a row lets that row finish, - /// then throws at the next check, even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. - /// Rows already handed out stay handed out. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early without an exception, /// use /// and return . @@ -97,11 +92,8 @@ static bool ReadNext( /// The token is passed to ReadAsync, so the provider /// cancels the read itself. When /// is it is checked before each Read instead. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the handler of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// /// /// The to iterate. @@ -173,11 +165,8 @@ public static async ValueTask ForEachAsync( /// /// The token is passed to ReadAsync, so the provider /// cancels the read itself. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the handler of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// /// /// The to iterate. @@ -193,11 +182,8 @@ public static ValueTask ForEachAsync(this DbDataReader reader, Func /// The token is passed to ReadAsync, so the provider /// cancels the read itself. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the handler of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// /// /// The to iterate. @@ -247,14 +233,8 @@ IEnumerable SelectCore() /// The iteration is deferred: nothing is read, /// and a canceled token does not throw, /// until the result is enumerated. - /// The token is checked before each read: - /// a cancel throws from the enumeration, and the read is not made. - /// A cancel while a row is being yielded or transformed - /// lets that row finish, then throws at the next check, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. - /// Rows already handed out stay handed out. + /// A canceled token throws from the enumeration before the next read; + /// rows already handed out stay handed out. /// To stop early without an exception, stop enumerating. /// /// @@ -527,12 +507,8 @@ public static IAsyncEnumerable AsAsyncEnumerable(this DbDataReader rea /// The iteration is deferred until the result is enumerated. /// The token is passed to ReadAsync, /// so the provider cancels the read itself. - /// A cancel throws from the enumeration. - /// A cancel while a row is being yielded or transformed - /// throws at the next read, even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. - /// Rows already handed out stay handed out. + /// A canceled token throws from the enumeration before the next read; + /// rows already handed out stay handed out. /// To stop early without an exception, leave the loop. /// /// @@ -667,10 +643,6 @@ public static ValueTask ToArrayAsync(this DbDataReader reader, /// /// Asynchronously iterates the remaining records of the current result set and returns the results of an asynchronous transform as an immutable array. /// - /// - /// On .NET 8 and later the immutable array wraps the array of the results, which is not copied again; - /// on .NET Standard it is a copy of it, as there is no way to wrap an array there. - /// /// /// The to read from. /// @@ -800,13 +772,8 @@ public void Dispose() { } /// /// /// - /// The token is checked before each read: - /// a cancel throws, and the read is not made. - /// A cancel during the predicate of a row lets that row finish, - /// then throws at the next check, even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. - /// Rows already handed out stay handed out. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early, return from the predicate: /// that ends the iteration without an exception. /// @@ -852,11 +819,8 @@ public static void IterateWhile( /// /// The token is passed to ReadAsync, so the provider /// cancels the read itself. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the predicate of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early, return from the predicate: /// that ends the iteration without an exception. /// @@ -895,11 +859,8 @@ public static async ValueTask IterateWhileAsync( /// cancels the read itself. /// When /// is it is checked before each Read instead. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the predicate of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early, return from the predicate: /// that ends the iteration without an exception. /// @@ -944,12 +905,9 @@ static async ValueTask IterateWhileAsyncInternal(IDataReader reader, Func /// /// A is read with ReadAsync, so the provider cancels the read itself; - /// any other reader is checked before each Read, and a cancel throws before the read is made. - /// A cancel throws, and rows already handed out stay handed out. - /// A cancel during the predicate of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// any other reader is checked before each Read. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early, return from the predicate: /// that ends the iteration without an exception. /// @@ -1004,11 +962,9 @@ public static async ValueTask IterateWhileAsync( /// /// When is , a is read with ReadAsync, /// so the provider cancels the read itself. - /// Otherwise the token is checked before each Read, and a cancel throws before the read is made. - /// A cancel during the predicate of a row throws at the next read, - /// even if that row was the last. - /// Once a read has returned no row the result is complete, - /// and a cancel after that is not an error. + /// Otherwise the token is checked before each Read. + /// A canceled token throws before the next read; + /// rows already handed out stay handed out. /// To stop early, return from the predicate: /// that ends the iteration without an exception. /// diff --git a/Source/Core/Extensions/DataRecord.cs b/Source/Core/Extensions/DataRecord.cs index 560602a3..d0ed53af 100644 --- a/Source/Core/Extensions/DataRecord.cs +++ b/Source/Core/Extensions/DataRecord.cs @@ -125,7 +125,7 @@ public static IEnumerable OrdinalMapping(this IDataRecord record, /// The requested column names. /// to order the results by ordinal ascending; to keep the requested order. /// An array of mappings. It is empty if is an empty collection. - /// or is . + /// is , or is and is not empty. /// One or more requested columns do not exist. The message lists all the invalid names. public static ColumnOrdinal[] GetOrdinalMapping(this IDataRecord record, IEnumerable columnNames, bool sort = false) { diff --git a/Source/Core/Extensions/Readers.docs.xml b/Source/Core/Extensions/Readers.docs.xml index 45e3a748..1bebb7de 100644 --- a/Source/Core/Extensions/Readers.docs.xml +++ b/Source/Core/Extensions/Readers.docs.xml @@ -15,38 +15,12 @@ - - This is not the recommended way to read rows: it holds the - connection while your code runs for each row. - - The reader, and the connection under it, stay open for as long as - your code takes per row, added up over all the rows. -
-
- In async code that time has no bound: every - in the loop body can yield, and nothing says - when the loop resumes. - Until it does, the connection is on hold: a pooled connection is - not returned to the pool, and the server may keep its locks and the - open result set. -
-
- These members suit work that must happen while the connection is - open, for example a result too large to buffer or a row-by-row - pipeline. - Otherwise use a call that lets go of the connection first: - - and - - buffer the rows and release the connection - (call .Map<T>() first), and - - streams them to a consumer without holding it - (the producer is unbounded: it reads without waiting for the - consumer and frees the connection while the consumer takes its - time, and the rows wait in memory until the consumer takes them; - dispose the enumerator, as - does). + Holds the reader and its connection open while your code runs for each + row; a pooled connection is not returned until the loop ends. + To release it sooner, buffer with ToListAsync or + ToArrayAsync after Map<T>(), or stream with + ToPooledStream. + Reader and command helpers.
@@ -75,29 +49,6 @@
- - - The values are read into a queue first, so the reader and its - connection can be released before the result is consumed. - Each value is removed as it is enumerated, so the result can be - enumerated only once. - - - - - - Only the first result set is read. - - - - - - Declare the once and pass it: a map built in - the call (a new RowMap<T>(...) or a collection expression - in the argument) is rebuilt, and its row reader compiled, on every call. - - - @@ -195,21 +146,6 @@ The to iterate. - - - The to read results from. - - - - - - The first column name to include in the request to the reader for each record. - - - The remaining column names to request from the reader for each record. - - - The limited set of ordinals to include. @@ -217,10 +153,6 @@ - - The column names to select. - - The pool to rent the row arrays from, or to @@ -317,18 +249,4 @@
- - - - - The model type to map the values to (using reflection). - - - - - - An optional prebuilt ; - reads by column name. - - diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index d604a1d5..feef0222 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -1,5 +1,7 @@ namespace Open.Database.Extensions; +// On netstandard2.0 the provider base types have no BeginTransactionAsync, DisposeAsync, CommitAsync or CloseAsync, +// so those paths begin, commit, dispose and close the transaction and connection synchronously. [SuppressMessage("Design", AnalyzerIds.CA1068, Justification = SuppressionJustifications.OverloadForEasierConsumption)] public static partial class TransactionExtensions { diff --git a/Source/Core/IDbConnectionFactory.cs b/Source/Core/IDbConnectionFactory.cs index e475838e..def94563 100644 --- a/Source/Core/IDbConnectionFactory.cs +++ b/Source/Core/IDbConnectionFactory.cs @@ -26,6 +26,7 @@ public interface IDbConnectionFactory /// A new . The caller owns it and is responsible for disposing it. /// /// The connection is not necessarily open. The expressive commands open it only if needed and dispose it when the command is finished. + /// The factory must return a connection; is not supported. /// IDbConnection Create(); } diff --git a/Source/Core/IDbConnectionPool.cs b/Source/Core/IDbConnectionPool.cs index f22db6c9..0c09f723 100644 --- a/Source/Core/IDbConnectionPool.cs +++ b/Source/Core/IDbConnectionPool.cs @@ -32,6 +32,7 @@ public interface IDbConnectionPool /// An that the caller hands back with when finished. /// /// The connection is not necessarily open. Callers that execute commands open it only if needed (see ) and put it back in its original state when they are done. + /// The pool must return a connection; is not supported. /// /// IDbConnection Take(); @@ -39,7 +40,7 @@ public interface IDbConnectionPool /// /// Gives a connection back to the pool. /// - /// The connection previously provided by . + /// The connection provided by . /// /// Depending on the implementation, the pool could be full and the connection disposed of immediately, or the pool could restore the connection to the state it was in when it was taken. /// diff --git a/Source/Core/IMappedQuery.cs b/Source/Core/IMappedQuery.cs index 1db7520d..3bdd36fe 100644 --- a/Source/Core/IMappedQuery.cs +++ b/Source/Core/IMappedQuery.cs @@ -1,7 +1,7 @@ namespace Open.Database.Extensions; /// -/// A query that reads its rows into a channel or a block feed, or one at a time. +/// A query whose rows can be read into a channel or a dataflow block, or one at a time. /// /// /// , , and implement it. @@ -11,7 +11,7 @@ namespace Open.Database.Extensions; public interface IMappedQuery { /// - /// Reads the rows into pooled chunks, one chunk at a time, and frees the connection before the consumer sees a row. + /// Reads the rows into pooled chunks, one chunk at a time, while the consumer reads; the connection is released when the read ends. /// /// /// The chunks, in order. A chunk is valid until the enumeration moves on, so copy what you keep. The enumeration can be taken once. @@ -22,15 +22,12 @@ IAsyncEnumerable> ToPooledBufferStream( /// Reads the rows one at a time off the open reader, lazily, as you pull them: on your own thread, with nothing read ahead. /// /// - /// While you pull rows, this holds the reader and the connection open, and each row is read when you pull it, on your own thread: there is no producer task and no channel. - /// That is not the best way to read rows: to read all of them use ToArrayAsync or ToListAsync; to read while the query runs use StreamBuffered or ToPooledStream. - /// To read the rows as a list or an array, use - /// or : they release the connection before the task completes. - /// To read while the query runs, use , which releases it when the read ends. + /// Reads each row as you pull it, on your thread, with nothing read ahead; the connection is held until you pull past the last row. + /// To read all rows use or : they release the connection before the task completes. /// 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 . /// - /// + /// Which to use: Terminals. /// /// /// The longest you may go without pulling the next row. Required; there is no default. @@ -46,15 +43,14 @@ IAsyncEnumerable Stream( /// Reads the rows lazily through a bounded channel that buffers up to 1,024 rows (the read holds one more while it waits for room), stopping the read when you stop pulling once the buffer is full. /// /// - /// The buffer is a ceiling, not a target, and it counts rows, not bytes: wide rows (blobs) cost memory, for each stream running at once. - /// A consumer that keeps up leaves it nearly empty; a larger buffer lets the read ride out a slow consumer instead of waiting on every row. - /// A result that fits is read whole, the later result sets included, and the connection released before you have pulled every row. + /// Reads ahead into a buffer of up to 1,024 rows on a producer task; the connection is held until the read ends, or, once the buffer is full, until passes without a pull. + /// The buffer counts rows, not bytes, so wide rows (blobs) cost memory for each stream running at once. /// Breaking out early never throws for rows or result sets you did not reach. /// 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. /// - /// + /// Which to use: Terminals. /// /// /// The longest you may go without pulling the next row once the buffer is full. Required; there is no default. diff --git a/Source/Core/Mapped.docs.xml b/Source/Core/Mapped.docs.xml index 4be64684..296829e7 100644 --- a/Source/Core/Mapped.docs.xml +++ b/Source/Core/Mapped.docs.xml @@ -115,39 +115,10 @@ - All rows are buffered in memory before the call returns. + All rows are buffered in memory before the result is available. - - The type returned by the handler. - - - - - Receives a forward-only sequence of mapped rows. - Enumerate it inside the handler; it is not valid after the handler - returns. - - - - - - Receives a forward-only asynchronous sequence of mapped rows. - Enumerate it inside the handler; it is not valid after the handler - returns. - - - - - - Receives a forward-only asynchronous sequence of mapped rows and the - cancellation token in effect. - Enumerate it inside the handler; the sequence and the token are not - valid after the handler returns. - - - A task that completes after the handler has completed and the connection @@ -155,13 +126,6 @@ - - - A task that produces the value returned by - after the connection has been released. - - - A row whose value is NULL is still a row, and @@ -204,13 +168,10 @@ - How is mapped is the same as for - : - a reads columns whose names differ from the - properties, and the overload without one reads by column name - (exactly, else ignoring case, else ignoring case and underscores, so - author_id feeds AuthorId). + Columns are read by name; to read columns whose names differ from the + properties, pass a . A single value such as is read from the first column. + See Columns named differently. @@ -221,27 +182,10 @@ - - - The to run the reader with; - is always added. - The default is . - - - The command to read from. - - The type the transform returns. - The command to read from. - - The function that converts each to a - . - - - is . @@ -262,19 +206,6 @@ - - - A token that can cancel the call. - It is used together with the command's own token; either one cancels. - It comes after the optional : - pass it by name (cancellationToken: token) or pass the behavior - too. - - - The operation was canceled. - - - The type of the state passed to the transform. The type the transform returns. @@ -284,43 +215,9 @@ 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: - - - - Method - Buffer; threads; connection held until; stall protection - - - Stream - None: no row is read ahead; your loop's thread (with AsyncReads(), the thread that finishes each read), with no producer task and no channel; until you pull past the last row; yes, on every pull. - - - StreamBuffered - Up to bufferSize rows (default 1,024; it counts rows, not bytes), plus one the read holds while it waits for room; a producer task and your loop; until the read ends, or, once the buffer is full, until the stall timeout passes without a pull (never with an infinite timeout); yes, once the buffer is full. - - - ToPooledStream - Unbounded: pooled chunks, the whole result if you are slow; a producer task and your loop; until the read ends, however slowly you read; none. - - - - Which to use: a fast loop, Stream; slow or async work per row, StreamBuffered; to free the connection as soon as possible, ToPooledStream. - - - All three are lazy: calling one does nothing until the first MoveNextAsync. - A slow or hung database read is bounded by the command's CommandTimeout and your cancellation token on every one of them; - the stall timeout is only about a slow consumer. - A cancel or a dispose stops the read promptly only as far as the provider honors the cancellation. + Rows are read on your thread, so a slow read blocks it; the command's CommandTimeout bounds a read the provider is blocked in. - A Map terminal returns the rows of the first result set diff --git a/Source/Core/MappedDbQuery.cs b/Source/Core/MappedDbQuery.cs index 76932092..91155edb 100644 --- a/Source/Core/MappedDbQuery.cs +++ b/Source/Core/MappedDbQuery.cs @@ -11,19 +11,12 @@ namespace Open.Database.Extensions; /// /// It is immutable, so a static field holds it: /// static readonly MappedDbQuery<Post> ByAuthor = DbQuery.Procedure("ByAuthor").Map<Post>();. +/// What is set here applies to every query made from it. /// /// -/// From here the order is the caller's. -/// ByAuthor.Using(source).AddParam("authorId", id).ToListAsync(ct) is the first way to write it; -/// ByAuthor.AddParam("authorId", id).Using(source).ToListAsync(ct) gives the same command. -/// returns the ordinary view, with the -/// options of this definition applied, so every terminal, Skip and Take are the ones the view has. -/// -/// -/// Set on the definition, for every query made from it: the map, , , , -/// , and (on the before Map) -/// . A query made from it can still apply SingleResult, CancelOnEarlyStop, AsyncReads, -/// SequentialAccess and UsePool for one call. Chosen per call: the parameters, Skip and Take. +/// returns the ordinary view, with the options of this definition applied. +/// The parameters can be added before or after Using; the command is the same. +/// See Map the definition too. /// /// /// The type each row is mapped to. diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 5a576559..aeee36c2 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -11,61 +11,11 @@ public static partial class CoreExtensions /// , is invoked. /// /// - /// - /// The mapping is compiled once per result-set shape and cached. - /// - /// - /// A type with a public parameterless constructor is built with - /// new T(), and its public settable properties - /// ( and ones too) - /// are set from the columns. - /// Any other type is built through its one public constructor - /// (a positional record, a record struct, a class with one constructor), - /// and the properties the constructor does not cover are set afterwards. - /// A property needs a column. - /// A single value such as - /// (a primitive, an enum, , , - /// a date or time, , byte[] - /// or a of one) - /// is read from the first column of each row, - /// converted as a property of that type is; - /// a NULL into a non-nullable value type throws naming the type and the row, - /// so declare int? when a NULL is expected. - /// A that cannot be mapped - /// (an interface, an abstract class, - /// a type with two or more public constructors and none without parameters) - /// throws when the map is built or - /// is read, - /// which the overloads without a do at the call. - /// See Records and constructors. - /// - /// - /// Pass a to read columns whose names differ from the - /// properties; the overload without a map reads by column name. - /// Columns match a property exactly, else ignoring case, else ignoring case - /// and underscores (author_id feeds AuthorId). - /// Declare the once and pass it: a map built in the - /// call (a new RowMap<T>(...) or a collection expression in the - /// argument) is rebuilt, and its row reader compiled, on every call; see - /// Columns named differently. - /// - /// - /// A terminal returns the rows of the first result set only - /// (a result here is one whole result set, what - /// moves between; never a row) - /// and never maps a later set. - /// It then reads through the later sets without reading their rows, so a - /// failure in a later statement is thrown as the provider raised it. - /// That is not done with SingleResult(), written before Map - /// (command.SingleResult().Map<T>(), see - /// ) or after it - /// (command.Map<T>().SingleResult(), the same), - /// when the caller stops reading early, - /// when CancelOnEarlyStop() canceled the command, - /// or when the mapping, a selector or the caller's handler throws. - /// A later failure can follow a write that already committed, so a caller - /// that retries can repeat it, and the rows read are lost when it throws. - /// + /// Reads each row into . + /// Declare a once and pass it to read columns whose names differ; a map built in the call is rebuilt on every call. + /// See Records and constructors, + /// Columns named differently + /// and Results, and a failure after the first one. /// /// The command to read from. /// @@ -1314,13 +1264,9 @@ public readonly partial record struct MappedQuery /// Stops after the first result set and does not read through the later ones. /// - /// A result here is one whole result set, what moves between; never a row. - /// By default a terminal returns the rows of the first result set only, then reads through the later ones without mapping them, so a failure in a later statement is thrown instead of lost. - /// A later failure can follow a write that already committed, so a caller that retries can repeat it, and the rows read are lost when it throws. - /// This call asserts nothing: it does not check that there is only one result set. It stops after the first, and a later failure goes unseen. - /// A read-through also does not happen when the caller stops reading early or the mapping, the selector or the caller's handler throws. - /// FirstOrDefault, First and AnyAsync with nothing skipped also ask the provider for a single row (not with ). - /// command.SingleResult().Map<T>() (see ) is the same as command.Map<T>().SingleResult(). + /// Stops after the first result set, so a later failure is not seen. It does not check that there is only one result set. + /// A later failure can follow a write that already committed. + /// Results, and a failure after the first one. /// /// The same query, without the read-through. /// @@ -1331,50 +1277,14 @@ public MappedQuery SingleResult() /// Cancels the command when a terminal stops before the last row, so the rows nobody asked for are discarded instead of being read off the wire. Off by default. /// /// - /// - /// Use it when the query can return far more rows than the terminal needs and the SQL cannot limit them: - /// on SQL Server LocalDB, FirstOrDefaultAsync over 3 million rows took 202 ms without it and 0.4 ms with it - /// (with SingleResult() too, in either order). + /// Use it when the query can return far more rows than the terminal needs and the SQL cannot limit them. /// Do not use it for a TOP 1 or key lookup: there is nothing to save. - /// A one-row lookup there took about 80 microseconds with or without it, and allocated a few hundred bytes more with it. - /// SingleResult() is not a substitute: alone it took the same 202 ms, because it does not avoid reading the unread rows. - /// The single row it asks the provider for is a hint, not a limit on what the server sends. - /// - /// The command is canceled at a stop that may leave rows unread: - /// - /// First, FirstOrDefault and AnyAsync with a row; - /// Single and SingleOrDefault on a second row; - /// a Take at its limit (CountAsync too), and a Take(0); - /// a stream that is broken, disposed, stalled (its stallTimeout expired) or canceled by its token; - /// a read that ends in an exception. - /// - /// - /// A result seen to its end is not canceled: First, AnyAsync and a Take at its limit read one more row first, and cancel only if there is one. - /// A terminal that reads every row (ToListAsync, CountAsync, a stream read to its end) cancels only if the read itself fails, or at a Take limit with rows left; - /// the refusals below apply to it too. - /// - /// Before you use it: - /// - /// + /// SingleResult() is not a substitute: it does not avoid reading the unread rows. + /// A terminal that stops with rows left cancels the command. + /// A terminal throws before the command runs (a stream at its first pull) if the command has a transaction, + /// an output, input-output or return-value parameter, an ambient TransactionScope, or if the source hands out no command. /// After a cancel, a later statement of the batch may or may not run, and its error is not reported either way. - /// SQL Server does not run what it has not reached, but after a small result it may have run it already; SQLite runs it all the same. - /// - /// - /// A terminal throws , before the command runs, when the command has a Transaction - /// or an output, input-output or return-value parameter, inside a TransactionScope (Transaction.Current is set), - /// and when the source hands out no command (a data reader, a , your own ). - /// A stream throws it at its first pull, and ToPooledBuffer through the buffer. - /// - /// A BEGIN TRAN inside the SQL and XACT_ABORT are not detected: do not use it with them. - /// The reader's is lost. - /// A command of your own (Map on an ) is canceled too. - /// It is verified on SQL Server LocalDB, and with SQLite for usability only. - /// - /// - /// A provider whose Cancel throws is treated as not canceled: the reader is closed and the later result sets read through as without this. - /// A provider that ignores Cancel but returns normally drains the rows as without this, and the later result sets are still skipped. - /// With this, the provider is not asked for . - /// + /// Stopping early. /// /// The same query, canceling its command on an early stop. /// @@ -1419,7 +1329,6 @@ public MappedQuery WithOptions(QueryOptions options) /// whether their rows are cleared when they go back. /// /// - /// /// Call it after Map (the pool is typed by the row). /// Both arguments are required: .UsePool(ArrayPool<Post>.Shared, clearOnReturn: true). /// controls the rows that hold no references; @@ -1427,25 +1336,9 @@ public MappedQuery WithOptions(QueryOptions options) /// An explicit clearOnReturn: false wins over the app-wide switch for this /// query, and an explicit clearOnReturn: true clears whatever the switch /// says. - /// A query that does not call UsePool has no say, and its collecting terminals - /// (the ones that copy the rows out) clear the value rows too, whatever the switch says. - /// - /// - /// It applies to every terminal of this query that rents pooled arrays, - /// the synchronous ones of included: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Applies to every pooling terminal of this query, including the synchronous ones. + /// A pool that hands out a shorter array than asked for makes the read throw . + /// Your own pool. /// /// /// The pool to rent from and give back to. It is yours: ODX never @@ -1472,6 +1365,14 @@ internal bool TryGetCall(out DbQueryCall call) internal MappedQuery WithCall(DbQueryCall call) => new(_core.WithCall(call)); + /// + /// Reads every mapped row into a new ; blocks the calling thread until all rows are read. + /// + /// A list of all the rows, in the order the database returned them. + /// + /// + /// + /// internal List ToList() => _core.ToList(); /// /// Asynchronously reads every mapped row into a new . @@ -1485,6 +1386,18 @@ internal MappedQuery WithCall(DbQueryCall call) /// /// public ValueTask> ToListAsync(CancellationToken cancellationToken = default) => _core.ToListAsync(cancellationToken); + /// + /// Reads every mapped row into a new array; blocks the calling thread until all rows are read. + /// + /// An array of all the rows, in the order the database returned them. + /// + /// + /// + /// A result with rows is a new array, exactly as long as the number of rows, and nothing else refers to it: keep it, change it or hand it on. + /// An empty result is the shared empty array, which has nothing to change. + /// + /// + /// internal T[] ToArray() => _core.ToArray(); /// /// Asynchronously reads every mapped row into a new array. @@ -1503,6 +1416,13 @@ internal MappedQuery WithCall(DbQueryCall call) /// /// public ValueTask ToArrayAsync(CancellationToken cancellationToken = default) => _core.ToArrayAsync(cancellationToken); + /// + /// Reads the first mapped row; blocks the calling thread until it is read. + /// + /// The first row, or if the query returns no rows. + /// + /// Rows after the first are not mapped. Add an ORDER BY to the SQL when "first" must be deterministic. + /// internal T? FirstOrDefault() => _core.FirstOrDefault(); /// /// Asynchronously reads the first mapped row. @@ -1517,6 +1437,11 @@ internal MappedQuery WithCall(DbQueryCall call) /// /// public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken = default) => _core.FirstOrDefaultAsync(cancellationToken); + /// + /// Reads the only mapped row; blocks the calling thread until it is read. + /// + /// The single row, or if the query returns no rows. + /// The query returns more than one row. internal T? SingleOrDefault() => _core.SingleOrDefault(); /// /// Asynchronously reads the only mapped row. @@ -1527,6 +1452,16 @@ internal MappedQuery WithCall(DbQueryCall call) /// /// public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken = default) => _core.SingleOrDefaultAsync(cancellationToken); + /// + /// Reads the first mapped row; blocks the calling thread until it is read, and throws if the query returns no rows. + /// + /// The first row. + /// The query returns no rows. + /// + /// Rows after the first are not mapped. Add an ORDER BY to the SQL when "first" must be deterministic. + /// + /// + /// internal T First() => _core.First(); /// @@ -1548,6 +1483,16 @@ internal T First() public ValueTask FirstAsync( CancellationToken cancellationToken = default) => _core.FirstAsync(cancellationToken); + /// + /// Reads the only mapped row; blocks the calling thread until it is read, and throws if the query returns no rows or more than one. + /// + /// The single row. + /// The query returns no rows, or more than one row. + /// + /// + /// + /// The more-than-one error is thrown at the second row, before the later result sets are read, so it is never replaced by a later failure. + /// internal T Single() => _core.Single(); /// @@ -1598,6 +1543,14 @@ public ValueTask AnyAsync( public ValueTask CountAsync( CancellationToken cancellationToken = default) => _core.CountAsync(cancellationToken); + /// + /// Reads every mapped row into a new ; blocks the calling thread until all rows are read. + /// + /// An immutable array of all the rows, in the order the database returned them. + /// + /// + /// + /// internal ImmutableArray ToImmutableArray() => _core.ToImmutableArray(); /// /// Asynchronously reads every mapped row into a new . @@ -1612,6 +1565,23 @@ public ValueTask CountAsync( /// // ToImmutableArrayAsync wraps the array without copying it on .NET 8 and later (the netstandard builds copy it once). public ValueTask> ToImmutableArrayAsync(CancellationToken cancellationToken = default) => _core.ToImmutableArrayAsync(cancellationToken); + /// + /// Reads every mapped row into a new , keyed by ; blocks the calling thread until all rows are read. + /// + /// The type of the dictionary key. + /// Produces the key for each mapped row. + /// The comparer for the keys, or to use the default comparer. + /// A dictionary of all the rows. + /// is . + /// A key is . + /// Two rows produce the same key. + /// + /// + /// + /// The built-in queries read every row first and add them after the last one, so a duplicate key (or a key) throws only after the whole read. + /// + /// + /// internal Dictionary ToDictionary(Func keySelector, IEqualityComparer? comparer = null) where TKey : notnull => _core.ToDictionary(keySelector, comparer); /// public ValueTask> ToDictionaryAsync(Func keySelector, CancellationToken cancellationToken = default) where TKey : notnull @@ -1626,6 +1596,7 @@ public ValueTask> ToDictionaryAsync(Func keyS /// /// A task that produces a dictionary of all the rows. /// is . + /// A key is . /// Two rows produce the same key. /// /// @@ -1637,6 +1608,26 @@ public ValueTask> ToDictionaryAsync(Func keyS /// /// public ValueTask> ToDictionaryAsync(Func keySelector, IEqualityComparer? comparer, CancellationToken cancellationToken = default) where TKey : notnull => _core.ToDictionaryAsync(keySelector, comparer, cancellationToken); + /// + /// Reads every mapped row into a new , + /// keyed by , with the value + /// returns for the row; blocks the calling thread until all rows are read. + /// + /// The type of the dictionary key. + /// The type of the dictionary value. + /// Produces the key for each mapped row. + /// Produces the value for each mapped row. + /// The comparer for the keys, or to use the default comparer. + /// A dictionary of all the rows. + /// or is . + /// A key is . + /// Two rows produce the same key. + /// + /// + /// Each selector is called once per row, key first. The built-in queries read every row first and build the dictionary right after the last one, so a duplicate key (or a key) throws, and the selectors run, only after the whole read. + /// + /// + /// internal Dictionary ToDictionary( Func keySelector, Func valueSelector, @@ -1664,6 +1655,7 @@ public ValueTask> ToDictionaryAsync( /// /// A task that produces a dictionary of all the rows. /// or is . + /// A key is . /// Two rows produce the same key. /// /// @@ -1682,6 +1674,15 @@ public ValueTask> ToDictionaryAsync( where TKey : notnull => _core.ToDictionaryAsync( keySelector, valueSelector, comparer, cancellationToken); + /// + /// Reads every mapped row into a new ; blocks the calling thread until all rows are read. + /// + /// The comparer for the rows, or to use the default comparer. + /// A set of the distinct rows. + /// + /// + /// + /// internal HashSet ToHashSet(IEqualityComparer? comparer = null) => _core.ToHashSet(comparer); /// public ValueTask> ToHashSetAsync(CancellationToken cancellationToken = default) @@ -1708,42 +1709,11 @@ public ValueTask> ToHashSetAsync(CancellationToken cancellationToken /// returned buffer is disposed. /// /// - /// - /// The call returns at once and starts the read on a background - /// producer, once, even if nobody reads the buffer yet - /// (it may finish before any read happens). - /// Loop over to get rows - /// while the query is still running, as often as you like until the - /// buffer is disposed, or await - /// for the complete result. - /// - /// - /// The rows stay valid until the buffer is disposed: - /// dispose it ( ) when you are done. - /// Disposing it while the read is still running cancels the - /// query; after the read finished it only releases the arrays. - /// A buffer that is never disposed holds its arrays until the - /// garbage collector takes it (there is no finalizer). - /// The connection ODX opened is closed when the read ends, - /// however slowly the buffer is read. - /// The producer is unbounded: it never waits for a reader, so a - /// slow reader lets rows pile up in memory (the read finishes at - /// full speed and frees the connection, while memory grows with - /// the backlog), as with an unbounded channel. - /// - /// - /// Use it when the rows are looped over more than once, or wanted - /// as a list with an indexer, and so must be kept. - /// To read them once and keep none, - /// gives them - /// an array at a time and - /// one at a time. - /// + /// Starts the read at the call. + /// Loop over to get rows while the query is still running, or await for the complete result. + /// Dispose the buffer when you are done: the rows stay valid until then, and disposing it while the read is still running cancels the query. + /// Lifetime and ownership. /// - /// - /// Here the clearing happens when the buffer, or the - /// view of it, is disposed. - /// /// /// /// The buffer, already reading. @@ -1759,47 +1729,12 @@ public PooledBuffer ToPooledBuffer( /// once, for one consumer: it buffers the result in pooled arrays (from an array pool), not a channel of rows. /// /// - /// - /// Lazy: nothing executes until the first - /// . - /// The stream can be enumerated once: - /// a second throws - /// . - /// - /// - /// Each holds exactly the rows of - /// one chunk and is valid until the next - /// or the end of the enumeration, - /// when its array goes back to the pool: - /// copy what you keep. - /// Nothing guards a memory held longer (it then reads rows - /// that were reused), so do not buffer the chunks themselves, for - /// example with ToListAsync or Buffer. - /// An enumerator that is never disposed never returns its arrays - /// (there is no finalizer): they go to the garbage collector. - /// A producer reads ahead without waiting for the consumer - /// (the queue is unbounded), so the connection ODX opened is - /// closed when the read ends, not when the consumer is done, - /// while memory grows with the backlog: a slow consumer lets - /// chunks pile up, as with an unbounded channel. - /// - /// - /// Disposing the enumerator, which a out of - /// always does, cancels the query and - /// returns every array still queued. - /// - /// - /// Use it for sequential, read-only access to the elements through the buffers. - /// is - /// the same without buffers; - /// keeps the - /// rows as a list. - /// + /// Lazy: nothing runs until the first ; the stream can be enumerated once. + /// Each is valid until the next ; copy what you keep. + /// Nothing guards a memory held longer (it then reads rows that were reused), so do not collect the chunks themselves, for example with ToListAsync. + /// Disposing the enumerator (a does) cancels the query and returns every queued array. + /// The streams. /// - /// - /// Here the clearing happens as each chunk goes back, once the consumer - /// is done with it. - /// /// /// /// The lazy, single-use stream. @@ -1814,15 +1749,12 @@ public IAsyncEnumerable> ToPooledBufferStream( /// Reads the rows one at a time off the open reader, lazily, as you pull them: on your own thread, with nothing read ahead. /// /// - /// While you pull rows, this holds the reader and the connection open, and each row is read when you pull it, on your own thread: there is no producer task and no channel. - /// That is not the best way to read rows: to read all of them use ToArrayAsync or ToListAsync; to read while the query runs use StreamBuffered or ToPooledStream. - /// To read the rows as a list or an array, use - /// or : they release the connection before the task completes. - /// To read while the query runs, use , which releases it when the read ends. + /// Reads each row as you pull it, on your thread, with nothing read ahead; the connection is held until you pull past the last row. + /// To read all rows use or : they release the connection before the task completes. /// 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 . /// - /// + /// Which to use: Terminals. /// /// /// The longest you may go without pulling the next row. Required; there is no default. @@ -1842,16 +1774,14 @@ public IAsyncEnumerable Stream( /// Reads the rows lazily through a bounded channel that buffers up to 1,024 rows (the read holds one more while it waits for room), stopping the read when you stop pulling once the buffer is full. /// /// - /// The buffer is a ceiling that keeps a read from outrunning its consumer without bound, not a target. - /// It counts rows, not bytes: narrow rows cost little, wide rows (blobs) cost memory, for each stream running at once. - /// A consumer that keeps up leaves it nearly empty; a larger buffer lets the read ride out a slow consumer instead of waiting on every row. - /// A result that fits is read whole, the later result sets included, and the connection released before you have pulled every row; while rows remain unread, this holds the reader and the connection open. + /// Reads ahead into a buffer of up to 1,024 rows on a producer task; the connection is held until the read ends, or, once the buffer is full, until passes without a pull. + /// The buffer counts rows, not bytes, so wide rows (blobs) cost memory for each stream running at once. /// Breaking out early never throws for rows or result sets you did not reach. /// 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. /// - /// + /// Which to use: Terminals. /// /// /// The longest you may go without pulling the next row once the buffer is full. Required; there is no default. @@ -1890,37 +1820,11 @@ public IAsyncEnumerable StreamBuffered( /// once, and yields the elements one by one: it buffers the result in pooled arrays (from an array pool), not a channel of rows. /// /// - /// - /// The same pipeline as - /// - /// (lazy, one consumer, a background producer, rolling pooled - /// chunks, a or a dispose cancels the query), - /// but each chunk is flattened into its elements, - /// so there is no buffer to handle and the stream works with - /// System.Linq.Async. - /// Each element is copied out before it is yielded, so it has - /// no lifetime to mind. - /// The producer is unbounded, as for that stream: a slow consumer - /// lets chunks pile up in memory. - /// A second enumeration throws - /// at its first - /// (not at ). - /// - /// - /// Which one to use: - /// is - /// sequential, read-only access to the elements through the - /// buffers; - /// this method is the same, without buffers; - /// is a - /// reusable, potentially indexable list to work with for a while. - /// + /// Lazy and single use; disposing the enumerator cancels the query and returns every queued array. + /// A second enumeration throws at its first . + /// Reads on a producer task into an unbounded queue of pooled chunks; the connection is released when the read ends, however slowly you read. + /// Which to use: The three terminals. /// - /// - /// Here the clearing happens as each chunk goes back, once the consumer - /// is done with its elements. - /// - /// /// /// /// The lazy, single-use stream of elements. diff --git a/Source/Core/MappedViews.cs b/Source/Core/MappedViews.cs index e6657298..9abda450 100644 --- a/Source/Core/MappedViews.cs +++ b/Source/Core/MappedViews.cs @@ -671,8 +671,8 @@ async ValueTask ReadAsync( /// as an expressive command does by default. /// /// -/// and return the types of ; -/// the they carry changes nothing here, since a reader view never reads through later result sets. +/// and return and ; +/// SingleResult on them changes nothing here, since a reader view never reads through later result sets. /// /// /// @@ -1133,8 +1133,8 @@ public IAsyncEnumerable ToPooledStream( /// The asynchronous terminals complete synchronously: the rows are already in memory. /// /// -/// and return the types of ; -/// the they carry changes nothing here, since a table has one result set. +/// and return and ; +/// SingleResult on them changes nothing here, since a table has one result set. /// /// /// diff --git a/Source/Core/Output.docs.xml b/Source/Core/Output.docs.xml index d4e1c551..2384cbcd 100644 --- a/Source/Core/Output.docs.xml +++ b/Source/Core/Output.docs.xml @@ -116,9 +116,8 @@ - A is sent as . - One read from a legacy datetime can differ from a row's in the last digits of its fraction - (.997 reads back as .9966667; see the article on expressive commands). + A is sent as ; a legacy datetime can read back differing in the last digits. + Output parameters. @@ -165,15 +164,10 @@ The capture: await it after the terminal. - is optional. A single value reads the parameter named after the variable (out DbCapture<int> total - reads @total; the last identifier of out this.total or out state.total is total), or the name passed last - (CaptureOutput(out DbCapture<int> x, "total")). One rule reads both: the last identifier, with a leading @ or : dropped; - a field prefix (m_ or s_) is also tried without it. - A model maps by its members and ignores the name: it never derives or refuses one, and a member that matches no parameter says so in its message. - Name the variable after the output parameter, or pass the name last; a variable named after an input parameter with a value is sent as - , and a variable named after an input parameter without a default is refused by SQL Server (error 8162 for a procedure, - error 137 for a text command, before any data): the output path is not gated by provider, and is tested on SQL Server only. - A compiler older than C# 10 does not supply the variable's name: pass it last. + is optional: a single value reads the parameter named after the variable (out DbCapture<int> total reads @total), or the name passed last. + A model maps by its members and ignores the name. + A variable named after an input parameter with a value is sent as . + Output parameters; Name a parameter from its argument. @@ -199,10 +193,9 @@ is optional, as for CaptureOutput(out DbCapture<int> total): the variable's name, or the name passed last. - This form takes only , so a wrong type with a shape is a compile error. - CaptureOutput<decimal>(out DbCapture<decimal> x, 19, 4) with an explicit type argument no longer compiles: - write CaptureOutput(out DbCapture<decimal> x, 19, 4), or CaptureOutputDecimal(out DbCapture<decimal?> x, 19, 4). - A NULL output faults the capture with a message that names the nullable form; when the parameter can be NULL, use the nullable form. + Write CaptureOutput(out DbCapture<decimal> x, 19, 4), or CaptureOutputDecimal(out DbCapture<decimal?> x, 19, 4); this form takes only . + A NULL output faults the capture; when the parameter can be NULL, use the nullable form. + Output parameters. No name can be taken from the variable or the text passed last (a discard, an element access, ). @@ -311,7 +304,7 @@ - Call the terminal first, then await the capture: var rows = await query.ToListAsync(); int total = await capture;. + Call the terminal first, then await the capture: var rows = await query.ToListAsync(cancellationToken); int total = await capture;. Awaiting it before the terminal was called throws, and so does awaiting it in the loop of the stream it belongs to. A default value belongs to no call, and every member throws. diff --git a/Source/Core/OutputDbNonQuery.cs b/Source/Core/OutputDbNonQuery.cs index 0b40cf06..ab21fc81 100644 --- a/Source/Core/OutputDbNonQuery.cs +++ b/Source/Core/OutputDbNonQuery.cs @@ -135,6 +135,8 @@ static OutputLayout Wrap( /// field holds it: /// /// +/// record AddPostResult(int Id); +/// /// static readonly OutputDbNonQuery<AddPostResult> AddPost /// = DbNonQuery.Procedure("[dbo].[AddPost]") /// .Output<AddPostResult>(); diff --git a/Source/Core/PooledBuffer.cs b/Source/Core/PooledBuffer.cs index 1773c55f..3ee5c1bf 100644 --- a/Source/Core/PooledBuffer.cs +++ b/Source/Core/PooledBuffer.cs @@ -7,65 +7,29 @@ namespace Open.Database.Extensions; /// /// /// Made by ToPooledBuffer() on a typed view. -/// The read starts when that method is called, -/// on a background producer, once, -/// even if nobody reads the buffer yet; it may finish before anyone -/// asks for the rows. -/// The connection ODX opened is closed by the query when the read ends, -/// which is before the result is complete: slow readers never hold it. +/// The read starts when that method is called, on a background producer, even if nobody reads the buffer yet. +/// The connection ODX opened is closed when the read ends, so slow readers never hold it. /// /// -/// Loop over to get rows while the read -/// runs, or await for all of them as one list. -/// Each loop starts at the first row. The rows can be looped over any -/// number of times, by several readers at once, during the read and after it. -/// Rows arrive an array at a time: an array is handed over when the next row -/// no longer fits in it, or when the read ends. By default the first holds 16 -/// rows and each next one twice as many. -/// If the read fails, a loop gets the rows read before the failure, then -/// the exception. -/// Leaving a loop early, or canceling the token of a loop, does not stop the -/// read: disposing the buffer does. +/// Loop over to get rows while the read runs, or await for all of them as one list. +/// Each loop starts at the first row, and the rows can be looped over any number of times, by several readers at once. +/// If the read fails, a loop gets the rows read before the failure, then the exception. +/// Leaving a loop early, or canceling the token of a loop, does not stop the read: disposing the buffer does. /// /// -/// While the buffer is not disposed its rows stay reachable, and every -/// it hands out is valid. -/// The arrays go back to the pool when the buffer is disposed, and not -/// before. -/// Dispose the buffer ( ) when you are done, -/// after your loops: a loop that is still running when the buffer is disposed -/// throws at its next step. -/// It is not safe to dispose while another thread is taking a row. -/// There is no finalizer: a buffer that is never disposed is not a leak, but -/// it holds its arrays (and the finished read) until the garbage collector -/// takes it, and the pool does not get them back. +/// Dispose the buffer ( ) when you are done, after your loops: +/// the arrays go back to the pool then, and a loop that is still running throws at its next step. +/// There is no finalizer: a buffer that is never disposed is not a leak, but it holds its arrays until the garbage collector takes it, and the pool does not get them back. +/// Disposing while the read is still running cancels the query. /// /// -/// Returning an array to a custom pool must not throw. -/// If it does, every other array is still returned, and the first exception -/// propagates from , and from -/// when the read had already finished; -/// from while the read is still running it -/// ends in the producer's task, which nobody observes. -/// With clearing on, a large array is cleared and returned on an internal background queue, -/// off the path of the caller that releases it; when that queue is full, the caller that -/// releases it clears and returns it instead. -/// A return that throws on the background queue is swallowed. +/// See Lifetime and ownership, +/// Cancellation and disposal, +/// Memory shape, +/// Pooled memory, +/// Your own pool +/// and When the clear happens. /// -/// -/// When the rows are to be cleared (see UsePool), they are cleared as -/// the arrays go back to the pool, and that happens when the buffer, or the -/// view of it, is disposed (not when the read -/// completes). -/// -/// -/// Disposing the buffer while it is still reading cancels the query, -/// and waits () for the provider call in -/// progress to return: a provider that ignores cancellation delays -/// the dispose by that call. -/// After the read finished, disposing only releases the arrays. -/// -/// /// /// // Clearing: an array of 128 KB or more of rows (value rows included) is cleared and returned by an internal diff --git a/Source/Core/PooledMemory.docs.xml b/Source/Core/PooledMemory.docs.xml index 84a8403f..26d22860 100644 --- a/Source/Core/PooledMemory.docs.xml +++ b/Source/Core/PooledMemory.docs.xml @@ -8,43 +8,13 @@ - Pooled memory: the rows are held in arrays rented from a pool and given - back when the call, the buffer or the stream is done. - By default that pool is ArrayPool<T>.Shared. - To use your own, call .UsePool(pool, clearOnReturn: ...) after - Map: the pool is yours, ODX rents from it and gives back to it, - and never disposes it. - The arrays it hands out may be longer than asked for: ODX uses the rows - it wrote and clears only those. + Rents its arrays from ArrayPool<T>.Shared, or from the pool + given to UsePool, and gives them back when the call, buffer or + stream is done. + Rows that hold references are always cleared. A pool that hands out a shorter array than asked for makes the read throw . - Returning an array must not throw. - - - Clearing: rows that hold references (a class, a string, a struct that - contains either) are always cleared before their array goes back, so a - pooled array never keeps a row alive; nothing turns that off. - Rows with no references (an int, a plain struct) depend on the - terminal. - The collecting terminals (ToList, ToArray, ToImmutableArray, - ToHashSet and the dictionaries, on a view or a reader) copy their rows out - and hide their pooling from the caller: when the query offers no pool - they always clear, whatever the app-wide setting says, and with - UsePool they follow it - (clearOnReturn: true clears, clearOnReturn: false keeps the rows as they are). - The buffers and the streams hand their arrays to the caller, so there the rows go back as they - are, unless asked: - UsePool(pool, clearOnReturn: true) clears them, - clearOnReturn: false keeps them as they are whatever the app-wide setting - says, and a query that does not call UsePool follows the setting. - The app-wide setting is the AppContext switch - Open.Database.Extensions.ClearPooledArrays (off by default; read - once, so set it before the first query). - Set it in the application's project file with - <RuntimeHostConfigurationOption - Include="Open.Database.Extensions.ClearPooledArrays" Value="true" - />, which puts it in runtimeconfig.json, or call - AppContext.SetSwitch before the first query. + Pooled memory. diff --git a/Source/Dataflow/DataflowExtensions.cs b/Source/Dataflow/DataflowExtensions.cs index bb37c381..bc0b2ca1 100644 --- a/Source/Dataflow/DataflowExtensions.cs +++ b/Source/Dataflow/DataflowExtensions.cs @@ -115,9 +115,9 @@ IAsyncEnumerable> chunks /// /// /// - /// The task is the done signal: it completes with the number of rows - /// the block accepted after the last result set was read through. - /// A failure or a cancel comes back through the task, and the block + /// The returned ValueTask<long> completes with the number of + /// rows the block accepted after the last result set was read through. + /// A failure or a cancel is thrown by the await, and the block /// is left as it was. /// /// @@ -125,13 +125,14 @@ IAsyncEnumerable> chunks /// Pass complete: true to complete it when the pass ends. /// /// - /// The query is read at full speed and the connection is closed when - /// the read ends. Each row is sent with SendAsync, which waits - /// while a bounded block is full, so no row is dropped; the rows wait in - /// an internal queue meanwhile, so your block does not limit memory. - /// A block that is already finished stops the pass before the command runs. - /// When the block declines a row for good (completed or faulted), the - /// pass stops without an exception and returns the rows accepted so far. + /// The rows are sent in order as they are read, and the connection is + /// closed when the read ends. + /// SendAsync waits while a bounded block is full; the rows wait in + /// memory meanwhile, so the block does not limit memory. + /// A block that is already finished ends the pass before the command runs. + /// A block that declines a row (completed or faulted) ends the pass + /// without an exception and returns the rows accepted so far. + /// Dataflow. /// /// /// The type of each row. @@ -207,8 +208,9 @@ public static ValueTask ToTargetBlock( /// and while the block is full they stay held until it takes the row or expires; /// with nothing ends that wait. /// To close the connection as soon as the rows are read, use - /// , which this otherwise matches. - /// See Stream for when to use this and what does. + /// ; + /// otherwise it behaves the same, apart from the stall timeout. + /// For when to use this and what does, see Terminals. /// /// /// The type of each row. @@ -216,7 +218,7 @@ public static ValueTask ToTargetBlock( /// The block to send to. /// /// The longest the block may take no row while the reader is held. - /// Required; passed to Stream. + /// Required; passed to with a buffer of one row. /// /// /// The number of rows the block accepted. @@ -247,9 +249,9 @@ public static ValueTask ToTargetBlockHoldingConnection( /// and while the block is full they stay held until it takes the row or expires; /// with nothing ends that wait. /// To close the connection as soon as the rows are read, use - /// . - /// See Stream for when to use this and what does. - /// works as for that member. + /// ; + /// otherwise it behaves the same, apart from the stall timeout. + /// For when to use this and what does, see Terminals. /// /// /// The type of each row. @@ -257,7 +259,7 @@ public static ValueTask ToTargetBlockHoldingConnection( /// The block to send to. /// /// The longest the block may take no row while the reader is held. - /// Required; passed to Stream. + /// Required; passed to with a buffer of one row. /// /// /// to complete the block when the pass ends, diff --git a/Source/MSSqlClient/ExpressiveSqlCommand.cs b/Source/MSSqlClient/ExpressiveSqlCommand.cs index ca00bf6f..325ee094 100644 --- a/Source/MSSqlClient/ExpressiveSqlCommand.cs +++ b/Source/MSSqlClient/ExpressiveSqlCommand.cs @@ -10,7 +10,7 @@ namespace Open.Database.Extensions; /// Nothing touches the database until an execute method is called. Create one with the Command and StoredProcedure extension methods in , add parameters with AddParam, optionally set a timeout and cancellation token, then run it with one of the execute methods (for example ExecuteNonQuery, ExecuteScalar, ExecuteReader, or Map<T>()). /// /// -/// Connections follow the same "get in, get out" model as : each execution takes a connection, opens it only if needed, runs the command, and releases the connection. A connection supplied directly is closed again only if this execution opened it and is never disposed; a connection from a factory is disposed, and one from a pool is given back. +/// Each execution takes a connection, opens it only if needed, runs the command, and releases the connection. A connection supplied directly is closed again only if this execution opened it and is never disposed; a connection from a factory is disposed, and one from a pool is given back. /// /// /// diff --git a/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs b/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs index 9616a10b..bfe06562 100644 --- a/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs +++ b/Source/MSSqlClient/Extensions/Command.ExecuteReader.cs @@ -81,7 +81,7 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// /// - /// + /// /// /// A task that represents the asynchronous operation. It completes after has completed and the reader has been disposed. /// @@ -130,7 +130,7 @@ public static ValueTask ExecuteReaderAsync(this SqlCommand command, /// /// /// - /// + /// /// /// A task that represents the asynchronous operation; its result is the value returned by . /// diff --git a/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml b/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml index 539b8cb9..28e30656 100644 --- a/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml +++ b/Source/MSSqlClient/Extensions/MSSqlClient.docs.xml @@ -347,11 +347,19 @@ The behavior to use with the data reader. is added when the command - opens a closed connection. + opens the connection. The default is . + + + The behavior to use with the data reader. + is added when the command + opens the connection. + + + A token that can cancel opening the connection and executing the @@ -398,31 +406,27 @@ If the connection is not open, it is opened first and closed (not - disposed) when the transaction completes, even if it fails. - A connection that was broken is closed and opened again, so it is closed - afterwards too. + disposed) when the transaction completes, even if it fails; + a broken connection is closed and opened again. A connection that was already open is left open. - A failure while closing is ignored, as by then the transaction has - already been committed or rolled back. + A failure while closing is ignored. To keep a connection open across several operations, open it before calling. - An exception thrown by the action, or a cancellation, rolls the - transaction back and propagates. The transaction is disposed before the connection is closed. - The action should not commit or roll back the transaction itself; - completion is handled here. - When no isolation level is given, + An exception or a cancellation rolls back and propagates. + The action must not commit or roll back the transaction itself. + With no isolation level given, is used. + Transactions. - The transaction is disposed with DisposeAsync, committed with - CommitAsync, and the connection closed with CloseAsync, - except on .NET Framework (net472), which does all three synchronously. + The transaction is committed with CommitAsync, disposed with + DisposeAsync, and the connection closed with CloseAsync. The token is checked just before the commit; the commit is not canceled once it has begun. diff --git a/docsite/articles/async-buffers.md b/docsite/articles/async-buffers.md index 6dd89fb4..ae6354b5 100644 --- a/docsite/articles/async-buffers.md +++ b/docsite/articles/async-buffers.md @@ -178,7 +178,7 @@ A stream still reads ahead without waiting for the client, as [described above]( ## The streams -`ToPooledBufferStream` yields one chunk at a time as a `ReadOnlyMemory`. A chunk holds exactly the rows of one chunk and is valid until the next step of the loop, when its array goes back to the pool. Copy what you keep, and do not collect the chunks themselves (with `ToListAsync` or `Buffer`, say): nothing guards a memory held longer. +`ToPooledBufferStream` yields one chunk at a time as a `ReadOnlyMemory`. A chunk holds exactly the rows of one chunk and is valid until the next step of the loop, when its array goes back to the pool. Copy what you keep, and do not collect the chunks themselves (with `ToListAsync`, say): nothing guards a memory held longer. [!code-csharp[](../samples/AsyncBuffers.cs#buffers_chunk_stream)] diff --git a/docsite/articles/channels-and-dataflow.md b/docsite/articles/channels-and-dataflow.md index 903b0df4..53c0d673 100644 --- a/docsite/articles/channels-and-dataflow.md +++ b/docsite/articles/channels-and-dataflow.md @@ -64,7 +64,7 @@ The query is read at the provider's pace into pooled chunks, and the connection ### A channel you own -`ToChannel(channel)` and `ToChannel(writer)` only write. They leave the channel open, so passes can share it, and the returned task is the done signal: it completes with the number of rows written, and a failure or a cancel comes back through it. `complete: true` completes the channel when the pass ends, with the exception that ended it if there was one. +`ToChannel(channel)` and `ToChannel(writer)` only write. They leave the channel open, so passes can share it, and the returned `ValueTask` is the done signal: it completes with the number of rows written, and a failure or a cancel is thrown by the await. `complete: true` completes the channel when the pass ends, with the exception that ended it if there was one. [!code-csharp[](../samples/ChannelsAndDataflow.cs#to_channel_owned)] @@ -72,7 +72,7 @@ When the channel is full, the write waits for room, before the command runs and ### Capping memory -`ToChannelHoldingConnection` pulls the rows one at a time from [`Stream`](xref:Open.Database.Extensions.IMappedQuery`1.Stream*), so a full channel limits memory. `Stream` says when to use it and what the required `stallTimeout` does. +`ToChannelHoldingConnection` pulls the rows one at a time from [`StreamBuffered`](xref:Open.Database.Extensions.IMappedQuery`1.StreamBuffered*) with a buffer of one row, so a full channel limits memory. [Terminals](mapping.md#terminals) says when to use it and what the required `stallTimeout` does. [!code-csharp[](../samples/ChannelsAndDataflow.cs#to_channel_holding)] @@ -82,7 +82,7 @@ When the channel is full, the write waits for room, before the command runs and The Dataflow package reads a mapped query at the provider's pace into pooled chunks and sends each row to a block, so the blocks, their task schedulers and their priorities stay yours. -`ToTargetBlock` sends the rows to a block you own and leaves it open, so passes can share it. The returned task is the done signal: it completes with the number of rows the block accepted, and a failure or a cancel comes back through it. `complete: true` completes the block when the pass ends, or faults it with the exception that ended it, a cancel included (a faulted block drops the rows it holds that were not received yet). +`ToTargetBlock` sends the rows to a block you own and leaves it open, so passes can share it. The returned `ValueTask` is the done signal: it completes with the number of rows the block accepted, and a failure or a cancel is thrown by the await. `complete: true` completes the block when the pass ends, or faults it with the exception that ended it, a cancel included (a faulted block drops the rows it holds that were not received yet). [!code-csharp[](../samples/ChannelsAndDataflow.cs#to_target_block)] @@ -92,7 +92,7 @@ Each row is sent with `SendAsync`, so a bounded block that is full makes the pas [!code-csharp[](../samples/ChannelsAndDataflow.cs#as_source_block)] -`ToTargetBlockHoldingConnection` pulls the rows one at a time from [`Stream`](xref:Open.Database.Extensions.IMappedQuery`1.Stream*), so a full block limits memory. `Stream` says when to use it and what the required `stallTimeout` does. +`ToTargetBlockHoldingConnection` pulls the rows one at a time from [`StreamBuffered`](xref:Open.Database.Extensions.IMappedQuery`1.StreamBuffered*) with a buffer of one row, so a full block limits memory. [Terminals](mapping.md#terminals) says when to use it and what the required `stallTimeout` does. ## Honest limits diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 7e3cf885..5b981fcd 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -60,7 +60,7 @@ public class PostQueries(IDbConnectionFactory db) [!code-csharp[](../samples/MapFirst.cs#mapfirst_values_first)] -What the definition fixes is what never changes from one call to the next: the command text, the map, and `SingleResult()`, `AsyncReads()` and `UsePool(pool, clearOnReturn)`, each of which returns a new definition. What each call chooses is the values and, on the view, `Skip` and `Take`: +What the definition fixes is what never changes from one call to the next: the command text (and, on the `DbQuery` before `Map`, `SetTimeout`), the map, and `SingleResult()`, `CancelOnEarlyStop()`, `AsyncReads()`, `SequentialAccess()` and `UsePool(pool, clearOnReturn)`, each of which returns a new definition. A query made from the definition can still apply any of those five switches for one call. What each call chooses is the values and, on the view, `Skip` and `Take`: [!code-csharp[](../samples/MapFirst.cs#mapfirst_paged)] @@ -255,7 +255,7 @@ There is no blocking form. Known limits: - The declared scale of a `decimal` also rounds a value sent in (`1.239` sent as `decimal(10,2)` arrives as `1.24`). - An InputOutput parameter whose outputs never arrive keeps the value sent: that case cannot be told from a real answer. - A parameter added with a null value (`AddParam(name, (int?)null, type)`) that is also an output member is sent as InputOutput too, so a lost output cannot be told from a NULL. For a pure output, add no value; add one only when the procedure reads it. -- A member on a parameter the procedure does not declare `OUTPUT` throws before the run when the metadata is known, and is the provider's error when it is not (SQL Server: 8162). +- A member on a parameter the procedure does not declare `OUTPUT` throws before the run when the metadata is known, and is the provider's error when it is not (SQL Server: 8162 for a procedure, 137 for text). - If the procedure was changed with `ALTER` while the process runs, the remembered metadata is out of date until it is dropped (by a failed call, or by eviction). A parameter changed from `IN` to an output gives one `InvalidOperationException`, and the next call passes; one changed from an output to `IN` reaches the provider's error, and the call after it is checked. If the procedure was changed, call again. A scale lowered by the change is not caught: the value rounds silently, as it does without metadata, until the remembered metadata is dropped. - A read of the metadata that the provider refuses (System.Data.SqlClient inside a pending transaction, for example) lets the call run, and is read again on every call. A call that keeps failing a check removes the remembered metadata for every caller of that procedure, so their next call reads it again. - SqlClient reports an error after the outputs are set, and a cancel while the command runs, with its own `SqlException`. diff --git a/docsite/articles/foundation.md b/docsite/articles/foundation.md index 54f67cd4..3e5c8075 100644 --- a/docsite/articles/foundation.md +++ b/docsite/articles/foundation.md @@ -35,6 +35,28 @@ Several helpers exist to keep the time a connection is open short: - `EnsureOpen()` and `EnsureOpenAsync()` open a closed (or broken) connection and return its prior state, so you can restore it. - Rows are read with `Map()` and a terminal ([Mapping rows to objects](mapping.md)); a buffered terminal such as `ToListAsync` releases the connection as soon as it returns. +## Connection scopes + +`EnsureOpenScope()` and `EnsureOpenScopeAsync()` open a connection if it needs opening and return a `ConnectionScope`: the connection, the state it was found in, and what to do with it when the scope is disposed. One type covers every source of a connection, and what disposing does depends on where the connection came from: + +- From a connection you hold: closes it if the scope opened it, leaves it open if it was already open, and never disposes it. +- From a connection factory: disposes it (`DisposeAsync` when the connection has one), as `factory.Open(...)` does. +- From a connection pool: gives it back with `IDbConnectionPool.Give`, as `pool.Open(...)` does. What giving back means (close it, keep it, dispose it) is the pool's. + +When you already hold the connection, the scope is only there to be disposed. When the connection came from a factory or a pool, the scope is how you get it: + +```csharp +await using var _ = await connection.EnsureOpenScopeAsync(cancellationToken); +// ... use the connection you already hold. + +await using var scope = await factory.EnsureOpenScopeAsync(cancellationToken); +var open = scope.Connection; +``` + +The scope keeps the type of the connection (a `SqlConnection` stays a `SqlConnection`), and deconstructs into the connection and the state it was found in: `var (sql, was) = scope;`. A connection that was broken is closed and opened again, so a scope that closes it closes it again afterwards; the broken state is not restored. + +Dispose the value you were given exactly once, and do not copy it: a second dispose of a copy disposes a factory's connection again, gives a pool's connection back again, or closes a connection that someone opened in between. Deconstruct a scope you hold, never the call itself: `var (c, s) = connection.EnsureOpenScope();` drops the scope, and the connection it opened stays open. A `default` scope holds nothing: disposing it does nothing, and reading `Connection` (or deconstructing it) throws `InvalidOperationException`. + ## Transactions Inside a transaction, a query or a write you declared runs on it with `Using(transaction)`, the same call as with a factory or a connection: @@ -53,7 +75,7 @@ Or, simply expressive, a command starts from the transaction: `transaction.Comma ## Reader and command helpers -The foundation also includes helpers you can use without the expressive syntax: `ForEach` and `ForEachAsync` over a reader, `Select` and `SelectAsync`, `AsAsyncEnumerable`, `ToDataTable` and friends on commands. Buffered reads copy the rows out of the reader first, so the connection can be released early. For rows without a model use `AsObjectArrays()` or `AsDictionaryRows()` (see [Rows without a model](mapping.md#rows-without-a-model)); for typed rows `Map()` is the better route (see [Performance](performance.md#where-it-is-not-faster)). +The foundation also includes helpers you can use without the expressive syntax: `ForEach` and `ForEachAsync` over a reader, `Select` and `SelectAsync`, `AsAsyncEnumerable`, `ToDataTable` and friends on commands. Buffered reads copy the rows out of the reader first, so the connection can be released early. The helpers that run your code for each row (`ForEach`, `ForEachAsync`, `IterateWhile`, `Select`, `SelectAsync`) hold the reader, and the connection under it, open for as long as your code takes per row, added up over all the rows. In async code that time has no bound: every `await` in the loop body can yield, and until the loop resumes and ends a pooled connection is not returned to the pool and the server may keep its locks and the open result set. When the work does not have to happen while the connection is open, buffer with `ToListAsync` or `ToArrayAsync` after `Map()`, or stream with `ToPooledStream`, which frees the connection while the consumer takes its time. For rows without a model use `AsObjectArrays()` or `AsDictionaryRows()` (see [Rows without a model](mapping.md#rows-without-a-model)); for typed rows `Map()` is the better route (see [Performance](performance.md#where-it-is-not-faster)). The reader helpers that take a token (`ForEach`, `ForEachAsync`, `IterateWhile`, `Select`, `SelectAsync`) check it at the top of the loop, before each read (the async forms hand it to `ReadAsync`, so the provider cancels the read itself). A cancel throws `OperationCanceledException` and the read is not made; the rows already handed out stay handed out. A cancel while the last row is handled throws at the next check. Once a read has returned no row the result is complete, and a cancel after that is not an error. To stop early, return `false` from the predicate or `break` out of the loop: do not cancel. `AsAsyncEnumerable` is the exception to the throwing rule: a cancelled token ends its enumeration quietly, and the rows already yielded stay yielded.