Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,20 @@ while (await reader.ReadAsync(cancellationToken))
And with Open.Database.Extensions, the query declared once (immutable, with no connection, safe in a static field) and run where it is needed:

```cs
// A field of your data-access class: declared once, with no connection.
static readonly MappedDbQuery<Post> ByAuthor
= DbQuery.Text("select * from posts where author = @author order by id")
.Map<Post>();

int author = 42;

Post[] posts = await ByAuthor.Using(connectionFactory)
.AddParam(author) // name and type inferred from the variable
.ToArrayAsync(cancellationToken);
public class PostQueries(IDbConnectionFactory<DbConnection> connectionFactory)
{
// Declared once: immutable, with no connection.
static readonly MappedDbQuery<Post> ByAuthor
= DbQuery.Text("select * from posts where author = @author order by id")
.Map<Post>();

public ValueTask<Post[]> ByAuthorAsync(
int author,
CancellationToken cancellationToken)
=> ByAuthor.Using(connectionFactory)
.AddParam(author) // name and type inferred from the variable
.ToArrayAsync(cancellationToken);
}
```

Or, simply expressive, with nothing to declare:
Expand Down
23 changes: 17 additions & 6 deletions Source/Channel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,30 @@ dotnet add package Open.ChannelExtensions
```

```cs
using System.Data.Common;
using System.Threading.Channels;
using Open.Database.Extensions;

public record Post(int Id, string Title);

// connectionFactory is a DbConnectionFactory<TConnection>, 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<Post> Latest
= DbQuery.Text("select * from posts order by id").Map<Post>();
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>();

// Returns right away: the rows are read in the background and the channel completes when they are all written.
ChannelReader<Post> reader = Latest.Using(connectionFactory)
.ToChannelReader();
// Returns right away: the rows are read in the background and the channel completes when they are all written.
public ChannelReader<Post> LatestPosts()
=> Latest.Using(connectionFactory)
.ToChannelReader();
}
```

Then, where you need the rows:

```cs
ChannelReader<Post> reader = new PostStreams(connectionFactory).LatestPosts();

await foreach (Post post in reader.ReadAllAsync())
{
Expand Down
31 changes: 22 additions & 9 deletions Source/Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,35 @@ public record Post(int Id, string Title);
// connectionString is yours, for example "Data Source=blog.db"; the query assumes a posts table (id, author, title, ...).
// Create the factory once per application. Use your provider's connection type.
var connectionFactory = new DbConnectionFactory<SqliteConnection>(() => new SqliteConnection(connectionString));
int author = 42;
```

// A field of your data-access class: declared once, immutable, with no connection.
static readonly MappedDbQuery<Post> ByAuthor
= DbQuery.Text("select * from posts where author = @author order by id")
.Map<Post>();
A query an application runs again and again is declared once, in your data-access class, and bound where it runs:

// The call opens a connection when the terminal runs and disposes it afterwards.
Post[] posts = await ByAuthor.Using(connectionFactory)
.AddParam(author) // name and type inferred from the variable
.ToArrayAsync();
```cs
using System.Data.Common;

public class PostQueries(IDbConnectionFactory<DbConnection> connectionFactory)
{
// Declared once: immutable, with no connection.
static readonly MappedDbQuery<Post> ByAuthor
= DbQuery.Text("select * from posts where author = @author order by id")
.Map<Post>();

// The call opens a connection when the terminal runs and disposes it afterwards.
public ValueTask<Post[]> ByAuthorAsync(
int author,
CancellationToken cancellationToken)
=> ByAuthor.Using(connectionFactory)
.AddParam(author) // name and type inferred from the variable
.ToArrayAsync(cancellationToken);
}
```

Or, simply expressive, with nothing to declare:

```cs
int author = 42;

Post[] posts = await connectionFactory
.Command("select * from posts where author = @author order by id")
.AddParam(author) // name and type inferred from the variable
Expand Down
24 changes: 17 additions & 7 deletions Source/Dataflow/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,31 @@ dotnet add package Open.Database.Extensions.Dataflow --prerelease
```

```cs
using System.Data.Common;
using System.Threading.Tasks.Dataflow;
using Open.Database.Extensions;

public record Post(int Id, string Title);

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

// A field of your data-access class: declared once, immutable, with no connection.
static readonly MappedDbQuery<Post> Latest
= DbQuery.Text("select * from posts order by id").Map<Post>();
// complete: true completes the block after the last row, or faults it with the exception that ended the pass, a cancel included.
public ValueTask<long> SendLatestAsync(ITargetBlock<Post> block)
=> Latest.Using(connectionFactory)
.ToTargetBlock(block, complete: true);
}
```

// complete: true completes the block after the last row, or faults it with the exception that ended the pass, a cancel included.
long count = await Latest.Using(connectionFactory)
.ToTargetBlock(block, complete: true);
Then, where you need the rows:

```cs
var block = new BufferBlock<Post>();
long count = await new PostPipeline(connectionFactory).SendLatestAsync(block);

// The block completes once every row has been received.
var received = new List<Post>();
Expand Down
46 changes: 30 additions & 16 deletions docsite/articles/expressive-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,22 @@ An expressive command is a small object you build with chained calls: pick the S
When the same query runs from several places, define it once, with no connection, and bind it where it runs. A `DbQuery` is immutable, so it is safe in a `static readonly` field and shared by every caller. `Using(source)` binds it to a connection, a transaction, a pool or a factory; each `AddParam` returns a new immutable call and leaves the one before it as it was, so a held call can branch.

```csharp
static readonly DbQuery PostsByAuthor
= DbQuery.Procedure("dbo.PostsByAuthor");

// The names come from the variables, as AddParam(author) does on a command.
List<Post> posts = await PostsByAuthor.Using(db)
.AddParam(authorId)
.AddParam(day)
.Map<Post>()
.ToListAsync(cancellationToken);
public class PostQueries(IDbConnectionFactory<DbConnection> db)
{
static readonly DbQuery PostsByAuthor
= DbQuery.Procedure("dbo.PostsByAuthor");

// The names come from the variables, as AddParam(author) does on a command.
public ValueTask<List<Post>> ByAuthorAsync(
int authorId,
DateTime day,
CancellationToken cancellationToken)
=> PostsByAuthor.Using(db)
.AddParam(authorId)
.AddParam(day)
.Map<Post>()
.ToListAsync(cancellationToken);
}
```

A procedure's parameter names are read through the ADO.NET schema collection `ProcedureParameters` (`DbConnection.GetSchema`) the first time a call needs them, and kept (see [Parameter names are read once](#parameter-names-are-read-once)).
Expand All @@ -25,13 +32,20 @@ To have the values checked at compile time, declare their type once. It is a `st
```csharp
readonly record struct AuthorDayParams(int AuthorId, DateTime Day);

static readonly DbQuery<AuthorDayParams> PostsByAuthorTyped
= DbQuery.Procedure("dbo.PostsByAuthor").Params<AuthorDayParams>();

List<Post> posts = await PostsByAuthorTyped.Using(db)
.AddParams(new(AuthorId: authorId, Day: day))
.Map<Post>()
.ToListAsync(cancellationToken);
public class PostQueries(IDbConnectionFactory<DbConnection> db)
{
static readonly DbQuery<AuthorDayParams> PostsByAuthorTyped
= DbQuery.Procedure("dbo.PostsByAuthor").Params<AuthorDayParams>();

public ValueTask<List<Post>> ByAuthorAsync(
int authorId,
DateTime day,
CancellationToken cancellationToken)
=> PostsByAuthorTyped.Using(db)
.AddParams(new(AuthorId: authorId, Day: day))
.Map<Post>()
.ToListAsync(cancellationToken);
}
```

### Map the definition too
Expand Down
23 changes: 15 additions & 8 deletions docsite/articles/mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,14 @@ A data class can return the mapped query and let each caller pick the terminal:
`AnyAsync` and `CountAsync` answer about the first result set without mapping a row or reading a column. They are on every mapped view and, with no `Map`, on a bound `DbQuery` and an expressive command:

```csharp
bool pending = await DbQuery.Procedure("GetPendingPosts")
.Using(factory)
.AnyAsync(cancellationToken);
static readonly DbQuery PendingPosts = DbQuery.Procedure("GetPendingPosts");

public ValueTask<bool> HasPendingAsync(CancellationToken cancellationToken)
=> PendingPosts.Using(factory)
.AnyAsync(cancellationToken);
```

```csharp
int count = await command
.Map<Post>()
.Skip(10)
Expand Down Expand Up @@ -477,11 +481,14 @@ A reader and a `DataTable` have no `.SingleResult()` before `Map`: their views n
SQL Server sends every row of a result, the ones you did not ask for included. `CancelOnEarlyStop()` cancels the command when a terminal stops with rows left, before the reader is closed, so the rest are discarded. It is off unless you call it. It goes on a mapped query or command, or on a mapped definition:

```csharp
Post? newest = await DbQuery.Procedure("GetPostsNewestFirst")
.Using(factory)
.Map<Post>()
.CancelOnEarlyStop()
.FirstOrDefaultAsync(cancellationToken);
static readonly MappedDbQuery<Post> NewestFirst
= DbQuery.Procedure("GetPostsNewestFirst")
.Map<Post>()
.CancelOnEarlyStop();

public ValueTask<Post?> NewestAsync(CancellationToken cancellationToken)
=> NewestFirst.Using(factory)
.FirstOrDefaultAsync(cancellationToken);
```

**Use it** when the query can return far more rows than the terminal needs and the SQL cannot limit them. On SQL Server LocalDB, `FirstOrDefaultAsync` over 3 million rows took 202 ms without it and 0.4 ms with it (with `SingleResult()` too, in either order). **Do not use it** for a `TOP 1` or key lookup: there is nothing to save. A one-row lookup there took about 80 µs with or without it, and allocated a few hundred bytes more with it. `SingleResult()` is not a substitute: alone it took the same 202 ms, because it does not avoid reading the unread rows. The single row it asks the provider for is a hint, not a limit on what the server sends.
Expand Down