diff --git a/README.md b/README.md index ec134a71..c17970c0 100644 --- a/README.md +++ b/README.md @@ -48,16 +48,20 @@ while (await reader.ReadAsync(cancellationToken)) And with Open.Database.Extensions, the query declared once (immutable, with no connection, safe in a static field) and run where it is needed: ```cs -// A field of your data-access class: declared once, with no connection. -static readonly MappedDbQuery ByAuthor - = DbQuery.Text("select * from posts where author = @author order by id") - .Map(); - -int author = 42; - -Post[] posts = await ByAuthor.Using(connectionFactory) - .AddParam(author) // name and type inferred from the variable - .ToArrayAsync(cancellationToken); +public class PostQueries(IDbConnectionFactory connectionFactory) +{ + // Declared once: immutable, with no connection. + static readonly MappedDbQuery ByAuthor + = DbQuery.Text("select * from posts where author = @author order by id") + .Map(); + + public ValueTask ByAuthorAsync( + int author, + CancellationToken cancellationToken) + => ByAuthor.Using(connectionFactory) + .AddParam(author) // name and type inferred from the variable + .ToArrayAsync(cancellationToken); +} ``` Or, simply expressive, with nothing to declare: diff --git a/Source/Channel/README.md b/Source/Channel/README.md index 4fced96c..8b828f47 100644 --- a/Source/Channel/README.md +++ b/Source/Channel/README.md @@ -10,19 +10,30 @@ dotnet add package Open.ChannelExtensions ``` ```cs +using System.Data.Common; using System.Threading.Channels; using Open.Database.Extensions; public record Post(int Id, string Title); // connectionFactory is a DbConnectionFactory, created once per application (see the Core package page, which also names the provider to install). -// A field of your data-access class: declared once, immutable, with no connection. -static readonly MappedDbQuery Latest - = DbQuery.Text("select * from posts order by id").Map(); +public class PostStreams(IDbConnectionFactory connectionFactory) +{ + // Declared once: immutable, with no connection. + static readonly MappedDbQuery Latest + = DbQuery.Text("select * from posts order by id").Map(); -// Returns right away: the rows are read in the background and the channel completes when they are all written. -ChannelReader reader = Latest.Using(connectionFactory) - .ToChannelReader(); + // Returns right away: the rows are read in the background and the channel completes when they are all written. + public ChannelReader LatestPosts() + => Latest.Using(connectionFactory) + .ToChannelReader(); +} +``` + +Then, where you need the rows: + +```cs +ChannelReader reader = new PostStreams(connectionFactory).LatestPosts(); await foreach (Post post in reader.ReadAllAsync()) { diff --git a/Source/Core/README.md b/Source/Core/README.md index fb9c12f6..81019146 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -18,22 +18,35 @@ public record Post(int Id, string Title); // connectionString is yours, for example "Data Source=blog.db"; the query assumes a posts table (id, author, title, ...). // Create the factory once per application. Use your provider's connection type. var connectionFactory = new DbConnectionFactory(() => new SqliteConnection(connectionString)); -int author = 42; +``` -// A field of your data-access class: declared once, immutable, with no connection. -static readonly MappedDbQuery ByAuthor - = DbQuery.Text("select * from posts where author = @author order by id") - .Map(); +A query an application runs again and again is declared once, in your data-access class, and bound where it runs: -// The call opens a connection when the terminal runs and disposes it afterwards. -Post[] posts = await ByAuthor.Using(connectionFactory) - .AddParam(author) // name and type inferred from the variable - .ToArrayAsync(); +```cs +using System.Data.Common; + +public class PostQueries(IDbConnectionFactory connectionFactory) +{ + // Declared once: immutable, with no connection. + static readonly MappedDbQuery ByAuthor + = DbQuery.Text("select * from posts where author = @author order by id") + .Map(); + + // The call opens a connection when the terminal runs and disposes it afterwards. + public ValueTask ByAuthorAsync( + int author, + CancellationToken cancellationToken) + => ByAuthor.Using(connectionFactory) + .AddParam(author) // name and type inferred from the variable + .ToArrayAsync(cancellationToken); +} ``` Or, simply expressive, with nothing to declare: ```cs +int author = 42; + Post[] posts = await connectionFactory .Command("select * from posts where author = @author order by id") .AddParam(author) // name and type inferred from the variable diff --git a/Source/Dataflow/README.md b/Source/Dataflow/README.md index 123e902c..874bbe04 100644 --- a/Source/Dataflow/README.md +++ b/Source/Dataflow/README.md @@ -9,21 +9,31 @@ dotnet add package Open.Database.Extensions.Dataflow --prerelease ``` ```cs +using System.Data.Common; using System.Threading.Tasks.Dataflow; using Open.Database.Extensions; public record Post(int Id, string Title); // connectionFactory is a DbConnectionFactory, created once per application (see the Core package page, which also names the provider to install). -var block = new BufferBlock(); +public class PostPipeline(IDbConnectionFactory connectionFactory) +{ + // Declared once: immutable, with no connection. + static readonly MappedDbQuery Latest + = DbQuery.Text("select * from posts order by id").Map(); -// A field of your data-access class: declared once, immutable, with no connection. -static readonly MappedDbQuery Latest - = DbQuery.Text("select * from posts order by id").Map(); + // complete: true completes the block after the last row, or faults it with the exception that ended the pass, a cancel included. + public ValueTask SendLatestAsync(ITargetBlock block) + => Latest.Using(connectionFactory) + .ToTargetBlock(block, complete: true); +} +``` -// complete: true completes the block after the last row, or faults it with the exception that ended the pass, a cancel included. -long count = await Latest.Using(connectionFactory) - .ToTargetBlock(block, complete: true); +Then, where you need the rows: + +```cs +var block = new BufferBlock(); +long count = await new PostPipeline(connectionFactory).SendLatestAsync(block); // The block completes once every row has been received. var received = new List(); diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index b846aee1..a29183e7 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -7,15 +7,22 @@ An expressive command is a small object you build with chained calls: pick the S When the same query runs from several places, define it once, with no connection, and bind it where it runs. A `DbQuery` is immutable, so it is safe in a `static readonly` field and shared by every caller. `Using(source)` binds it to a connection, a transaction, a pool or a factory; each `AddParam` returns a new immutable call and leaves the one before it as it was, so a held call can branch. ```csharp -static readonly DbQuery PostsByAuthor - = DbQuery.Procedure("dbo.PostsByAuthor"); - -// The names come from the variables, as AddParam(author) does on a command. -List posts = await PostsByAuthor.Using(db) - .AddParam(authorId) - .AddParam(day) - .Map() - .ToListAsync(cancellationToken); +public class PostQueries(IDbConnectionFactory db) +{ + static readonly DbQuery PostsByAuthor + = DbQuery.Procedure("dbo.PostsByAuthor"); + + // The names come from the variables, as AddParam(author) does on a command. + public ValueTask> ByAuthorAsync( + int authorId, + DateTime day, + CancellationToken cancellationToken) + => PostsByAuthor.Using(db) + .AddParam(authorId) + .AddParam(day) + .Map() + .ToListAsync(cancellationToken); +} ``` A procedure's parameter names are read through the ADO.NET schema collection `ProcedureParameters` (`DbConnection.GetSchema`) the first time a call needs them, and kept (see [Parameter names are read once](#parameter-names-are-read-once)). @@ -25,13 +32,20 @@ To have the values checked at compile time, declare their type once. It is a `st ```csharp readonly record struct AuthorDayParams(int AuthorId, DateTime Day); -static readonly DbQuery PostsByAuthorTyped - = DbQuery.Procedure("dbo.PostsByAuthor").Params(); - -List posts = await PostsByAuthorTyped.Using(db) - .AddParams(new(AuthorId: authorId, Day: day)) - .Map() - .ToListAsync(cancellationToken); +public class PostQueries(IDbConnectionFactory db) +{ + static readonly DbQuery PostsByAuthorTyped + = DbQuery.Procedure("dbo.PostsByAuthor").Params(); + + public ValueTask> ByAuthorAsync( + int authorId, + DateTime day, + CancellationToken cancellationToken) + => PostsByAuthorTyped.Using(db) + .AddParams(new(AuthorId: authorId, Day: day)) + .Map() + .ToListAsync(cancellationToken); +} ``` ### Map the definition too diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 05f0b6c1..a7dc8588 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -421,10 +421,14 @@ A data class can return the mapped query and let each caller pick the terminal: `AnyAsync` and `CountAsync` answer about the first result set without mapping a row or reading a column. They are on every mapped view and, with no `Map`, on a bound `DbQuery` and an expressive command: ```csharp -bool pending = await DbQuery.Procedure("GetPendingPosts") - .Using(factory) - .AnyAsync(cancellationToken); +static readonly DbQuery PendingPosts = DbQuery.Procedure("GetPendingPosts"); +public ValueTask HasPendingAsync(CancellationToken cancellationToken) + => PendingPosts.Using(factory) + .AnyAsync(cancellationToken); +``` + +```csharp int count = await command .Map() .Skip(10) @@ -477,11 +481,14 @@ A reader and a `DataTable` have no `.SingleResult()` before `Map`: their views n SQL Server sends every row of a result, the ones you did not ask for included. `CancelOnEarlyStop()` cancels the command when a terminal stops with rows left, before the reader is closed, so the rest are discarded. It is off unless you call it. It goes on a mapped query or command, or on a mapped definition: ```csharp -Post? newest = await DbQuery.Procedure("GetPostsNewestFirst") - .Using(factory) - .Map() - .CancelOnEarlyStop() - .FirstOrDefaultAsync(cancellationToken); +static readonly MappedDbQuery NewestFirst + = DbQuery.Procedure("GetPostsNewestFirst") + .Map() + .CancelOnEarlyStop(); + +public ValueTask NewestAsync(CancellationToken cancellationToken) + => NewestFirst.Using(factory) + .FirstOrDefaultAsync(cancellationToken); ``` **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). **Do not use it** for a `TOP 1` or key lookup: there is nothing to save. A one-row lookup there took about 80 µs 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.