Skip to main content

Crate rok_db

Crate rok_db 

Source
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

§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

featureenables
chronochrono date/time column types
uuiduuid::Uuid columns
jsonserde_json::Value and sqlx::types::Json<T> columns
migrateDb::migrate for running sqlx migrations
testingtest and testing::TestDb: a temporary database per test
serdeSerialize for pages, cursors and validation errors
axumError implements axum’s IntoResponse (implies serde)
metricsquery, cache and pool metrics, see metrics
fullall 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 in rok_audit_log with the old and new row as JSONB.
join
Typed joins (RFC 0001).
metrics
Metrics through the metrics facade (feature metrics). 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, upsert and insert_many.
web
Web integration: serde support (feature serde) and axum responses (feature axum).

Macros§

impl_value
Make a type usable as a rok-db column value (in models, filters and set), given that it already implements sqlx’s Type and Encode for PostgreSQL plus Clone + Debug. Implements CustomType and From<T> / From<&T> for Value (Option<T> then works too).

Structs§

BelongsTo
C belongs to P through the foreign key column C.fk → P.pk.
CacheStats
Counters describing how a QueryCache is performing.
Change
One row change of model M.
ChangeStream
Row changes of model M, from Model::changes.
Column
A column of model M.
Cursor
An opaque position in a keyset-paginated result, returned by Select::cursor_paginate.
CursorPage
One page of a keyset-paginated query.
CustomValue
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 Db connection pool, created with Db::builder.
Expr
A boolean condition on model M, used in WHERE clauses.
HasMany
P has many C through the foreign key column C.fk → P.pk.
HasOne
P has at most one C through the foreign key column C.fk → P.pk.
Insert
An INSERT of a single row built column by column, created with Model::create. Columns you don’t set get their database default; timestamp columns default to now().
InsertMany
An INSERT of whole records, created with Model::insert_many. Generated columns are skipped and timestamps are set to now().
JoinOn
An ad-hoc join condition to = from, created with Column::on.
Joined
A SELECT over root model M with joined models J, created with Select::join or Select::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 Select whose results are cached, created with Select::memoize.
Notification
A message received on a channel.
Order
An ORDER BY term on model M, created with Column::asc or Column::desc.
Page
One page of results, returned by Select::paginate.
PoolStats
Connection pool statistics, from Db::stats.
Projected
A SELECT of specific columns or aggregates, created with Select::select. Decode rows into tuples or any sqlx::FromRow type.
Projection
A value expression of model M that can be selected: a column, an aggregate (User::AGE.avg()), a cast or raw SQL.
QueryCache
An in-memory cache for memoized query results.
Raw
A raw SQL query with bound parameters, created with raw.
Select
A SELECT query over model M, created with Model::query or Model::filter.
Sql
A rendered SQL statement together with its bound parameters.
Tracked
A record that remembers its loaded values, so save writes 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 UPDATE over model M, created with Model::update_all or Select::update.
ValidationErrors
Every validation failure of a record.

Enums§

ChangeOp
The kind of change reported by a ChangeStream.
CopyTarget
Where Model::copy_in runs: 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§

CustomType
Marker for user-defined column types stored through Value::custom.
Executor
Anything that can run a query: &Db, &mut Tx, a plain sqlx &PgPool or &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
Self is the root or one of the joined models of the query scope S ((Root, Joins), with Joins = () or (EarlierJoins, Model)).
IntoJoin
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).
IntoProjections
A list of Projections: a single column or projection, a tuple of up to 12 of them, an array or a Vec.
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 wrapped rok_db::Error) to use it with Db::transaction_with.
StreamExt
Extension traits for consuming streams (try_next, try_collect, …). An extension trait for Streams that provides a variety of convenient combinator functions.
TryStreamExt
Extension traits for consuming streams (try_next, try_collect, …). Adapters specific to Result-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 Send future, as returned by Db::transaction closures. An owned dynamically typed Future for use in cases where you can’t statically type your result or need to add some indirection.
BoxStream
A boxed Send stream, as returned by Select::stream. An owned dynamically typed Stream for 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 (feature testing). The database is created on the server named by DATABASE_URL, passed in as a Db, and dropped afterwards — even if the test panics. Without DATABASE_URL the test is skipped.

Derive Macros§

DbEnum
Derive a column type for a field-less enum (stored as TEXT or a PostgreSQL enum). Derive a column type for a field-less enum, stored as TEXT (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::FromRow for a plain struct, without depending on sqlx. Derive sqlx::FromRow for decoding query results into a plain struct, e.g. the output of Select::select with aliased projections — without depending on sqlx directly.
Model
Derive Model for a struct. See the crate docs for an example. Derive rok_db::Model (and sqlx::FromRow) for a struct with named fields.