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
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,22 @@ 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<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);
```

Or, simply expressive, with nothing to declare:

```cs
int author = 42;
Expand All @@ -57,7 +72,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<SqliteConnection>(() => 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<SqliteConnection>(() => 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

Expand Down
17 changes: 14 additions & 3 deletions Source/Channel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ 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>();

// Returns right away: the rows are read in the background and the channel completes when they are all written.
ChannelReader<Post> reader = connectionFactory
.Command("select * from posts order by id")
.Map<Post>()
ChannelReader<Post> reader = Latest.Using(connectionFactory)
.ToChannelReader();

await foreach (Post post in reader.ReadAllAsync())
Expand All @@ -28,6 +30,15 @@ await foreach (Post post in reader.ReadAllAsync())
}
```

Or, simply expressive, with nothing to declare:

```cs
ChannelReader<Post> reader = connectionFactory
.Command("select * from posts order by id")
.Map<Post>()
.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
Expand Down
15 changes: 14 additions & 1 deletion Source/Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,20 @@ public record Post(int Id, string Title);
var connectionFactory = new DbConnectionFactory<SqliteConnection>(() => 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<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.
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
Expand Down
17 changes: 14 additions & 3 deletions Source/Dataflow/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ 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>();

// 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.
long count = await connectionFactory
.Command("select * from posts order by id")
.Map<Post>()
long count = await Latest.Using(connectionFactory)
.ToTargetBlock(block, complete: true);

// The block completes once every row has been received.
Expand All @@ -29,6 +31,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<Post>()
.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
Expand Down
10 changes: 9 additions & 1 deletion docsite/articles/async-buffers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand All @@ -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<T>`:

[!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:
Expand Down
6 changes: 6 additions & 0 deletions docsite/articles/async-reads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

</div>
Expand Down
6 changes: 5 additions & 1 deletion docsite/articles/channels-and-dataflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand Down
6 changes: 5 additions & 1 deletion docsite/articles/coming-from-dapper.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand Down
84 changes: 46 additions & 38 deletions docsite/articles/expressive-commands.md
Original file line number Diff line number Diff line change
@@ -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:

<div class="side-by-side">
<div>

**Factory form**

[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_call)]

</div>
<div>

**Connection form**

[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_own)]

</div>
</div>

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<TConnection>` | `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<TConnection>` (for example `IDbConnectionFactory<DbConnection>`). 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

Expand Down Expand Up @@ -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<TParams>()` declares typed values. Set a timeout with `SetTimeout` on a `DbNonQuery`, or on the `DbQuery` before `Scalar<T>()`. 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:

<div class="side-by-side">
<div>

**Factory form**

[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_call)]

</div>
<div>

**Connection form**

[!code-csharp[](../samples/ConnectionPattern.cs#ode_list_own)]

</div>
</div>

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<TConnection>` | `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<TConnection>` (for example `IDbConnectionFactory<DbConnection>`). 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:
Expand Down Expand Up @@ -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<T>()` (the statement that returns the id depends on your database; SQLite is shown). `ExecuteReturnAsync<T>()` is only for a procedure's `RETURN` code.
Expand Down Expand Up @@ -223,6 +225,12 @@ The library reads with the default access mode, in which SqlClient reads a whole

`ExecuteScalarAsync<T>()` converts the value the provider returns the way `Map<T>()` 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<T>()` 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<T>` and a write is a `DbNonQuery`. `Scalar<T>()` converts as `ExecuteScalarAsync<T>()` 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)]
Expand Down
6 changes: 6 additions & 0 deletions docsite/articles/foundation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
12 changes: 10 additions & 2 deletions docsite/articles/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):

<div class="side-by-side">
<div>
Expand All @@ -56,7 +64,7 @@ There are two ways to start a command: from the factory, or from a connection yo
</div>
</div>

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

Expand Down
Loading