Skip to content
Merged
4 changes: 2 additions & 2 deletions Source/Channel/Open.Database.Extensions.Channel.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Rows from a mapped query into a System.Threading.Channels channel. Includes Open.Database.Extensions.Core.</Description>
<PackageTags>ado;ado extensions;sql;connection factory;extensions;channel;channels</PackageTags>
<Description>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.</Description>
<PackageTags>ado.net;sql;database;channels;system.threading.channels;producer-consumer;async;data-access</PackageTags>
</PropertyGroup>

<ItemGroup>
Expand Down
40 changes: 20 additions & 20 deletions Source/Channel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -16,49 +16,49 @@ using Open.Database.Extensions;

public record Post(int Id, string Title);

// connectionFactory is a DbConnectionFactory<TConnection>, created once per application (see the Core package page, which also names the provider to install).
public class PostStreams(IDbConnectionFactory<DbConnection> connectionFactory)
{
// Declared once: immutable, with no connection.
static readonly MappedDbQuery<Post> Latest
= DbQuery.Text("select * from posts order by id").Map<Post>();
= DbQuery.Text("select id, title from posts order by id")
.Map<Post>();

// Returns right away: the rows are read in the background and the channel completes when they are all written.
public ChannelReader<Post> LatestPosts()
// Returns at once: the rows are read in the background,
// and the channel completes after the last one.
public ChannelReader<Post> LatestPosts(CancellationToken cancellationToken)
=> Latest.Using(connectionFactory)
.ToChannelReader();
.ToChannelReader(cancellationToken);
}
```

Then, where you need the rows:

```cs
ChannelReader<Post> reader = new PostStreams(connectionFactory).LatestPosts();
ChannelReader<Post> 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<Post> reader = connectionFactory
.Command("select * from posts order by id")
.Command("select id, title from posts order by id")
.Map<Post>()
.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<T>()`. 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
4 changes: 2 additions & 2 deletions Source/Core/Open.Database.Extensions.Core.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Useful set of utilities and abstractions for simplifying modern data-access operations and ensuring DI compatibility.</Description>
<PackageTags>ado;ado extensions;sql;connection factory;extensions;</PackageTags>
<Description>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.</Description>
<PackageTags>ado.net;adonet;sql;database;data-access;dbconnection;mapping;stored-procedure;source-generator;connection-factory</PackageTags>
<LangVersion>preview</LangVersion>
</PropertyGroup>

Expand Down
99 changes: 38 additions & 61 deletions Source/Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()` 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<SqliteConnection>(() => 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<DbConnection> 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<Post> ByAuthor
= DbQuery.Text("select * from posts where author = @author order by id")
= DbQuery.Text("select id, title from posts where author = @author")
.Map<Post>();

// 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<Post[]> ByAuthorAsync(
int author,
CancellationToken cancellationToken)
Expand All @@ -42,71 +35,55 @@ public class PostQueries(IDbConnectionFactory<DbConnection> 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<SqliteConnection>(
() => 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<Post>()
.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<T>()` 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<T>()`. 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<T>()`. 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<T>` 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<T>()` 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<T>`, 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<T>()` 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<T>()` 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<T>()`. 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<T>()`, 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
4 changes: 2 additions & 2 deletions Source/Dataflow/Open.Database.Extensions.Dataflow.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>Rows from a mapped query into a TPL Dataflow block. Includes Open.Database.Extensions.Core.</Description>
<PackageTags>ado;ado extensions;dataflow;data;database</PackageTags>
<Description>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.</Description>
<PackageTags>ado.net;sql;database;dataflow;tpl-dataflow;pipeline;async;data-access</PackageTags>
</PropertyGroup>

<ItemGroup>
Expand Down
Loading