From d00507bc5aac61d4dec1f5c58b9d2c30b1608b03 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:59:21 -0800 Subject: [PATCH 1/4] Give the trimming and native AOT text a docsite home and fix three stale docsite statements The trimming and native AOT section moves, as written, from the Core package README to the end of the mapping article, where the docsite owns it. The known-limitations list in the version 11 article now links to it there, and the package README no longer has to carry it. Three statements in docsite articles did not match the code: - The output parameters limitation said they are not set on the chain. They are read with Output() and ExecuteOutputAsync, or beside rows with CaptureOutput; the limitation now says that, and that there is no blocking form and an output model uses the runtime map. - The limitation about synchronous ToTargetBlock overloads described overloads that do not exist; every ToTargetBlock overload returns a ValueTask and sends with SendAsync. It now states what does happen: a block that declines a row for good stops the pass without an exception, and only the returned count shows the shortfall. - The Channels and Dataflow article said to import Open.ChannelExtensions alongside the Channel package. The Channel package depends only on Core, so it now calls Open.ChannelExtensions an optional companion. Documentation only; no code or run-time cost changes. Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/channels-and-dataflow.md | 2 +- docsite/articles/mapping.md | 30 +++++++++++++++++++++++ docsite/articles/whats-new-11.md | 6 ++--- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/docsite/articles/channels-and-dataflow.md b/docsite/articles/channels-and-dataflow.md index d360191b..903b0df4 100644 --- a/docsite/articles/channels-and-dataflow.md +++ b/docsite/articles/channels-and-dataflow.md @@ -54,7 +54,7 @@ The producer is unbounded. It never waits for the consumer, so the read finishes ![Open.Database.Extensions.Channel: You write the SQL. ODX writes the other twenty lines.](../images/hero-channel.svg) -**Import [Open.ChannelExtensions](https://www.nuget.org/packages/Open.ChannelExtensions/) alongside `Open.Database.Extensions.Channel`.** The Channel package depends only on Core and `System.Threading.Channels`, and does one job: it puts the rows of a mapped query into a channel as fast as it can. Everything after the dump (`Transform`, `Batch`, `Join`, `ReadAll`) is what Open.ChannelExtensions is for. +**[Open.ChannelExtensions](https://www.nuget.org/packages/Open.ChannelExtensions/) is an optional companion to `Open.Database.Extensions.Channel`.** The Channel package depends only on Core and `System.Threading.Channels`, and does one job: it puts the rows of a mapped query into a channel as fast as it can. Everything after the dump (`Transform`, `Batch`, `Join`, `ReadAll`) is what Open.ChannelExtensions is for. `ToChannelReader()` and `ToChannel()` make an unbounded channel and start reading at the call: diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 64cdbb6e..bcf3b1af 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -566,3 +566,33 @@ A result that ends where the terminal stops was seen to its end: it is not cance ## How it works The mapping from a result-set shape (column names and column types) to `T` is compiled once and cached, so a repeated query does no reflection and no compilation. + +## Trimming and native AOT + +Open.Database.Extensions is not marked trimmable, and native AOT is not supported in 11.0. `Map()` and `AddParams(...)` read your types and the provider's data reader type by reflection, and build row readers as expression trees. Under native AOT, .NET interprets these expression trees instead of compiling them, so every row the runtime map reads is slower. + +If you publish with `PublishTrimmed=true`, keep what ODX reads: the public constructors, properties and fields of every type you pass to `Map()` and of every object you pass to `AddParams`, and the public methods of the provider's data reader type. A model type that is not kept fails at the first query with `'Post' cannot be mapped: it has no public constructor.` A reader type that is not kept fails with `Value cannot be null. (Parameter 'method')`. + +This keeps all three. Call `TrimRoots.Keep()` once at startup. `Post` and `Args` stand for your own model type and your own `AddParams` object type: + +```cs +using System.Diagnostics.CodeAnalysis; +using Microsoft.Data.Sqlite; +using static System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes; + +static class TrimRoots +{ + [DynamicDependency( + PublicConstructors | PublicProperties | PublicFields, + typeof(Post))] + [DynamicDependency( + PublicConstructors | PublicProperties | PublicFields, + typeof(Args))] + [DynamicDependency(PublicMethods, typeof(SqliteDataReader))] + public static void Keep() { } +} +``` + +It was measured with a trimmed, self-contained publish on .NET 10 (win-x64) and `Microsoft.Data.Sqlite` 10.0.14, whose reader type is `SqliteDataReader`. Other providers and .NET 11 were not run. + +With these roots the trimmer reports a few IL2111 warnings; they are expected and the publish works. diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index d9b8fe7e..f9140b44 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -176,11 +176,11 @@ Every mapped overload takes one `RowMap? map` where 10.x took key/value pairs ## Known limitations -- The library is not marked trimmable and does not support native AOT. The runtime map builds its row readers as expression trees; under native AOT, .NET interprets them instead of compiling them, so every row it reads is slower. A trimmed app keeps its model types and the provider's reader type: the recipe is in the [Core README](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Source/Core/README.md#trimming-and-native-aot). -- Output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name. +- The library is not marked trimmable and does not support native AOT. The runtime map builds its row readers as expression trees; under native AOT, .NET interprets them instead of compiling them, so every row it reads is slower. A trimmed app keeps its model types and the provider's reader type: the recipe is in [Trimming and native AOT](mapping.md#trimming-and-native-aot). +- Output parameters are read into a model with `Output()` and `ExecuteOutputAsync`, or beside rows with `CaptureOutput` (see [Output parameters](expressive-commands.md#output-parameters)); there is no blocking form, and an output model uses the runtime map, not a generated reader. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name. - A missing column for a `required` property is reported by `Map` at the first row, so an empty result does not report it. - The unmapped `ToChannel` overloads can lose the row that was in flight when a read fails while the target is full. The cause is in the underlying channel library. -- The synchronous `ToTargetBlock` overloads post each row without waiting: when the target is complete, or bounded and full, reading stops without an error, and only the number the call returns (the rows read and handed over) shows the shortfall. Use the `Async` overload to feed a bounded target. +- A `ToTargetBlock` pass whose block declines a row for good (completed or faulted) stops without an exception: only the returned count, the rows the block accepted, shows the shortfall. - `AddParams(source)` sends every public member of `source` that the procedure declares, so pass an object you trust, and add a value that only the server may decide with `AddParam("name", value)`. - The unit tests run on in-memory providers, the documentation samples on SQLite, and the benchmarks on the in-memory provider, SQLite and SQL Server LocalDB. Feedback from other providers and workloads is welcome. - The tests of the mapper, the pipelines and the commands run on net11.0. The net10.0, netstandard2.0, netstandard2.1 and net472 builds share the code through `#if` switches; a small test project runs the `AddParam` overloads on net472, net8.0, net10.0 and net11.0 under older language versions. From 4118e0be271bbc8e30d3d5d9d07765e767d3856f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:59:22 -0800 Subject: [PATCH 2/4] Rewrite the package READMEs and the NuGet descriptions and tags of the four published packages Each README now leads with what the package does for the reader, shows a definition-first sample (a query declared once, then the same call built where it is needed), passes a cancellation token in every sample, and says the traps in a short "Good to know" list (one connection factory, give a stored procedure its schema, AddParams sends every declared member, the rows a consumer has not read wait in memory, a declined row stops a dataflow pass without an exception). The package table now lives in the Core README only; the others link to it. The hero image links stay on master. The Description and PackageTags of Core, MSSqlClient, Channel and Dataflow say what a reader can choose on, and the double space in the Channel and Dataflow descriptions is gone. The tags avoid "orm" and competitor names. Documentation and package metadata only; no code or run-time cost changes. Co-Authored-By: Claude Sonnet 5.5 --- .../Open.Database.Extensions.Channel.csproj | 4 +- Source/Channel/README.md | 40 ++++---- .../Core/Open.Database.Extensions.Core.csproj | 4 +- Source/Core/README.md | 99 +++++++------------ .../Open.Database.Extensions.Dataflow.csproj | 4 +- Source/Dataflow/README.md | 56 ++++++----- ...pen.Database.Extensions.MSSqlClient.csproj | 4 +- Source/MSSqlClient/README.md | 80 +++++++++------ 8 files changed, 146 insertions(+), 145 deletions(-) diff --git a/Source/Channel/Open.Database.Extensions.Channel.csproj b/Source/Channel/Open.Database.Extensions.Channel.csproj index 53f46b7d..e6c13dbe 100644 --- a/Source/Channel/Open.Database.Extensions.Channel.csproj +++ b/Source/Channel/Open.Database.Extensions.Channel.csproj @@ -1,8 +1,8 @@  - Rows from a mapped query into a System.Threading.Channels channel. Includes Open.Database.Extensions.Core. - ado;ado extensions;sql;connection factory;extensions;channel;channels + Read a query's rows into a System.Threading.Channels channel: the query fills it in the background and closes the connection when the last row is read. Includes Open.Database.Extensions.Core. + ado.net;sql;database;channels;system.threading.channels;producer-consumer;async;data-access diff --git a/Source/Channel/README.md b/Source/Channel/README.md index 8b828f47..6e621f8c 100644 --- a/Source/Channel/README.md +++ b/Source/Channel/README.md @@ -2,11 +2,11 @@ [![Open.Database.Extensions.Channel: You write the SQL. ODX writes the other twenty lines.](https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/docsite/images/hero-channel.svg)](https://open-net-libraries.github.io/Open.Database.Extensions/) -Rows from a mapped query into a `System.Threading.Channels` channel. **Import [Open.ChannelExtensions](https://www.nuget.org/packages/Open.ChannelExtensions/) alongside this package** for everything after the dump (`Transform`, `Batch`, `Join`, `ReadAll`). This package depends only on [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) and `System.Threading.Channels`. +Read a query's rows into a `System.Threading.Channels` channel that any consumer or pipeline can read. The query fills the channel in the background while your consumer works, and the connection is closed when the last row is read, however slowly the consumer reads. ```sh dotnet add package Open.Database.Extensions.Channel --prerelease -dotnet add package Open.ChannelExtensions +dotnet add package Open.ChannelExtensions # optional: Transform, Batch, Join and ReadAll for the rows ``` ```cs @@ -16,49 +16,49 @@ 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). public class PostStreams(IDbConnectionFactory connectionFactory) { // Declared once: immutable, with no connection. static readonly MappedDbQuery Latest - = DbQuery.Text("select * from posts order by id").Map(); + = DbQuery.Text("select id, title 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. - public ChannelReader LatestPosts() + // Returns at once: the rows are read in the background, + // and the channel completes after the last one. + public ChannelReader LatestPosts(CancellationToken cancellationToken) => Latest.Using(connectionFactory) - .ToChannelReader(); + .ToChannelReader(cancellationToken); } ``` Then, where you need the rows: ```cs -ChannelReader reader = new PostStreams(connectionFactory).LatestPosts(); +ChannelReader reader = postStreams.LatestPosts(cancellationToken); -await foreach (Post post in reader.ReadAllAsync()) +await foreach (Post post in reader.ReadAllAsync(cancellationToken)) { // Use the post. } ``` -Or, simply expressive, with nothing to declare: +Or build the call where you need it: ```cs ChannelReader reader = connectionFactory - .Command("select * from posts order by id") + .Command("select id, title from posts order by id") .Map() - .ToChannelReader(); + .ToChannelReader(cancellationToken); ``` -`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). +## Which one -## The packages +- `ToChannelReader()` and `ToChannel()` make an unbounded channel and complete it after the last row, or with the exception that ended the read. +- `ToChannel(channel)` writes into a channel you own and leaves it open, so several queries can write to it; the returned count is the rows written, and `complete: true` completes it. +- `ToChannelHoldingConnection(..., stallTimeout)` pulls the rows one at a time, so a full channel limits memory. It holds the connection until the last row is read, so a slow consumer keeps it open: use it only when memory matters more. `stallTimeout` is required; see [Capping memory](https://open-net-libraries.github.io/Open.Database.Extensions/articles/channels-and-dataflow.html#capping-memory). -| Package | What it adds | Targets | -|---|---|---| -| [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) | The foundation, expressive commands and `Map()`. Provider-agnostic: start here. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| [Open.Database.Extensions.MSSqlClient](https://www.nuget.org/packages/Open.Database.Extensions.MSSqlClient/) | `SqlConnectionFactory` and stored procedures on `Microsoft.Data.SqlClient`. | net472, net10.0, net11.0 | -| **Open.Database.Extensions.Channel** (this package) | Rows into `System.Threading.Channels`. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| [Open.Database.Extensions.Dataflow](https://www.nuget.org/packages/Open.Database.Extensions.Dataflow/) | Rows into TPL Dataflow blocks. | netstandard2.0, netstandard2.1, net10.0, net11.0 | +**Good to know:** the rows the consumer has not read yet wait in memory. For one consumer and a few rows, `ToListAsync` is simpler and costs less. See [Channels and Dataflow](https://open-net-libraries.github.io/Open.Database.Extensions/articles/channels-and-dataflow.html). + +Brings [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) with it; install your ADO.NET provider beside it. [Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Source and issues](https://github.com/Open-NET-Libraries/Open.Database.Extensions) · MIT license diff --git a/Source/Core/Open.Database.Extensions.Core.csproj b/Source/Core/Open.Database.Extensions.Core.csproj index 1e01a286..629f2b2a 100644 --- a/Source/Core/Open.Database.Extensions.Core.csproj +++ b/Source/Core/Open.Database.Extensions.Core.csproj @@ -1,8 +1,8 @@ - Useful set of utilities and abstractions for simplifying modern data-access operations and ensuring DI compatibility. - ado;ado extensions;sql;connection factory;extensions; + You write the SQL; this writes the ADO.NET around it. Define a query once, map rows to your types with row readers written at build time, and run it on any ADO.NET provider with best-practice connection handling. + ado.net;adonet;sql;database;data-access;dbconnection;mapping;stored-procedure;source-generator;connection-factory preview diff --git a/Source/Core/README.md b/Source/Core/README.md index 6018c592..09b35bd9 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -2,37 +2,30 @@ [![Open.Database.Extensions.Core: You write the SQL. ODX writes the other twenty lines.](https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/docsite/images/hero-core.svg)](https://open-net-libraries.github.io/Open.Database.Extensions/) -Core is the foundation of Open.Database.Extensions: ADO.NET extension methods with best-practice defaults, expressive commands that open, run and dispose their own connection, and `Map()` to turn rows into objects. It has no database dependency of its own. **Use it for any ADO.NET database;** most applications need only this package. +You write the SQL. Open.Database.Extensions (ODX) writes the ADO.NET around it: the connection, the parameters, the read loop, the mapping to your types and the disposal. It works with any ADO.NET provider and holds a connection open only while a query needs it. ```sh dotnet add package Open.Database.Extensions.Core --prerelease dotnet add package Microsoft.Data.Sqlite # your provider; SQLite is used below ``` +## Define a query once + ```cs -using Microsoft.Data.Sqlite; +using System.Data.Common; using Open.Database.Extensions; 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)); -``` - -A query an application runs again and again is declared once, in your data-access class, and bound where it runs: - -```cs -using System.Data.Common; - public class PostQueries(IDbConnectionFactory connectionFactory) { - // Declared once: immutable, with no connection. + // Declared once: immutable, with no connection, safe in a static field. + // Assumes a table posts(id, author, title). static readonly MappedDbQuery ByAuthor - = DbQuery.Text("select * from posts where author = @author order by id") + = DbQuery.Text("select id, title from posts where author = @author") .Map(); - // The call opens a connection when the terminal runs and disposes it afterwards. + // Opens a connection, reads every row, then disposes the connection. public ValueTask ByAuthorAsync( int author, CancellationToken cancellationToken) @@ -42,71 +35,55 @@ public class PostQueries(IDbConnectionFactory connectionFactory) } ``` -Or, simply expressive, with nothing to declare: +Create the factory once per application, with your provider's connection type: + +```cs +using Microsoft.Data.Sqlite; + +// connectionString, for example "Data Source=blog.db" +var connectionFactory = new DbConnectionFactory( + () => new SqliteConnection(connectionString)); +``` + +## Or build it where you need it ```cs int author = 42; Post[] posts = await connectionFactory - .Command("select * from posts where author = @author order by id") + .Command("select id, title from posts where author = @author") .AddParam(author) // name and type inferred from the variable .Map() - .ToArrayAsync(); + .ToArrayAsync(cancellationToken); ``` -`AddParam(author)` names the parameter `author` after the variable; `AddParam("author", 42)` names it yourself. Already have a connection? Start from it instead: `connection.Command("...")`. You own the connection; the command opens it only if it is closed and closes only what it opened. +Already have a connection or a transaction? Pass it to `Using(...)`, or start from it with `connection.Command("...")`. The call opens a connection only if it is closed, and closes only what it opened. -## Generated row readers +## What else it does -This package carries a source generator: a plain `Map()` on a command, a reader or a `DbQuery` gets its row reader written at build time. What it needs, what it changes, when the runtime map reads the rows instead, and how to switch it off are in [Generated readers](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#generated-readers). +- **Writes and single values** run the same way: `DbNonQuery.Text("...")` with `ExecuteNonQueryAsync`, and `DbQuery.Text("...").Scalar()`. See [Writes and scalars](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#writes-and-scalars). +- **Stored procedures** with `DbQuery.Procedure("[dbo].[PostsByAuthor]")`: on SQL Server, `AddParam(titleContains)` finds `@title_contains`. A write that returns output parameters reads them, and the return code, into one model with `DbNonQuery.Procedure(...).Output()`. See [Parameters](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#parameters) and [Output parameters](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#output-parameters). +- **Mapping by name**: snake_case columns to PascalCase members, records and constructors, `required` and `init`, clear NULL rules, and a `RowMap` for columns named differently. See [Mapping rows to objects](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html). +- **Row readers written at build time.** A plain `Map()` gets its row reader from this package's source generator when you build; other cases use the runtime map. See [Generated readers](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#generated-readers). +- **Terminals**: `ToArrayAsync` and `ToListAsync` (buffered, the usual choice), `FirstOrDefaultAsync`, `SingleOrDefaultAsync`, and `ToPooledStream` to work on rows while the query is read. See [Terminals](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#terminals). -## Where to go next +## Good to know -- [Getting started](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html) -- [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html): parameters, stored procedures, timeouts, terminals -- [Mapping rows to objects](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html): the matching rules, `RowMap`, NULL handling -- [Coming from Dapper](https://open-net-libraries.github.io/Open.Database.Extensions/articles/coming-from-dapper.html): the same jobs side by side -- [Performance](https://open-net-libraries.github.io/Open.Database.Extensions/articles/performance.html) - -## Trimming and native AOT - -Open.Database.Extensions is not marked trimmable, and native AOT is not supported in 11.0. `Map()` and `AddParams(...)` read your types and the provider's data reader type by reflection, and build row readers as expression trees. Under native AOT, .NET interprets these expression trees instead of compiling them, so every row the runtime map reads is slower. - -If you publish with `PublishTrimmed=true`, keep what ODX reads: the public constructors, properties and fields of every type you pass to `Map()` and of every object you pass to `AddParams`, and the public methods of the provider's data reader type. A model type that is not kept fails at the first query with `'Post' cannot be mapped: it has no public constructor.` A reader type that is not kept fails with `Value cannot be null. (Parameter 'method')`. - -This keeps all three. Call `TrimRoots.Keep()` once at startup. `Post` and `Args` stand for your own model type and your own `AddParams` object type: - -```cs -using System.Diagnostics.CodeAnalysis; -using Microsoft.Data.Sqlite; -using static System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes; - -static class TrimRoots -{ - [DynamicDependency( - PublicConstructors | PublicProperties | PublicFields, - typeof(Post))] - [DynamicDependency( - PublicConstructors | PublicProperties | PublicFields, - typeof(Args))] - [DynamicDependency(PublicMethods, typeof(SqliteDataReader))] - public static void Keep() { } -} -``` - -It was measured with a trimmed, self-contained publish on .NET 10 (win-x64) and `Microsoft.Data.Sqlite` 10.0.14, whose reader type is `SqliteDataReader`. Other providers and .NET 11 were not run. - -With these roots the trimmer reports a few IL2111 warnings; they are expected and the publish works. +- **Give a stored procedure its schema** (`[dbo].[Name]`) and its parameter names are read once per server and database. Without one, keep one connection factory for the application (static or a singleton). See [Parameter names are read once](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#parameter-names-are-read-once). +- **`AddParams(source)` sends an object's public members** that the SQL or the procedure declares (every member, when the names are not known). Pass an object you trust, and add a value only the server should decide with `AddParam("name", value)`. +- **Trimming and native AOT:** the library is not marked trimmable and native AOT is not supported in 11.0. A trimmed app keeps a few types: see [Trimming and native AOT](https://open-net-libraries.github.io/Open.Database.Extensions/articles/mapping.html#trimming-and-native-aot). ## The packages | Package | What it adds | Targets | |---|---|---| -| **Open.Database.Extensions.Core** (this package) | The foundation, expressive commands and `Map()`. Provider-agnostic: start here. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| [Open.Database.Extensions.MSSqlClient](https://www.nuget.org/packages/Open.Database.Extensions.MSSqlClient/) | `SqlConnectionFactory` and stored procedures on `Microsoft.Data.SqlClient`. | net472, net10.0, net11.0 | +| **Open.Database.Extensions.Core** (this package) | Expressive commands, `DbQuery` and `Map()`, for any ADO.NET provider. Start here. | netstandard2.0, netstandard2.1, net10.0, net11.0 | +| [Open.Database.Extensions.MSSqlClient](https://www.nuget.org/packages/Open.Database.Extensions.MSSqlClient/) | `SqlConnectionFactory` and SQL Server on `Microsoft.Data.SqlClient`. | net472, net10.0, net11.0 | | [Open.Database.Extensions.Channel](https://www.nuget.org/packages/Open.Database.Extensions.Channel/) | Rows into `System.Threading.Channels`. | netstandard2.0, netstandard2.1, net10.0, net11.0 | | [Open.Database.Extensions.Dataflow](https://www.nuget.org/packages/Open.Database.Extensions.Dataflow/) | Rows into TPL Dataflow blocks. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -Every other package depends on Core, so installing one brings Core with it. +Each of the other packages brings Core with it. .NET 8 and .NET 9 use the netstandard2.1 build. + +**Coming from v10?** Version 11 is a significant break, mainly in how typed results are mapped and returned. See the [migration guide](https://open-net-libraries.github.io/Open.Database.Extensions/articles/whats-new-11.html). -[Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Source and issues](https://github.com/Open-NET-Libraries/Open.Database.Extensions) · MIT license +[Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/) · [Getting started](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html) · [Coming from Dapper](https://open-net-libraries.github.io/Open.Database.Extensions/articles/coming-from-dapper.html) · [Performance](https://open-net-libraries.github.io/Open.Database.Extensions/articles/performance.html) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Source and issues](https://github.com/Open-NET-Libraries/Open.Database.Extensions) · MIT license diff --git a/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj b/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj index 899b71d1..79730b54 100644 --- a/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj +++ b/Source/Dataflow/Open.Database.Extensions.Dataflow.csproj @@ -1,8 +1,8 @@  - Rows from a mapped query into a TPL Dataflow block. Includes Open.Database.Extensions.Core. - ado;ado extensions;dataflow;data;database + Send a query's rows into a TPL Dataflow pipeline you build: your blocks and schedulers, with the connection closed when the read ends. Includes Open.Database.Extensions.Core. + ado.net;sql;database;dataflow;tpl-dataflow;pipeline;async;data-access diff --git a/Source/Dataflow/README.md b/Source/Dataflow/README.md index 874bbe04..bc378c6c 100644 --- a/Source/Dataflow/README.md +++ b/Source/Dataflow/README.md @@ -2,7 +2,7 @@ [![Open.Database.Extensions.Dataflow: You write the SQL. ODX writes the other twenty lines.](https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/docsite/images/hero-dataflow.svg)](https://open-net-libraries.github.io/Open.Database.Extensions/) -Rows from a mapped query into a TPL Dataflow pipeline you build. `ToTargetBlock` sends the rows to a block you own, so its scheduler and priorities stay yours; `AsSourceBlock` makes a block for you. The connection is closed when the read ends. This package depends only on [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) and `System.Threading.Tasks.Dataflow`. +Send a query's rows into a TPL Dataflow pipeline you build. The blocks, their schedulers and their priorities stay yours; the query is read at the provider's pace, and the connection is closed when the read ends. ```sh dotnet add package Open.Database.Extensions.Dataflow --prerelease @@ -15,50 +15,54 @@ 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). public class PostPipeline(IDbConnectionFactory connectionFactory) { // 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) + = DbQuery.Text("select id, title from posts order by id") + .Map(); + + // complete: true completes the block after the last row, + // or faults it with the exception that ended the read. + public ValueTask SendLatestAsync( + ITargetBlock block, + CancellationToken cancellationToken) => Latest.Using(connectionFactory) - .ToTargetBlock(block, complete: true); + .ToTargetBlock(block, complete: true, cancellationToken); } ``` -Then, where you need the rows: +Then, with a pipeline of your own: ```cs -var block = new BufferBlock(); -long count = await new PostPipeline(connectionFactory).SendLatestAsync(block); +var format = new TransformBlock( + static post => $"#{post.Id} {post.Title}", + new ExecutionDataflowBlockOptions { BoundedCapacity = 100 }); + +var sink = new ActionBlock(static text => Console.WriteLine(text)); +format.LinkTo(sink, new DataflowLinkOptions { PropagateCompletion = true }); -// The block completes once every row has been received. -var received = new List(); -while (await block.OutputAvailableAsync()) - received.Add(await block.ReceiveAsync()); +// The count is the rows the block accepted. +long sent = await postPipeline.SendLatestAsync(format, cancellationToken); ``` -Or, simply expressive, with nothing to declare: +Or build the call where you need it: ```cs -long count = await connectionFactory - .Command("select * from posts order by id") +long sent = await connectionFactory + .Command("select id, title from posts order by id") .Map() - .ToTargetBlock(block, complete: true); + .ToTargetBlock(format, complete: true, cancellationToken); ``` -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). +## Which one + +- `ToTargetBlock(block)` sends the rows to a block you own and leaves it open, so several queries can send to it; the returned count is the rows the block accepted. +- `AsSourceBlock()` makes the block for you (an unbounded `BufferBlock`, or one from the `DataflowBlockOptions` you pass) and starts reading at the call. +- `ToTargetBlockHoldingConnection(..., stallTimeout)` pulls the rows one at a time, so a full block limits memory. It holds the connection until the last row is read, so a slow block keeps it open: use it only when memory matters more. `stallTimeout` is required. -## The packages +**Good to know:** each row is sent with `SendAsync`, so a full bounded block makes the pass wait and no row is dropped; the rows wait in memory meanwhile. A block that declines a row for good (completed or faulted) stops the pass without an exception: check the returned count. A block faulted by `complete: true` drops the rows it holds that were not received yet. See [Channels and Dataflow](https://open-net-libraries.github.io/Open.Database.Extensions/articles/channels-and-dataflow.html#dataflow). -| Package | What it adds | Targets | -|---|---|---| -| [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) | The foundation, expressive commands and `Map()`. Provider-agnostic: start here. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| [Open.Database.Extensions.MSSqlClient](https://www.nuget.org/packages/Open.Database.Extensions.MSSqlClient/) | `SqlConnectionFactory` and stored procedures on `Microsoft.Data.SqlClient`. | net472, net10.0, net11.0 | -| [Open.Database.Extensions.Channel](https://www.nuget.org/packages/Open.Database.Extensions.Channel/) | Rows into `System.Threading.Channels`. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| **Open.Database.Extensions.Dataflow** (this package) | Rows into TPL Dataflow blocks. | netstandard2.0, netstandard2.1, net10.0, net11.0 | +Brings [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) with it; install your ADO.NET provider beside it. [Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Source and issues](https://github.com/Open-NET-Libraries/Open.Database.Extensions) · MIT license diff --git a/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj b/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj index 7fd0e9ee..d2669e15 100644 --- a/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj +++ b/Source/MSSqlClient/Open.Database.Extensions.MSSqlClient.csproj @@ -2,8 +2,8 @@ net472;net10.0;net11.0 - Useful set of utilities and abstractions for simplifying modern SQL Client data-access operations and ensuring DI compatibility. - ado;ado extensions;sql;connection factory;extensions; + SQL Server for Open.Database.Extensions on Microsoft.Data.SqlClient: SqlConnectionFactory, stored procedures with parameters named from your arguments, and output parameters read into a model. Includes Open.Database.Extensions.Core. + ado.net;sql-server;sqlserver;mssql;microsoft.data.sqlclient;stored-procedure;output-parameters;data-access;connection-factory diff --git a/Source/MSSqlClient/README.md b/Source/MSSqlClient/README.md index 8b3ff1f8..b0890032 100644 --- a/Source/MSSqlClient/README.md +++ b/Source/MSSqlClient/README.md @@ -2,7 +2,7 @@ [![Open.Database.Extensions.MSSqlClient: You write the SQL. ODX writes the other twenty lines.](https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/docsite/images/hero-mssqlclient.svg)](https://open-net-libraries.github.io/Open.Database.Extensions/) -SQL Server for Open.Database.Extensions: `SqlConnectionFactory`, SQL-specific commands, and stored procedures on `Microsoft.Data.SqlClient`. **Use it when** your database is SQL Server. It includes [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) and the `Microsoft.Data.SqlClient` provider, so there is nothing else to install. +SQL Server for Open.Database.Extensions: `SqlConnectionFactory`, stored procedures whose parameters are named from your arguments, and output parameters read into a model, on `Microsoft.Data.SqlClient`. It brings [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) and the provider with it, so it is the only package to install. ```sh dotnet add package Open.Database.Extensions.MSSqlClient --prerelease @@ -13,49 +13,69 @@ using Open.Database.Extensions; public record Post(int Id, string Title); -// Create the factory once per application. -var connectionFactory = new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true"); -int author = 42; - -Post[] posts = await connectionFactory - .Command("select * from posts where author = @author") - .AddParam(author) // name and type inferred from the variable - .Map() - .ToArrayAsync(); +public class PostQueries(SqlConnectionFactory connectionFactory) +{ + // Declared once. The procedure declares @author and @title_contains. + static readonly MappedDbQuery Search + = DbQuery.Procedure("[dbo].[SearchPosts]") + .Map(); + + public ValueTask SearchAsync( + int author, + string titleContains, + CancellationToken cancellationToken) + => Search.Using(connectionFactory) + .AddParam(author) // name and type inferred from the variable + .AddParam(titleContains) // finds @title_contains + .ToArrayAsync(cancellationToken); +} ``` -## Stored procedures: name the argument, not the parameter +Create the factory once per application, for example `new SqlConnectionFactory(@"Server=(localdb)\MSSQLLocalDB;Database=Blog;Integrated Security=true")`. -`AddParam(value)` takes the parameter name from the argument expression and matches it to the procedure's real parameters (exactly, then ignoring case, then ignoring case and underscores), so `search.TitleContains` finds `@title_contains`. `AddParams(search)` sends every member of the object that the procedure declares. +Or build the call where you need it, and send a whole object: ```cs -// search holds the arguments: any object with the members you want to send, here an anonymous one. var search = new { Author = 42, TitleContains = "ode" }; Post[] posts = await connectionFactory .StoredProcedure("[dbo].[SearchPosts]") - .AddParam(search.Author) // name and type inferred from the member - .AddParam(search.TitleContains) + .AddParams(search) // the members the procedure declares .Map() - .ToArrayAsync(); + .ToArrayAsync(cancellationToken); +``` -// Or give it the whole object: the members the procedure declares are sent, the rest are ignored. -posts = await connectionFactory - .StoredProcedure("[dbo].[SearchPosts]") - .AddParams(search) - .Map() - .ToArrayAsync(); +`AddParam(value)` matches the argument's name to the procedure's real parameters, ignoring case, underscores and a common prefix such as `p_`. A name that matches nothing throws and lists what the procedure declares. See [Name a parameter from its argument](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#name-a-parameter-from-its-argument). + +## Output parameters and return codes + +```cs +// ReturnValue reads the RETURN code; every other member is an output parameter. +public record AddPostResult(int Id, DateTime CreatedUtc, int ReturnValue); + +public class PostCommands(SqlConnectionFactory connectionFactory) +{ + // Declared once. The model is checked here, not on the first call. + static readonly OutputDbNonQuery AddPost + = DbNonQuery.Procedure("[dbo].[AddPost]") + .Output(); + + public ValueTask AddAsync( + string title, + CancellationToken cancellationToken) + => AddPost.Using(connectionFactory) + .AddParam(title) // name and type inferred from the variable + .ExecuteOutputAsync(cancellationToken); +} ``` -Parameter names are read once, and again after a call that cannot be built or that the database rejects. A name with a schema (`[dbo].[SearchPosts]`) is kept per server and database, whichever connection or factory runs it; a name without one is kept per connection factory, so keep one factory for those (a connection or factory you create for each call reads them for every command). The return value of a procedure is readable with `ExecuteReturn()`; output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. See [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html) for the rules and limits. +To read rows and outputs from one call, capture them with `CaptureOutput(out DbCapture total)`, and await `total` after the terminal. See [Output parameters](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html#output-parameters). + +## Good to know -## The packages +- **Give a procedure its schema** (`[dbo].[SearchPosts]`): its parameter names are then read once per server and database. A name without one is kept per connection factory, so keep one factory for the application. +- **`AddParams(source)` sends every member the procedure declares.** Pass an object you trust, and add a value only the server should decide with `AddParam("name", value)`. -| Package | What it adds | Targets | -|---|---|---| -| [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/) | The foundation, expressive commands and `Map()`. Provider-agnostic: start here. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| **Open.Database.Extensions.MSSqlClient** (this package) | `SqlConnectionFactory` and stored procedures on `Microsoft.Data.SqlClient`. | net472, net10.0, net11.0 | -| [Open.Database.Extensions.Channel](https://www.nuget.org/packages/Open.Database.Extensions.Channel/) | Rows into `System.Threading.Channels`. | netstandard2.0, netstandard2.1, net10.0, net11.0 | -| [Open.Database.Extensions.Dataflow](https://www.nuget.org/packages/Open.Database.Extensions.Dataflow/) | Rows into TPL Dataflow blocks. | netstandard2.0, netstandard2.1, net10.0, net11.0 | +The other packages are listed on [Open.Database.Extensions.Core](https://www.nuget.org/packages/Open.Database.Extensions.Core/). [Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Source and issues](https://github.com/Open-NET-Libraries/Open.Database.Extensions) · MIT license From 9fa348f1f4c4722c7d4ad4fdef99d1c2e93d841e Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:38:43 -0800 Subject: [PATCH 3/4] Say that the trimming message of a model type starts with the text, since the message goes on to say how to fix it Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/mapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docsite/articles/mapping.md b/docsite/articles/mapping.md index 4b06050d..506c907a 100644 --- a/docsite/articles/mapping.md +++ b/docsite/articles/mapping.md @@ -571,7 +571,7 @@ The mapping from a result-set shape (column names and column types) to `T` is co Open.Database.Extensions is not marked trimmable, and native AOT is not supported in 11.0. `Map()` and `AddParams(...)` read your types and the provider's data reader type by reflection, and build row readers as expression trees. Under native AOT, .NET interprets these expression trees instead of compiling them, so every row the runtime map reads is slower. -If you publish with `PublishTrimmed=true`, keep what ODX reads: the public constructors, properties and fields of every type you pass to `Map()` and of every object you pass to `AddParams`, and the public methods of the provider's data reader type. A model type that is not kept fails at the first query with `'Post' cannot be mapped: it has no public constructor.` A reader type that is not kept fails with `Value cannot be null. (Parameter 'method')`. +If you publish with `PublishTrimmed=true`, keep what ODX reads: the public constructors, properties and fields of every type you pass to `Map()` and of every object you pass to `AddParams`, and the public methods of the provider's data reader type. A model type that is not kept fails at the first query with a message that starts `'Post' cannot be mapped: it has no public constructor.` A reader type that is not kept fails with `Value cannot be null. (Parameter 'method')`. This keeps all three. Call `TrimRoots.Keep()` once at startup. `Post` and `Args` stand for your own model type and your own `AddParams` object type: From 40cfa7e8f5278bbe4b254df212c749b208ea4a04 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:48:47 -0800 Subject: [PATCH 4/4] Remove the whats-new line about unmapped ToChannel overloads, which do not exist, and say what to do about a provider's parameter names Source/Channel has only the ToChannel overloads of a mapped query, so the line described nothing. The line on a provider that reports no procedure parameter names now says to pass the declared name with AddParam(name, value). Co-Authored-By: Claude Sonnet 5.5 --- docsite/articles/whats-new-11.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docsite/articles/whats-new-11.md b/docsite/articles/whats-new-11.md index f9140b44..64dff4c9 100644 --- a/docsite/articles/whats-new-11.md +++ b/docsite/articles/whats-new-11.md @@ -177,9 +177,8 @@ Every mapped overload takes one `RowMap? map` where 10.x took key/value pairs ## Known limitations - The library is not marked trimmable and does not support native AOT. The runtime map builds its row readers as expression trees; under native AOT, .NET interprets them instead of compiling them, so every row it reads is slower. A trimmed app keeps its model types and the provider's reader type: the recipe is in [Trimming and native AOT](mapping.md#trimming-and-native-aot). -- Output parameters are read into a model with `Output()` and `ExecuteOutputAsync`, or beside rows with `CaptureOutput` (see [Output parameters](expressive-commands.md#output-parameters)); there is no blocking form, and an output model uses the runtime map, not a generated reader. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name. +- Output parameters are read into a model with `Output()` and `ExecuteOutputAsync`, or beside rows with `CaptureOutput` (see [Output parameters](expressive-commands.md#output-parameters)); there is no blocking form, and an output model uses the runtime map, not a generated reader. On providers other than SQL Server, which report no procedure parameter names, `AddParam(search.Author)` sends the last member of the expression, `Author`, as the name; when the procedure declares another name, pass it with `AddParam("name", search.Author)`. - A missing column for a `required` property is reported by `Map` at the first row, so an empty result does not report it. -- The unmapped `ToChannel` overloads can lose the row that was in flight when a read fails while the target is full. The cause is in the underlying channel library. - A `ToTargetBlock` pass whose block declines a row for good (completed or faulted) stops without an exception: only the returned count, the rows the block accepted, shows the shortfall. - `AddParams(source)` sends every public member of `source` that the procedure declares, so pass an object you trust, and add a value that only the server may decide with `AddParam("name", value)`. - The unit tests run on in-memory providers, the documentation samples on SQLite, and the benchmarks on the in-memory provider, SQLite and SQL Server LocalDB. Feedback from other providers and workloads is welcome.