Commands and parameters
This page covers running SQL from .NET with RasterizedDb.Data: creating commands, passing values safely, executing them synchronously or asynchronously, sending several statements at once, loading many rows, and stopping a statement that runs too long.
Creating a command
A command is statement text plus its parameters. It runs on a connection, or on a data source's shared connection:
using RasterizedDb.Data;
await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");
await using var connection = await dataSource.OpenConnectionAsync();
// Three equivalent ways to make a command on a connection:
await using var a = new RasterizedDbCommand("SELECT 1", connection);
await using var b = connection.CreateCommand("SELECT 1");
await using var c = connection.CreateCommand();
c.CommandText = "SELECT 1";
// A command with no connection of its own (see "Commands without a connection"):
await using var d = dataSource.CreateCommand("SELECT 1");CommandType is always Text. There are no stored procedures to call by name; call a function with SELECT f(…).
Executing
| method | returns |
|---|---|
ExecuteNonQueryAsync() / ExecuteNonQuery() | The number of rows the statement changed. For a write with RETURNING in the binary format, the number of rows it returned. -1 when the server reports no count (DDL, for example). |
ExecuteScalarAsync() / ExecuteScalar() | The first column of the first row; null when there is no row; DBNull.Value when that cell is NULL. |
ExecuteReaderAsync() / ExecuteReader() | A RasterizedDbDataReader over the rows. See Reading results. |
await using var update = connection.CreateCommand("UPDATE orders SET status = 'shipped' WHERE id = @id");
update.Parameters.Add("id", 42L);
int changed = await update.ExecuteNonQueryAsync();
await using var count = connection.CreateCommand("SELECT count(*) FROM orders");
long total = (long)(await count.ExecuteScalarAsync())!;Async and sync
Every execute call has an …Async form taking an optional CancellationToken, and a synchronous form that blocks the calling thread on its I/O. The async forms do not tie up a thread while waiting for the server; prefer them in servers and UI code.
The whole answer to a statement arrives before the reader is returned, so reader.ReadAsync() and reader.Read() never wait on the network.
Errors
A statement the server refuses throws RasterizedDbException, a DbException:
| member | meaning |
|---|---|
SqlState | The five-character SQLSTATE the server sent, such as 23505 or 42P01. |
Kind | Server (the server refused the statement), Transport (the connection failed; whether the statement ran is unknown), Protocol, Authentication, Timeout, TransactionLost, Unsupported (the statement cannot be sent in the form asked for). |
IsTransient | A serialization failure (40001) or deadlock (40P01): the transaction can be run again. See Transactions. |
IsStatementTimeout | The server stopped the statement at its statement timeout (57014). The connection goes on. |
IsUniqueViolation | A unique or primary key was violated. |
CommitOutcomeUnknown | A COMMIT whose connection failed: it may or may not have committed. |
After a server error the connection stays usable (inside a transaction, the transaction is failed until rolled back).
try
{
await using var insert = connection.CreateCommand("INSERT INTO users (email) VALUES (@email)");
insert.Parameters.Add("email", "ada@example.com");
await insert.ExecuteNonQueryAsync();
}
catch (RasterizedDbException e) when (e.IsUniqueViolation)
{
Console.WriteLine("that email is already registered");
}Parameters
Never build SQL by concatenating values. Use placeholders and parameters.
Placeholders
Two forms are accepted; a statement uses one or the other, not both (mixing them is an ArgumentException):
| form | matched to |
|---|---|
@name | The parameter of that name, ignoring case. The same name may appear several times. |
$1, $2, … | The parameter at that position in the collection ($1 is the first). Names are ignored. $0 is an error. |
// Named
await using var byName = connection.CreateCommand(
"SELECT id FROM users WHERE email = @email OR backup_email = @email");
byName.Parameters.Add("email", "ada@example.com");
// Positional
await using var byPosition = connection.CreateCommand(
"SELECT id FROM users WHERE created_at > $1 AND country = $2");
byPosition.Parameters.AddWithValue(DateTime.UtcNow.AddDays(-7));
byPosition.Parameters.AddWithValue("BG");A placeholder inside a string literal, a quoted identifier, a dollar-quoted string or a comment is left alone, so '@home' and -- $1 are text, not parameters. A cast right after a placeholder works: $1::bigint, @id::integer.
A placeholder with no matching parameter throws InvalidOperationException when the command runs.
Adding parameters
| call | what it adds |
|---|---|
Parameters.Add("name", value) | A RasterizedDbParameter<T>: the value is held without boxing. Returns it, so you can change TypedValue and run the command again. |
Parameters.AddWithValue("name", value) | A RasterizedDbParameter holding object? value. |
Parameters.AddWithValue(value) | A positional parameter, for $n. |
Parameters.Add(new RasterizedDbParameter("name", value)) | A parameter you built yourself. |
The name may be written with or without its @ ("@email" and "email" are the same). Parameters are input only: setting Direction to anything but Input throws NotSupportedException.
Reusing a command with new values:
await using var insert = connection.CreateCommand("INSERT INTO events (kind) VALUES (@kind)");
var kind = insert.Parameters.Add("kind", "start");
await insert.ExecuteNonQueryAsync();
kind.TypedValue = "stop";
await insert.ExecuteNonQueryAsync();How values reach the server
The native protocol has no separate message for values, so the driver writes each value into the statement as the SQL literal for it, under the server's quoting rules: text is single-quoted with ' doubled, bytes become a '\x…' literal, a negative number is put in parentheses. A value can never become SQL syntax. In the binary result format, where the server supports it, the statement text and the values travel apart, so the server sees the same statement text every time and can reuse its parse.
A text value containing a NUL character (\0) is refused with ArgumentException.
Parameter types
| .NET value | written as |
|---|---|
null, DBNull.Value | NULL |
bool | true / false |
short, int, long, byte, sbyte, ushort, uint, ulong, Int128, UInt128, BigInteger | an integer |
decimal | an exact number (for numeric) |
double | a number; NaN and the infinities as 'NaN', 'Infinity', '-Infinity' |
float | a number cast to real |
string, char, char[], ReadOnlyMemory<char> | text |
byte[], ReadOnlyMemory<byte>, Memory<byte>, ArraySegment<byte> | bytea |
Guid | uuid |
DateTime with Kind Utc or Local | an instant in UTC (timestamp with time zone) |
DateTime with Kind Unspecified | a wall-clock time with no zone (timestamp) |
DateTimeOffset | an instant, converted to UTC |
DateOnly | date |
TimeOnly | time |
TimeSpan | interval (days and the rest of the day) |
RasterizedDbInterval | interval with months, days and microseconds kept apart |
JsonDocument, JsonElement, JsonNode | the JSON text |
IPAddress | its text |
an enum | its underlying integer |
T[], List<T>, any other IEnumerable of the types above | an array literal, '{…}' |
Dates and timestamps must fall in years 1 to 9999. Any other type throws NotSupportedException; convert it to one of these first.
Setting DbType picks a different form for a few values:
DbType | value | written as |
|---|---|---|
Date | DateTime | its date only |
Time | DateTime | its time of day only |
Time | TimeSpan under one day | time instead of interval |
DateTime, DateTime2 | DateTime with Kind Utc or Local | its wall-clock time with no zone (timestamp) |
DateTimeOffset | DateTime with Kind Unspecified | an instant, taking the value as UTC |
Other DbType values, and Size, Precision and Scale, change nothing about what is sent.
Preparing
Prepare() does nothing that needs the server: there are no server-side prepared statements. The driver scans each distinct statement text once and caches the result either way, and in the binary result format the server answers a repeated statement text from the parse it learned the first time. Keeping the statement text constant and passing values as parameters is what makes repeated statements fast.
Several statements in one command
In the text result format (the default) a command may hold several statements separated by ;. They run as one implicit transaction: all take effect or none does. The reader has one result per statement that returns rows; move between them with NextResult():
await using var command = connection.CreateCommand(
"UPDATE stock SET quantity = quantity - 1 WHERE sku = @sku; " +
"SELECT quantity FROM stock WHERE sku = @sku");
command.Parameters.Add("sku", "A-100");
await using var reader = await command.ExecuteReaderAsync();
Console.WriteLine($"rows changed: {reader.RecordsAffected}");
while (await reader.ReadAsync())
{
Console.WriteLine($"left: {reader.GetInt32(0)}");
}In the binary result format a command holds exactly one statement; a second one throws RasterizedDbException with Kind Unsupported.
Batches
RasterizedDbBatch (the ADO.NET DbBatch) sends several commands, each with its own parameters, in one round trip:
await using var batch = connection.CreateBatch();
for (var i = 1; i <= 3; i++)
{
var insert = batch.BatchCommands.Add("INSERT INTO items (id, name) VALUES (@id, @name)");
insert.Parameters.Add("id", i);
insert.Parameters.Add("name", $"item {i}");
}
batch.BatchCommands.Add("SELECT count(*) FROM items");
await using var reader = await batch.ExecuteReaderAsync();
Console.WriteLine($"inserted: {reader.RecordsAffected}");
await reader.ReadAsync();
Console.WriteLine($"now: {reader.GetInt64(0)}");- The statements are sent as one simple query, in the text format, and the server runs them as one implicit transaction: if one fails, none takes effect.
- The reader has one result per statement that returns rows.
RecordsAffectedis the total over the batch; a single batch command'sRecordsAffectedis always -1. - A batch needs a connection (
connection.CreateBatch(), or setbatch.Connection). It cannot run on a data source's shared connection. batch.Timeoutis the batch's command timeout.
Commands without a connection
A command made by dataSource.CreateCommand(...) has no connection of its own. It runs on one connection that every such command of the data source shares, with any number of statements in flight at once, answered in any order. This is the cheapest way to run many independent statements that each commit on their own:
var names = await Task.WhenAll(Enumerable.Range(1, 100).Select(async id =>
{
await using var select = dataSource.CreateCommand("SELECT name FROM users WHERE id = @id");
select.Parameters.Add("id", id);
return await select.ExecuteScalarAsync() as string;
}));What such a command cannot do:
- Transaction control (
BEGIN,COMMIT,SAVEPOINT, …) is refused withKindUnsupported. Open aRasterizedDbConnectionand useBeginTransactionAsync. - Anything that lives on a connection does not carry from one command to the next: temporary tables, a sequence's
currval, session settings.
The shared connection opens on first use and is replaced when it fails or goes quiet.
Bulk inserts
connection.BulkInsertAsync loads many rows with as few statements as possible: multi-row INSERTs of up to rowsPerStatement rows (1000 unless given), and about a megabyte each, written straight into the request:
var rows = Enumerable.Range(1, 50_000)
.Select(i => new object?[] { i, $"name {i}", DateTime.UtcNow });
await using var transaction = await connection.BeginTransactionAsync();
long inserted = await connection.BulkInsertAsync("people", ["id", "name", "created_at"], rows);
await transaction.CommitAsync();Each statement commits on its own unless a transaction is open; open one, as above, to make the whole load atomic. Values follow the parameter types table. It returns the number of rows the server reported inserted.
Timeouts
Two limits apply to every statement:
| limit | default | what happens |
|---|---|---|
The server's statement limit (--rdb-request-timeout) | 30 s | The server stops the statement and answers SQLSTATE 57014 (IsStatementTimeout). The connection and any transaction on it go on; the transaction is failed until rolled back. |
The driver's Command Timeout (connection string), or command.CommandTimeout | 30 s | If no answer has come this long after sending, plus two seconds, the driver closes the connection and throws Kind Timeout. Whether the statement ran is unknown. |
The two seconds of grace mean that, with both at their defaults, the server's own 57014 answer arrives first. For long statements (reports, imports), raise the server's limit as well as the driver's: start the server with a larger --rdb-request-timeout, or run SET statement_timeout inside a transaction, and set CommandTimeout to match. CommandTimeout = 0 waits indefinitely.
Cancellation
Pass a CancellationToken to stop a statement that should not run any longer:
using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await using var report = connection.CreateCommand("SELECT region, sum(total) FROM orders GROUP BY region");
try
{
await using var reader = await report.ExecuteReaderAsync(cancel.Token);
// ...
}
catch (OperationCanceledException)
{
Console.WriteLine("the report took too long");
}When the token is cancelled, the driver asks the server to stop the statement and waits for it to confirm. Then it throws OperationCanceledException, and the connection stays open, along with any transaction on it (which must then be rolled back). If the server does not confirm within five seconds, the connection is closed instead. A command on a data source's shared connection stops waiting at once and tells the server.
command.Cancel(), called from another thread, stops a statement too. The stopped statement fails with SQLSTATE 57014. It works for every text-format statement, and for a binary-format one when command.Cancelable = true is set before it runs. A synchronous call has no token to say it may be cancelled, so it needs Cancelable:
await using var command = new RasterizedDbCommand("SELECT count(*) FROM big_table", connection)
{
ResultFormat = RasterizedDbResultFormat.Binary,
Cancelable = true,
};
var running = Task.Run(() => command.ExecuteScalar());
// Later, from another thread:
command.Cancel();
try
{
await running;
}
catch (RasterizedDbException e) when (e.SqlState == "57014")
{
Console.WriteLine("stopped");
}Cancellation needs a server that knows cancelable requests. Against an older one, a binary-format statement is not interrupted: a cancelled token closes its connection instead.
Notices
The server can send notices with an answer (RAISE NOTICE, a DROP TABLE IF EXISTS that found no table, warnings). They are raised on the connection's Notice event:
connection.Notice += (_, e) =>
Console.WriteLine($"{e.Notice.Severity}: {e.Notice.Message} ({e.Notice.SqlState})");
await using var drop = connection.CreateCommand("DROP TABLE IF EXISTS not_there");
await drop.ExecuteNonQueryAsync();Severity is NOTICE, WARNING, INFO, LOG or DEBUG. Set Notices=false in the connection string to not ask for them.
Limits
- No server-side prepared statements;
Prepare()only caches the driver's own scan of the text. - Parameters are input only. No output or return-value parameters, no
CommandType.StoredProcedure. @nameand$ncannot be mixed in one statement.- A batch and a multi-statement command always run in the text format, as one implicit transaction.
- Commands on a data source's shared connection cannot use transactions, temporary tables or session state.
- A statement's whole answer is held in memory, and must fit
Max Message Size(8 MiB unless raised). Page through big results withLIMIT/OFFSETor a key range, or raise the limit.