The ORM
#[derive(Model)] maps a Rust struct to a table. You get typed CRUD calls, a query builder, upserts and bulk updates that return what was stored, optimistic locking, server-set timestamps, soft delete, validation hooks, aggregates and keyset pagination, all on a Client or inside a transaction. This page covers models and queries; Relations and Migrations build on it.
The ORM needs the derive feature, which is on by default.
A model
use rasterizeddb_client::prelude::*;
#[derive(SqlEnum, Debug, Clone, Copy, PartialEq)]
enum Plan {
Free,
Pro,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "accounts")]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(unique)]
email: String,
#[rdb(index)]
name: Option<String>,
plan: Plan,
balance: Numeric,
tags: Vec<String>,
#[rdb(default = "0")]
logins: i32,
#[rdb(created_at)]
created_at: Timestamp,
}
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
client.create_table::<Account>().await?;
Ok(())
}create_table sends:
CREATE TABLE IF NOT EXISTS accounts (id BIGSERIAL, email TEXT NOT NULL, name TEXT, plan TEXT NOT NULL,
balance NUMERIC NOT NULL, tags TEXT[] NOT NULL, logins INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (id))followed by the unique key on email and the index on name.
The derive generates:
- the
Modeltrait: the table's name and columns, and how to write each field; FromRow, reading the model's own select list;- one constant per column, named as the field (
Account::email), for the query builder; - one constant per relation field (see Relations).
A field's Rust type gives its column type (Types has the full list): i64 is BIGINT, String is TEXT, Option<T> makes the column nullable, Vec<String> is TEXT[], a SqlEnum is TEXT. Every other column is NOT NULL. A field of a type the ORM does not know needs sql_type, json or an implementation of SqlType.
The table name defaults to the struct's name in snake case (OrderLine → order_line).
Attributes
Field attributes
| attribute | meaning |
|---|---|
primary_key | part of the primary key; several fields make a composite key |
serial | assigned by the server's sequence (BIGSERIAL for an i64, SERIAL for an i32, SMALLSERIAL for an i16): left out of inserts, read back |
unique | a UNIQUE constraint on the column |
index | a secondary index, b-tree |
index = "hash" | a secondary index of that kind: btree, hash, gin, jsonb_path_ops |
column = "name" (or rename = "name") | the column's name, when it is not the field's |
sql_type = "VARCHAR(64)" | the column's DDL type, instead of the field type's default |
default = "…" | a DEFAULT expression in the DDL (also used when a migration adds the column) |
renamed_from = "old" | an earlier column name, for the migrator to rename in place; may repeat |
json | any Serialize + Deserialize type, stored as JSONB (needs the serde_json feature) |
text | selected as col::text and read with the type's FromSql, for a type of your own |
skip | not a column; the field gets Default::default() on reads |
version | an integer for optimistic locking (see Optimistic locking) |
created_at | set to the server's now() on insert, never written again |
updated_at | set to the server's now() on insert and on every update |
soft_delete | an Option<Timestamp>: delete marks the row instead of removing it (see Soft delete) |
references = "users(id)" | a foreign key to one column, with optional on_delete / on_update = "cascade", "restrict", "set null", "set default" or "no action" (Relations) |
has_many(…), has_one(…), belongs_to(…), many_to_many(…), count_of = "…" | a relation field, not a column (Relations) |
Struct attributes
| attribute | meaning |
|---|---|
table = "name" | the table's name |
renamed_from = "old" | an earlier table name, for the migrator to rename |
hooks | call the struct's ModelHooks implementation (see Hooks and validation) |
partition_by = "tenant_id, group_id" | a hash-partitioned table on one to three columns (see Partitioned tables) |
partitions = 16 | the number of partitions, with partition_by; without it the server's default |
Attributes can be combined in one #[rdb(…)] or spread over several. An unknown attribute, a partition_by naming a column the model does not have, or a wrong foreign-key action is a compile error.
Compression and sharding attributes
| attribute | on | meaning |
|---|---|---|
compression, compression = "zstd(9)" | a field | the column's COMPRESSION clause: zstd (level 3) or zstd(1) to zstd(22) |
row_compression, row_compression = "zstd(…)" | the struct | the table's row compression |
shard_by = "column" | the struct | the column a client-side router sends rows by (Client-side sharding) |
shard = "global" / shard = "unsharded" | the struct | a table copied to every shard, or kept on one |
See Compression for what the server does with the compression clauses.
Create, read, update, delete
The calls come from the ModelExt trait, which the prelude imports. They work on anything that runs statements: a Client, a &Client, or a Transaction. Each is one statement (insert_many may be several, see below).
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "members")]
struct Member {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(unique)]
email: String,
name: Option<String>,
}
#[tokio::main]
async fn main() -> Result<()> {
let db = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
db.create_table::<Member>().await?;
// The stored row comes back, with the id the server assigned.
let ada = db.insert(&Member { id: 0, email: "ada@example.com".into(), name: None }).await?;
let found: Option<Member> = db.find(ada.id).await?;
let mut changed = ada.clone();
changed.name = Some("Ada".into());
let stored = db.update(&changed).await?; // every non-key column
let existed: bool = db.delete(&stored).await?;
println!("{found:?} {existed}");
Ok(())
}| call | returns | sends |
|---|---|---|
create_table::<M>() | () | CREATE TABLE IF NOT EXISTS … with keys, indexes and foreign keys |
drop_table::<M>() | () | DROP TABLE IF EXISTS … |
insert(&row) | M as stored | INSERT … RETURNING the model's columns; serial columns left to the server |
insert_many(&rows) | Vec<M> as stored | multi-row INSERT … RETURNING, up to 500 rows and about 1 MiB of SQL per statement |
upsert(&row) | M as stored | INSERT … ON CONFLICT (primary key) DO UPDATE … RETURNING (see Upserts) |
update(&row) | M as stored | UPDATE … SET every non-key column WHERE the key; Error::RowCount when there is no such row |
update_many(&rows) | Vec<M> as stored | one UPDATE for all rows, all or nothing (see Many rows in one statement) |
delete(&row) | bool: whether there was a row | DELETE … WHERE the key (a soft delete marks it) |
force_delete(&row) | bool | a real DELETE, even with a soft-delete column |
restore(&row) | M | clears a soft-delete mark |
find::<M>(key) | Option<M> | the row with this single-column primary key |
find_by_key::<M>(params![a, b]) | Option<M> | the row with this composite primary key, in key column order |
all::<M>() | Vec<M> | every row of the table |
insert_many is atomic per statement only: a large batch of several statements can be half-written if a later one fails. Run it in a transaction to make it one change.
Every write that returns a row gets it from the statement itself (RETURNING), never by reading it again afterwards. What comes back is what the server stored, with serial keys, server timestamps and type coercion applied, and no other write can land in between.
Since the calls take any executor, ORM code runs inside a transaction unchanged:
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "orders")]
struct Order {
#[rdb(primary_key, serial)]
id: i64,
customer: String,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "order_lines")]
struct OrderLine {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(references = "orders(id)", on_delete = "cascade")]
order_id: i64,
sku: String,
quantity: i32,
}
async fn place(db: &Client, customer: &str, items: &[(&str, i32)]) -> Result<Order> {
let tx = db.begin().await?;
let order = tx.insert(&Order { id: 0, customer: customer.to_string() }).await?;
let lines: Vec<OrderLine> = items
.iter()
.map(|(sku, quantity)| OrderLine { id: 0, order_id: order.id, sku: sku.to_string(), quantity: *quantity })
.collect();
tx.insert_many(&lines).await?;
tx.commit().await?;
Ok(order)
}Upserts
upsert and insert_many return builders that run when awaited. Await them as they are, or say first what a clash does:
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "members")]
struct Member {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(unique)]
email: String,
name: String,
visits: i64,
}
async fn upserts(db: &Client, m: Member, batch: Vec<Member>) -> Result<()> {
// On the primary key: every column written as given.
let a = db.upsert(&m).await?;
// On another unique key: the serial id is left to the server.
let b = db.upsert(&m).on_conflict(Member::email).await?;
// Choose what a clash updates.
let c = db.upsert(&m).on_conflict(Member::email).do_update(Member::name).await?;
let d = db.upsert(&m).on_conflict(Member::email).do_update_all_except((Member::visits,)).await?;
// Keep the stored row: None when the key was taken.
let fresh: Option<Member> = db.upsert(&m).on_conflict(Member::email).do_nothing().await?;
// Many rows, the same choices.
let inserted = db.insert_many(&batch).on_conflict(Member::email).do_nothing().await?;
let merged = db
.insert_many(&batch)
.on_conflict(Member::email)
.do_update((Member::name, Member::visits))
.await?;
// See the statement first.
println!("{}", db.upsert(&m).on_conflict(Member::email).to_sql()?);
let _ = (a, b, c, d, fresh, inserted, merged);
Ok(())
}| builder call | meaning |
|---|---|
on_conflict(columns) | the conflict target: one column or a tuple of columns (default: the primary key) |
do_update(columns) | on a clash, update only these columns |
do_update_all_except(columns) | on a clash, update every column but these |
do_nothing() | on a clash, keep the stored row; upsert then returns Option<M>, insert_many only the rows inserted |
to_sql() | the statement(s) it would send |
- With the default target (the primary key), every column is written as given, a serial key included: an upsert names its row. A new row with
id: 0is stored with id 0; useinsertto get a sequence value. - With another target, serial columns are left to the server, as an insert leaves them.
- The default update writes every column except the key, the target, serial and
created_atcolumns.versionandupdated_atmove as on any update and cannot be named indo_update. - Only a clash on the target is absorbed: under
on_conflict(Member::id), a row whose email is taken is still a unique-violation error, and the statement writes nothing. insert_many(…).do_nothing()with no target skips a clash on any unique key.- A multi-row upsert that updates a model with a
versioncolumn is refused (Error::Unsupported); upsert such rows one at a time, or useupdate_many.
Many rows in one statement
update_many writes every row given, by primary key, as one UPDATE, so the change commits whole or not at all. If any row is gone, soft-deleted, or (with a version column) at another version than the struct holds, nothing is updated and the call fails with Error::Conflict naming the rows. Rows come back as stored, in the order given; each is validated first.
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
struct Doc {
#[rdb(primary_key)]
id: i64,
body: String,
#[rdb(version)]
version: i64,
}
async fn trim_all(db: &Client) -> Result<()> {
let mut docs = Doc::query().filter(Doc::id.is_in([1i64, 2, 3])).all(db).await?;
for d in &mut docs {
d.body = d.body.trim().to_string();
}
match db.update_many(&docs).await {
Ok(stored) => println!("{} updated", stored.len()),
Err(e) if e.is_conflict() => println!("someone got there first: read again"),
Err(e) => return Err(e),
}
Ok(())
}A change of more than UPDATE_MANY_MAX_BYTES (1 MiB) of SQL is refused with Error::Unsupported, not split, since two statements could half-apply. Update fewer rows per call, or run several calls in one transaction.
Optimistic locking
A #[rdb(version)] integer field makes every write check that nobody changed the row since you read it:
| call | writes | matches |
|---|---|---|
insert, insert_many | version 1 | |
update | version = version + 1 | the key, at the struct's version |
upsert | 1 when new; version + 1 when it exists | the existing row only at the struct's version |
delete, force_delete | the key, at the struct's version | |
update_many | version + 1 on each row | every row at its struct's version |
query().update()…run() | version = version + 1 (unless a set names it) | the filter |
A write that finds the row at another version fails with Error::Conflict and writes nothing: read the row again, reapply the change, retry. A row that is simply gone stays Error::RowCount for update and Ok(false) for delete (one more statement tells the two cases apart).
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
struct Doc {
#[rdb(primary_key)]
id: i64,
body: String,
#[rdb(version)]
version: i64,
}
async fn shout(db: &Client, id: i64) -> Result<Doc> {
let mut doc: Doc = db.find(id).await?.ok_or(Error::RowCount { expected: "exactly 1", got: 0 })?;
loop {
doc.body.push('!');
match db.update(&doc).await {
Ok(stored) => return Ok(stored),
Err(e) if e.is_conflict() => {
doc = db.find(id).await?.ok_or(Error::RowCount { expected: "exactly 1", got: 0 })?;
}
Err(e) => return Err(e),
}
}
}Because delete checks the version too, a row someone changed after you read it is not deleted on the strength of the old copy. To delete by key alone, use Doc::query().filter(Doc::id.eq(id)).delete(db), which checks nothing.
For pessimistic locking (SELECT … FOR UPDATE), see Transactions.
Timestamps
#[rdb(created_at)] and #[rdb(updated_at)] fields are written by the server: now() in the statement, so every client agrees on one clock. An insert or upsert sets both (the struct's values are ignored); every update, including the bulk query().update(), sets updated_at again and never touches created_at. The row that comes back holds the server's times. The two can differ by microseconds within one insert.
Soft delete
#[rdb(soft_delete)] on an Option<Timestamp> field turns deleting into marking:
| call | does |
|---|---|
delete(&row) | UPDATE … SET deleted_at = now() (and the version and update time) of the row while it is not deleted; false when it already was |
query()…delete(db) | the same, for the filtered rows |
every query, find, relation load, count and aggregate | leaves out rows whose mark is set |
.with_deleted(), .only_deleted() | on a query or a relation: all rows, or only the marked ones |
restore(&row) | clears the mark and returns the row (Error::Unsupported for a model with no soft-delete column) |
force_delete(&row), query()…force_delete(db) | a real DELETE |
update(&row) | updates the row whether it is marked or not |
upsert(&row) | writes the row as given, the mark included: upserting a struct whose mark is None restores the row |
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
struct Note {
#[rdb(primary_key, serial)]
id: i64,
body: String,
#[rdb(created_at)]
created_at: Timestamp,
#[rdb(updated_at)]
updated_at: Timestamp,
#[rdb(soft_delete)]
deleted_at: Option<Timestamp>,
}
async fn bin_and_back(db: &Client, note: Note) -> Result<()> {
db.delete(¬e).await?; // marked
let live = Note::query().count(db).await?; // leaves it out
let bin = Note::query().only_deleted().all(db).await?; // finds it
let back = db.restore(&bin[0]).await?;
db.force_delete(&back).await?; // gone
println!("{live}");
Ok(())
}Hooks and validation
#[rdb(hooks)] on the struct makes the ORM call its ModelHooks implementation. Every method has a default that does nothing, so implement only what you need:
use rasterizeddb_client::orm::ModelHooks;
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(hooks)]
struct Person {
#[rdb(primary_key, serial)]
id: i64,
email: String,
frozen: bool,
#[rdb(skip)]
domain: String,
}
impl ModelHooks for Person {
fn validate(&self) -> std::result::Result<(), String> {
if self.email.contains('@') {
Ok(())
} else {
Err(format!("{:?} is not an email", self.email))
}
}
fn before_update(&self) -> rasterizeddb_client::Result<()> {
if self.frozen {
return Err(Error::Unsupported(format!("person {} is frozen", self.id)));
}
Ok(())
}
fn after_load(&mut self) {
self.domain = self.email.split('@').nth(1).unwrap_or("").to_string();
}
}| hook | runs | effect |
|---|---|---|
validate(&self) -> Result<(), String> | before every insert, upsert and update of a row, and for each row of insert_many and update_many | an Err is Error::Invalid and nothing is sent, not even the valid rows of a batch |
before_insert(&self) | before an insert (an upsert runs it and before_update) | any Err vetoes the write |
before_update(&self) | before an update | any Err vetoes the write |
before_delete(&self) | before a delete | any Err vetoes the write |
after_load(&mut self) | on every row the ORM reads into the model, the rows writes return included | adjust the struct |
Hooks are synchronous and run in your process. The bulk query().update() and query().delete() take no rows and run no hooks.
Partitioned tables
partition_by makes create_table (and a migrator's model sync) create the table hash-partitioned on one to three columns. They must be NOT NULL, and every primary and unique key must include them:
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "assets", partition_by = "tenant_id, group_id", partitions = 64)]
struct Asset {
#[rdb(primary_key)]
tenant_id: i64,
#[rdb(primary_key)]
group_id: i64,
#[rdb(primary_key)]
id: Uuid,
body: Option<String>,
}CREATE TABLE IF NOT EXISTS assets (…, PRIMARY KEY (tenant_id, group_id, id))
PARTITION BY HASH (tenant_id, group_id) PARTITIONS 64Everything else works on it unchanged: the server routes each row by its key, and a query that fixes the key reads one partition. Converting an existing plain table is a migrator option (Migrations); reshaping partitions is the administration API's job. See Partitioning.
Queries
Model::query() starts a SELECT of the model's rows. Narrow it and run it with a terminal call:
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "accounts")]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
email: String,
name: Option<String>,
visits: i64,
balance: Numeric,
}
async fn queries(db: &Client) -> Result<()> {
let page = Account::query()
.filter(Account::balance.gt(Numeric::new("10")?) & Account::name.is_not_null())
.filter(Account::email.like("%@example.com") | Account::id.is_in([1i64, 2, 3]))
.order_by(Account::visits.desc().nulls_last())
.limit(20)
.offset(40)
.all(db)
.await?;
let n: u64 = Account::query().filter(Account::visits.ge(100)).count(db).await?;
let ada: Account = Account::query().filter(Account::email.eq("ada@example.com")).one(db).await?;
let any: bool = Account::query().filter(Account::visits.eq(0)).exists(db).await?;
// What the builder cannot say, with parameters still escaped:
let raw = Account::query()
.filter(Expr::raw("lower(email) = $1", params!["ada@example.com"]))
.first(db)
.await?;
println!("{} {n} {ada:?} {any} {raw:?}", page.len());
Ok(())
}Successive filter calls are joined with AND.
Conditions
On a column constant (Account::email):
| method | SQL |
|---|---|
eq(v), ne(v), lt(v), le(v), gt(v), ge(v) | =, <>, <, <=, >, >= |
like(pattern), ilike(pattern) | LIKE, ILIKE |
between(low, high) | BETWEEN low AND high |
is_null(), is_not_null() | IS NULL, IS NOT NULL |
is_in(values), not_in(values) | IN (…), NOT IN (…), from any iterator of values |
asc(), desc() | an ordering, for order_by; then .nulls_first() or .nulls_last() |
Combining conditions (Expr):
| form | SQL |
|---|---|
a & b, a.and(b) | (a) AND (b) |
a | b, a.or(b) | (a) OR (b) |
!a, a.not() | NOT (a) |
Expr::all([a, b, c]), Expr::any([a, b, c]) | all of them, any of them |
Expr::raw(sql, params![…]) | your own SQL, with $n parameters rendered safely |
expr.to_sql() | the condition's SQL |
Values are written as safe literals, as for params!.
Terminal calls
| call | returns |
|---|---|
all(db) | Vec<M> |
first(db) | Option<M>: the first row in the query's order |
one(db) | M; no row or more than one is Error::RowCount |
count(db) | u64 |
exists(db) | bool |
page(db) | a keyset Page<M> (see Keyset pages and streams) |
stream(db, batch_size) | a RowStream |
delete(db) | u64 rows deleted (or marked, with soft delete) |
delete_returning(db) | Vec<M>: the rows deleted |
force_delete(db) | u64: a real DELETE with soft delete |
update() | a bulk-update builder (below) |
to_sql() | the SELECT it would send |
Each takes any executor (&Client, &Transaction), so query functions are generic:
use rasterizeddb_client::prelude::*;
#[derive(Model)]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
visits: i64,
}
async fn busiest<E: Executor>(db: &E) -> Result<Option<Account>> {
Account::query().order_by(Account::visits.desc()).first(db).await
}Bulk updates and deletes
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "accounts")]
struct Account {
#[rdb(primary_key, serial)]
id: i64,
name: Option<String>,
visits: i64,
}
async fn tidy(db: &Client) -> Result<()> {
let renamed: Vec<Account> = Account::query()
.filter(Account::name.is_null())
.update()
.set(Account::name, "anonymous")
.set_raw(Account::visits, "visits + $1", params![1])
.run(db)
.await?;
let removed: u64 = Account::query().filter(Account::visits.eq(0)).delete(db).await?;
// Every row, on purpose:
Account::query().every_row().update().set(Account::visits, 0i64).run(db).await?;
println!("{} {removed}", renamed.len());
Ok(())
}update() builds one UPDATE … RETURNING: set(column, value) assigns a value, set_raw(column, sql, params![…]) an expression; run(db) returns the rows as stored; to_sql() shows it. A bulk update or delete with no filter is refused unless you call every_row() first, so a forgotten filter cannot empty or rewrite a table.
Projections and aggregates
select reads chosen columns and aggregates instead of whole models. One item reads as its value, a tuple as a tuple; all_as reads each row into a #[derive(FromRow)] struct by position:
use rasterizeddb_client::prelude::*;
#[derive(Model)]
#[rdb(table = "sales")]
struct Sale {
#[rdb(primary_key)]
id: i64,
region: String,
units: i32,
amount: i64,
}
#[derive(FromRow, Debug)]
struct RegionTotal {
region: String,
sales: i64,
amount: Option<i64>,
}
async fn report(db: &Client) -> Result<()> {
let regions: Vec<String> = Sale::query().select(Sale::region).distinct().all(db).await?;
let (n, total, mean): (i64, Option<i64>, Option<Numeric>) = Sale::query()
.select((count_rows(), Sale::amount.sum(), Sale::units.avg()))
.one(db)
.await?;
let by_region: Vec<RegionTotal> = Sale::query()
.select((Sale::region, count_rows(), Sale::amount.sum()))
.group_by(Sale::region)
.having(count_rows::<Sale>().ge(10))
.order_by(Sale::amount.sum().desc())
.all_as(db)
.await?;
println!("{regions:?} {n} {total:?} {mean:?} {by_region:?}");
Ok(())
}On a projection: group_by(columns), having(expr), distinct(), order_by(order), limit(n), to_sql(), and the terminal calls all, first, one, all_as. Filters set before select apply.
| aggregate | reads as | over no rows |
|---|---|---|
count_rows(), col.count(), col.count_distinct() | i64 | 0 |
col.sum() over an integer column | Option<i64> (summed exactly, then cast to BIGINT) | None |
col.sum() over f32/f64; over Numeric | Option<f64>; Option<Numeric> | None |
col.avg() over an integer or Numeric column; over a float | Option<Numeric> (exact); Option<f64> | None |
col.min(), col.max() | Option<T> | None |
An aggregate also gives conditions (eq, ne, gt, ge, lt, le) for having, and orderings (asc, desc). A sum of integers past i64 is the server's error, never a wrapped number.
Keyset pages and streams
OFFSET pages make the server read the rows it skips, and shift when rows are added before them. A keyset page starts after a row's sort key instead. page(db) reads up to limit rows in the query's order and returns a Page with items, next_cursor and prev_cursor:
use rasterizeddb_client::orm::Cursor;
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug)]
#[rdb(table = "events")]
struct Event {
#[rdb(primary_key)]
id: i64,
kind: String,
at: Timestamp,
}
/// `after` is the cursor text a previous call handed to the caller.
async fn logins(db: &Client, after: Option<&str>) -> Result<(Vec<Event>, Option<String>)> {
let q = Event::query()
.filter(Event::kind.eq("login"))
.order_by(Event::at.desc())
.limit(50);
let page = match after {
Some(text) => q.after(&Cursor::decode(text)?).page(db).await?,
None => q.page(db).await?,
};
let next = page.next_cursor.map(|c| c.encode()).transpose()?;
Ok((page.items, next))
}- The sort key is the
ORDER BYcolumns, then the primary key (in the last column's direction) to break ties, so every row has one place. after(&cursor)reads the page after a cursor;before(&cursor)the page before it.- Sort keys must be
NOT NULLcolumns. A nullable key, anoffset, or an order by an expression is refused. Cursor::encode()gives an opaque, URL-safe string;Cursor::decode(text)reads one back. A decoded cursor is written into the next statement as escaped literals, so a client cannot smuggle SQL in through one.page.next_cursorisNoneon the last page,page.prev_cursoron the first.
stream(db, batch_size) reads every matching row in keyset batches, one statement each, so a table of any size is read without an answer past the message limit:
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug)]
#[rdb(table = "events")]
struct Event {
#[rdb(primary_key)]
id: i64,
at: Timestamp,
}
async fn export(db: &Client) -> Result<()> {
let mut rows = Event::query().order_by(Event::at.asc()).stream(db, 1000);
while let Some(event) = rows.next().await {
let event = event?;
println!("{} {}", event.id, event.at);
}
Ok(())
}next() yields one row at a time, next_batch() a whole batch. A RowStream is also a futures_core::Stream, so futures::StreamExt works on it. Each batch is its own statement: outside a transaction, a row written while the stream runs is seen or not depending on where it sorts.
The same struct in the cache
A model can also live in the server's key/value cache, as a hash per row, or the cache can sit in front of its table as a read-through cache (client.cached::<Account>(ttl), or Account::cached(&client, ttl)). See Key/value cache.
Limits
- One
referencesnames one column. A composite foreign key is written as SQL in a migration step. indexcreates a single-column index; a multi-column index is SQL in a migration step or the administration API.- The ORM has no
SELECT … FOR UPDATEcall; write it as SQL in a transaction (Transactions). - No joins in the query builder: load related rows with relations, or write the join as SQL and read it with
#[derive(FromRow)]. - Keyset pages need non-null sort columns.
insert_manyof more than 500 rows (or about 1 MiB) is several statements, atomic together only inside a transaction.