Expand description
§rok-db
An ergonomic, type-safe async ORM for PostgreSQL, built on sqlx.
use rok_db::prelude::*;
#[derive(Debug, Clone, Model)]
struct User {
#[rok(primary_key, generated)]
id: i64,
email: String,
name: Option<String>,
age: i32,
}
let db = Db::connect("postgres://postgres@localhost/app").await?;
// Create
let ann = User { id: 0, email: "ann@example.com".into(), name: None, age: 31 }
.insert(&db)
.await?;
// Read with typed, model-scoped columns
let adults = User::filter(User::AGE.gte(18))
.filter(User::EMAIL.ends_with("@example.com"))
.order_by(User::AGE.desc())
.limit(10)
.all(&db)
.await?;
// Update
let mut ann = User::find_or_fail(&db, ann.id).await?;
ann.name = Some("Ann".into());
let ann = ann.save(&db).await?;
// Bulk update & delete
User::filter(User::AGE.lt(18)).update().set(User::NAME, None::<String>).exec(&db).await?;
User::filter(User::EMAIL.is_null()).delete(&db).await?;
// Pagination (one round trip)
let page = User::order_by(User::ID).paginate(&db, 1, 20).await?;
println!("{} of {} users", page.len(), page.total);
// Transactions
db.transaction(|tx| Box::pin(async move {
ann.delete(&mut *tx).await?;
Ok::<_, rok_db::Error>(())
})).await?;§Defining models
#[derive(Model)] implements Model and sqlx::FromRow, and adds one
typed Column constant per field (User::EMAIL, …). See
Model for every attribute.
§Relations
#[rok(belongs_to = User)], #[rok(has_many(posts = Post::USER_ID))] and
#[rok(has_one(..))] generate relation constants (BelongsTo,
HasMany, HasOne) and lazy query methods. Eager-load related
records for many parents with one extra query: see relation.
§More features
- Streaming:
Select::streamyields rows one at a time. - Aggregates & projections:
Select::sum,Select::avg,Select::group_by,Select::havingandSelect::selectwithProjections, decoded into tuples orFromRowstructs. - Timestamps:
#[rok(timestamps)]managescreated_at/updated_at. - Keyset pagination:
Select::cursor_paginatewith opaqueCursors. - Soft deletes:
#[rok(soft_delete)],Select::with_trashed,Model::restore,Model::force_delete. - Optimistic locking:
#[rok(version)]; stale writes fail withError::Conflict. - Upserts:
Model::upsert_on,Model::insert_manyandInsert::on_conflictwithdo_nothing/do_update/do_update_all. - Subqueries:
Column::in_subquery,Expr::existsandColumn::eq_outerfor correlation. - Custom column types:
DbEnum,DbNewtypeandimpl_value!. - Validation & hooks:
#[rok(validate(…))]rules (validate) and theHookstrait. - Scopes:
#[rok(default_scope = …)],Select::scope,Select::unscoped. - Retrying transactions:
Db::transaction_withwithTxOptions. - Change tracking:
Model::track/TrackedandModel::save_only. - Bulk loading:
Model::copy_inwith binaryCOPY. - Web & metrics: the
webmodule (serde,axumfeatures) andmetrics(metricsfeature). - PostgreSQL types: arrays (
Vec<T>fields,Column::array_has,Column::eq_any), JSONB (Column::json_text,Column::json_has_key) and full-text search (Column::search,Column::search_rank). - Read replicas:
DbBuilder::read_replica,Select::on_primary,Db::primary. - LISTEN/NOTIFY:
Db::listen,Db::notifyand model change feeds (Model::changes, seenotify). - Multi-instance caching:
DbBuilder::shared_cache_invalidation. - Multi-tenancy:
#[rok(tenant)]andtenant::with_tenant. - Audit log (feature
json): theauditmodule. - Joins:
Select::join/Select::left_joinwith compile-time checked columns across models (seejoin). - Composite primary keys: several
#[rok(primary_key)]fields; look records up with tuples (IntoKey). - Memoization:
Select::memoizecaches results in the pool’sQueryCachewith automatic invalidation on writes. - Query logging: every statement is logged through
tracing(rok_db::queryat DEBUG,rok_db::slow_queryat WARN; seeDbBuilder::slow_query_threshold).
§Executors
Every query method accepts any Executor: &Db, &mut Tx (write
&mut *tx inside a transaction closure), or a plain sqlx &PgPool /
&mut PgConnection — so rok-db slots into existing sqlx code.
§Raw SQL
When the builder isn’t enough, raw() runs any SQL with ? placeholders
and decodes into models or any FromRow type; Expr::raw embeds a raw
condition in a builder query. Every builder has a to_sql() method for
inspecting the generated statement.
§Cargo features
| feature | enables |
|---|---|
chrono | chrono date/time column types |
uuid | uuid::Uuid columns |
json | serde_json::Value and sqlx::types::Json<T> columns |
migrate | Db::migrate for running sqlx migrations |
testing | test and testing::TestDb: a temporary database per test |
serde | Serialize for pages, cursors and validation errors |
axum | Error implements axum’s IntoResponse (implies serde) |
metrics | query, cache and pool metrics, see metrics |
full | all of the above except testing |
Modules§
- audit
- A trigger-based audit log (feature
json): every insert, update and delete of an audited table — through rok-db, bulk queries or raw SQL — is recorded inrok_audit_logwith the old and new row as JSONB. - join
- Typed joins (RFC 0001).
- metrics
- Metrics through the
metricsfacade (featuremetrics). Install any recorder (Prometheus, StatsD, OpenTelemetry, …) and rok-db reports: - migration
- Versioned migrations embedded in Rust code.
- notify
- PostgreSQL
LISTEN/NOTIFY, and typed change feeds for models. - prelude
- Everything you need for day-to-day use:
use rok_db::prelude::*; - relation
- Relations between models, declared with
#[derive(Model)]attributes. The parent model must have a single-column primary key. - sqlx
- The sqlx crate rok-db is built on, re-exported for advanced use. The async SQL toolkit for Rust, built with ❤️ by the LaunchBadge team.
- tenant
- Row-level multi-tenancy for models with a
#[rok(tenant)]column. - testing
- Test support: a fresh, isolated database per test (feature
testing). - validate
- Validation of model fields, run automatically before
insert,save,upsertandinsert_many. - web
- Web integration: serde support (feature
serde) and axum responses (featureaxum).
Macros§
- impl_
value - Make a type usable as a rok-db column value (in models, filters and
set), given that it already implements sqlx’sTypeandEncodefor PostgreSQL plusClone + Debug. ImplementsCustomTypeandFrom<T>/From<&T>forValue(Option<T>then works too).
Structs§
- Belongs
To Cbelongs toPthrough the foreign key columnC.fk → P.pk.- Cache
Stats - Counters describing how a
QueryCacheis performing. - Change
- One row change of model
M. - Change
Stream - Row changes of model
M, fromModel::changes. - Column
- A column of model
M. - Cursor
- An opaque position in a keyset-paginated result, returned by
Select::cursor_paginate. - Cursor
Page - One page of a keyset-paginated query.
- Custom
Value - A value of a user-defined type; see
Value::custom. - Db
- A pooled PostgreSQL connection handle — the entry point of rok-db.
- DbBuilder
- Builder for a
Dbconnection pool, created withDb::builder. - Expr
- A boolean condition on model
M, used inWHEREclauses. - HasMany
Phas manyCthrough the foreign key columnC.fk → P.pk.- HasOne
Phas at most oneCthrough the foreign key columnC.fk → P.pk.- Insert
- An
INSERTof a single row built column by column, created withModel::create. Columns you don’t set get their database default; timestamp columns default tonow(). - Insert
Many - An
INSERTof whole records, created withModel::insert_many. Generated columns are skipped and timestamps are set tonow(). - JoinOn
- An ad-hoc join condition
to = from, created withColumn::on. - Joined
- A
SELECTover root modelMwith joined modelsJ, created withSelect::joinorSelect::left_join. See the module docs. - Listener
- A dedicated connection listening on one or more channels, created with
Db::listen. It reconnects automatically if the connection drops (notifications sent meanwhile are lost). - Memoized
- A
Selectwhose results are cached, created withSelect::memoize. - Notification
- A message received on a channel.
- Order
- An
ORDER BYterm on modelM, created withColumn::ascorColumn::desc. - Page
- One page of results, returned by
Select::paginate. - Pool
Stats - Connection pool statistics, from
Db::stats. - Projected
- A
SELECTof specific columns or aggregates, created withSelect::select. Decode rows into tuples or anysqlx::FromRowtype. - Projection
- A value expression of model
Mthat can be selected: a column, an aggregate (User::AGE.avg()), a cast or raw SQL. - Query
Cache - An in-memory cache for memoized query results.
- Raw
- A raw SQL query with bound parameters, created with
raw. - Select
- A
SELECTquery over modelM, created withModel::queryorModel::filter. - Sql
- A rendered SQL statement together with its bound parameters.
- Tracked
- A record that remembers its loaded values, so
savewrites only the columns you changed — or nothing at all. - Tx
- An open database transaction, created with
Db::begin. - TxOptions
- Settings for
Db::transaction_with. - Update
- A bulk
UPDATEover modelM, created withModel::update_allorSelect::update. - Validation
Errors - Every validation failure of a record.
Enums§
- Change
Op - The kind of change reported by a
ChangeStream. - Copy
Target - Where
Model::copy_inruns: a pool (one connection is borrowed), a transaction or a plain connection. - Direction
- Sort direction for
ORDER BY. - Error
- Every error rok-db can produce.
- Isolation
- Transaction isolation level, see
TxOptions::isolation. - Value
- A dynamically typed, bindable SQL value.
Traits§
- Custom
Type - Marker for user-defined column types stored through
Value::custom. - Executor
- Anything that can run a query:
&Db,&mut Tx, a plain sqlx&PgPoolor&mut PgConnection. - Hooks
- Lifecycle hooks, called around the record-level writes of
Model(insert,insert_all/insert_many,upsert,save,delete,force_delete). Bulk query operations (Select::update,Select::delete, …) don’t call hooks. - InScope
Selfis the root or one of the joined models of the query scopeS((Root, Joins), withJoins=()or(EarlierJoins, Model)).- Into
Join - Something that can be joined: a relation constant or
ColumnA.on(ColumnB). - IntoKey
- A primary key value: a single value, or a tuple for models with a
composite primary key (
#[rok(primary_key)]on several fields). - Into
Projections - A list of
Projections: a single column or projection, a tuple of up to 12 of them, an array or aVec. - Model
- A database-backed record.
- Retryable
- Errors that can tell whether retrying the transaction might succeed.
Implemented for
Error; implement it for your own error type (usually by delegating to a wrappedrok_db::Error) to use it withDb::transaction_with. - Stream
Ext - Extension traits for consuming streams (
try_next,try_collect, …). An extension trait forStreams that provides a variety of convenient combinator functions. - TryStream
Ext - Extension traits for consuming streams (
try_next,try_collect, …). Adapters specific toResult-returning streams
Functions§
- raw
- Start a raw SQL query — the escape hatch for anything the query builder doesn’t express.
Type Aliases§
- BoxFuture
- A boxed
Sendfuture, as returned byDb::transactionclosures. An owned dynamically typedFuturefor use in cases where you can’t statically type your result or need to add some indirection. - BoxStream
- A boxed
Sendstream, as returned bySelect::stream. An owned dynamically typedStreamfor use in cases where you can’t statically type your result or need to add some indirection. - Result
- Convenient alias for results returned by rok-db.
Attribute Macros§
- test
- Run an async test against a fresh, temporary database (feature
testing). Run an async test against a fresh, temporary database (featuretesting). The database is created on the server named byDATABASE_URL, passed in as aDb, and dropped afterwards — even if the test panics. WithoutDATABASE_URLthe test is skipped.
Derive Macros§
- DbEnum
- Derive a column type for a field-less enum (stored as
TEXTor a PostgreSQL enum). Derive a column type for a field-less enum, stored asTEXT(default) or as a native PostgreSQL enum. - DbNewtype
- Derive a column type for a single-field tuple struct. Derive a column type for a single-field tuple struct (a “newtype”), stored exactly like its inner type:
- FromRow
- Derive
sqlx::FromRowfor a plain struct, without depending on sqlx. Derivesqlx::FromRowfor decoding query results into a plain struct, e.g. the output ofSelect::selectwith aliased projections — without depending on sqlx directly. - Model
- Derive
Modelfor a struct. See the crate docs for an example. Deriverok_db::Model(andsqlx::FromRow) for a struct with named fields.