rok-db
An ergonomic, type-safe async ORM for PostgreSQL, built on sqlx.
- One derive —
#[derive(Model)]gives you CRUD, aFromRowimpl and typed column constants. - Typed, model-scoped columns —
User::EMAIL.eq(..)can't be used to filterPosts, and typos are compile errors. - One executor story — every method accepts
&Db,&mut Tx,&PgPoolor&mut PgConnection. Sendfutures everywhere — works intokio::spawn, axum handlers, etc.- Relations without N+1 —
belongs_to,has_many,has_onewith batched eager loading. - Batteries included — streaming, aggregates and projections, automatic timestamps, memoized (cached) queries and structured query logging.
- Escape hatches —
Expr::raw,rok_db::raw(..),to_sql()on every builder, and full access to sqlx.
Install
[]
= { = "https://github.com/ateeq1999/rok-db", = ["chrono", "uuid", "json"] }
= { = "1", = ["macros", "rt-multi-thread"] }
| feature | enables |
|---|---|
chrono |
DateTime<Utc>, NaiveDateTime, NaiveDate, NaiveTime |
uuid |
Uuid columns |
json |
serde_json::Value and Json<T> columns |
migrate |
Db::migrate("./migrations") |
full |
all of the above |
Quick start
use *;
// table: "users"
async
Defining models
// default: snake_case plural of the struct name
Every column gets a constant named after its field: Post::SLUG, Post::AUTHOR, Post::CREATED_AT.
| Attribute | On | Meaning |
|---|---|---|
table = "name" |
struct | table name (default: snake_case plural) |
timestamps |
struct | manage created_at / updated_at automatically |
has_many(posts = Post::USER_ID) |
struct | one-to-many relation → User::POSTS, user.posts() |
has_one(profile = Profile::USER_ID) |
struct | one-to-one relation → User::PROFILE, user.profile() |
primary_key |
field | primary key (default: id) |
generated |
field | filled in by the database; never written |
column = "name" |
field | column name differs from the field |
skip |
field | not a column |
created_at / updated_at |
field | managed timestamp with a custom name |
belongs_to = User |
field | user_id → Post::USER, post.user() (or belongs_to(author = User)) |
API overview
On the model (User::…) |
|
|---|---|
query(), filter(expr), order_by(col) |
start a SELECT |
find(db, id) / find_or_fail(db, id) / find_many(db, ids) |
by primary key |
all(db), count(db) |
whole table |
create().set(col, v)….exec(db) |
insert column by column |
insert_all(db, &records) |
multi-row insert, returns stored rows |
update_all().filter(..).set(..).exec(db) |
bulk update |
On a record (user.…) |
|
|---|---|
insert(db) |
insert (skipping generated columns), returns stored row |
save(db) |
update by primary key, returns stored row |
upsert(db) |
INSERT … ON CONFLICT (pk) DO UPDATE |
delete(db) |
delete by primary key |
reload(db) |
re-read from the database |
On a query (Select) |
|
|---|---|
filter, filter_opt, filter_if |
WHERE (combined with AND) |
order_by, limit, offset, for_update, for_share |
|
all, first, one, count, exists |
run it |
paginate(db, page, per_page) |
Page<T> with total, total_pages(), has_next() — one round trip |
update().set(..)/increment(..)/set_raw(..) |
turn into a bulk UPDATE |
delete(db) |
bulk DELETE |
stream(db) |
rows one at a time |
sum, avg, min, max |
aggregates over the matching rows |
group_by, having, select(..) |
projections and grouped aggregates |
memoize(ttl) |
cache the result (see below) |
to_sql() |
inspect the generated SQL and parameters |
Column operators: eq ne gt gte lt lte like not_like ilike contains starts_with ends_with is_in not_in between is_null is_not_null asc desc.
Combine expressions with .and(..), .or(..), !expr, Expr::all_of(..), Expr::any_of(..), or Expr::raw("lower(email) = ?", [v]).
Relations
// Lazy: a query you can refine
let recent = user.posts.order_by.limit.all.await?;
let author = post.user.one.await?;
// Eager: one extra query for any number of records (no N+1)
let users = all.await?;
let posts = POSTS.load.await?;
for user in &users
let authors = USER.load.await?; // `authors.get(&post)`
Streaming
use *; // brings `try_next`, `try_collect`, … into scope
let mut users = query.stream;
while let Some = users.try_next.await?
Aggregates and projections
let total: = query.sum.await?;
let avg_age: = query.avg.await?;
let oldest: = query.max.await?;
// GROUP BY / HAVING into tuples…
let per_author: = query
.group_by
.having
.select
.fetch_all
.await?;
// …or into your own structs
let stats: = query
.group_by
.select
.fetch_all
.await?;
Aggregates: count, count_distinct, sum, avg, min, max, plus .cast("BIGINT") and
Projection::raw(..).
Timestamps
The database clock is used (now()), so values are consistent across servers. Bulk updates
set updated_at too, unless you set it yourself.
Memoized queries
Cache read results in memory, with automatic invalidation:
let db = builder.query_cache.connect.await?;
let admins = filter
.memoize
.all // also: first, one, count, exists, paginate
.await?;
db.cache.unwrap.stats; // hits, misses, entries
- Entries expire after their TTL and are keyed by the exact SQL and parameters.
- Any write rok-db makes to a table (insert, save, upsert, delete, bulk update/delete — in transactions too, and again on commit) invalidates that table's cached results.
- Writes rok-db can't see (other services, raw SQL, cascades and triggers on other tables) need
raw(..).invalidates("users"),cache.invalidate("users"), or a short TTL. - Without a configured cache (or with a plain sqlx pool),
memoizesimply runs the query.
Query logging
Every statement is logged through tracing:
| target | level | content |
|---|---|---|
rok_db::query |
DEBUG |
SQL, elapsed time, row count; failures with the error |
rok_db::query |
TRACE |
bound parameter values (may contain sensitive data) |
rok_db::slow_query |
WARN |
queries slower than the threshold (default 1s) |
rok_db::cache |
DEBUG |
memoized cache hits |
let db = builder.slow_query_threshold.connect.await?;
// e.g. RUST_LOG=rok_db=debug with tracing-subscriber's EnvFilter
Transactions
let user = db.transaction.await?; // commits on Ok, rolls back on Err
let mut tx = db.begin.await?; // or manage it yourself
filter.for_update.one.await?;
tx.commit.await?;
Raw SQL
let users: = raw
.bind
.bind
.fetch_all
.await?;
let total: i64 = raw.scalar.await?;
Errors
rok_db::Error has helpers for the common cases: is_not_found(), is_unique_violation(), is_foreign_key_violation() and constraint().
Crates
| crate | |
|---|---|
rok-db |
the crate to depend on: re-exports everything plus the derive |
rok-db-core |
runtime: Db, Model, query builders, Value |
rok-db-macros |
#[derive(Model)] |
Contributing
Contributions are welcome! Start with CONTRIBUTING.md for setup, the change protocol and commit conventions. Larger changes go through the RFC process; see GOVERNANCE.md for how decisions are made. Please report security issues privately as described in SECURITY.md. Everyone is expected to follow the Code of Conduct. Notable changes are listed in the changelog.
Development
DATABASE_URL=postgres://postgres:postgres@localhost/rok_db_test \
Database tests use per-connection TEMP tables, so they never touch existing data.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.