Important
This page describes the v13 prerelease source, and its dependency examples pin the published
13.0.0-rc.1exactly: Cargo never selects a prerelease on its own, and a plain"13.0.0-rc.1"would also accept later prereleases (see the v13 migration guide). The v12 line (rullst-orm@12) reached end of life on 16 October 2026; see the release record. Use a path dependency only for checkout-local review.
🚀 Visit the Official Website & Documentation Hub 🚀
Built on top of sqlx and procedural macros, Rullst ORM brings the delightful, fluent syntax of Active Record frameworks directly to the high-performance Rust ecosystem.
🛡️ Security Engineering
Rullst ORM uses SQLx bindings, validated identifiers, typed errors, and layered CI checks. Workflow badges are scoped test results, not a guarantee for an application or deployment.
🚀 Why Rullst ORM?
Rullst ORM generates Active Record operations and a fluent query builder from
#[derive(Orm)]. SQLx remains available for queries that do not fit the
generated API. Both work with SQLite, PostgreSQL and MySQL/MariaDB; Turso/libSQL
and the side stores have their own APIs, as
Database Support lists.
Key Features:
- Generated CRUD: Insert, update, delete, restore, and find operations for
supported model shapes.
restore()andforce_delete()use the same savepoint, hook/observer, audit and post-commit cache/event/Scout pipeline asdelete()/save(); see Active Record CRUD. - Fluent Query Builder: Chain methods such as
.where_eq(),.limit(), and.order_by(); values are bound and structural identifiers are validated. - Relationships and eager loading:
has_many,has_one,belongs_to, and polymorphic relationship helpers, with explicit eager-load methods. - Opt-in tenant scope:
#[orm(tenant_column = "account_id")]adds the configured task-local tenant to generated model queries. Applications must establish the tenant context at their authenticated boundary. - Actor-bound audit revisions:
#[orm(auditable)]requires a validated user/service/systemAuditContext; the active tenant and optional correlation ID are recorded with recursively redacted bounded changes. Generated instance saves/deletes/restores/force-deletes and their audit entry share a savepoint and fail together. Eligible v2 updates expose guarded revision restoration, which rejects stale, cross-tenant, redacted, malformed, legacy, create/delete, and oversized revisions and records a compensating audit entry. The host still derives authenticated principal/tenant authority, while bulk per-row history and durable export remain explicit. See Auditable Revisions. - Field privacy:
#[orm(encrypted)]transparently encrypts supportedStringfields with a versioned AES-256-GCM envelope. Randomized ciphertext cannot be filtered or sorted; use a separate keyed blind index where needed. Encrypted and#[orm(masked)]values appear as"***"in generatedto_json(), audit rows and committed events, are omitted from Scout documents, and stay encrypted insave_to_redishashes.SecretStringfields are redacted the same way, andSecretStringserializes as an encrypted envelope rather than plaintext.RULLST_ENCRYPTION_KEY(and its_KEY_ID/_KEYRINGcompanions) is read from the process environment, then from./.env; see field encryption. - Native relational enums:
#[derive(Enum)]owns one closed label mapping for SQLx, Serde and ORM values.Blueprint::native_enumemits a named, drift-checked PostgreSQL type withstrict-postgres, inline MySQL/MariaDBENUM, or a SQLiteTEXT CHECKconstraint. - Scout hooks and providers:
#[orm(searchable)]calls a configuredSearchEngineafter generated writes/deletes.scout-httpsupplies bounded Meilisearch, Elasticsearch and Algolia adapters; the generated effect is process-local unless the application composes the transactional outbox. See Scout Search Providers. - Typed pgvector queries:
pgvectorre-exportsVectorwith SQLx support; vector/distance values in L2, cosine and inner-product helpers are bound, not interpolated. The strict PostgreSQL matrix creates the extension and runs a typed live lifecycle. See RAG Systems & Vector Search. - Generated embeddings:
aiimpliespgvectorand addssave_with_embedding(&rullst_ai::AiClient)to models with an#[orm(embedding_for = "...")]field; the application must also depend onrullst-ai. - Qdrant: the adapter was removed in 13.0.0-alpha.5; the
Qdrant recipe uses the official
qdrant-clientcrate in the application. - Native Redis structures:
redisadds an immutable namespace and bounded Hash, Set and Sorted Set operations in addition to.remember; remote endpoints require TLS and live evidence covers isolation and native commands. - Portable document recovery: SurrealDB and the deterministic store expose identifier-preserving inventory (an application’s own store, such as the MongoDB recipe’s, can too). An application-operated, AES-256-GCM snapshot binds application/collection scope, compares two bounded source observations, resumes only into an exact destination subset and verifies the final inventory. Writers, schema provisioning, key custody and durable backup storage remain explicit operator responsibilities. See Polyglot Persistence.
- Structured telemetry: generated/raw query and stream spans expose only static model/table/operation metadata, managed transactions record bounded outcomes, and Rullst-created pools emit checkout timing. Core’s opt-in OpenTelemetry layer can export the standard tracing signals; subscriber, sampling, collector and separately configured SQLx logs remain host policy.
- Comparative SQLite evidence: a lockfile-pinned Criterion harness gives Rullst, Diesel and SeaORM one typed connection, the same indexed schema, 100-row seed, SQLite policy and five logical operations. The CI history is scoped comparison evidence; it does not claim universal or negligible overhead, networked-database throughput or complete-application performance.
- Durable opt-in outbox:
Outbox::enqueuecommits a stream-scoped, idempotent event with relational domain state. Exact lease tokens, bounded retry and dead-letter are shared by SQLite, PostgreSQL, MySQL and MariaDB, and streams and event keys are case-sensitive on all of them. Delivery is at least once, so the application dispatcher and consumer remain idempotent; generated observers are not silently converted into events. A nestedOrm::transactionjoins the active transaction through a savepoint, so a helper that enqueues inside its own transaction stays atomic with its caller. Concurrent sibling nested transactions take turns on the shared connection, and a savepoint left open makes the enclosing transaction roll back instead of committing. See the transactional outbox tutorial. - Database-first introspection:
cargo rullst generate:modelsreads SQLite, PostgreSQL, or MySQL metadata using bound schema/table parameters, normalizes table module identifiers, and rejects unsafe SQL identifiers, collisions, or columns requiring unsupported ORM remapping before writing files. - Additive migration generation:
make:migration:autocompares supported model definitions and emits a migration for review. - Cascading soft deletes: Opt-in relationship metadata can cascade through
generated delete methods; transaction-aware variants use the supplied
transaction. The related model must also use soft deletes; a cascade into a
model without them fails to compile instead of hard-deleting its rows. The
children are selected within the tenant scope but outside the related
model’s
global_scope. - Transactional partial updates (v13 candidate):
.update_partial()merges selected values into a fresh row and performs its full save lifecycle, with explicit transaction support. Use it instead ofsave(), which writes the whole row, when requests may edit the same row at the same time; see concurrent updates and counters and the contract and migration. - Model policies:
#[orm(policy = "MyPolicy")]invokes the configured policy on generated create/update/delete/restore operations. - Strict lazy-loading prevention: the global toggle makes generated lazy relationship methods return a validation error instead of performing the query.
- Explicit Capability Boundaries: Unsupported replication paths fail closed instead of reporting simulated success.
🛠️ Quick Start
Installation
Install the v13 prerelease with an exact pin:
cargo add rullst-orm@=13.0.0-rc.1 -F strict-sqlite
cargo add tokio -F full
The code that #[derive(Orm)] generates needs nothing else: since
13.0.0-alpha.4 it reaches SQLx, tracing and tokio through rullst_orm,
and it implements SQLx’s FromRow for the model itself, so do not also
derive FromRow (two implementations do not compile, E0119). The build
therefore compiles no SQLx macro crate. tokio runs the example’s
#[tokio::main].
rullst-orm does not enable SQLx’s macros or derive features. To use
sqlx::query! or #[derive(sqlx::FromRow)] on your own structs, enable
them in your manifest, for example
sqlx = { version = "0.9", default-features = false, features = ["derive"] }
(macros for query!). This builds sqlx-macros and, for the
compile-time macros, a second copy of the SQLx driver for the build host. A
model whose FromRow you write yourself, by hand or with that derive,
declares #[orm(custom_from_row)] so #[derive(Orm)] does not generate one.
Select the driver of your database: strict-sqlite, strict-postgres or
strict-mysql, or drivers-all for all three on SQLx’s dynamic Any pool.
Since 13.0.0-alpha.3 the crate enables no driver by default; without one,
Orm::init fails at startup with an error that names the feature to enable.
Zero-to-Hero Example
use rullst_orm::schema::Schema;
use rullst_orm::{Orm, RowSnapshot};
// 1. Just add the Orm macro to your struct!
#[derive(Debug, Clone, Orm)]
pub struct User {
pub id: i32, // ID = 0 means it hasn't been saved yet
pub name: String,
pub email: String,
#[orm(hidden)] // Excluded from generated to_json(), audit, event and search projections
pub password: String,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
#[tokio::main]
async fn main() -> Result<(), rullst_orm::Error> {
// 2. Initialize the connection pool (SQLite, Postgres, MySQL/MariaDB)
Orm::init("sqlite::memory:").await?;
// 3. Create the `users` table (a migration does this in an application)
Schema::create("users", |table| {
table.id();
table.string("name");
table.string("email");
table.string("password");
})
.await?;
// 4. Create a new user through the generated Active Record API
let mut user = User {
id: 0,
name: "Alice".to_string(),
email: "[email protected]".to_string(),
password: "secret_password".to_string(),
snapshot: RowSnapshot::default(),
};
user.save().await?; // Runs INSERT and hydrates the generated ID.
// 5. Fluent Queries
let active_users = User::query()
.where_like("email", "%@example.com")
.order_by_desc("id")
.limit(10)
.get()
.await?;
println!("Found {} user(s)", active_users.len());
Ok(())
}
Orm::init and Orm::init_with_options hand out pooled connections. SQLx
pings each connection when it returns to the pool. Since 13.0.0-rc.1 a
PostgreSQL or MySQL pool pings it again before handing it out (SQLx’s
test_before_acquire is off) only when it has been idle for at least 500 ms,
because a server or a network may have closed it since; a connection that
fails that ping is closed, and the pool takes another or opens a new one. A
connection idle for less passed the release ping less than 500 ms earlier, so
a one-statement request takes two round trips instead of three. A database
restart takes longer than 500 ms, so once the server is back every old
connection is pinged and replaced; a connection that dies less than 500 ms
after its release fails its next query, and SQLx then closes it. Since
13.0.0-alpha.6 a SQLite pool never pings a connection before handing it out:
its connections are files the process opened itself, and the ping to the
connection’s worker thread cost about as much as a primary-key query. A
connection that failed still fails its next query, and SQLx then closes it.
SQLite journal mode (WAL)
A SQLite database keeps the journal mode recorded in its file, and Orm::init
does not change it: a new file uses the rollback journal (DELETE). In that
mode every statement locks and unlocks the database file and checks for a
journal left by a crash, and readers wait while a transaction commits. In a
profile of the SaaS starter’s signed-in dashboard that locking was about 14 %
of the server’s CPU. With the write-ahead log (WAL) readers no longer lock the
file for each statement (they take a lighter lock in shared memory) and never
wait for the writer; on CI runners the same page then used 2–7 % less server
CPU per request (13.0.0-alpha.6 calibration). Since 13.0.0-alpha.6 you choose
the mode explicitly:
use rullst_orm::{Orm, OrmConfig, SqliteJournalMode};
let config = OrmConfig::default().with_sqlite_journal_mode(SqliteJournalMode::Wal);
Orm::init_with_config("sqlite://data/app.db?mode=rwc", config).await?;
An application that Server starts sets it in Rullst.toml instead, and
Server and the Artisan commands (db:migrate, …) apply it:
[database]
url = "sqlite://db.sqlite"
# WAL: reads stop locking the file per query; set "delete" for a database on NFS/SMB storage.
sqlite_journal_mode = "wal"
Projects generated by cargo rullst new since 13.0.0-alpha.6 contain these
lines. The first connection sets the mode and checks what SQLite reports; a
mode SQLite does not take (a read-only database, a VFS or filesystem without
shared memory) fails initialization with Error::DatabaseError. PostgreSQL
and MySQL URLs, and an in-memory SQLite database, ignore the setting.
synchronous stays SQLite’s FULL, so a committed transaction survives a
power loss as before, and the busy timeout stays SQLx’s 5 seconds (writers
still take turns).
What WAL changes:
- Two more files. SQLite keeps
<file>-waland<file>-shmnext to the database while it is open (and removes them when the last connection closes cleanly). Keep them on the same volume and never delete them while the application runs; the generated.gitignoreand.dockerignorealready exclude them. - Backups. Committed transactions can sit in the
-walfile until a checkpoint copies them into the database, so copying the database file alone is not a backup. Use SQLite’s backup command, which is consistent while the application runs:sqlite3 app.db ".backup app-backup.db", orVACUUM INTO 'app-backup.db'from SQL. To restore, stop the application and runsqlite3 app.db ".restore app-backup.db"; if you copy a backup over the file instead, deleteapp.db-walandapp.db-shmfirst. The VM deployment guide shows both with a container volume. - One host, local disk. WAL shares an index in memory (
-shm) between every process that opens the database, so they must run on one machine and the file must be on a local filesystem. Do not use WAL on a network filesystem (NFS, SMB/CIFS, Azure Files and similar volumes): keep the rollback journal there withsqlite_journal_mode = "delete"(orSqliteJournalMode::Delete), which also switches a database that is already in WAL back.cargo rullst doctorwarns when a WAL database is on such a mount.
A switch between modes does not wait for readers: when another process is
reading the database at that moment, initialization fails with database is locked; start again once it is idle. Without the setting, an application
keeps whatever mode its file has, so existing databases and their backups do
not change on upgrade.
Concurrent updates and counters
Every model chooses what save() writes to a row it loaded, and since
13.0.0-alpha.6 a model that does not choose fails to compile with an error
that shows both one-line fixes:
| Choice | save() of a loaded record |
|---|---|
#[sqlx(skip)] pub snapshot: RowSnapshot, (a field, recommended) | writes only the columns this handle changed, so concurrent edits of other columns persist |
#[orm(full_row_save)] (on the struct) | writes every persisted column of the handle, so the last writer wins |
A full-row save loses updates: when two requests load the same row and change
different fields (a student saves a profile edit while an XP award is saved),
the later save() writes back the other field as it was read, and the first
change silently disappears. Choose full_row_save only for a model whose code
relies on overwriting the whole row. Turso-primary models always write every
column and declare #[orm(full_row_save)]. Until 13.0.0-alpha.5 a model
without the field got full-row saves without saying so.
An insert sends every field either way, so database column defaults (such as
DEFAULT CURRENT_TIMESTAMP) do not apply to model fields, except to fields
marked #[orm(db_default)].
Dirty tracking (v13). With one #[sqlx(skip)] field of type
RowSnapshot, save() writes only the columns that this handle changed:
#![allow(unused)]
fn main() {
use rullst_orm::{Orm, RowSnapshot};
#[derive(Debug, Clone, Orm)]
#[orm(table = "profiles")]
pub struct Profile {
pub id: i32,
pub name: String,
pub bio: String,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
async fn rename(id: i32, name: String) -> Result<(), rullst_orm::Error> {
let mut profile = Profile::find(id)
.await?
.ok_or(rullst_orm::Error::RecordNotFound)?;
profile.name = name;
// `profile.dirty_columns()` is now `["name"]`.
profile.save().await // UPDATE profiles SET name = ? WHERE id = ?
}
}
- Records read through the ORM (
find,first,get,all,paginate, relations, streams, the query cache and the rowupdate_partial()reads) remember a 64-bit fingerprint of every column thatsave()updates: 16 bytes per record plus 8 per column, never the values.save()compares the current values with them:#[orm(encrypted)]andSecretStringfields by plaintext, so an unchanged secret is not encrypted again, JSON fields (#[sqlx(json)],Json<T>,serde_json::Value) by their canonical document, and other fields by their Serde serialization. - The
UPDATEsets only the changed columns, keeps the tenant predicate and returns the stored row (PostgreSQL and SQLite; MySQL/MariaDB read it again in the same transaction). The columns it did not write,#[orm(db_default)]columns and the soft-delete marker take their stored values, so the handle, the audit diff, model events and the search document describe the row as stored. A row deleted meanwhile still fails withRecordNotFound. - When nothing changed,
save()runs noUPDATE, noupdating,updatedorsavedobservers, noafter_savehook, audit entry or post-commit event. Thebefore_savehook and thesavingobservers run first and may change fields; a model with neither, and without a policy, does not even open a transaction. - A record built in code holds
RowSnapshot::default():save()inserts it, or, with a non-zeroid, writes every column.mark_all_dirty()makes a loaded record do the same, for code that relied on overwriting the row.is_dirty()tells whethersave()has anything to write. - A failed
save()keeps its changes pending. When a caller-owned transaction rolls back after a successfulsave(), reload the record or callmark_all_dirty(). - A
before_savehook that stampsupdated_aton every call makes every save write; stamp it only whenself.is_dirty(). - Mark the field
#[serde(skip)]when the model derives Serde traits. Any two snapshots compare equal and hash alike, so a derivedPartialEqorHashlooks at the columns only. Since 13.0.0-alpha.3 every SQLx model that the CLI writes declares the field:make:model(andmake:resource),generate:models(with#[serde(skip)]; for a table with its ownsnapshotcolumn the field isrow_snapshot),auth,make:billing,make:chat-sessionand the models of everycargo rullst newstarter (Blank, API and SaaS) and of the LMS example. Their struct literals setsnapshot: RowSnapshot::default(). Turso models have no dirty tracking: the CLI writes them with#[orm(full_row_save)]. A model of a project generated earlier that lacks the field no longer compiles: add the field, or#[orm(full_row_save)]to keep its behaviour;cargo rullst upgradelists each such model (V13-ORM-SAVE-MODE). - The
ORM differential databasesCI job runs this partial-save scenario (two handles that change different columns, an unchanged save,mark_all_dirty(),update_partial(), refreshed#[orm(db_default)]timestamps, a row deleted meanwhile) on PostgreSQL, MySQL and MariaDB and compares each transcript with SQLite’s; the driver contract and the SQLite tests check which columns eachUPDATEwrote and that two concurrent saves of different fields both persist.
Dirty tracking merges edits of different columns. Two writers of the same column still race, and the last one wins:
- To change some fields of a row that other requests may edit, use
update_partial(). It reads the current row in a transaction (withSELECT ... FOR UPDATEon PostgreSQL and MySQL/MariaDB), sets only the fields you chose and saves through the normal policy, hooks, audit and cache lifecycle. On SQLite a contendedupdate_partial()can fail with a database error instead of waiting; retry it. It merges fields, but it does not detect two editors changing the same field: that needs a revision column checked by the application. - For a counter, run one atomic statement with
Orm::raw. Its values are bound and it joins the activeOrm::transaction, but it skips the model’s tenant scope, policy, hooks, audit and cache invalidation: add the tenant condition yourself. Raw SQL uses the driver’s own markers,$1,$2on PostgreSQL and?on SQLite and MySQL/MariaDB.
#![allow(unused)]
fn main() {
use rullst_orm::{Orm, RowSnapshot};
#[derive(Debug, Clone, Orm)]
#[orm(table = "students")]
pub struct Student {
pub id: i32,
pub bio: String,
pub xp: i32,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
/// Changes only `bio`: an XP award committed meanwhile is kept.
async fn edit_bio(student: &mut Student, bio: String) -> Result<(), rullst_orm::Error> {
student.update_partial().bio(bio).save().await
}
/// Adds XP in one statement, so concurrent awards add up.
async fn award_xp(student_id: i32, points: i32) -> Result<(), rullst_orm::Error> {
let sql = if Orm::driver()? == "postgres" {
"UPDATE students SET xp = xp + $1 WHERE id = $2"
} else {
"UPDATE students SET xp = xp + ? WHERE id = ?"
};
let changed = Orm::raw(sql).bind(points).bind(student_id).execute().await?;
if changed == 0 {
return Err(rullst_orm::Error::RecordNotFound);
}
Ok(())
}
}
Database errors
A unique or primary-key violation returns Error::UniqueViolation, and a
foreign-key violation (a missing referenced row, or deleting a row that is
still referenced) returns Error::ForeignKeyViolation. Generated writes, query
builders and Orm::raw all map them; every other database failure stays
Error::DatabaseError(String). constraint holds the name PostgreSQL reports
and is None on SQLite and MySQL/MariaDB. The message of these two errors
names only the constraint, because the database’s own text can quote the
rejected value (MySQL reports Duplicate entry '[email protected]').
#![allow(unused)]
fn main() {
use rullst_orm::{Error, Orm, RowSnapshot};
#[derive(Debug, Clone, Orm)]
#[orm(table = "members")]
pub struct Member {
pub id: i32,
pub email: String,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
/// `Ok(None)` when the email is already registered.
async fn register(email: String) -> Result<Option<Member>, Error> {
let mut member = Member { id: 0, email, snapshot: RowSnapshot::default() };
match member.save().await {
Ok(()) => Ok(Some(member)),
Err(Error::UniqueViolation { .. }) => Ok(None),
Err(error) => Err(error),
}
}
}
Orm::transaction returns its closure’s error unchanged after the rollback,
so a violation inside it keeps its variant too. The closure may return the
application’s own error type when it implements From<rullst_orm::Error> and
Display; failures of the transaction itself, such as a commit rejected by a
deferred constraint, arrive through that conversion.
Query values
Filters such as where_eq and where_in, Orm::raw(..).bind(..) and
with_tenant take any value that converts into RullstValue: String/&str,
i32, i64, u32, f64, bool, the date/time types Timestamp,
DateTime, Date and Time (see
date and time columns), a #[derive(Enum)] type
(see native database enums) and Option of those. In a filter
(where_eq, where_in, where_between, their or_where variants and the
per-column helpers) None is the SQL NULL literal: a comparison with NULL
never matches, on every backend, so filter missing values with where_null.
Orm::raw(..).bind(None) binds SQL NULL typed as text: on PostgreSQL write
CAST($1 AS BIGINT) to store it in a column of another type. RullstValue is #[non_exhaustive]; give a
match on it a wildcard arm.
#![allow(unused)]
fn main() {
use rullst_orm::{Orm, RowSnapshot};
#[derive(Debug, Clone, Orm)]
#[orm(table = "progress")]
pub struct Progress {
pub id: i32,
pub lesson_id: Option<i64>,
pub seconds: i64,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
async fn for_lesson(lesson_id: Option<i64>) -> Result<Vec<Progress>, rullst_orm::Error> {
let query = Progress::query();
match lesson_id {
Some(lesson_id) => query.where_eq("lesson_id", lesson_id).get().await,
None => query.where_null("lesson_id").get().await,
}
}
}
Query row cap
Generated builders start with a global row cap (Orm::set_max_query_limit,
1,000 by default; 0 disables it). limit() clamps to that cap and
unsafe_unlimited() removes it for one explicit query. paginate(page, per_page) clamps per_page to the same cap, because the value often comes
from request input; PaginationResult::per_page and last_page report the
effective page size. count() and the paginate() total count the rows the
query returns: a distinct() or group_by() query is counted as a derived
table, so the total is the number of distinct rows or groups.
Eager loading runs one related-model query for all parents of a batch and
never assigns relations from a result truncated by that cap: when the related
rows exceed it, get() fails with a Validation error naming the relation.
Load fewer parents per query, raise the cap, or choose explicitly with
with_<relation>_constrained(...): an explicit smaller limit(n) there applies
to the whole batch, and unsafe_unlimited() loads every related row.
Parents that share a related row or group all receive it: every child of one
belongs_to parent, parents whose non-unique local_key matches the same
has_many/has_one rows, and duplicated parent rows. The shared value is
cloned for all but the last such parent, so a related model without Clone
loads normally until a row must be shared, and then get() fails with a
Validation error instead of leaving a parent without its relation.
A relation key may be a nullable foreign key (author_id: Option<i32>) on
either model. A None key matches no row, like SQL NULL: the lazy loader
returns None or an empty list without a query, an eager load gives such a
parent None (or Some(vec![]) for a to-many relation), and a related row
whose key is None belongs to no parent.
Native database enums
Generated applications should select a strict primary feature. PostgreSQL
native enums specifically require strict-postgres, because SQLx’s dynamic
Any driver cannot decode custom PostgreSQL types:
rullst-orm = { version = "=13.0.0-rc.1", features = ["strict-postgres"] }
Derive one label contract and use it in schema code:
#![allow(unused)]
fn main() {
use rullst_orm::schema::{Blueprint, Schema};
use rullst_orm::{Enum, Orm};
#[derive(Enum, Debug, Clone, Copy, PartialEq, Eq)]
#[rullst_enum(type_name = "account_status", rename_all = "snake_case")]
enum AccountStatus {
AwaitingReview,
Active,
}
async fn create_schema() -> Result<(), rullst_orm::Error> {
Orm::init("postgres://user:password@localhost/application").await?;
Schema::create("accounts", |table: &mut Blueprint| {
table.id();
table.native_enum::<AccountStatus>("status").not_null();
}).await?;
Ok(())
}
}
The derive accepts 1–64 unique labels of at most 63 bytes using ASCII letters,
digits, spaces, underscores or hyphens. An existing PostgreSQL type must have
the exact same ordered labels or schema creation fails. MySQL/MariaDB store the
labels in the table’s inline ENUM; SQLite enforces them through TEXT CHECK.
Adding, removing or reordering labels is an explicit reviewed migration. Drop
every dependent table before calling Schema::drop_native_enum::<T>() on
PostgreSQL; the method is a validated no-op on the other backends. The enum
type creation, its label check and drop_native_enum use the active
Orm::transaction or test sandbox like the table DDL, so they roll back with it
and the type can be dropped right after its tables in the same transaction.
Builder filters on a model field whose type derives Enum (or
Option<...> of it) work on every backend: on PostgreSQL the comparison,
IN and BETWEEN markers of that column become CAST(? AS "<type_name>"),
because a text parameter has no operator against a named enum type. This
covers where_eq, where_in, the generated where_<column> helpers and
their or_/not_ variants; where_like and raw SQL are unchanged.
Constraints, indexes and foreign keys
Schema::create declares unique constraints, indexes, foreign keys and CHECK
constraints next to the columns. Every name is validated with the identifier
grammar before it reaches DDL:
#![allow(unused)]
fn main() {
use rullst_orm::schema::{Blueprint, ColumnDefault, ForeignKeyAction, Schema};
async fn create_schema() -> Result<(), rullst_orm::Error> {
Schema::create("enrollments", |table: &mut Blueprint| {
table.id();
// An `INTEGER NOT NULL` column referencing `users(id)`.
table
.foreign_id("user_id", "users")
.on_delete(ForeignKeyAction::Cascade);
table.integer("course_id").not_null();
table
.foreign("course_id")
.references("courses", "id")
.on_delete(ForeignKeyAction::Restrict);
// MySQL/MariaDB cannot index a TEXT column: give indexed strings a length.
table.string("code").not_null().unique().col_type = "VARCHAR(64)".to_string();
table.integer("progress").not_null().default(ColumnDefault::Integer(0));
table.unique(&["user_id", "course_id"]);
table.index(&["course_id", "progress"]).name("enrollments_course_progress");
table.check("progress BETWEEN 0 AND 100");
table.timestamps();
}).await?;
Ok(())
}
}
Column::unique()adds a column-levelUNIQUE;unique(&[...])a table constraint named<table>_<columns>_uniqueunless.name(...)sets one.index(&[...])andunique_index(&[...])areCREATE [UNIQUE] INDEX IF NOT EXISTS <table>_<columns>_index|_uniquestatements afterCREATE TABLEon PostgreSQL and SQLite, andINDEXclauses ofCREATE TABLEon MySQL/MariaDB (which has noIF NOT EXISTSfor indexes). Names are at most 63 bytes, so PostgreSQL never truncates them; a longer default name fails and asks for.name(...).foreign(column).references(table, column)adds<table>_<column>_foreignwith optionalon_delete/on_update(Cascade,Restrict,SetNull,NoAction).foreign_id(column, table)also adds theINTEGER NOT NULLcolumn and referencestable(id). The column type must match the referenced one (id()isINTEGER),SetNullneeds a nullable column, and SQLite enforces foreign keys only withPRAGMA foreign_keys = ON, which SQLx sets on every connection it opens.check(expression)addsCHECK (expression). The expression is trusted developer SQL emitted as written: building fails when it is empty, longer than 512 bytes, or contains;, a comment,\,$, a backtick, a control character or unbalanced parentheses or quotes, but never build it from request data. MySQL enforces CHECK from 8.0.16 and MariaDB from 10.2.1.- On MySQL/MariaDB a unique, index or foreign-key column whose type is
TEXT,BLOBorJSON(a plainstring(), ortimestamps()on theAnypool) fails before any DDL runs: set a boundedcol_typesuch asVARCHAR(255).
A unique or foreign-key violation from a later write returns
Error::UniqueViolation/Error::ForeignKeyViolation; PostgreSQL reports the
constraint name.
Schema::table alters an existing table with the same builders: it adds the
blueprint’s columns (ALTER TABLE ... ADD COLUMN), then its unique
constraints, indexes, foreign keys and checks, all validated before the first
statement runs:
#![allow(unused)]
fn main() {
use rullst_orm::schema::{Blueprint, ForeignKeyAction, Schema};
async fn add_reviewer() -> Result<(), rullst_orm::Error> {
Schema::table("posts", |table: &mut Blueprint| {
table.integer("reviewer_id");
table
.foreign("reviewer_id")
.references("users", "id")
.on_delete(ForeignKeyAction::SetNull);
table.index(&["reviewer_id"]);
}).await?;
Ok(())
}
}
SQLite cannot add a constraint to an existing table. There a unique
constraint, or a unique() column, becomes the equivalent unique index, and a
foreign key on a column added in the same call becomes that column’s
REFERENCES clause (the column must be nullable without a default). Any other
foreign key (on an existing column, or a second one on the same new column), a CHECK, a primary-key column, a NOT NULL column without a
default or a current-time default returns Error::UnsupportedSchemaChange
before any statement runs; rebuild such a table with a new Schema::create.
MySQL/MariaDB commit each DDL statement on its own, so a failure there can leave
the earlier statements applied.
Date and time columns
date(), time(), timestamp() and timestamp_tz() hold the ORM’s
date/time types Date, Time, DateTime and Timestamp
(rullst_orm::temporal, also exported as rullst_orm::*, and in the facade
as rullst::orm::* and rullst::db::*):
| Helper | Rust field | Wraps | PostgreSQL | MySQL/MariaDB | SQLite (ISO-8601 text) |
|---|---|---|---|---|---|
date | Date | jiff::civil::Date | DATE | DATE | 2026-10-15 |
time | Time | jiff::civil::Time | TIME | TIME(6) | 09:30:00.500 |
timestamp | DateTime | jiff::civil::DateTime | TIMESTAMP | DATETIME(6) | 2026-10-15 09:30:00.500 |
timestamp_tz | Timestamp | jiff::Timestamp | TIMESTAMPTZ | DATETIME(6) (UTC) | 2026-10-15T09:30:00.500+00:00 |
Each type wraps the jiff 1 type beside it,
converts to and from it with From and dereferences to it, so jiff’s
arithmetic, formatting and time zones apply (event.starts_at.as_second());
rullst_orm::jiff (rullst::orm::jiff) re-exports the crate.
Timestamp::now() reads the system clock, and the result of jiff arithmetic
converts back with .into(). Display, Debug, serde and FromStr are
byte for byte those of the chrono types they replace (a Timestamp
displays as 2026-10-15 09:30:00.500 UTC and serializes as
"2026-10-15T09:30:00.500Z"); parsing accepts every form chrono accepted,
then jiff’s own forms. The jiff value behind Deref formats in jiff’s style
(2026-10-15T09:30:00.5Z). Default is chrono’s: the Unix epoch,
1970-01-01T00:00:00, 1970-01-01 and midnight. The types
exist because SQLx has date/time codecs only for chrono and time, and
Rust’s orphan rule keeps the ORM from adding them to jiff’s types. Up to
13.0.0-alpha.5 these columns held chrono values; the new types write the
same bytes and read every form the chrono types read, so existing rows need
no migration (see moving off chrono).
RullstValue has a variant for each (Timestamp, CivilDateTime,
CivilDate, CivilTime).
jiff’s range ends sooner than chrono’s, and a value outside it is a decode
error, never a clamped value: DateTime, Date and Time hold years -9999 to
9999, and Timestamp -9999-01-02T01:59:59Z..=9999-12-30T22:00:00.999999999Z.
A timestamp_tz row holding the end-of-time sentinel 9999-12-31 23:59:59
does not read as a Timestamp; the error suggests NULL in an
Option<Timestamp> field for “no end”, a value within the range, or reading
the column as a civil DateTime, which keeps the full range. Find such rows
with WHERE col > '9999-12-30 22:00:00+00' on PostgreSQL or
WHERE col > '9999-12-30 22:00:00' on MySQL/MariaDB. A leap second (:60)
reads as second 59, and a few lenient text forms that only chrono read from
stored timestamps (a space before the offset, a UTC suffix) no longer
decode; Rullst writes none of these values. rullst::db::* exports the four
names, so a module that also has use chrono::prelude::* imports them by name.
MySQL/MariaDB store a UTC instant in DATETIME(6) because their TIMESTAMP
ends in 2038; SQLx sets the session time zone to +00:00, so values and
CURRENT_TIMESTAMP defaults are UTC (other clients see the same UTC wall
time). The ORM sends a Timestamp (a model field, a filter value or an
Orm::raw binding) to them as its UTC wall time in a DATETIME parameter:
MariaDB turns a TIMESTAMP parameter into NULL outside 1970–2038, and a
Timestamp that you bind with SQLx directly is sent as one. Bind its UTC wall
time, DateTime::from(jiff::tz::TimeZone::UTC.to_datetime(*value)), for the
same effect. A ColumnDefault::CurrentTimestamp default is the current UTC time in
the column’s own form: CURRENT_TIMESTAMP on a PostgreSQL TIMESTAMPTZ, the
UTC wall time (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') on the zone-less types,
CURRENT_TIMESTAMP(6), (CURRENT_DATE) or (CURRENT_TIME(6)) on
MySQL/MariaDB, and on SQLite the same text SQLx writes, so stored values of one
column compare and sort as text (strftime('%Y-%m-%dT%H:%M:%f+00:00', 'now')
for timestamp_tz).
table.timestamps() adds nullable created_at/updated_at timestamp_tz()
columns that default to the current time. Model fields, filters and ordering
use these types; RullstValue converts them (where_gt("starts_at", Timestamp::now())), and #[orm(db_default)] leaves a column to its database
default:
// Needs a strict driver feature (see below).
use rullst_orm::{Date, Orm, RowSnapshot, Timestamp};
#[derive(Debug, Clone, Orm)]
#[orm(table = "events")]
pub struct Event {
pub id: i32,
pub starts_at: Timestamp,
pub day: Date,
pub ends_at: Option<Timestamp>,
// Never written by `save()`: INSERT keeps the column DEFAULT and UPDATE
// keeps the stored value. The handle keeps its own value (here `None`)
// until the row is read again.
#[orm(db_default)]
pub created_at: Option<Timestamp>,
pub updated_at: Timestamp,
#[sqlx(skip)]
pub snapshot: RowSnapshot,
}
#[orm(db_default)] fields are left out of the generated INSERT and of
every UPDATE of save(), update_partial() has no setter for them and
#[derive(Nexus)] shows them read-only. Set an updated_at without it
yourself (Timestamp::now()) or maintain it with a trigger. A model with a
RowSnapshot field refreshes them from the stored row after each update.
#[orm(db_default)] is also the option for any column that the database or
your own SQL manages, such as the generated users.is_admin and
users.session_epoch: queries can filter, order, group and select it, and
ORM writes never touch it. #[orm(skip)] means something else: the field is
not a database column for the ORM, so a filter, ordering, grouping or
select on it fails with Error::Validation. A skipped field that the table
does not have also needs #[sqlx(skip)] (or #[sqlx(default)]), because the
model’s FromRow still reads #[orm(skip)] fields.
| Option | The column | Filters, ordering, grouping, select | ORM writes |
|---|---|---|---|
#[orm(skip)] | is not a database column for the ORM | rejected | never |
#[orm(db_default)] | exists and is managed by the database | allowed | never |
Date/time columns and fields need a strict driver feature
(strict-postgres, strict-mysql or strict-sqlite, which generated projects
use). SQLx’s dynamic Any pool, selected by drivers-all without a
strict feature, carries only integer, float, text and blob values: it cannot
decode a date/time field, and it cannot read a PostgreSQL or MySQL/MariaDB
DATE, TIME, TIMESTAMP or TIMESTAMPTZ column at all. On that pool
Schema::create and Schema::table reject those helpers on PostgreSQL and
MySQL/MariaDB with Error::Validation, SQLite keeps its ISO-8601 text for
String fields, date/time filter values bind as that same text, and
timestamps() keeps the alpha.1 TEXT DEFAULT CURRENT_TIMESTAMP columns
(DEFAULT (CURRENT_TIMESTAMP) on MySQL/MariaDB, which accept a default on
TEXT, BLOB, JSON and GEOMETRY columns only as an expression; other
non-NULL defaults on those types are wrapped the same way, MySQL 8.0.13+,
MariaDB 10.2.1+). soft_deletes() stays a TEXT deleted_at column on every
pool; declare timestamp_tz("deleted_at") for a native one. The Turso adapter
does not use the Blueprint and keeps text timestamps.
table.float(...) and table.boolean(...) map to f64 and bool model
fields. PostgreSQL receives DOUBLE PRECISION and BOOLEAN (an integer
ColumnDefault of 0/1 becomes FALSE/TRUE); MySQL/MariaDB receive
DOUBLE and an INTEGER 0/1 flag; SQLite keeps REAL and INTEGER. This
applies to newly built DDL only: PostgreSQL columns created by earlier versions
remain REAL/INTEGER until a reviewed migration alters them, and a model that
paired boolean() with an integer field on PostgreSQL must switch to bool
(or use integer()) for new tables.
📚 Documentation
We recently launched a brand-new Interactive Documentation Hub!
👉 Explore the Full Documentation in the Rullst Book
🛡️ Security
Rullst ORM uses SQLx prepared-statement bindings for values accepted by its query builders. Structural identifiers are restricted to a bounded ASCII identifier grammar before interpolation. Raw SQL and application authorization remain the caller’s responsibility; these controls reduce injection risk but are not an absolute safety guarantee.
📄 License
This project is licensed under the MIT License.