Queries
This page covers running SQL from the Rust client: the query calls, $n parameters, reading rows, writing many rows at once, notices, and the simple-query form for tools that show results they did not write. For the typed query builder, see The ORM.
The calls
Every call below exists on Client and, through the Executor trait, on a Transaction too. Code written against E: Executor runs unchanged on its own or inside a transaction (see Transactions).
| call | parameters | returns |
|---|---|---|
run(sql) | none: the text is sent as written | Rows |
fetch_all::<T>(sql, params![…]) | &[&dyn ToSql] | Vec<T>, every row |
fetch_one::<T>(sql, params![…]) | &[&dyn ToSql] | T; no row, or more than one, is Error::RowCount |
fetch_optional::<T>(sql, params![…]) | &[&dyn ToSql] | Option<T>; more than one row is Error::RowCount |
fetch_scalar::<T>(sql, params![…]) | &[&dyn ToSql] | the first column of exactly one row |
exec(sql, params![…]) | &[&dyn ToSql] | u64: rows affected |
query_with(sql, params![…]) | &[&dyn ToSql] | Rows |
execute(sql, &[Param::…]) | &[Param] | u64: rows affected |
query(sql, &[Param::…]) | &[Param] | Rows |
Client alone also has:
| call | returns | what it does |
|---|---|---|
table_exists(name) | bool | whether a table of this name exists |
simple_query(sql), simple_query_with(sql, &options) | SimpleAnswer | runs SQL as a PostgreSQL simple query and answers with column names and text cells; see The simple-query form |
simple_session() | SimpleSession | a connection of its own for simple queries, where a BEGIN lasts across calls |
cancel(&token) | bool | stops a simple query sent with that cancel token |
set_notice_handler(f), clear_notice_handler() | see Notices | |
admin() | Admin | typed administration calls; see Administration |
kv() | the key/value API | see Key/value cache |
"Rows affected" is the count a write reported, or the number of rows a statement returned (DELETE … RETURNING, a SELECT).
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
client
.run("CREATE TABLE IF NOT EXISTS players (id BIGSERIAL, name TEXT NOT NULL, score DOUBLE PRECISION, PRIMARY KEY (id))")
.await?;
let id: i64 = client
.fetch_scalar("INSERT INTO players (name, score) VALUES ($1, $2) RETURNING id", params!["ada", 9.5f64])
.await?;
let top: Vec<(i64, String, Option<f64>)> = client
.fetch_all("SELECT id, name, score FROM players ORDER BY score DESC LIMIT $1", params![10i64])
.await?;
let one: (String, Option<f64>) = client
.fetch_one("SELECT name, score FROM players WHERE id = $1", params![id])
.await?;
let maybe: Option<(String,)> = client
.fetch_optional("SELECT name FROM players WHERE name = $1", params!["nobody"])
.await?;
let changed = client
.exec("UPDATE players SET score = score + $1 WHERE id = $2", params![1.0f64, id])
.await?;
let count: i64 = client.fetch_scalar("SELECT count(*) FROM players", params![]).await?;
println!("{top:?} {one:?} {maybe:?} {changed} {count}");
Ok(())
}Parameters
$1, $2… in the statement are replaced by the values you pass, in order. params! builds the list from any values that implement ToSql:
use rasterizeddb_client::params;
let name = String::from("ada");
let age: Option<i32> = None; // None is written as NULL
let list = params![name, age, 42i64]; // &[&dyn ToSql]
assert_eq!(list.len(), 3);
let none = params![]; // no parameters
assert!(none.is_empty());The native protocol has no bound parameters on the wire, so the client writes each value into the statement as a literal, by the rules the server reads literals with (PostgreSQL's, with standard_conforming_strings on). A value can never become SQL:
- text is single-quoted with
'doubled; text holding a NUL byte is refused withError::Param; - bytes become a
'\x…'hex literal; - a negative number is parenthesised, so it cannot follow a
-and start a comment; - a
$1inside a string, a quoted identifier or a comment is left alone; - a
$nwith no value isError::Param.
When the server supports it, the client sends the statement text and the values side by side instead, so the server does not have to find the values in the text again. This is chosen automatically on first use; the results are the same either way.
run renders nothing: $1 in its text is sent as written.
For values whose type is decided at run time, pass Param values to query and execute:
use rasterizeddb_client::{Client, Options, Param, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let n = client
.execute("DELETE FROM players WHERE name = $1 OR score < $2", &[Param::Text("bot"), Param::F64(0.0)])
.await?;
println!("deleted {n}");
Ok(())
}Param has a variant per kind of value: Null, Bool, I16, I32, I64, U64, I128, F32, F64, Numeric(&str), Text(&str), Bytes(&[u8]), Uuid, Timestamp, Date, Time, Interval, Json(&str) and Array(ArrayRef). Types lists which Rust types map to which.
Building SQL by hand
When an identifier or a literal has to be part of the SQL itself, quote it with the crate's helpers rather than formatting it in:
| function | returns |
|---|---|
quote_ident(name) | Result<String>: name as an identifier, bare when it is a plain lower-case name that is not a keyword, otherwise double-quoted |
quote_text(s) | Result<String>: s as a single-quoted literal |
quote_bytes(bytes) | String: a '\x…' literal |
render(sql, &[Param]), render_dyn(sql, params![…]) | Result<String>: the statement with its placeholders filled, as the client would send it |
check_statement(sql) | Result<()>: the check run applies (one statement, no transaction control) |
use rasterizeddb_client::{quote_ident, Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let table = "events_2026";
let sql = format!("SELECT count(*) FROM {}", quote_ident(table)?);
let n: i64 = client.fetch_scalar(&sql, &[]).await?;
println!("{n}");
Ok(())
}One statement per call
A string holding a second statement is refused before anything is sent (Error::Unsupported). BEGIN, START, COMMIT, END, ROLLBACK, ABORT, SAVEPOINT and RELEASE are refused too: use client.begin() and the Transaction methods instead (see Transactions).
Each statement sent on a Client commits on its own, and is atomic: it applies whole or not at all.
Reading rows
The native protocol sends no column names. Column i of a row is item i of your select list (or your RETURNING list). Name columns explicitly rather than SELECT *, so the order is the one your code expects.
fetch_all, fetch_one, fetch_optional and Rows::decode_all read each row as any FromRow type:
T | reads |
|---|---|
a tuple of up to twelve FromSql types | column i into element i |
Vec<Value> | every column, whatever its type |
a struct with #[derive(FromRow)] | column i into field i, in declaration order |
a struct with #[derive(Model)] | the model's own select list (see The ORM) |
A row with more or fewer columns than the type expects is an error (Error::Column), so a select list that drifted from the code is caught at once.
use rasterizeddb_client::prelude::*;
#[derive(FromRow, Debug)]
struct Order {
id: i64,
customer: String,
total: Numeric,
shipped: Option<Timestamp>,
}
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let open: Vec<Order> = client
.fetch_all(
"SELECT id, customer, total, shipped FROM orders WHERE shipped IS NULL AND total > $1",
params![Numeric::new("100")?],
)
.await?;
println!("{open:?}");
Ok(())
}#[derive(FromRow)] takes two field attributes: #[rdb(skip)] (no column; the field gets Default::default()) and #[rdb(json)] (the column holds JSON, deserialized with serde; needs the serde_json feature).
Rows by hand
query_with, query and run return Rows, which you can walk yourself:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let rows = client.query_with("SELECT id, name, score FROM players", params![]).await?;
println!("{} rows", rows.len());
for row in &rows {
let id: i64 = row.get(0)?;
let name: &str = row.get(1)?; // borrows from `rows`
let score: Option<f64> = row.get(2)?; // NULL is None
let all: Vec<Value> = row.values()?; // whatever the types
println!("{id} {name} {score:?} {all:?}");
}
Ok(())
}on Rows | returns |
|---|---|
len(), is_empty() | the number of rows |
get(i) | Option<Row>: row i |
iter(), for row in &rows | each Row |
rows_affected() | Option<u64>: the count a write reported |
decode_all::<T>() | Result<Vec<T>> |
decode_first::<T>() | Result<Option<T>> |
notices() | the notices the statement raised |
on Row | returns |
|---|---|
get::<T>(i) | column i as any FromSql type; Option<T> for a column that may be NULL |
is_null(i) | whether column i is NULL (past the end of the row is an error) |
values() | every column as Value |
decode::<T>() | the whole row as a FromRow type |
len(), is_empty() | the number of columns |
tag(i), raw(i) | the cell's type tag and raw bytes, for custom decoding |
get_i64, get_i32, get_i16, get_f64, get_f32, get_bool, get_text, get_bytes, get_numeric | shortcuts for get with that type |
get_opt_i64, get_opt_i32, get_opt_i16, get_opt_f64, get_opt_f32, get_opt_bool, get_opt_text, get_opt_bytes, get_opt_numeric | the same, None for NULL |
Reading a NULL into a type that is not an Option is an error, never a default value.
Writing many rows at once
Writes that belong together can go in one statement, which needs no transaction:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
// One statement: all three rows or none.
client
.exec(
"INSERT INTO ledger (account, amount) VALUES ($1, $2), ($3, $4), ($5, $6)",
params![1i64, -50i64, 2i64, 30i64, 3i64, 20i64],
)
.await?;
// An upsert that returns what was stored.
let (id, hits): (i64, i64) = client
.fetch_one(
"INSERT INTO pages (path, hits) VALUES ($1, 1) \
ON CONFLICT (path) DO UPDATE SET hits = pages.hits + 1 RETURNING id, hits",
params!["/index"],
)
.await?;
// Every id in one array parameter.
let ids = vec![1i64, 2, 3];
let gone = client.exec("DELETE FROM pages WHERE id = ANY($1)", params![ids]).await?;
println!("{id} {hits} {gone}");
Ok(())
}Several statements that must commit together go in a transaction. The ORM's insert_many writes many model rows in multi-row statements (see The ORM).
Large results
A whole answer is held in memory and must fit Options::max_message_size (8 MiB by default). For a read of unknown size:
- page it with
ORDER BY … LIMIT $1and a condition on the last key you read (WHERE id > $2); - or, for a model, use the ORM's keyset pages or row stream, which read in batches of one statement each (The ORM);
- or raise
max_message_size(Connecting).
Prepared statements
There is no prepare call in the client. Statements are sent as text each time with their values, as described under Parameters. Build the SQL string once (a const or a static) and reuse it with new params!.
Notices
What the server says about a statement without failing it (RAISE NOTICE in a DO block, DROP TABLE IF EXISTS naming no table, CREATE TABLE IF NOT EXISTS naming one that exists, a BEGIN inside a transaction) comes with the answer. Each is a Notice with severity, sqlstate and message (all String).
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
// Every notice of every statement on this client and its transactions,
// including those of a statement that then failed.
client.set_notice_handler(|n| eprintln!("{}: {} ({})", n.severity, n.message, n.sqlstate));
let rows = client.run("DROP TABLE IF EXISTS gone").await?;
for notice in rows.notices() {
println!("{notice}");
}
Ok(())
}NOTICE: table "gone" does not exist, skipping (00000)
NOTICE: table "gone" does not exist, skipping (SQLSTATE 00000)The first line is the handler's; the second is the notice's Display form.
The handler runs on the task that awaits the statement, before the call returns: keep it short. Setting a handler replaces the previous one; clear_notice_handler() removes it. A simple query's notices are on its SimpleAnswer only.
The simple-query form
simple_query is for programs that show results of SQL they did not write: a console, an export, an admin tool. It answers as a PostgreSQL server would answer a simple query:
- each result's column names and type OIDs, and every cell as PostgreSQL's text form;
- each statement's command tag (
SELECT 3,INSERT 0 2); - several
;-separated statements in one call, run as one implicit transaction; - nothing is rendered:
$1is sent as written.
use rasterizeddb_client::{Client, Options, Result, SimpleResult};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let answer = client
.simple_query("SELECT id, name FROM players ORDER BY id LIMIT 3; SELECT count(*) AS n FROM players")
.await?;
for result in &answer.results {
match result {
SimpleResult::Rows { columns, rows, tag } => {
let names: Vec<&str> = columns.iter().map(|c| c.name.as_str()).collect();
println!("{names:?}");
for row in rows {
// Each cell is Option<String>: None is NULL.
println!("{row:?}");
}
println!("{tag}");
}
SimpleResult::Command { tag, rows } => println!("{tag} {rows:?}"),
}
}
Ok(())
}| type | fields / methods |
|---|---|
SimpleAnswer | results: Vec<SimpleResult>, notices: Vec<String>, transaction: TransactionStatus |
SimpleResult::Rows | columns: Vec<SimpleColumn>, rows: Vec<Vec<Option<String>>>, tag: String |
SimpleResult::Command | tag: String, rows: Option<u64> |
SimpleResult | tag(), row_count() |
SimpleColumn | name: String, type_oid: u32 |
TransactionStatus | Idle, InBlock, Failed |
SimpleOptions | cancel: Option<CancelToken>, max_rows: Option<u64> |
SimpleOptions::max_rows caps the rows sent for each result: the rest are counted in the tag and dropped by the server, which guards a console against a SELECT * it cannot show.
A failed statement is Error::Server with its SQLSTATE. A BEGIN sent through Client::simple_query must be ended in the same call, because the client's connections are shared; one left open is rolled back and reported as an error.
Sessions
A console where a BEGIN typed in one call is committed in a later one needs its own connection: client.simple_session() opens one.
use rasterizeddb_client::{Client, Options, Result, TransactionStatus};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let session = client.simple_session().await?;
session.query("BEGIN").await?;
session.query("UPDATE players SET score = 0 WHERE name = 'bot'").await?;
assert_eq!(session.transaction(), TransactionStatus::InBlock);
session.query("COMMIT").await?;
Ok(())
}on SimpleSession | does |
|---|---|
query(sql), query_with(sql, &options) | as simple_query, on the session's connection |
transaction() | where the session's transaction stood after its last call |
ping() | sends nothing to run, which keeps the connection (and an open block) from being closed as idle |
The server closes a connection idle for its request timeout (30 s by default), rolling back an open block. Call ping() while a user is thinking inside a block.
Cancelling a statement
A simple query sent with a CancelToken can be stopped from anywhere that holds a client of the same user:
use rasterizeddb_client::{CancelToken, Client, Options, Result, SimpleOptions};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<()> {
let client = Arc::new(Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?);
let token = CancelToken::new();
let options = SimpleOptions { cancel: Some(token.clone()), max_rows: Some(1000) };
let running = {
let client = client.clone();
tokio::spawn(async move { client.simple_query_with("SELECT * FROM big", &options).await })
};
let was_running = client.cancel(&token).await?;
let outcome = running.await.expect("the task panicked");
// When it was stopped: Err(Server("… (SQLSTATE 57014)")).
println!("{was_running} {:?}", outcome.is_err());
Ok(())
}cancel returns whether a statement was running: false when the query has ended, has not started, or is between two of its statements. Use a fresh token per query: a token is refused while another query of the same user still holds it.
Limits
- One statement per call, outside
simple_query. - Answers carry no column names on the ordinary calls: read by position.
- No server-side prepared statements from this client.
Client::cancelstops simple queries only. An ordinary call is bounded by the server's statement timeout (Connecting).- A whole answer is held in memory, up to
max_message_size.