From b05e12f1fccc52c0de5c0a8115863f8076d8ad32 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:57:12 -0800 Subject: [PATCH 1/3] Samples: the same queries declared once, and the scalar forms checked against the definition path Adds `Defined.cs`: the queries the docs show as one-liners, written the way an application writes them, as `static readonly` definitions (`DbQuery.Text(...).Map()`, `DbNonQuery.Text(...)`, `Scalar()`) with the source and the values bound where they run: a list, a list on a connection you own, a write on a transaction, the first/single, new-id, page, dictionary and early-stop terminals, a pooled buffer and stream, an `AsyncReads` declaration, a declared `RowMap`, scalars and a write. `Program.cs` runs every new sample and checks what it returns (13 checks), and checks that the definition path reads what the same call on a command reads: `Scalar()` over a SQLite bigint, `Scalar()`, a value that does not fit, no rows and NULL for a type that takes null and for one that does not, `Scalar()`, and `DbNonQuery` against `ExecuteNonQueryAsync` (10 checks). All pass: `Scalar()` converts as `ExecuteScalarAsync()` does. The custom conversion form (`ExecuteScalarAsync(Func)`) has no counterpart on the definition path, so that sample stays ad hoc. Co-Authored-By: Claude Sonnet 5.5 --- docsite/samples/Defined.cs | 308 +++++++++++++++++++++++++++++++++++++ docsite/samples/Program.cs | 44 ++++++ 2 files changed, 352 insertions(+) create mode 100644 docsite/samples/Defined.cs diff --git a/docsite/samples/Defined.cs b/docsite/samples/Defined.cs new file mode 100644 index 00000000..2b11dfb7 --- /dev/null +++ b/docsite/samples/Defined.cs @@ -0,0 +1,308 @@ +using System.Data.Common; +using Microsoft.Data.Sqlite; +using Open.Database.Extensions; +using static Samples.Sql; + +namespace Samples; + +// The same queries as the ad hoc samples, declared once: the recommended way +// to write the call an application makes again and again. A query is +// immutable and holds no connection, so it lives in a static field; the +// source and the values are bound where it runs. +// The ad hoc samples beside them show how little code a one-off needs. + +#region defined_list +public class DefinedPostQueries( + IDbConnectionFactory connectionFactory) +{ + // Declared once: immutable, with no connection, safe in a static field. + static readonly MappedDbQuery ByAuthor + = DbQuery.Text(ListSql).Map(); + + public ValueTask> ByAuthorAsync( + int author, + CancellationToken cancellationToken) + => ByAuthor + .Using(connectionFactory) + .AddParam(author) // name and type inferred from the variable + .ToListAsync(cancellationToken); +} +#endregion + +public static class DefinedOwnConnection +{ + #region defined_list_own + static readonly MappedDbQuery ByAuthor + = DbQuery.Text(ListSql).Map(); + + public static async Task> ByAuthorAsync( + string connectionString, + int author, + CancellationToken cancellationToken) + { + // A connection you own: the call opens it only if it is closed, + // closes only what it opened, and never disposes it. + await using var connection = new SqliteConnection(connectionString); + return await ByAuthor + .Using(connection) + .AddParam(author) // name and type inferred from the variable + .ToListAsync(cancellationToken); + } + #endregion +} + +public static class DefinedTransactions +{ + #region defined_transaction + // A write is a DbNonQuery: declared once, like a query. + static readonly DbNonQuery InsertTemporary = DbNonQuery.Text(InsertSql); + + public static ValueTask InsertInTransactionAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => connectionFactory.UsingAsync(connection + => connection.ExecuteTransactionAsync(async transaction => + { + // The definition runs on the transaction. Using takes a + // DbTransaction; the callback's is an IDbTransaction. + await InsertTemporary + .Using((DbTransaction)transaction) + .AddParam("id", 100) + .ExecuteNonQueryAsync(cancellationToken); + }, cancellationToken)); + #endregion +} + +public static class DefinedTerminals +{ + #region defined_queries + // Declared once, next to the rest of the data layer. + static readonly MappedDbQuery Latest + = DbQuery.Text("select * from posts order by id").Map(); + + static readonly MappedDbQuery ById + = DbQuery.Text(OneSql).Map(); + + // The insert and a select of the new id in one command + // (SQLite: last_insert_rowid()). A write that returns a value is declared + // as a query, so that its result can be mapped. + static readonly MappedDbQuery AddDraft + = DbQuery.Text(""" + insert into posts (author, title, body, views) + values (@author, 'Draft', null, 0); + select last_insert_rowid() + """).Map(); + #endregion + + #region defined_first_single + public static async Task<(Post? First, Post? Single)> FirstAndSingleAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + { + Post? first = await Latest + .Using(connectionFactory) + .FirstOrDefaultAsync(cancellationToken); + + // SingleOrDefaultAsync returns null for no rows + // and throws if there is more than one row. + Post? single = await ById + .Using(connectionFactory) + .AddParam("id", 2) + .SingleOrDefaultAsync(cancellationToken); + + return (first, single); + } + #endregion + + #region defined_new_id + // SingleAsync throws unless exactly one row comes back, + // so there is no handler and no check. + public static ValueTask AddDraftAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => AddDraft + .Using(connectionFactory) + .AddParam("author", 42) + .SingleAsync(cancellationToken); + #endregion + + #region defined_page + // The page is chosen where the query runs, not where it is declared. + // Skipped rows are advanced without being mapped, + // and reading stops once the take is satisfied. + public static ValueTask PageAsync( + IDbConnectionFactory connectionFactory, + int skip, + int take, + CancellationToken cancellationToken) + => Latest + .Using(connectionFactory) + .Skip(skip) + .Take(take) + .ToArrayAsync(cancellationToken); + #endregion + + #region defined_dictionary + public static ValueTask> BodiesAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + // A key selector and a value selector build the lookup in one pass: + // no Post is kept, only the text. + => Latest + .Using(connectionFactory) + .ToDictionaryAsync( + static post => post.Id, + static post + => post.Body ?? "", + cancellationToken: cancellationToken); + #endregion + + #region defined_stream_early + // Only to stop early: Stream holds the connection open while each row + // is read. The timeout is the longest you may go without pulling the + // next row. To read all the rows, use ToArrayAsync, the buffered way. + public static async Task StopAtAsync( + IDbConnectionFactory connectionFactory, + string title, + CancellationToken cancellationToken) + { + int stoppedAt = 0; + await foreach (Post post in Latest + .Using(connectionFactory) + .Stream(TimeSpan.FromSeconds(30), cancellationToken)) + { + stoppedAt = post.Id; + if (post.Title == title) + { + break; + } + } + + return stoppedAt; + } + #endregion +} + +public static class DefinedBuffers +{ + #region defined_buffer_data_layer + static readonly MappedDbQuery Latest + = DbQuery.Text("select * from posts order by id").Map(); + + // The data layer: it starts the read and returns at once. + // Nothing here waits for the rows. The caller disposes the buffer. + public static PooledBuffer LatestPosts( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => Latest + .Using(connectionFactory) + .ToPooledBuffer(cancellationToken); + #endregion + + #region defined_buffer_page + // The same terminals are on every query, whatever it was declared with. + public static async Task PageIdsAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + { + await using PooledBuffer buffer = Latest + .Using(connectionFactory) + .Skip(1).Take(2) + .ToPooledBuffer(cancellationToken); + + PooledArray posts = await buffer.Items; + return [.. posts.Select(static p => p.Id)]; + } + #endregion + + #region defined_stream + // The query is the producer: it reads the rows in the background, + // in chunks, and the connection is free as soon as the last row + // is read. Nothing runs until the first read. + public static IAsyncEnumerable LatestStream( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => Latest + .Using(connectionFactory) + .ToPooledStream(cancellationToken); + #endregion +} + +public static class DefinedAsyncReads +{ + #region defined_async_reads + // The opt-in is part of the declaration: every call of this query + // reads its rows with ReadAsync. + static readonly MappedDbQuery Latest + = DbQuery.Text("select * from posts order by id") + .Map() + .AsyncReads(); + + public static ValueTask> LatestAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => Latest + .Using(connectionFactory) + .ToListAsync(cancellationToken); + #endregion +} + +public static class DefinedShaping +{ + #region defined_shaped + // The shape is declared with the query: a RowMap that leaves + // City alone, kept in the same static field as the text. + static readonly MappedDbQuery Authors + = DbQuery + .Text("select handle, city, editor from authors order by handle") + .Map(ShapingMaps.NoCityMap); + + public static ValueTask AuthorsAsync( + IDbConnectionFactory connectionFactory, + CancellationToken cancellationToken) + => Authors + .Using(connectionFactory) + .ToArrayAsync(cancellationToken); + #endregion +} + +public static class DefinedScalars +{ + #region defined_scalars + // A scalar is read as a T the way Map() reads a column: a SQLite + // bigint as an int, and a value that does not fit throws + // ValueMappingException. No rows and NULL are null for a type that + // takes null, and throw for one that does not. + static readonly ScalarDbQuery PostCount + = DbQuery.Text("select count(*) from posts").Scalar(); + + static readonly ScalarDbQuery AuthorCount + = DbQuery.Text(CountSql).Scalar(); + + // A write is a DbNonQuery: it returns the number of rows affected. + static readonly DbNonQuery Touch = DbNonQuery.Text(TouchSql); + + public static async Task<(int Posts, long ByAuthor, int Touched)> + CountsAsync( + IDbConnectionFactory connectionFactory, + int author, + CancellationToken cancellationToken) + { + int posts = await PostCount + .Using(connectionFactory) + .ExecuteScalarAsync(cancellationToken); + + long byAuthor = await AuthorCount + .Using(connectionFactory) + .AddParam(author) + .ExecuteScalarAsync(cancellationToken); + + int touched = await Touch + .Using(connectionFactory) + .AddParam(author) + .ExecuteNonQueryAsync(cancellationToken); + + return (posts, byAuthor, touched); + } + #endregion +} diff --git a/docsite/samples/Program.cs b/docsite/samples/Program.cs index 69b1417c..a0f2d999 100644 --- a/docsite/samples/Program.cs +++ b/docsite/samples/Program.cs @@ -63,6 +63,18 @@ void Check(bool condition, string what) Check(await factory.Command("select id from posts where id > 1000").ExecuteScalarAsync() is null, "ExecuteScalarAsync over no rows is null"); Check(factory.Command(Sql.CountSql).AddParam("author", 42).ExecuteScalar() == 3 && factory.Command(Sql.CountSql).AddParam("@author", 42).ExecuteScalar() == 3, "a parameter name is sent as written: SQLite accepts it with or without the @"); +// The definition path (DbQuery...Scalar(), DbNonQuery) reads what the same call on a command reads: the same conversion, the same null and the same errors. +Check(await factory.Command("select count(*) from posts").ExecuteScalarAsync() == 5 && await DbQuery.Text("select count(*) from posts").Scalar().Using(factory).ExecuteScalarAsync() == 5, "Scalar() converts a SQLite bigint as ExecuteScalarAsync does"); +Check(await factory.Command(Sql.CountSql).AddParam("author", 42).ExecuteScalarAsync() == 3 && await DbQuery.Text(Sql.CountSql).Scalar().Using(factory).AddParam("author", 42).ExecuteScalarAsync() == 3, "Scalar() equals ExecuteScalarAsync"); +Check(await ThrowsAsync(async () => await DbQuery.Text("select 5000000000").Scalar().Using(factory).ExecuteScalarAsync()), "Scalar() over a value that does not fit throws ValueMappingException, as ExecuteScalarAsync does"); +Check(await ThrowsAsync(async () => await DbQuery.Text("select id from posts where id > 1000").Scalar().Using(factory).ExecuteScalarAsync()), "Scalar() over no rows throws ValueMappingException, as ExecuteScalarAsync does"); +Check(await ThrowsAsync(async () => await DbQuery.Text("select max(id) from posts where id > 1000").Scalar().Using(factory).ExecuteScalarAsync()), "Scalar() over NULL throws ValueMappingException, as ExecuteScalarAsync does"); +Check(await DbQuery.Text("select id from posts where id > 1000").Scalar().Using(factory).ExecuteScalarAsync() is null && await factory.Command("select id from posts where id > 1000").ExecuteScalarAsync() is null, "Scalar() over no rows is null, as ExecuteScalarAsync is"); +Check(await DbQuery.Text("select max(id) from posts where id > 1000").Scalar().Using(factory).ExecuteScalarAsync() is null && await factory.Command("select max(id) from posts where id > 1000").ExecuteScalarAsync() is null, "Scalar() over NULL is null, as ExecuteScalarAsync is"); +Check(await DbQuery.Text("select title from posts where id = 1").Scalar().Using(factory).ExecuteScalarAsync() == "Post 1" && await factory.Command("select title from posts where id = 1").ExecuteScalarAsync() == "Post 1", "Scalar() equals ExecuteScalarAsync"); +Check(await DbQuery.Text("select body from posts where id = 2").Scalar().Using(factory).ExecuteScalarAsync() is null && await factory.Command("select body from posts where id = 2").ExecuteScalarAsync() is null, "Scalar() over a NULL is null, as ExecuteScalarAsync is"); +Check(await DbNonQuery.Text(Sql.TouchSql).Using(factory).AddParam("author", 42).ExecuteNonQueryAsync() == 3 && await factory.Command(Sql.TouchSql).AddParam("author", 42).ExecuteNonQueryAsync() == 3, "DbNonQuery returns the rows affected, as ExecuteNonQueryAsync does"); + // Mapping. Db.Seed(); Post[] all = await Mapping.MapDefaultAsync(connection, CancellationToken.None); @@ -662,6 +674,38 @@ await ThrowsAsync(() => HowLittleCode.CollectAsync(od await NoServiceLayerLifetimeChecks.RunAsync(Check); await ReturnedBufferChecks.RunAsync(Check); +// Definition-first: the same queries declared once (Defined.cs). +Db.Seed(); +Check((await new DefinedPostQueries(factory).ByAuthorAsync(42, CancellationToken.None)).Select(p => p.Id).SequenceEqual([1, 2, 3]), "a declared query returns the rows of the ad hoc one"); +Check((await DefinedOwnConnection.ByAuthorAsync(Db.ConnectionString, 7, CancellationToken.None)).Select(p => p.Id).SequenceEqual([4, 5]), "a declared query runs on a connection you own"); +await DefinedTransactions.InsertInTransactionAsync(factory, CancellationToken.None); +Check(await factory.Command("select count(*) from posts where id = 100").ExecuteScalarAsync() == 1, "a declared write runs on a transaction and commits with it"); +await factory.Command("delete from posts where id = 100").ExecuteNonQueryAsync(); +(Post? definedFirst, Post? definedSingle) = await DefinedTerminals.FirstAndSingleAsync(factory, CancellationToken.None); +Check(definedFirst?.Id == 1 && definedSingle?.Id == 2, "a declared query: FirstOrDefaultAsync and SingleOrDefaultAsync"); +long definedNewId = await DefinedTerminals.AddDraftAsync(factory, CancellationToken.None); +Check(definedNewId > 5 && await factory.Command("select count(*) from posts where id = @id").AddParam("id", definedNewId).ExecuteScalarAsync() == 1, "a declared insert and select of the new id: SingleAsync"); +await factory.Command("delete from posts where id = @id").AddParam("id", definedNewId).ExecuteNonQueryAsync(); +Check((await DefinedTerminals.PageAsync(factory, 1, 2, CancellationToken.None)).Select(p => p.Id).SequenceEqual([2, 3]), "a declared query is paged where it runs"); +Dictionary definedBodies = await DefinedTerminals.BodiesAsync(factory, CancellationToken.None); +Check(definedBodies.Count == 5 && definedBodies[1] == "Body 1" && definedBodies[2] == "", "a declared query builds a dictionary with a key and a value selector"); +Check(await DefinedTerminals.StopAtAsync(factory, "Post 3", CancellationToken.None) == 3, "a declared query streams and stops early"); +using (PooledBuffer definedBuffer = DefinedBuffers.LatestPosts(factory, CancellationToken.None)) +{ + Check((await definedBuffer.Items).Count == 5, "a declared query into a pooled buffer"); +} + +Check((await DefinedBuffers.PageIdsAsync(factory, CancellationToken.None)).SequenceEqual([2, 3]), "a declared query into a pooled buffer, skipped and taken"); +List definedStreamIds = []; +await foreach (Post post in DefinedBuffers.LatestStream(factory, CancellationToken.None)) + definedStreamIds.Add(post.Id); + +Check(definedStreamIds.SequenceEqual([1, 2, 3, 4, 5]), "a declared query into a pooled stream"); +Check((await DefinedAsyncReads.LatestAsync(factory, CancellationToken.None)).Count == 5, "a declared query that opts in to AsyncReads"); +Check((await DefinedShaping.AuthorsAsync(factory, CancellationToken.None)) is [{ Handle: "ada", City: "", Editor: "Kim" }, { Handle: "grace", City: "", Editor: "Lee" }], "a declared query with a declared RowMap leaves the member unmapped"); +(int definedPosts, long definedByAuthor, int definedTouched) = await DefinedScalars.CountsAsync(factory, 42, CancellationToken.None); +Check(definedPosts == 5 && definedByAuthor == 3 && definedTouched == 3, "declared scalars and a declared write"); + Console.WriteLine($"All {checks} sample checks passed."); return 0; From 5a3d802f8a8c2052b9557cd3310f414d9af9bd0b Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:57:12 -0800 Subject: [PATCH 2/3] Docs: the declared form first where an application writes the call, then the ad hoc one-liner The query an application runs again and again is declared once, as a `static readonly` definition with no connection (`DbQuery.Text(...).Map()`), and bound where it runs; the docs now show that form first in the places that are application code, and then the same call ad hoc ("Or, simply expressive"), with nothing to declare. The places that demonstrate one feature in one line, or compare line counts, stay ad hoc. - Declared first: the README, the Core, Channel and Dataflow package pages, Getting started (the first query, and from a connection you own), the foundation's transactions (`Using(transaction)`), Coming from Dapper (the consumer of the registered factory), Expressive commands ("Defining a query once" moves ahead of the command form, which is retitled "Building a command where you need it"), the mapping terminals (first and single, a new id, a dictionary, a page, a stream that stops early), the async buffers (a page, the data layer), Channels and Dataflow (the producer), Async reads (the opt-in is part of the declaration), Shaping rows (a map declared with its query), and What's new (the `DbQuery` section moves to the top). - Stays ad hoc: How little code (one call against one call; a sentence says what declaring adds), the rule demonstrations of Mapping, and the rest of the feature demonstrations. - Said plainly: a declared query has fixed text, so `AddParamIf` is a command-form call; the scalar that converts in your own way (`ExecuteScalarAsync(value => ...)`) has no declared counterpart, while `Scalar()` converts as `ExecuteScalarAsync()` does (checked by the samples). Every new sample compiles in the samples project and is run and checked there; the new regions are in `Defined.cs`. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 20 +++++- Source/Channel/README.md | 19 ++++- Source/Core/README.md | 16 ++++- Source/Dataflow/README.md | 19 ++++- docsite/articles/async-buffers.md | 10 ++- docsite/articles/async-reads.md | 6 ++ docsite/articles/channels-and-dataflow.md | 6 +- docsite/articles/coming-from-dapper.md | 6 +- docsite/articles/expressive-commands.md | 84 +++++++++++++---------- docsite/articles/foundation.md | 6 ++ docsite/articles/getting-started.md | 12 +++- docsite/articles/how-little-code.md | 2 + docsite/articles/mapping.md | 24 +++++++ docsite/articles/shaping-rows.md | 4 ++ docsite/articles/whats-new-11.md | 34 ++++----- docsite/index.md | 4 ++ 16 files changed, 203 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 47c8673a..a8435b8b 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,23 @@ while (await reader.ReadAsync(cancellationToken)) } ``` -And with Open.Database.Extensions: +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); +``` + +Or, simply expressive, with nothing to declare: ```cs int author = 42; @@ -57,7 +73,7 @@ Post[] posts = await connectionFactory .ToArrayAsync(cancellationToken); ``` -`AddParam(author)` names the parameter after the variable. `connectionFactory` is created once per application, for example `new DbConnectionFactory(() => new SqliteConnection(connectionString))`. Or start from a connection you already have: the command opens it only if it is closed, and closes only what it opened. +`AddParam(author)` names the parameter after the variable. `connectionFactory` is created once per application, for example `new DbConnectionFactory(() => new SqliteConnection(connectionString))`. Or start from a connection you already have: the call opens it only if it is closed, and closes only what it opened. ## Install diff --git a/Source/Channel/README.md b/Source/Channel/README.md index 2bcfdf77..f592d71b 100644 --- a/Source/Channel/README.md +++ b/Source/Channel/README.md @@ -16,10 +16,14 @@ 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(); + // Returns right away: the rows are read in the background and the channel completes when they are all written. -ChannelReader reader = connectionFactory - .Command("select * from posts order by id") - .Map() +ChannelReader reader = Latest + .Using(connectionFactory) .ToChannelReader(); await foreach (Post post in reader.ReadAllAsync()) @@ -28,6 +32,15 @@ await foreach (Post post in reader.ReadAllAsync()) } ``` +Or, simply expressive, with nothing to declare: + +```cs +ChannelReader reader = connectionFactory + .Command("select * from posts order by id") + .Map() + .ToChannelReader(); +``` + `ToChannelReader()` and `ToChannel()` make an unbounded channel, and the connection is closed when the read ends, however slowly you read the channel. `ToChannel(channel)` writes into a channel you own and leaves it open. `ToChannelHoldingConnection` pulls the rows one at a time to cap memory and holds the connection until the last row is read: use it only for that. See [Channels and Dataflow](https://open-net-libraries.github.io/Open.Database.Extensions/articles/channels-and-dataflow.html). ## The packages diff --git a/Source/Core/README.md b/Source/Core/README.md index 1b5ac9ba..e9a75ab9 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -20,7 +20,21 @@ public record Post(int Id, string Title); var connectionFactory = new DbConnectionFactory(() => new SqliteConnection(connectionString)); int author = 42; -// The command opens a connection when the terminal runs and disposes it afterwards. +// 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(); + +// 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(); +``` + +Or, simply expressive, with nothing to declare: + +```cs 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 4c68b246..1e0bc0cf 100644 --- a/Source/Dataflow/README.md +++ b/Source/Dataflow/README.md @@ -17,10 +17,14 @@ 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(); +// 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. -long count = await connectionFactory - .Command("select * from posts order by id") - .Map() +long count = await Latest + .Using(connectionFactory) .ToTargetBlock(block, complete: true); // The block completes once every row has been received. @@ -29,6 +33,15 @@ while (await block.OutputAvailableAsync()) received.Add(await block.ReceiveAsync()); ``` +Or, simply expressive, with nothing to declare: + +```cs +long count = await connectionFactory + .Command("select * from posts order by id") + .Map() + .ToTargetBlock(block, complete: true); +``` + Each row is sent with `SendAsync`, so a bounded block that is full makes the pass wait. See [Channels and Dataflow](https://open-net-libraries.github.io/Open.Database.Extensions/articles/channels-and-dataflow.html). ## The packages diff --git a/docsite/articles/async-buffers.md b/docsite/articles/async-buffers.md index fa250840..6dd89fb4 100644 --- a/docsite/articles/async-buffers.md +++ b/docsite/articles/async-buffers.md @@ -31,7 +31,11 @@ Three panels, each a pair of bars that start at zero, on one scale: how long the The streams do nothing until the first `MoveNextAsync`, and they can be enumerated once. A second `GetAsyncEnumerator` on the chunk stream throws `InvalidOperationException`; on the element stream the same exception comes at the first `MoveNextAsync`. -The same terminals are on a view with `Skip` and `Take`: +The same terminals are on a query with `Skip` and `Take`, whether it was declared once or built at the call: + +[!code-csharp[](../samples/Defined.cs#defined_buffer_page)] + +Or, simply expressive, ad hoc: [!code-csharp[](../samples/AsyncBuffers.cs#buffers_skip_take)] @@ -54,6 +58,10 @@ The same terminals are on a view with `Skip` and `Take`: The use case that shaped `ToPooledBuffer` is a data layer that hands rows up to a layer that does not know about the database. A command factory method returns `PooledBuffer`: +[!code-csharp[](../samples/Defined.cs#defined_buffer_data_layer)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/AsyncBuffers.cs#buffers_data_layer)] The method returns at once and the read is already running. The layer above, a controller say, awaits the rows when it needs them, serializes them and disposes the buffer: diff --git a/docsite/articles/async-reads.md b/docsite/articles/async-reads.md index b68c6d28..c97dbbb3 100644 --- a/docsite/articles/async-reads.md +++ b/docsite/articles/async-reads.md @@ -24,6 +24,12 @@ The same query, both ways: **Opt in** +On a declared query the opt-in is part of the declaration, so every call of that query reads with `ReadAsync`: + +[!code-csharp[](../samples/Defined.cs#defined_async_reads)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/AsyncReads.cs#asyncreads_optin)] diff --git a/docsite/articles/channels-and-dataflow.md b/docsite/articles/channels-and-dataflow.md index c3f88db8..d360191b 100644 --- a/docsite/articles/channels-and-dataflow.md +++ b/docsite/articles/channels-and-dataflow.md @@ -24,7 +24,11 @@ Both are lazy and single-use, and a `break` or a dispose cancels the query: it w ### One producer, one consumer -The query reads ahead into buffers, and the consumer does its slow work row by row: +The query is declared once, like any other, and is the producer wherever it runs: + +[!code-csharp[](../samples/Defined.cs#defined_stream)] + +Or, simply expressive, ad hoc. The query reads ahead into buffers, and the consumer does its slow work row by row: [!code-csharp[](../samples/ChannelsAndDataflow.cs#stream_producer_consumer)] diff --git a/docsite/articles/coming-from-dapper.md b/docsite/articles/coming-from-dapper.md index 4beff717..6a3ff62e 100644 --- a/docsite/articles/coming-from-dapper.md +++ b/docsite/articles/coming-from-dapper.md @@ -201,7 +201,11 @@ Across the list, one row, scalar and no-result-set calls above, Dapper takes 13 [!code-csharp[](../samples/ConnectionPattern.cs#di_registration)] -Consumers take the factory as a constructor parameter and never see a connection string: +Consumers take the factory as a constructor parameter and never see a connection string. Where Dapper code keeps its SQL in a `const string` and repeats the call, the extensions let you declare the SQL, and the map, once as a `static readonly` query (immutable, with no connection), and bind the factory and the values where it runs: + +[!code-csharp[](../samples/Defined.cs#defined_list)] + +Or, simply expressive, a consumer builds the command at the call, with nothing to declare: [!code-csharp[](../samples/ConnectionPattern.cs#di_consumer)] diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 753999bf..b846aee1 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -1,43 +1,6 @@ # Expressive commands -An expressive command is a small object you build with chained calls: pick the SQL (or stored procedure), add parameters, then call a terminal that runs it. - -## Two starting points - -The factory form (`connectionFactory.Command(sql)` or `connectionFactory.StoredProcedure(name)`) and the connection form (`connection.Command(sql)` or `connection.StoredProcedure(name)`) look the same after the first call. In the samples `author` is a variable (`int author = 42;`). Side by side, row against row: - -
-
- -**Factory form** - -[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_call)] - -
-
- -**Connection form** - -[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_own)] - -
-
- -In the factory form the command creates, opens and disposes a connection for every terminal. In the connection form the connection is yours: the command opens it only when it is closed, closes only what it opened, and never disposes it. See [who owns the connection](foundation.md#who-owns-the-connection). - -A connection pool (`IDbConnectionPool`) is also a valid source, but it is there for a pooling scheme of your own: a pool a particular database needs, or one kept in memory and reused locally. Providers already pool their connections (Microsoft SQL Server included), so with those a factory is the right source and a pool of your own adds nothing. - -A command is not safe to share across threads: one built from a single connection throws `InvalidOperationException` if two terminals run at once. - -## Which command type you get - -| You call it on | You get | Reader type | -|---|---|---| -| `IDbConnection`, `IDbTransaction`, `IDbConnectionFactory` | `ExpressiveCommand` | `IDataReader` | -| `DbConnection`, `DbTransaction`, `IDbConnectionFactory` | `ExpressiveDbCommand` | `DbDataReader` (async reads) | -| `SqlConnection` or a `SqlConnectionFactory` (MSSqlClient package) | `ExpressiveSqlCommand` | `SqlDataReader` | - -Choose by what you need: only the last two rows have `Async` terminals, so a service that awaits starts from a `DbConnection` or an `IDbConnectionFactory` (for example `IDbConnectionFactory`). Pass a `CommandType` as the second argument of `Command` if you need `TableDirect`. +An expressive command is a small object you build with chained calls: pick the SQL (or stored procedure), add parameters, then call a terminal that runs it. The call an application runs again and again is best [declared once](#defining-a-query-once) and bound where it runs; a call you need once is built where you need it, as in [Building a command where you need it](#building-a-command-where-you-need-it). ## Defining a query once @@ -103,6 +66,43 @@ A write is a `DbNonQuery`, made with `Text` or `Procedure` and run with `Execute Both take the same sources as a query, and their values before or after `Using`; `Params()` declares typed values. Set a timeout with `SetTimeout` on a `DbNonQuery`, or on the `DbQuery` before `Scalar()`. Output and return parameters are not supported here: use a command for them (see [Return values and output parameters](#return-values-and-output-parameters)). +## Building a command where you need it + +Not every call is worth declaring. For a one-off, or a command built from what the caller supplies, build it where you need it: simply expressive, with nothing to declare. The factory form (`connectionFactory.Command(sql)` or `connectionFactory.StoredProcedure(name)`) and the connection form (`connection.Command(sql)` or `connection.StoredProcedure(name)`) look the same after the first call. In the samples `author` is a variable (`int author = 42;`). Side by side, row against row: + +
+
+ +**Factory form** + +[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_call)] + +
+
+ +**Connection form** + +[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_own)] + +
+
+ +In the factory form the command creates, opens and disposes a connection for every terminal. In the connection form the connection is yours: the command opens it only when it is closed, closes only what it opened, and never disposes it. See [who owns the connection](foundation.md#who-owns-the-connection). + +A connection pool (`IDbConnectionPool`) is also a valid source, but it is there for a pooling scheme of your own: a pool a particular database needs, or one kept in memory and reused locally. Providers already pool their connections (Microsoft SQL Server included), so with those a factory is the right source and a pool of your own adds nothing. + +A command is not safe to share across threads: one built from a single connection throws `InvalidOperationException` if two terminals run at once. + +## Which command type you get + +| You call it on | You get | Reader type | +|---|---|---| +| `IDbConnection`, `IDbTransaction`, `IDbConnectionFactory` | `ExpressiveCommand` | `IDataReader` | +| `DbConnection`, `DbTransaction`, `IDbConnectionFactory` | `ExpressiveDbCommand` | `DbDataReader` (async reads) | +| `SqlConnection` or a `SqlConnectionFactory` (MSSqlClient package) | `ExpressiveSqlCommand` | `SqlDataReader` | + +Choose by what you need: only the last two rows have `Async` terminals, so a service that awaits starts from a `DbConnection` or an `IDbConnectionFactory` (for example `IDbConnectionFactory`). Pass a `CommandType` as the second argument of `Command` if you need `TableDirect`. + ## Parameters Name a parameter in the way that fits what you have: @@ -167,6 +167,8 @@ A derived name stays as written when no real names were read: a text command, an [!code-csharp[](../samples/ExpressiveCommands.cs#param_if)] +A declared query has fixed text and a fixed set of parameters, so `AddParamIf`, which goes with SQL text that varies with the same condition, belongs to the command form. + ### A generated id To get the id an insert generated, select it in the same command and read it with `ExecuteScalarAsync()` (the statement that returns the id depends on your database; SQLite is shown). `ExecuteReturnAsync()` is only for a procedure's `RETURN` code. @@ -223,6 +225,12 @@ The library reads with the default access mode, in which SqlClient reads a whole `ExecuteScalarAsync()` converts the value the provider returns the way `Map()` converts a column. A value that is already a `T` is returned as it is. An integer converts to another integer type with a range check (a `bigint` read as `int`, an `int` read as `long`), and any other value is converted by the same code `Map()` uses (a `numeric`, which is a `decimal`, read as `long`). A value that cannot be converted, or does not fit, throws `ValueMappingException` with the conversion's own error inside. A `NULL` or no row into a non-nullable value type throws `ValueMappingException`; ask for the nullable type, `int?` or `long?`, when a NULL or no row is expected. +Declared, a scalar is a `ScalarDbQuery` and a write is a `DbNonQuery`. `Scalar()` converts as `ExecuteScalarAsync()` does: a `bigint` read as `int`, a value that does not fit throws `ValueMappingException`, and no rows and `NULL` are `null` for a type that takes null and throw for one that does not. The form that converts in your own way (`ExecuteScalarAsync(value => ...)`) is a command-level call, with no declared counterpart. + +[!code-csharp[](../samples/Defined.cs#defined_scalars)] + +Or, simply expressive, on a command: + [!code-csharp[](../samples/ExpressiveCommands.cs#scalar_read_as_int)] [!code-csharp[](../samples/ExpressiveCommands.cs#scalar_and_nonquery)] diff --git a/docsite/articles/foundation.md b/docsite/articles/foundation.md index e6c24a06..54f67cd4 100644 --- a/docsite/articles/foundation.md +++ b/docsite/articles/foundation.md @@ -37,6 +37,12 @@ Several helpers exist to keep the time a connection is open short: ## 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: + +[!code-csharp[](../samples/Defined.cs#defined_transaction)] + +Or, simply expressive, a command starts from the transaction: `transaction.Command(...)`, as in the two examples below. + `ExecuteTransactionConditionalAsync` begins a transaction, runs your action, and commits only if the action returns `true`, nothing throws and the cancellation token was not cancelled. Otherwise it rolls back. A connection that was closed is opened for the transaction and closed again afterwards; one that was open stays open. [!code-csharp[](../samples/Transactions.cs#transaction)] diff --git a/docsite/articles/getting-started.md b/docsite/articles/getting-started.md index 2a8f0a81..aafdd7fd 100644 --- a/docsite/articles/getting-started.md +++ b/docsite/articles/getting-started.md @@ -37,7 +37,15 @@ A command needs a connection. A connection factory creates them, and you create [!code-csharp[](../samples/ConnectionPattern.cs#ode_setup_once)] -There are two ways to start a command: from the factory, or from a connection you own. Both end the same way, with `AddParam` for parameters and a terminal (the call that runs the query, such as `ToListAsync()`). In the samples `author` is a variable (`int author = 42;`) and `AddParam(author)` names the parameter `author` after it; `AddParam("author", 42)` names it yourself. Side by side, row against row ("nothing" marks a step the factory makes unnecessary): +The way to write a query an application runs again and again is to declare it once. A query is immutable and holds no connection, so it lives in a `static readonly` field; where it runs you bind the source (`Using`), add the values (`AddParam`) and call a terminal (the call that runs the query, such as `ToListAsync()`). In the samples `author` is a variable (`int author = 42;`) and `AddParam(author)` names the parameter `author` after it; `AddParam("author", 42)` names it yourself: + +[!code-csharp[](../samples/Defined.cs#defined_list)] + +The source is a connection factory, as above, or a connection you own: + +[!code-csharp[](../samples/Defined.cs#defined_list_own)] + +Or, simply expressive: for a one-off call there is nothing to declare. Build the command where you need it, from the factory or from a connection you own. Both end the same way, with `AddParam` and a terminal. Side by side, row against row ("nothing" marks a step the factory makes unnecessary):
@@ -56,7 +64,7 @@ There are two ways to start a command: from the factory, or from a connection yo
-In both forms the command opens the connection only if it is closed. The factory form disposes the connection when the terminal returns; in the connection form the command closes only what it opened and never disposes it. See [Who owns the connection](foundation.md#who-owns-the-connection). +In every form the call opens the connection only if it is closed. The factory form disposes the connection when the terminal returns; in the connection form the command closes only what it opened and never disposes it. See [Who owns the connection](foundation.md#who-owns-the-connection). ## Before and after diff --git a/docsite/articles/how-little-code.md b/docsite/articles/how-little-code.md index 1f936113..15995415 100644 --- a/docsite/articles/how-little-code.md +++ b/docsite/articles/how-little-code.md @@ -4,6 +4,8 @@ The same four tasks, written with Open.Database.Extensions (ODX), Dapper, EF Cor Everything here is async. ODX, Dapper and plain ADO.NET share the same SQL string in each of tasks 1 to 3 (tasks 2 and 3 add `where author = @author`); EF Core writes the same query as LINQ. The tasks read the `posts` table of the [sample database](getting-started.md#your-first-query) into the `Post` class. +The ODX snippets build each command where it is used, which is how a call is counted fairly against the others, one call against one call. An application that runs the same query from several places declares it once as a `static readonly` field instead (see [Your first query](getting-started.md#your-first-query)): that adds one declaration to the file, and the call then names only the source and the values. + ## How the lines are counted Each cell counts the lines of one method as it would appear in a data-access class: the signature through the closing brace, without blank lines and without comments. `using` directives are not counted. The numbers below are the output of `docsite/tools/count-region-lines.ps1`. The code is written vertically, one argument and one call per line, the same way for all four libraries. diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index f2248b00..05f0b6c1 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -327,24 +327,48 @@ Some columns are not the type the model wants: a number the model keeps as text, `ToArrayAsync`, `ToListAsync`, `ToImmutableArrayAsync`, `ToDictionaryAsync`, `ToHashSetAsync`, `FirstAsync`, `FirstOrDefaultAsync`, `SingleAsync` and `SingleOrDefaultAsync`. `FirstAsync` and `SingleAsync` throw `InvalidOperationException` when the query returns no row (and `SingleAsync` when it returns more than one); the `OrDefault` forms return `null` for no rows. A row whose value is `NULL` is still a row. Prefer `ToArrayAsync` for results you only read: it allocates one exactly sized array, and an empty result is the shared empty array. Use `ToListAsync` when you add to or remove from the result afterwards. +An application declares these queries once and runs them where it needs them, so the queries are declared first, and each call below is shown on them, then written ad hoc, with nothing to declare: + +[!code-csharp[](../samples/Defined.cs#defined_queries)] + +[!code-csharp[](../samples/Defined.cs#defined_first_single)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/Mapping.cs#map_first_single)] An insert that returns its new id is one `SingleAsync`: no handler, and no check for the row you expect, because it throws unless there is exactly one. The failure is thrown after the connection is released and the later result sets are read, so a failure in one of them comes first. +[!code-csharp[](../samples/Defined.cs#defined_new_id)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/Mapping.cs#map_single_insert)] `ToDictionary` keys the rows by a key selector. Add a value selector to keep something other than the whole row, such as an id-to-text lookup, built in one pass: +[!code-csharp[](../samples/Defined.cs#defined_dictionary)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/Mapping.cs#map_dictionary_values)] For a result that nobody else can change, use `ToImmutableArrayAsync`: it wraps the exactly sized array the read produced, with no second copy on .NET 8 and later (the netstandard2.0 build copies it once). There is no `ToImmutableDictionary` or `ToImmutableHashSet` terminal. For a lookup that cannot change, call `ToFrozenDictionary()` on the result of `ToDictionaryAsync`. `Skip` and `Take` are part of the query: skipped rows are advanced without being mapped, and reading stops once the take is satisfied. Call `Skip` before `Take`, as the types enforce: +[!code-csharp[](../samples/Defined.cs#defined_page)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/Mapping.cs#map_paging)] Buffered terminals are the way to read all the rows: use `ToArrayAsync` unless you need rows as they arrive. **`Stream(stallTimeout, cancellationToken)` holds the reader and the connection open while your loop works on each row**, so keep that loop fast; to hand rows to another consumer, use [`ToPooledStream`](channels-and-dataflow.md); for the raw reader, use `ExecuteReaderAsync`: +[!code-csharp[](../samples/Defined.cs#defined_stream_early)] + +Or, simply expressive, ad hoc: + [!code-csharp[](../samples/Mapping.cs#map_stream)] To read rows as they arrive there are three ways, and they differ in what they buffer and how long they hold the connection: diff --git a/docsite/articles/shaping-rows.md b/docsite/articles/shaping-rows.md index 0e2f0f47..5c107f9d 100644 --- a/docsite/articles/shaping-rows.md +++ b/docsite/articles/shaping-rows.md @@ -72,6 +72,10 @@ You may look for an `Ignore(member)`. It exists as a pair whose column is the C# `City` is `""` in every row although the query returns `city`. The `null` needs no `!` after it. +A map is a static value, so it can be declared with the query it shapes, in the same `static readonly` field as the SQL text, and every call of the query reads with it: + +[!code-csharp[](../samples/Defined.cs#defined_shaped)] + ## Being strict There is no strict mode, because a mode would change every rule. There are three ways to say what you mean, each at the place it applies: diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index 70762c54..149a1590 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -6,6 +6,23 @@ Each member that is gone has a replacement that is shorter, and the old way is n Packages: use `Open.Database.Extensions.MSSqlClient` (on `Microsoft.Data.SqlClient`) for SQL Server. The `Open.Database.Extensions.SqlClient` package (on `System.Data.SqlClient`) is not published for 11; every type in it has its twin in `MSSqlClient`. Version 11 targets `net11.0` next to `net10.0`, `netstandard2.0` and `netstandard2.1` (`MSSqlClient`: `net472`, `net10.0` and `net11.0`). +## `DbQuery` + +A query is defined once, mapped, with no connection; the source and the values are given where it runs. There is nothing to migrate: it is new in 11. + +```cs +static readonly MappedDbQuery ByAuthor = DbQuery + .Text("select * from posts where author = @author") + .Map(); + +public ValueTask> ByAuthorAsync(int author, CancellationToken cancellationToken) + => ByAuthor.Using(connectionFactory).AddParam(author).ToListAsync(cancellationToken); +``` + +See [Expressive commands](expressive-commands.md). + +`DbNonQuery` and `DbQuery.Scalar()` run a write or a single value through the same chain as `DbQuery`. See [Writes and scalars](expressive-commands.md#writes-and-scalars). + ## Mapping: `Map()` Every way of turning rows into objects is `Map()` followed by a terminal. The terminals read straight from the reader through a mapping compiled once and cached, so nothing is boxed on the common path. @@ -106,23 +123,6 @@ The blocking calls (`Execute`, `ExecuteNonQuery`, `ExecuteScalar`, `ExecuteReade `Execute(f)` and `ExecuteReader(f)` infer `T`: a call that named `T` alone needs both type arguments or none. A command type of your own that implements `IExecuteReader` or `IExecuteCommand` throws `NotSupportedException` when a blocking call reaches it: use the async call. -## `DbQuery` - -A query is defined once, mapped, with no connection; the source and the values are given where it runs. There is nothing to migrate: it is new in 11. - -```cs -static readonly MappedDbQuery ByAuthor = DbQuery - .Text("select * from posts where author = @author") - .Map(); - -public ValueTask> ByAuthorAsync(int author, CancellationToken cancellationToken) - => ByAuthor.Using(connectionFactory).AddParam(author).ToListAsync(cancellationToken); -``` - -See [Expressive commands](expressive-commands.md). - -`DbNonQuery` and `DbQuery.Scalar()` run a write or a single value through the same chain as `DbQuery`. See [Writes and scalars](expressive-commands.md#writes-and-scalars). - ## Parameters - **`AddParam(parameterName)` with a string variable** added a parameter with that name and no value in 10.x. In 11 it adds a parameter named `parameterName` whose value is the string. A literal, `AddParam("name")`, throws `ArgumentException`. For a parameter with no value pass its direction, `AddParam("name", ParameterDirection.Output)`. diff --git a/docsite/index.md b/docsite/index.md index c7d8d528..61eda37e 100644 --- a/docsite/index.md +++ b/docsite/index.md @@ -14,6 +14,10 @@ Extensions on the standard ADO.NET types that make everyday database work short Here `author` is an `int` variable: the parameter name `author` comes from the argument. +In an application the same query is declared once, with no connection, and bound where it runs: + +[!code-csharp[](samples/Defined.cs#defined_list)] + ## The idea 1. **A foundation of best-practice extensions.** Most of the library is a provider-agnostic collection of extensions on `IDbConnection`, `IDbCommand`, `IDataReader` and friends. They apply the usual best practices (open late, close early, dispose what you create, honor cancellation). See [The foundation](articles/foundation.md). From 936926b993dec3a9f8f69dd6fb0cb32aa7a76c30 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:08:11 -0800 Subject: [PATCH 3/3] Samples and READMEs: the first call stays on the receiver's line The chain style of the new declared samples and README snippets: the first call stays on the receiver's line (`await ByAuthor.Using(connectionFactory)`), and the chain goes vertical from the second call, each call on its own line; no receiver is alone on a line. A text too long for the receiver's line breaks inside the first call's argument. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 9 +++--- Source/Channel/README.md | 8 ++---- Source/Core/README.md | 9 +++--- Source/Dataflow/README.md | 8 ++---- docsite/samples/Defined.cs | 58 ++++++++++++++------------------------ 5 files changed, 35 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index a8435b8b..ec134a71 100644 --- a/README.md +++ b/README.md @@ -49,14 +49,13 @@ And with Open.Database.Extensions, the query declared once (immutable, with no c ```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(); +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) +Post[] posts = await ByAuthor.Using(connectionFactory) .AddParam(author) // name and type inferred from the variable .ToArrayAsync(cancellationToken); ``` diff --git a/Source/Channel/README.md b/Source/Channel/README.md index f592d71b..4fced96c 100644 --- a/Source/Channel/README.md +++ b/Source/Channel/README.md @@ -17,13 +17,11 @@ 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(); +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) +ChannelReader reader = Latest.Using(connectionFactory) .ToChannelReader(); await foreach (Post post in reader.ReadAllAsync()) diff --git a/Source/Core/README.md b/Source/Core/README.md index e9a75ab9..fb9c12f6 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -21,13 +21,12 @@ var connectionFactory = new DbConnectionFactory(() => new Sqli 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(); +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. -Post[] posts = await ByAuthor - .Using(connectionFactory) +Post[] posts = await ByAuthor.Using(connectionFactory) .AddParam(author) // name and type inferred from the variable .ToArrayAsync(); ``` diff --git a/Source/Dataflow/README.md b/Source/Dataflow/README.md index 1e0bc0cf..123e902c 100644 --- a/Source/Dataflow/README.md +++ b/Source/Dataflow/README.md @@ -18,13 +18,11 @@ public record Post(int Id, string Title); var block = new BufferBlock(); // 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(); +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. -long count = await Latest - .Using(connectionFactory) +long count = await Latest.Using(connectionFactory) .ToTargetBlock(block, complete: true); // The block completes once every row has been received. diff --git a/docsite/samples/Defined.cs b/docsite/samples/Defined.cs index 2b11dfb7..3364ab3c 100644 --- a/docsite/samples/Defined.cs +++ b/docsite/samples/Defined.cs @@ -22,8 +22,7 @@ static readonly MappedDbQuery ByAuthor public ValueTask> ByAuthorAsync( int author, CancellationToken cancellationToken) - => ByAuthor - .Using(connectionFactory) + => ByAuthor.Using(connectionFactory) .AddParam(author) // name and type inferred from the variable .ToListAsync(cancellationToken); } @@ -43,8 +42,7 @@ public static async Task> ByAuthorAsync( // A connection you own: the call opens it only if it is closed, // closes only what it opened, and never disposes it. await using var connection = new SqliteConnection(connectionString); - return await ByAuthor - .Using(connection) + return await ByAuthor.Using(connection) .AddParam(author) // name and type inferred from the variable .ToListAsync(cancellationToken); } @@ -65,8 +63,7 @@ public static ValueTask InsertInTransactionAsync( { // The definition runs on the transaction. Using takes a // DbTransaction; the callback's is an IDbTransaction. - await InsertTemporary - .Using((DbTransaction)transaction) + await InsertTemporary.Using((DbTransaction)transaction) .AddParam("id", 100) .ExecuteNonQueryAsync(cancellationToken); }, cancellationToken)); @@ -99,14 +96,12 @@ select last_insert_rowid() IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) { - Post? first = await Latest - .Using(connectionFactory) + Post? first = await Latest.Using(connectionFactory) .FirstOrDefaultAsync(cancellationToken); // SingleOrDefaultAsync returns null for no rows // and throws if there is more than one row. - Post? single = await ById - .Using(connectionFactory) + Post? single = await ById.Using(connectionFactory) .AddParam("id", 2) .SingleOrDefaultAsync(cancellationToken); @@ -120,8 +115,7 @@ select last_insert_rowid() public static ValueTask AddDraftAsync( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) - => AddDraft - .Using(connectionFactory) + => AddDraft.Using(connectionFactory) .AddParam("author", 42) .SingleAsync(cancellationToken); #endregion @@ -135,8 +129,7 @@ public static ValueTask PageAsync( int skip, int take, CancellationToken cancellationToken) - => Latest - .Using(connectionFactory) + => Latest.Using(connectionFactory) .Skip(skip) .Take(take) .ToArrayAsync(cancellationToken); @@ -148,8 +141,7 @@ public static ValueTask> BodiesAsync( CancellationToken cancellationToken) // A key selector and a value selector build the lookup in one pass: // no Post is kept, only the text. - => Latest - .Using(connectionFactory) + => Latest.Using(connectionFactory) .ToDictionaryAsync( static post => post.Id, static post @@ -167,8 +159,7 @@ public static async Task StopAtAsync( CancellationToken cancellationToken) { int stoppedAt = 0; - await foreach (Post post in Latest - .Using(connectionFactory) + await foreach (Post post in Latest.Using(connectionFactory) .Stream(TimeSpan.FromSeconds(30), cancellationToken)) { stoppedAt = post.Id; @@ -194,8 +185,7 @@ static readonly MappedDbQuery Latest public static PooledBuffer LatestPosts( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) - => Latest - .Using(connectionFactory) + => Latest.Using(connectionFactory) .ToPooledBuffer(cancellationToken); #endregion @@ -205,9 +195,9 @@ public static async Task PageIdsAsync( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) { - await using PooledBuffer buffer = Latest - .Using(connectionFactory) - .Skip(1).Take(2) + await using PooledBuffer buffer = Latest.Using(connectionFactory) + .Skip(1) + .Take(2) .ToPooledBuffer(cancellationToken); PooledArray posts = await buffer.Items; @@ -222,8 +212,7 @@ public static async Task PageIdsAsync( public static IAsyncEnumerable LatestStream( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) - => Latest - .Using(connectionFactory) + => Latest.Using(connectionFactory) .ToPooledStream(cancellationToken); #endregion } @@ -241,8 +230,7 @@ static readonly MappedDbQuery Latest public static ValueTask> LatestAsync( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) - => Latest - .Using(connectionFactory) + => Latest.Using(connectionFactory) .ToListAsync(cancellationToken); #endregion } @@ -253,15 +241,14 @@ public static class DefinedShaping // The shape is declared with the query: a RowMap that leaves // City alone, kept in the same static field as the text. static readonly MappedDbQuery Authors - = DbQuery - .Text("select handle, city, editor from authors order by handle") + = DbQuery.Text( + "select handle, city, editor from authors order by handle") .Map(ShapingMaps.NoCityMap); public static ValueTask AuthorsAsync( IDbConnectionFactory connectionFactory, CancellationToken cancellationToken) - => Authors - .Using(connectionFactory) + => Authors.Using(connectionFactory) .ToArrayAsync(cancellationToken); #endregion } @@ -288,17 +275,14 @@ static readonly ScalarDbQuery AuthorCount int author, CancellationToken cancellationToken) { - int posts = await PostCount - .Using(connectionFactory) + int posts = await PostCount.Using(connectionFactory) .ExecuteScalarAsync(cancellationToken); - long byAuthor = await AuthorCount - .Using(connectionFactory) + long byAuthor = await AuthorCount.Using(connectionFactory) .AddParam(author) .ExecuteScalarAsync(cancellationToken); - int touched = await Touch - .Using(connectionFactory) + int touched = await Touch.Using(connectionFactory) .AddParam(author) .ExecuteNonQueryAsync(cancellationToken);