rok-db 0.1.0

An ergonomic, type-safe async ORM for PostgreSQL built on sqlx
Documentation

rok-db

CI License: MIT OR Apache-2.0 MSRV 1.85

An ergonomic, type-safe async ORM for PostgreSQL, built on sqlx.

  • One derive — #[derive(Model)] gives you CRUD, a FromRow impl and typed column constants.
  • Typed, model-scoped columns — User::EMAIL.eq(..) can't be used to filter Posts, and typos are compile errors.
  • One executor story — every method accepts &Db, &mut Tx, &PgPool or &mut PgConnection.
  • Send futures everywhere — works in tokio::spawn, axum handlers, etc.
  • Relations without N+1 — belongs_to, has_many, has_one with 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

[dependencies]

rok-db = { git = "https://github.com/ateeq1999/rok-db", features = ["chrono", "uuid", "json"] }

tokio = { version = "1", features = ["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 rok_db::prelude::*;

#[derive(Debug, Clone, Model)]          // table: "users"
struct User {
    #[rok(primary_key, generated)]      // BIGSERIAL, filled in by Postgres
    id: i64,
    email: String,
    name: Option<String>,
    age: i32,
}

#[tokio::main]
async fn main() -> rok_db::Result<()> {
    let db = Db::connect_env().await?;  // reads DATABASE_URL

    // Create
    let ann = User { id: 0, email: "ann@example.com".into(), name: None, age: 31 }
        .insert(&db)
        .await?;

    // Read
    let user = User::find_or_fail(&db, ann.id).await?;
    let adults = User::filter(User::AGE.gte(18))
        .filter(User::NAME.is_not_null().or(User::EMAIL.ends_with("@example.com")))
        .order_by(User::AGE.desc())
        .limit(10)
        .all(&db)
        .await?;

    // Update
    let mut user = user;
    user.name = Some("Ann".into());
    let user = user.save(&db).await?;

    // Delete
    user.delete(&db).await?;
    Ok(())
}

Defining models

#[derive(Model)]
#[rok(table = "app.blog_posts")]        // default: snake_case plural of the struct name
struct Post {
    #[rok(primary_key)]                 // default: the field named `id`
    slug: String,
    #[rok(column = "author_id")]        // column name differs from the field
    author: i64,
    #[rok(generated)]                   // DB default / trigger: read but never written
    created_at: chrono::DateTime<chrono::Utc>,
    #[rok(skip)]                        // not a column; Default::default() on load
    rendered_html: String,
}

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

#[derive(Model)]
#[rok(has_many(posts = Post::USER_ID))]
struct User { id: i64, name: String }

#[derive(Model)]
struct Post {
    id: i64,
    #[rok(belongs_to = User)]
    user_id: i64,
    title: String,
}

// Lazy: a query you can refine
let recent = user.posts().order_by(Post::ID.desc()).limit(5).all(&db).await?;
let author = post.user().one(&db).await?;

// Eager: one extra query for any number of records (no N+1)
let users = User::all(&db).await?;
let posts = User::POSTS.load(&db, &users).await?;
for user in &users {
    println!("{}: {} posts", user.name, posts.get(user).len());
}
let authors = Post::USER.load(&db, &recent).await?;   // `authors.get(&post)`

Streaming

use rok_db::prelude::*; // brings `try_next`, `try_collect`, … into scope

let mut users = User::query().stream(&db);
while let Some(user) = users.try_next().await? {
    // rows arrive one at a time; memory stays flat
}

Aggregates and projections

let total: Option<i64> = Post::query().sum(&db, Post::VIEWS).await?;
let avg_age: Option<f64> = User::query().avg(&db, User::AGE).await?;
let oldest: Option<i32> = User::query().max(&db, User::AGE).await?;

// GROUP BY / HAVING into tuples…
let per_author: Vec<(i64, i64)> = Post::query()
    .group_by(Post::USER_ID)
    .having(Projection::count_all().gte(10))
    .select((Post::USER_ID, Projection::count_all()))
    .fetch_all(&db)
    .await?;

// …or into your own structs
#[derive(rok_db::FromRow)]
struct RoleStats { role: String, users: i64 }

let stats: Vec<RoleStats> = User::query()
    .group_by(User::ROLE)
    .select((User::ROLE, Projection::count_all().alias("users")))
    .fetch_all(&db)
    .await?;

Aggregates: count, count_distinct, sum, avg, min, max, plus .cast("BIGINT") and Projection::raw(..).

Timestamps

#[derive(Model)]
#[rok(timestamps)]
struct Note {
    id: i64,
    body: String,
    created_at: chrono::DateTime<chrono::Utc>,   // set to now() on insert
    updated_at: chrono::DateTime<chrono::Utc>,   // set to now() on insert and every update
}

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 = Db::builder().query_cache(10_000).connect(url).await?;

let admins = User::filter(User::ROLE.eq("admin"))
    .memoize(Duration::from_secs(60))
    .all(&db)                       // 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), memoize simply 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 = Db::builder().slow_query_threshold(Duration::from_millis(200)).connect(url).await?;
// e.g. RUST_LOG=rok_db=debug with tracing-subscriber's EnvFilter

Transactions

let user = db.transaction(|tx| Box::pin(async move {
    let user = new_user.insert(&mut *tx).await?;
    Profile::create().set(Profile::USER_ID, user.id).exec(&mut *tx).await?;
    Ok::<_, rok_db::Error>(user)
})).await?;                              // commits on Ok, rolls back on Err

let mut tx = db.begin().await?;          // or manage it yourself
User::filter(User::ID.eq(1)).for_update().one(&mut *tx).await?;
tx.commit().await?;

Raw SQL

let users: Vec<User> = rok_db::raw("SELECT * FROM users WHERE age > ? AND email ILIKE ?")
    .bind(18)
    .bind("%@example.com")
    .fetch_all(&db)
    .await?;

let total: i64 = rok_db::raw("SELECT COUNT(*) FROM users").scalar(&db).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

cargo test --workspace --all-features          # SQL-generation tests run everywhere

DATABASE_URL=postgres://postgres:postgres@localhost/rok_db_test \

  cargo test --workspace --all-features        # plus end-to-end tests against Postgres

cargo run -p rok-db --example blog             # needs DATABASE_URL

Database tests use per-connection TEMP tables, so they never touch existing data.

License

Licensed under either of

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.