Introduction
TideORM is an async ORM for Rust applications. You declare a model as a plain struct with one attribute, its relations as fields of that struct, and read and write rows through a fluent query builder. It runs on PostgreSQL, MySQL, MariaDB and SQLite, and on CockroachDB, YugabyteDB, TiDB and Vitess through the PostgreSQL and MySQL drivers.
This book is for Rust developers building an application on a SQL database: a web service, a worker, a command-line tool. It assumes you know Rust and async/await; it does not assume you know any other ORM.
A First Look
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub active: bool, #[tideorm(has_many = "Post", foreign_key = "user_id")] pub posts: HasMany<Post>, } async fn recent_active_users() -> tideorm::Result<Vec<User>> { User::query() .where_eq(User::ACTIVE, true) .with(User::POSTS) .order_desc(User::ID) .limit(10) .get() .await } }
#[tideorm::model] generates everything else: the table mapping, User::create, User::find, user.update(), the typed column constants (User::ACTIVE) and the relation names (User::POSTS). A misspelt column or a value of the wrong type is a compile error.
What TideORM Gives You
- Models with validation, callbacks, automatic timestamps, soft deletes, query scopes, encrypted fields and tokenized IDs.
- Queries that cover filters, OR groups, joins, aggregates, unions, window functions, CTEs, JSON and array operators, full-text search and pagination, plus raw SQL when you need it.
- Relations declared as struct fields (
HasOne,HasMany,BelongsTo,HasManyThroughand polymorphic ones), loaded lazily or in batches. - Data tools: transactions with savepoints, migrations, seeders, schema sync for development, and schema export.
- Operations: classified errors you can retry on, query logging, profiling and opt-in project rules checked by
cargo check.
Optional modules (file attachments, translations, full-text search, the entity manager, dirty tracking and encrypted fields) sit behind Cargo features that add no dependencies.
Reading Map
| If you want to | Read |
|---|---|
| Add TideORM to a project | Installation, then Quick Start |
| Connect, tune the pool or set options | Configuration |
| Know how a backend differs, or how Rust types map to columns | Databases and Compatible Servers |
| Define models and write rows | Defining Models, Reading and Writing |
| Build queries | Query Builder and the pages under it |
| Load related rows | Relations |
| Group writes, change the schema, fill tables | Transactions, Migrations, Seeding |
| Handle failures and see what runs | Errors, Logging and Profiling |
| Test your application | Testing |
| Fix something that does not work | Troubleshooting |
The API cheat sheet lists signatures at a glance, and the Rust API reference documents every public item, optional modules included. The TideORM CLI scaffolds projects and runs migrations and seeders, and tideorm-examples holds complete applications.
Installation
Add tideorm to your Cargo.toml with one backend feature and one runtime feature, and add the async runtime itself:
[dependencies]
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
That is all a project needs to define models and run queries; serde, chrono and serde_json come through tideorm and its prelude. The Quick Start builds a complete program on it.
The dependency may be renamed (orm = { package = "tideorm", .. }, then #[orm::model]): the macros read the name from the crate's Cargo.toml, [workspace.dependencies] included. A crate that defines models must depend on tideorm itself, under whatever name; a re-export through another crate is not enough.
Choosing a Backend
Each backend is a Cargo feature that builds its driver:
# PostgreSQL
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio"] }
# MySQL or MariaDB
tideorm = { version = "0.18.2", default-features = false, features = ["mysql", "runtime-tokio"] }
# SQLite
tideorm = { version = "0.18.2", default-features = false, features = ["sqlite", "runtime-tokio"] }
The default feature set is ["postgres", "runtime-tokio"]. Set default-features = false and name your features explicitly: a MySQL- or SQLite-only project that leaves the defaults on still compiles the whole PostgreSQL driver.
Backend features add to each other. With several enabled, the connection URL picks the backend at runtime (see Databases), so one binary can talk to PostgreSQL and SQLite at once. A URL for a backend whose feature is not compiled in is refused with a configuration error that names the feature to enable.
| Feature | Builds | Use it for |
|---|---|---|
postgres | The PostgreSQL driver | PostgreSQL |
mysql | The MySQL driver | MySQL and MariaDB |
sqlite | The SQLite driver, with a bundled SQLite (3.46 or later) | SQLite; no system library is needed |
mariadb, tidb, vitess | The same as mysql | Naming the server you run in your manifest |
cockroachdb, yugabytedb | The same as postgres | Naming the server you run in your manifest |
The server-named features are aliases: features = ["cockroachdb"] and features = ["postgres"] build the same code. Compatible Servers lists what differs on each server.
Choosing a Runtime
| Feature | Runtime |
|---|---|
runtime-tokio | Tokio (default) |
runtime-async-std | async-std |
Enable one, and add that runtime to your own dependencies so you can start it (#[tokio::main], #[async_std::main]).
Optional Modules
Six features unlock optional APIs. They add no dependencies; they only make the API visible:
| Feature | Unlocks |
|---|---|
attachments | File attachments on models (HasAttachments, tideorm::attachments); see File Attachments |
translations | Translated fields (HasTranslations, ApplyTranslations, tideorm::translations); see Translations |
fulltext | Full-text search and highlighting (tideorm::fulltext); see Full-Text Search |
entity-manager | The EntityManager persistence context: an identity map, find, find_managed, load, save, persist, merge, remove, detach and flush; see Entity Manager |
dirty-tracking | changed_fields() and original_value() on models; see Reading and Writing |
encrypted-fields | #[tideorm(encrypted = "..")] columns, encrypted on write and decrypted on load; see Encrypted Fields |
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio", "fulltext", "entity-manager"] }
Each page for a feature-gated API names its feature at the top.
What Else Your Crate Needs
Nothing, for the models themselves. The code #[tideorm::model] generates reaches serde, serde_json and chrono through TideORM, and tideorm::prelude re-exports the types models usually hold: DateTime, Utc, NaiveDate, NaiveDateTime, NaiveTime, Decimal, Uuid and JsonValue.
Add a dependency only when your own code needs it:
serde, if your own code derivesSerializeorDeserialize.chrono, if you spell a type with an explicitchrono::path.
Supported Rust Versions
TideORM needs Rust 1.94 or later. Every TideORM crate (the macros, the engine, the SQL builder and the drivers) declares rust-version = "1.94", and CI checks the library with that toolchain. To build with it explicitly, run cargo +1.94.0 build.
The CLI
The TideORM CLI is a separate crate whose binary is named tideorm. It scaffolds projects (tideorm init), generates models, migrations and seeders, and runs migrations and seeders through your project's own code. You do not need it to use the library.
Quick Start
This page builds a complete program: two models with a relation, an in-memory SQLite database, and every basic operation from creating rows to deleting them. It needs no database server.
Set Up the Project
cargo new tide-quickstart
cd tide-quickstart
[dependencies]
tideorm = { version = "0.18.2", default-features = false, features = ["sqlite", "runtime-tokio"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
The Program
Replace src/main.rs with:
use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub name: String, pub active: bool, // A relation is a field, not a column #[tideorm(has_many = "Post", foreign_key = "user_id")] pub posts: HasMany<Post>, } #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub title: String, pub published: bool, #[tideorm(belongs_to = "User", foreign_key = "user_id")] pub author: BelongsTo<User>, } #[tokio::main] async fn main() -> tideorm::Result<()> { // Connect, and create the tables from the models (development only) TideConfig::init() .database("sqlite::memory:") .max_connections(1) .models::<(User, Post)>() .sync(true) .connect() .await?; // Create: an auto-increment key left at 0 is numbered by the database let user = User { email: "ada@example.com".into(), name: "Ada".into(), active: true, ..Default::default() } .save() .await?; for (title, published) in [("Hello", true), ("Draft", false)] { Post::create(Post { user_id: user.id, title: title.into(), published, ..Default::default() }) .await?; } // Query with the generated typed columns let published = Post::query() .where_eq(Post::USER_ID, user.id) .where_eq(Post::PUBLISHED, true) .order_asc(Post::ID) .get() .await?; println!("published: {}", published.len()); // Load a relation lazily... let posts = user.posts.load().await?; println!("{} wrote {} posts", user.name, posts.len()); // ...or together with the rows that own it let users = User::query().with(User::POSTS).get().await?; let loaded = users[0].posts.get_cached().map_or(0, |posts| posts.len()); println!("eager-loaded posts: {loaded}"); // Update: find returns None when no row has the key let mut user = User::find(user.id).await?.expect("Ada exists"); user.name = "Ada Lovelace".into(); let user = user.update().await?; println!("renamed to {}", user.name); // Read one column, as its field's type (Vec<String>) let titles = Post::query().order_asc(Post::ID).pluck(Post::TITLE).await?; println!("titles: {titles:?}"); // Delete Post::query().where_eq(Post::USER_ID, user.id).delete().await?; user.delete().await?; println!("users left: {}", User::query().count().await?); Ok(()) }
cargo run prints:
published: 1
Ada wrote 2 posts
eager-loaded posts: 2
renamed to Ada Lovelace
titles: ["Hello", "Draft"]
users left: 0
What the Program Does
#[tideorm::model(table = "..")]turns a struct into a model. It generatesDefault, the serde impls, the CRUD methods, and a typed constant for each column (Post::USER_ID) and each relation (User::POSTS). A misspelt constant, or a value of the wrong type for its column, fails to compile. Defining Models covers every attribute.TideConfig::init()..connect()opens the connection pool and makes it the global database every model call uses.sync(true)creates missing tables and columns from the registered models; it is for development, and Migrations are for production. Configuration lists every setting.save()andcreate()insert a row and return the model as stored, with its key filled in.find(),update()anddelete()work by primary key. Reading and Writing covers them and the batch writes.query()starts a query builder;get(),count(),pluck()anddelete()are some of its terminals.load()queries a relation;with()loads it for every row of a query in one extra query, read back withget_cached(). See Relations.
Using Migrations Instead of Sync
In an application with real data, create tables with migrations: they are versioned, reversible, and each runs once. Replace .models::<..>().sync(true) with a migration:
#![allow(unused)] fn main() { use tideorm::migration::{Migration, Schema}; use tideorm::prelude::*; struct CreateUsers; #[tideorm::async_trait::async_trait] impl Migration for CreateUsers { fn version(&self) -> &str { "20261115_001" } fn name(&self) -> &str { "create_users" } async fn up(&self, schema: &mut Schema) -> tideorm::Result<()> { schema .create_table("users", |table| { table.id(); table.string("email").not_null(); table.string("name").not_null(); table.boolean("active").not_null(); }) .await } async fn down(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.drop_table("users").await } } async fn connect() -> tideorm::Result<()> { TideConfig::init() .database("sqlite::memory:") .max_connections(1) .migration(CreateUsers) .run_migrations(true) .connect() .await?; Ok(()) } }
Migrations explains the schema builder and the Migrator, which runs, rolls back and reports migrations outside startup.
Running on Another Backend
Swap the backend feature and the URL; the models and queries stay the same:
| Backend | Feature | URL |
|---|---|---|
| SQLite file | sqlite | sqlite://./app.db?mode=rwc (mode=rwc creates the file) |
| PostgreSQL | postgres | postgres://user:pass@localhost/app |
| MySQL or MariaDB | mysql | mysql://user:pass@localhost/app |
Read the URL from the environment, such as DATABASE_URL, rather than writing credentials into code. Databases covers what differs between backends.
Examples
The TideORM repository ships runnable programs in examples/. Each is a complete SQLite program, except postgres:
| Example | Shows |
|---|---|
crud | Insert, typed filters, update and delete |
relations | Declaring and eager-loading a has-many relation by its constant |
transactions | Committing a closure, and returning Err to roll back |
migrations | Registering and running a reversible migration |
scopes | Declaring a reusable typed query scope |
postgres | Connecting with DATABASE_URL and running a read-only query |
Run one from a checkout of the repository:
cargo +1.94.0 run --no-default-features --features sqlite,runtime-tokio --example crud
DATABASE_URL=postgres://user:password@localhost/database cargo +1.94.0 run --example postgres
The tideorm-examples repository holds larger end-to-end applications, and tideorm init from the TideORM CLI scaffolds a project with models, migrations and seeders already wired up.
Where Next
- Defining Models: attributes, keys, hidden fields and custom column names.
- Reading and Writing: every way to create, read, update and delete rows.
- Query Builder: filters, ordering, pagination and chunked reads.
- Relations: every relation type, eager loading and nested saves.
- Transactions: grouping writes, savepoints, and choosing the database a call uses.
- Errors: telling a duplicate key from a deadlock, and what to retry.
Configuration
TideConfig connects TideORM at startup: it opens the connection pool, installs it as the global database every model call uses, and can run migrations, schema sync and seeders on the way. Database::builder() opens further pools, with driver options a URL cannot express.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn start() -> tideorm::Result<()> { let url = std::env::var("DATABASE_URL").expect("DATABASE_URL is set"); TideConfig::init() .database(url) .max_connections(20) .connect() .await?; Ok(()) } }
Basic Connection
#![allow(unused)] fn main() { // One call: connect and install the global database Database::init("postgres://localhost/mydb").await?; // The same through TideConfig, which takes the other settings on this page TideConfig::init() .database("postgres://localhost/mydb") .connect() .await?; }
The URL's scheme picks the backend: postgres:// or postgresql://, mysql:// or mariadb://, and sqlite:. A URL carries credentials, so read it from the environment (such as DATABASE_URL) rather than writing it into code; TideORM does not read a URL from the environment itself.
connect() returns the global &'static Database. Database::init(url) does the same with the driver's pool defaults (see Driver Options); Database::connect(url) opens a pool without making it global, and Database::set_global(db) installs one you built. Databases covers running several databases side by side.
What connect() Does
connect() runs these steps in order, each only when enabled:
- Installs the configuration: languages, hidden attributes, the encryption key and token codecs, the attachment URL generator.
- Opens the pool and installs it as the global database. A
mysql://URL that reaches a MariaDB server is detected here, from the server's handshake. - Runs the registered migrations, with
run_migrations(true). - Syncs the schema from the registered models, with
sync(true). - Runs the registered seeders, with
run_seeds(true). - Writes the schema file, with
schema_file(path).
The steps are not one atomic unit. A failure part-way leaves the earlier steps applied: a seeder error returns Err with the migrations and sync already done.
connect() fails when no URL was set, when the backend cannot be told from the URL and database_type(..) does not name it, when a MySQL server cannot report its version, or when a step fails.
#![allow(unused)] fn main() { TideConfig::init() .database(url) .migration(CreateUsers) // register; runs only with run_migrations(true) .migration(CreatePosts) .run_migrations(true) .seed(DemoUsers) // register; runs only with run_seeds(true) .run_seeds(true) .connect() .await?; }
| Setting | Effect |
|---|---|
migration(m) | Registers a migration. Migrations run in version order, whatever order they were registered in. See Migrations |
run_migrations(bool) | Runs the registered migrations on connect. Off by default |
seed(s) | Registers a seeder, after any already registered. See Seeding |
run_seeds(bool) | Runs the registered seeders on connect, after migrations and sync. Off by default; a failed seeder does not undo what ran before it |
models::<T>() | Registers a model, or a tuple of models (models::<(User, Post)>()), for schema sync and schema export |
auto_models() | Registers every model compiled into the binary |
models_matching(pattern) | Registers the compiled models whose source file matches a glob: * matches one path segment, ** any number. The file must still be reachable through mod declarations, and a pattern matching no model logs a warning |
sync(bool) | Creates missing tables and columns for the registered models. For development; use migrations in production. See Schema Sync and Export |
force_sync(bool) | Drops and recreates every registered table on each connect, deleting its rows. Needs sync(true). Refused when TIDEORM_ENV is production, unless TIDEORM_ALLOW_FORCE_SYNC is 1 or true |
schema_file(path) | Writes the schema SQL to path once per connect, after any sync, for review in diffs. TideConfig::schema_file_path() reports the path |
connect_only() connects with the same configuration but skips migrations, sync, seeders and the schema file, whatever the builder enabled. The migration and seed runners the CLI scaffolds connect this way, so a force_sync in the application's configuration cannot drop the tables they are about to work on.
apply() installs the configuration without connecting at all: no pool is opened, so the URL and pool settings go unused. Use it in tests and tools that need the settings but not a database.
TideConfig::is_connected() says whether a global database is installed.
Pool Configuration
#![allow(unused)] fn main() { use std::time::Duration; TideConfig::init() .database("postgres://localhost/mydb") .max_connections(20) .min_connections(5) .connect_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(300)) .max_lifetime(Duration::from_secs(3600)) .acquire_timeout(Duration::from_secs(5)) .connect() .await?; }
| Setting | Default | Meaning |
|---|---|---|
max_connections | 10 | The ceiling on open connections, and so on concurrent database work, for the whole process. Keep it below what the server allows across all your instances |
min_connections | 1 | Connections kept open even while idle; more trades idle server connections for fewer cold starts |
connect_timeout | 8 s | The bound on each attempt to open a connection: socket, TLS, handshake, authentication and connection hooks |
acquire_timeout | 8 s | The bound on a whole checkout: waiting for a free connection, its ping and hooks, and opening a new one |
idle_timeout | 10 min | Closes a connection left unused this long |
max_lifetime | 30 min | Closes a connection this old, however busy. Keep it under any idle or lifetime limit the server, or a proxy in front of it, enforces |
The two timeouts are independent. Whichever deadline passes first ends the wait, so raising connect_timeout does not extend the wait for a free slot.
Dropping a running query, through a timeout or a cancelled task, does not stop it on the server: its connection goes back to the pool once the statement finishes, on SQLite once the connection's worker thread has run it. To bound a statement's work, set a server-side limit such as PostgreSQL's statement_timeout (below).
pool(..) replaces every pool setting at once with a PoolConfig, which starts from the defaults above and has a setter of the same name for each one. Its fields are public, so the same values can feed Database::builder():
#![allow(unused)] fn main() { let pool = PoolConfig::default() .max_connections(20) .acquire_timeout(Duration::from_secs(2)); TideConfig::init() .database("postgres://localhost/mydb") .pool(pool.clone()) .connect() .await?; let replica = Database::builder() .url(replica_url) .max_connections(pool.max_connections) .acquire_timeout(pool.acquire_timeout) .build() .await?; }
Driver Options
A URL names the common settings. For the rest, such as PostgreSQL's application_name or SQLite's journal mode, give Database::builder() the driver's own options instead of a URL:
#![allow(unused)] fn main() { let db = Database::builder() .postgres_options( PgConnectOptions::new() .host("localhost") .database("mydb") .application_name("billing") .options([("statement_timeout", "5s")]), ) .max_connections(20) .build() .await?; Database::set_global(db)?; }
| Builder method | Takes | Feature |
|---|---|---|
postgres_options | PgConnectOptions (host, port, username, password, database, ssl_mode(PgSslMode), application_name, options, ..) | postgres |
mysql_options | MySqlConnectOptions (host, port, username, password, database, ssl_mode(MySqlSslMode), charset, timezone, ..), for MySQL or MariaDB | mysql |
sqlite_options | SqliteConnectOptions (filename, create_if_missing, journal_mode(SqliteJournalMode), synchronous, foreign_keys, busy_timeout, read_only, ..) | sqlite |
All of these types are in tideorm::prelude. A SQLite example:
#![allow(unused)] fn main() { use std::time::Duration; let db = Database::builder() .sqlite_options( SqliteConnectOptions::new() .filename("app.db") .create_if_missing(true) .journal_mode(SqliteJournalMode::Wal) .busy_timeout(Duration::from_secs(10)), ) .build() .await?; }
SQLite connections enforce foreign keys, wait up to 5 s for a locked database, and do not create a missing file unless asked (create_if_missing(true), or ?mode=rwc in a URL).
The builder also takes a URL (url(..)) and the pool settings of the previous section. A setting left unset keeps the driver's default, which is not always TideConfig's: the driver keeps no idle connection and waits 30 s for a free one, where TideConfig keeps one and waits 8. build() fails without a URL or driver options, with max_connections(0), and with min_connections above max_connections. The builder's {:?} masks a URL's credentials and leaves driver options out, since they hold the password.
An in-memory SQLite database lives only while a connection to it is open, so its pool keeps one connection open and closes none for being idle or old, whatever the settings say. With cache=private each connection gets a database of its own, so such a pool must hold one connection; so does SQLite's own URI, sqlite:file::memory:, unless it adds ?cache=shared, which makes it one database for the whole process.
Statement Cache
Each connection prepares a parameterized statement once and reuses it while it lives, keeping up to 100 and dropping the least recently used. statement_cache_capacity(n) changes that on every backend, for URLs and driver options alike. With 0 no statement is kept and each is prepared for its own run, which a transaction-pooling proxy such as PgBouncer needs. db.cached_statements().await? reports how many statements one of the handle's connections holds.
Pinned Sessions
A pool hands each statement whichever connection is free, so what one statement sets for its session (SET, PRAGMA, MySQL's GET_LOCK) may not hold for the next, and stays on that connection for whatever statement takes it later. pin_session() opens a connection of its own, with the pool's settings but outside its slots, and every statement through the returned handle runs on it, transactions included:
#![allow(unused)] fn main() { let session = db.pin_session().await?; session.exec_raw("SET FOREIGN_KEY_CHECKS = 0").await?; // ... statements that rely on that setting ... session.close().await?; }
The connection closes with close() or once the last clone of the handle drops, and is never replaced: once it is lost, the handle's statements fail. A second transaction begun on the session waits until the first ends. pin_session() fails on a transaction's handle and on a private SQLite database (in memory without a shared cache, or temporary), where a new connection would open an empty database.
Health Checks and Shutdown
db.ping().await? checks that the handle's own connection answers, even inside a transaction opened on another database; any failure is an Error::Connection.
db.pool_status()? reports what the pool holds now, to export as metrics or show in a health endpoint: size (open connections), idle, max_connections, and in_use(). A pinned session's or a transaction's handle answers with the pool it came from.
let status = db.pool_status()?;
metrics::gauge!("db_connections_in_use").set(status.in_use() as f64);
db.close().await? waits for the connections in use to come back and closes the pool (SQLite then releases its file). Every clone of the handle shares the pool, so statements on any of them fail afterwards. It fails on a transaction's handle, which belongs to its scope.
Database Types
TideORM reads the backend from the URL. Name it with database_type(..) only when the scheme does not say:
#![allow(unused)] fn main() { TideConfig::init() .database_type(DatabaseType::Postgres) // Postgres, MySQL, MariaDB or SQLite .database("postgres://localhost/mydb") .connect() .await?; }
A mysql:// URL that reaches MariaDB is detected when the pool opens, and TideConfig::get_database_type() then answers MariaDB. A handle's own Database::backend() is the authority for the statements it runs; see Databases.
Application-Wide Settings
TideConfig also holds settings every model shares. connect() and apply() install them.
#![allow(unused)] fn main() { TideConfig::init() .database(url) .encryption_key(std::env::var("TIDEORM_KEY").expect("TIDEORM_KEY is set")) .hidden_attributes(["password_digest"]) .languages(["en", "fr", "ar"]) .fallback_language("en") .file_base_url("https://cdn.example.com/") .connect() .await?; }
| Setting | Effect |
|---|---|
encryption_key(key) | The master key for tokenization and encrypted fields. Per-column keys are derived from it, so changing it makes every earlier ciphertext and token unreadable. Load it from the environment or a secret manager |
token_encoder(f), token_decoder(f) | Replace how tokens are encoded and decoded, given the serialized key (or token) and the model name. Set both: a token the decoder rejects reads as Ok(None), so a mismatched pair fails silently |
hidden_attributes([..]) | Fields left out of every model's to_json(), on top of each model's own hidden fields. A direct serde_json::to_value still sees them |
languages([..]), fallback_language(..) | The languages translated fields accept, ["en"] by default, and the one read when a translation is missing, "en" by default. See Translations |
file_base_url(url), file_base_url_for(field, url) | The prefix of attachment URLs, for every field or for one field; with none, the stored key is the URL. See File Attachments |
file_url_generator(f) | Replaces attachment URL generation entirely, for signed or expiring URLs (attachments feature) |
Config::global() returns the installed settings, and Config::get_languages(), get_fallback_language(), get_hidden_attributes() and get_file_base_url_for(field) read single ones.
Resetting Global State
TideORM keeps the global database, the configuration and the tokenization settings in process-wide state, so models run without a connection threaded through every call. All of it can be reset, for tests, benchmarks and applications that reconfigure TideORM while running:
#![allow(unused)] fn main() { use tideorm::prelude::*; Database::reset_global(); TideConfig::reset(); // the tokenization key and codecs too TideConfig::init() .database("sqlite::memory:") .connect() .await?; }
TideConfig::reset() clears the configuration only, Database::reset_global() the global connection, and TokenConfig::reset() only the tokenization settings. apply(), connect() and connect_only() overwrite the configuration applied before them; one that names no database type clears the stored type instead of keeping the old one. Testing shows how to avoid global state in tests altogether.
Environment Variables
TideORM reads these from the process environment. A boolean flag is on only when set to 1 or true. The connection URL is not one of them: pass it to .database(..) yourself.
| Variable | Effect |
|---|---|
TIDE_LOG_QUERIES | Prints every statement to stderr and records it in the query logger's history; see Logging and Profiling. Read once, at the first statement |
TIDE_LOG_LEVEL | The QueryLogger level: error, warn, info, debug or trace |
TIDE_SLOW_QUERY_MS | The slow-query threshold, in milliseconds, of the logger and the profiler |
TIDE_LOG_SEEDS | Logs each seeder as it runs and rolls back |
TIDEORM_ENV | production (any case) makes force_sync(true) fail before it drops anything |
TIDEORM_ALLOW_FORCE_SYNC | Lets force_sync(true) run even when TIDEORM_ENV is production |
Databases
TideORM runs the same models and queries on PostgreSQL, MySQL, MariaDB and SQLite, and writes each statement in the dialect of the database it runs on. This page covers how the backend is chosen, using several databases at once, how Rust types map to columns, and where the backends differ.
Supported Databases
| Database | Feature | URL |
|---|---|---|
| PostgreSQL | postgres | postgres://user:pass@localhost:5432/app (or postgresql://) |
| MySQL | mysql | mysql://user:pass@localhost:3306/app |
| MariaDB | mysql (or its alias mariadb) | mysql://user:pass@localhost:3306/app (or mariadb://) |
| SQLite | sqlite | sqlite://./app.db?mode=rwc, or sqlite::memory: |
CockroachDB, YugabyteDB, TiDB and Vitess run through the PostgreSQL and MySQL drivers; see Compatible Servers.
#![allow(unused)] fn main() { // PostgreSQL TideConfig::init().database("postgres://user:pass@localhost/mydb").connect().await?; // MySQL or MariaDB TideConfig::init().database("mysql://user:pass@localhost/mydb").connect().await?; // SQLite: a file, created if missing because of mode=rwc TideConfig::init().database("sqlite://./data.db?mode=rwc").connect().await?; }
sqlite::memory: gives each pool its own in-memory database, shared by the pool's connections and gone when the pool closes.
How the Backend Is Chosen
The URL's scheme picks the backend, and with it the SQL dialect: placeholders ($1 on PostgreSQL, ? elsewhere), identifier quoting ("name" on PostgreSQL and SQLite, `name` on MySQL and MariaDB), and every clause that differs. TideConfig::database_type(..) names it only when the scheme cannot (see Configuration).
MySQL and MariaDB share a protocol, so a mysql:// URL can reach either. The connection reads which one answered from the server's handshake as it opens, and from then on TideORM writes MariaDB's dialect where the two differ.
A handle answers for its own connection:
#![allow(unused)] fn main() { let db = require_db()?; match db.backend() { DatabaseType::Postgres => println!("PostgreSQL"), DatabaseType::MySQL => println!("MySQL"), DatabaseType::MariaDB => println!("MariaDB"), DatabaseType::SQLite => println!("SQLite"), } if let Some(server) = db.server() { println!("connected to {server}"); // "CockroachDB", "TiDB", .. } }
| Call | Answers |
|---|---|
db.backend() | The DatabaseType of the handle's connection: Postgres, MySQL, MariaDB or SQLite. A disconnected handle falls back to the configured type, and then to Postgres with a warning |
db.try_backend() | The same, but a disconnected handle is an error instead of a guess |
db.server() | The DatabaseServer that answered: Postgres, CockroachDb, YugabyteDb, MySql, MariaDb, TiDb, Vitess or Sqlite. None for a disconnected handle, or a lazy pool that has not opened a connection yet. server.backend() gives its dialect |
TideConfig::get_database_type() | The type connect() settled on, or the one apply() declared; a fallback for code with no handle |
DatabaseType also answers a few questions about a backend:
| Method | Returns |
|---|---|
supports_arrays() | true on PostgreSQL only: native array columns |
supports_returning() | true on PostgreSQL and SQLite: UPDATE .. RETURNING, which BatchUpdateBuilder::execute_returning() needs |
optimal_batch_size() | A rule of thumb for rows per batch: 1000 on PostgreSQL, 500 on MySQL and MariaDB, 100 on SQLite |
as_str() | "PostgreSQL", "MySQL", "MariaDB" or "SQLite" |
DatabaseType::from_url(url) | The backend a URL's scheme names, or None |
#![allow(unused)] fn main() { let db_type = require_db()?.backend(); if db_type.supports_returning() { // execute_returning() is available } }
Several Databases at Once
The global database TideConfig installs is a default, not a limit. Database::connect(url) (or Database::builder()) opens another pool without replacing it, and there are three ways to send work there:
#![allow(unused)] fn main() { let replica = Database::connect(&replica_url).await?; // One query let recent = User::query_with(&replica).order_desc(User::ID).limit(10).get().await?; // One lookup by key let user = User::find_with(user_id, &replica).await?; // Every model call inside a block, with no handle passed around let tenant = Database::connect(&tenant_url).await?; let user = tenant .scope(async { let user = User::create(user).await?; Post::create(Post { user_id: user.id, ..Default::default() }).await?; Ok(user) }) .await?; }
Inside scope, a call that names no database (User::create, User::query(), user.update()) runs on the scope's database. Database::current() returns whichever database such a call would use here: the enclosing transaction's, else the scope's, else the global one.
A call that names a database joins the innermost enclosing transaction opened on that database's pool; inside another database's transaction it keeps to its own connection, so a replica read inside a primary's transaction still goes to the replica. Transactions covers how transactions and scopes combine.
Work started with tokio::spawn inside a scope runs outside it, on the global database: await it inside the scope, or open the scope inside the spawned task.
Data Type Mappings
A field's Rust type decides its column type. Schema sync and migrations create these columns, and reads and writes convert through them:
| Rust type | PostgreSQL | MySQL and MariaDB | SQLite | Notes |
|---|---|---|---|---|
i8 | SMALLINT | TINYINT | INTEGER | |
i16 | SMALLINT | SMALLINT | INTEGER | |
i32 | INT4 | INT | INTEGER | |
i64 | BIGINT | BIGINT | INTEGER | Recommended for primary keys |
u8 | SMALLINT | TINYINT UNSIGNED | INTEGER | |
u16 | INT4 | SMALLINT UNSIGNED | INTEGER | |
u32 | BIGINT | INT UNSIGNED | INTEGER | |
u64 | BIGINT | BIGINT UNSIGNED | INTEGER | PostgreSQL and SQLite store up to i64::MAX; a larger value is refused when it is written |
f32 | REAL | FLOAT | REAL | |
f64 | DOUBLE PRECISION | DOUBLE | REAL | |
bool | BOOLEAN | TINYINT(1) | INTEGER | |
String | TEXT | LONGTEXT | TEXT | Schema sync creates a MySQL key or indexed column as VARCHAR(255), because MySQL cannot index TEXT without a prefix length |
Uuid | UUID | BINARY(16) | TEXT | MySQL binds a UUID as 16 raw bytes, so the column must be BINARY(16) |
Decimal | DECIMAL | DECIMAL(65,30) | REAL | See Decimals on SQLite |
serde_json::Value | JSONB | JSON | TEXT | MariaDB stores JSON as LONGTEXT |
Vec<u8> | BYTEA | LONGBLOB | BLOB | Binary data |
NaiveDate | DATE | DATE | TEXT | Date only |
NaiveTime | TIME | TIME(6) | TEXT | Time only |
NaiveDateTime | TIMESTAMP | DATETIME(6) | TEXT | No time zone |
DateTime<Utc> | TIMESTAMPTZ | DATETIME(6) | TEXT | With time zone; DateTime<Local> and DateTime<FixedOffset> map the same way |
Option<T> | nullable | nullable | nullable | Wraps any type above to make the column nullable |
PostgreSQL's INT4 is its INTEGER, written out so CockroachDB, which reads a bare INT as 64-bit, creates the same column.
tideorm::prelude has short names for some of these: Json and Jsonb for serde_json::Value, Text for String, and IntArray, BigIntArray, TextArray, BoolArray, FloatArray and JsonArray for the array types below.
Arrays
On PostgreSQL a field can be an array: Vec<i32>, Vec<i64>, Vec<f64>, Vec<bool>, Vec<String> or Vec<serde_json::Value>, stored as the matching T[] column. MySQL, MariaDB and SQLite have no array columns: keep a list in a JSON column (serde_json::Value) there, and the array filters and updates work on it as a JSON array. See JSON and Arrays.
Enums, Newtypes and Other Types
A field of a type with no column mapping fails to compile, with an error at the field that says the type "is not a type a column can hold". Give the type a mapping, or keep it out of the table:
-
An enum stored as text derives
DeriveActiveEnum, with the value each variant stores:#![allow(unused)] fn main() { use tideorm::prelude::*; #[derive( Debug, Clone, Default, PartialEq, Eq, tideorm::orm::EnumIter, tideorm::orm::DeriveActiveEnum, serde::Serialize, serde::Deserialize, )] #[orm(rs_type = "String", db_type = "String(StringLen::None)")] pub enum OrderStatus { #[default] #[orm(string_value = "pending")] Pending, #[orm(string_value = "shipped")] Shipped, } #[tideorm::model(table = "orders")] pub struct Order { #[tideorm(primary_key, auto_increment)] pub id: i64, pub status: OrderStatus, } } -
A newtype over a mapped type derives
tideorm::orm::DeriveValueTypeand takes its inner type's column (struct Cents(i64)is aBIGINT). -
A field that is not a column at all is marked
#[tideorm(skip)].
UnixTimestamp and UnixTimestampMillis in the prelude convert between epoch seconds or milliseconds and DateTime<Utc>, and have no column type of their own: store the i64 (as_seconds()) and convert at the edges.
Dates and Times
Use DateTime<Utc> for moments in time, such as when a row was created or a session expires; on PostgreSQL it is a TIMESTAMPTZ. Use NaiveDateTime for a wall-clock time with no zone, NaiveDate for a date and NaiveTime for a time of day.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "sessions")] pub struct Session { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub expires_at: DateTime<Utc>, // TIMESTAMPTZ pub last_seen: NaiveDateTime, // TIMESTAMP pub birthday: Option<NaiveDate>, // DATE pub opens_at: NaiveTime, // TIME } }
Each has a migration column method of its own:
#![allow(unused)] fn main() { schema.create_table("sessions", |t| { t.id(); t.big_integer("user_id").not_null(); t.timestamptz("expires_at").not_null(); t.timestamp("last_seen").default_now(); t.date("birthday"); t.time("opens_at").not_null(); t.timestamps(); // created_at and updated_at, TIMESTAMPTZ }).await?; }
timestamps() creates TIMESTAMPTZ columns that default to now; timestamps_naive() creates TIMESTAMP ones. See Migrations.
PostgreSQL's infinity and -infinity dates and TIME '24:00:00' have no Rust value, so a typed read of such a row fails with an error naming the column; get_json() returns them as text.
MySQL and MariaDB Storage
- Every timestamp is a
DATETIME(6): MySQL'sTIMESTAMPonly spans 1970 to 2038, and a column without fractional digits drops microseconds. Each connection runs in UTC, so aDateTime<Utc>is stored as its UTC wall time. - Text and binary columns are
LONGTEXTandLONGBLOB, becauseTEXTandBLOBstop at 64 KB, and tables are createdDEFAULT CHARSET=utf8mb4whatever the database's default, so any RustStringfits. - Each connection takes
NO_BACKSLASH_ESCAPESout of its session's SQL mode, since SQL written for MySQL escapes with backslashes.
Decimals on SQLite
SQLite has no exact decimal type, and a REAL keeps about 15 significant digits. A decimal is read as SQLite stores it, so a column declared TEXT keeps every digit but compares as text. Store minor units in an integer (cents in an i64) to keep both.
Backend Differences
The query builder, the model API and migrations work on every backend. These are the places where what runs differs:
| Feature | PostgreSQL | MySQL | MariaDB | SQLite |
|---|---|---|---|---|
| JSON columns and JSON filters | Yes (JSONB) | Yes | Yes | Yes (JSON1 functions) |
Array columns (Vec<T> fields) | Yes | No: JSON arrays | No: JSON arrays | No: JSON arrays |
| A single-row insert returns the row in one statement | Yes | No: read back after | Yes (10.5+) | Yes |
execute_returning() (UPDATE .. RETURNING) | Yes | No | No | Yes |
| Upsert | ON CONFLICT | Locked read, then update or insert | As MySQL | ON CONFLICT |
| Window functions and CTEs | Yes | Yes | Yes | Yes |
GROUPS window frames | Yes | No | No | Yes |
| Full-text search | Yes | Yes | Yes | Yes (FTS5) |
Schema-qualified tables (schema.table) | Schemas | Databases | Databases | No |
lock_for_update() | Yes | Yes | Yes | Renders nothing: SQLite locks the whole database |
lock_for_share() | FOR SHARE | FOR SHARE | LOCK IN SHARE MODE | Renders nothing |
skip_locked(), nowait() | Yes | Yes | Yes (SKIP LOCKED from 10.6) | Render nothing |
A clause a backend lacks fails the query with an error when it runs; TideORM never drops it or runs the query without it. debug_for(DatabaseType::MySQL) and build_sql_preview_for(..) show a query in another backend's dialect (see Logging and Profiling).
JSON Operations
JSON filters are written once and translated to each backend:
#![allow(unused)] fn main() { Product::query() .where_json_contains("metadata", json!({"featured": true})) .get() .await?; }
| Operation | PostgreSQL | MySQL and MariaDB | SQLite |
|---|---|---|---|
| Contains | (col)::jsonb @> value | JSON_CONTAINS(col, value), with type guards | Rebuilt from json_each |
| Key exists | jsonb_typeof(col) = 'object' AND (col)::jsonb ? 'key' | JSON_CONTAINS_PATH(col, 'one', '$."key"') | json_type(col, '$."key"') IS NOT NULL |
| Path exists | jsonb_path_exists((col)::jsonb, 'strict $.path', '{}', TRUE) | JSON_CONTAINS_PATH(col, 'one', '$.path') | json_type(col, '$.path') IS NOT NULL |
where_json_key_not_exists and where_json_path_not_exists negate the two tests. On every backend a member that holds JSON null exists, and a NULL column matches neither a test nor its negation. A path is $ followed by .key, ."quoted key" or [index] steps, or those steps alone, read from the root (a.b[0] is $.a.b[0]). Every backend reads it strictly: a key exists only in an object, never as a string element of an array, a step never looks inside an array it does not index, and an index never reads a value that is not an array as an array of one (MySQL's indexed steps check their parent is an array). A path with other steps fails the query, except on PostgreSQL (not CockroachDB), which reads it as the JSONPath written.
PostgreSQL's JSON operators exist only for jsonb, so the column is cast: they work on a json column (what t.json(..) creates) too, and on a jsonb column the cast is dropped at planning, so its GIN index still applies.
SQLite has no containment operators, so TideORM rebuilds PostgreSQL's @> and <@ from json_each: an object matches key by key, an array element by element, and a bare scalar matches a top-level array that holds it. MySQL's JSON_CONTAINS lets a value match an array holding it at any depth, so on its own {"tags": "a"} would match {"tags": ["a", "b"]}; TideORM adds a type check for each path of the document you pass, so MySQL and MariaDB follow PostgreSQL there too. Below an array the paths are not known in advance, so MySQL's reading stays there: [{"k": [1, 2]}] contains [{"k": 1}] on MySQL and not on PostgreSQL.
Equality on a JSON column (where_eq) compares documents, not text: = on MySQL's JSON type, JSON_EQUALS on MariaDB, and a structural comparison built from json_each on SQLite, so key order and 1.0 against 1 do not matter.
Array Operations
The array filters (where_array_contains, where_array_contained_by, where_array_overlaps) take a list of values:
#![allow(unused)] fn main() { Product::query() .where_array_contains("tags", vec!["sale", "featured"]) .get() .await?; }
| Backend | Column | How each filter runs |
|---|---|---|
| PostgreSQL | A native array | Each value is tested with value = ANY(col): all of them for contains, any for overlaps; contained-by checks that no element lies outside the list |
| MySQL and MariaDB | A JSON array | Contains and contained-by are JSON_CONTAINS with the list as a JSON document; overlaps is the containment of any one value. A column holding something other than an array matches nothing |
| SQLite | A JSON array | Each value is looked up with EXISTS (SELECT 1 FROM json_each(col) ..), compared as JSON, so 1 is not true. A column holding something other than an array matches nothing |
JSON and Arrays covers every JSON and array filter and update.
Other Differences
- Text length and types. SQLite checks neither, so a string longer than its
VARCHAR(255)is stored there and refused by PostgreSQL and MySQL.#[validate(max_length = 255)]keeps the backends in step; see Validation. - Trailing spaces. MariaDB's default collations ignore trailing spaces in
=; MySQL 8's do not. - Window defaults. MariaDB's
LAGandLEADtake no default value, so TideORM writes the default with aCASEaround them. - Subquery limits. MySQL and MariaDB refuse a
LIMITin anINsubquery. - Transactions. SQLite refuses a read-only transaction (
AccessMode::ReadOnly), and runs a migration inside a transaction, wherePRAGMA foreign_keyshas no effect. See Transactions and Migrations. - Altering tables. SQLite's
ALTER TABLEcannot change or drop some columns; TideORM refuses those with an error that explains how to rebuild the table. MySQL and MariaDB keep a changed column'sNOT NULL, default, auto-increment and comment, as PostgreSQL does. See Migrations. - Batch inserts. PostgreSQL, MariaDB and SQLite insert a batch with multi-row
INSERT .. RETURNING; MySQL inserts multi-row statements and reads them back with oneSELECTwhen the keys are known in advance, and otherwise inserts row by row. See Reading and Writing. - Upserts. MySQL's
ON DUPLICATE KEY UPDATEfires on any unique key, so on MySQL and MariaDB TideORM locks the row the conflict columns name and updates it or inserts, in one transaction. See Reading and Writing. - Large
where_inlists. Past 1,000 values PostgreSQL binds one array (= ANY($1)), SQLite binds a text list as one JSON value, and an all-integer list is written as literals elsewhere, which keeps a query under the backend's parameter limit. Any other list binds one parameter per value, so on MySQL and MariaDB a text list stops at 65,535 values (error 1390).
Compatible Servers
Four distributed databases speak a protocol TideORM already has a driver for, and TideORM runs on them with no change to your models or queries:
| Server | Protocol | Feature | URL |
|---|---|---|---|
| CockroachDB | PostgreSQL | cockroachdb | postgresql://root@host:26257/app |
| YugabyteDB (YSQL) | PostgreSQL | yugabytedb | postgresql://yugabyte@host:5433/app |
| TiDB | MySQL | tidb | mysql://root@host:4000/app |
Vitess (vtgate) | MySQL | vitess | mysql://user@host:15306/keyspace |
Each feature is another name for its protocol's (cockroachdb and yugabytedb for postgres,
tidb and vitess for mysql) and builds the same code, so either name works (see Installation). The backend
stays DatabaseType::Postgres or DatabaseType::MySQL, so the SQL dialect is that protocol's.
The connection also learns which server answered, from what the server reports as it connects
(CockroachDB's crdb_version parameter, the -YB-, -TiDB- and -Vitess marks in the version
string), and Database::server() returns it (see Databases):
use tideorm::prelude::*;
match db.server() {
Some(DatabaseServer::CockroachDb) => println!("CockroachDB"),
Some(server) => println!("{server}"),
None => println!("not connected yet"),
}
TideORM's own PostgreSQL and MySQL test suites run against each server in CI (CockroachDB 26.4, YugabyteDB 2025.2, TiDB 8.5 and Vitess 24 on MySQL 8.0). A scenario that needs something a server does not have is skipped there; the lists below name each one.
CockroachDB
Each new connection sets three session variables, so SQL written for PostgreSQL means the same thing there:
serial_normalization = sql_sequence: aSERIALcolumn takes its values from a sequence, as on PostgreSQL, instead ofunique_rowid()'s large, unordered 64-bit values.autocommit_before_ddl = off: DDL inside a transaction stays in it, so a failed migration rolls back as a whole instead of committing the statements before it.create_table_with_schema_locked = off: a new table can be altered inside a transaction, which migrations do.
A variable the server's version lacks is left out.
Integer widths. CockroachDB reads a bare INT or SERIAL as 64-bit. Migrations therefore
write INT4, SERIAL4 and BIGINT/BIGSERIAL explicitly (the same types on PostgreSQL), so an
i32 field gets the 32-bit column it decodes from. Write INT4 in your own SQL too. TideORM
leaves default_int_size at 8: at 4 every sequence, BIGSERIAL's included, would stop at
2,147,483,647.
Transactions. CockroachDB runs every transaction SERIALIZABLE and may abort one that
conflicts with another (SQLSTATE 40001, "restart transaction"). That error's failure_kind() is
SerializationFailure and is_retryable() is true: run the transaction again (see
Retrying a Transaction).
Shared locks. Under SERIALIZABLE CockroachDB takes no lock for lock_for_share() (unless
its enable_shared_locking_for_serializable setting is on), so such a read waits for a row locked
FOR UPDATE as a plain read does, and nowait() does not make it fail.
Decimals in a list. CockroachDB reads each value of an IN list as the column's type, so
against an integer column it would round a decimal 5.4 to 5, and fail on a u64 past
i64::MAX (which TideORM binds as a decimal). TideORM casts a decimal in a where_in list to
NUMERIC, so it compares as on PostgreSQL. Write the cast in your own SQL too.
Ordering. In ascending order CockroachDB puts NULLs first, PostgreSQL last. TideORM keeps
CockroachDB's order (its null_ordered_last setting makes it refuse a SELECT DISTINCT ordered
by a nullable column); write NULLS LAST in a raw order_by if the order matters.
Migrations and seeds are serialized with a transaction-scoped advisory lock
(pg_advisory_xact_lock), held on a pinned session for the whole run: CockroachDB has no
session-level pg_advisory_lock. drop_index_if_exists on a table in a schema that does not
exist fails there (3F000), where PostgreSQL skips it.
Schema export. SchemaWriter writes CockroachDB's own SHOW CREATE ALL SCHEMAS, TYPES,
TABLES, ROUTINES and TRIGGERS output: its pg_catalog lacks what the PostgreSQL export
reads. Indexes and defaults are inside each CREATE TABLE, and foreign keys follow the tables,
then an ALTER SEQUENCE .. OWNED BY for each sequence a column owns, which SHOW CREATE leaves out.
A table or view calling a routine comes before that routine in the file.
Not available on CockroachDB: a raw JSONPath in where_json_path_exists (wildcards, filters:
PostgreSQL's @?; a plain path such as a.b[1] works), multirange and multidimensional array
values, NULLS NOT DISTINCT unique constraints, deferrable constraints, arrays of JSONB, a
where_in of arrays on an array column, and the cidr, geometric and range types.
YugabyteDB
TideORM connects to YugabyteDB's YSQL API (port 5433) as it does to PostgreSQL; nothing is set on its connections.
Keys. Each connection caches 100 sequence values by default, so auto-increment keys are
unique but have gaps and are not in insertion order across connections. For dense keys start the
servers with --tserver_flags=ysql_sequence_cache_minval=1.
Ordering. Tables are hash-sharded, so rows come back in hash order unless the query has an
order_by: never rely on insertion order, as with HasMany::load(), which adds no ORDER BY.
Indexes. A GIN index (FullTextIndex, a JSONB index) is created as YugabyteDB's ybgin,
and the schema export writes it so. New tables get YugabyteDB's REPLICA IDENTITY CHANGE, which
the export keeps.
DDL commits as it runs. A CREATE, ALTER or DROP inside a transaction is not rolled
back with it, so a migration that fails part-way leaves the DDL before the failure applied, as on
MySQL; mark reconciles the ledger afterwards.
Read restarts. YugabyteDB retries a read restart by itself only for a single statement. A
DDL statement just after another connection's DDL, or a statement in a multi-statement
exec_raw, can fail with SQLSTATE 40001 ("Restart read required"); is_retryable() is true,
so run it again, and send raw statements one per call.
Clocks. A YugabyteDB server stops when its clock drifts more than 0.5 s from the others
(max_clock_skew_usec); open connections then fail with SQLSTATE 57P01.
Not available on YugabyteDB: nondeterministic (case-insensitive) collations,
DEFERRABLE unique constraints, REPLICA IDENTITY USING INDEX, CLUSTER,
ALTER DOMAIN .. ADD CONSTRAINT, ALTER TABLE .. ENABLE RULE, and a partition with a generation
expression of its own (as on PostgreSQL before 16). UNLOGGED and storage parameters such as fillfactor are
accepted and ignored. A SQL function RETURNS SETOF <table> whose body selects a whole row
(SELECT t FROM t) fails when called (SQLSTATE 42804); select the columns instead.
TiDB
TiDB is tested as one TiDB server; nothing is set on its connections beyond what MySQL's get.
Collation. TiDB's default collation is utf8mb4_bin, so text compares case-sensitively:
where_eq("email", "Ada@example.com") does not find ada@example.com, as it does under MySQL 8's
utf8mb4_0900_ai_ci. Declare the column with a _ci collation if comparisons should ignore case.
Keys. Each TiDB server hands out AUTO_INCREMENT values from its own cached range, so keys
are unique but not consecutive, and not in insertion order across servers.
CHECK constraints are neither stored nor enforced unless tidb_enable_check_constraint is on
(SET GLOBAL tidb_enable_check_constraint = ON); foreign keys are enforced from TiDB 8.5.
Row locks. A locking read outside a transaction takes no lock and waits for none, so lock rows
inside a transaction; there nowait() fails with LockNotAvailable as on MySQL.
TiDB parses SKIP LOCKED but ignores it, returning rows other transactions hold, so
skip_locked() fails the query on TiDB. lock_for_share() fails unless
tidb_enable_noop_functions is on, and then takes no lock.
Not available on TiDB: SERIALIZABLE transactions (error 8048), FULLTEXT indexes and so
full-text search, JSON_TABLE and so array_remove on a JSON array column, invisible columns,
CONCAT in an expression default, and stored procedures, functions, triggers and events (the
schema export has none to write).
Vitess
TideORM connects to vtgate; the database in the URL is the keyspace. It is tested on one
unsharded keyspace.
Several keyspaces. A vtgate serving more than one keyspace cannot drop a view: an
unqualified DROP VIEW fails with VT09005 ("no database selected") even with the keyspace
selected, and a keyspace-qualified one reaches the tablet as written, where the MySQL database is
named vt_<keyspace> unless the tablet sets --init_db_name_override, so DROP VIEW IF EXISTS
finds nothing there. tideorm db wipe and migrate fresh therefore fail on a keyspace that holds
a view; drop views with Online DDL (SET @@ddl_strategy = 'vitess') instead.
Row cap. By default a tablet returns at most 10,000 rows from one statement
(--queryserver-config-max-result-size) and fails a longer result with error 1317. TideORM splits
an insert_all into statements of at most 10,000 rows, since each is read back with one SELECT.
Read a larger result with chunk() or paginate() (see Query Builder), or raise
the limit.
Transaction timeout. A tablet kills a transaction open for 30 seconds by default
(--queryserver-config-transaction-timeout). A long batch in one transaction, such as an
insert_all of tens of thousands of models whose keys are text (inserted a row at a time), needs
more.
Locks. Migrations and seeds take GET_LOCK, which vtgate holds on a reserved connection of
the session and releases when the session ends.
Schema export. SchemaWriter leaves out the ALTER DATABASE COLLATE statements it writes
for MySQL, since Vitess manages a keyspace's collation; each table names its own in its
CREATE TABLE.
Not available through Vitess: CREATE DATABASE and ALTER DATABASE (keyspaces are managed by
Vitess), and CREATE FUNCTION, TRIGGER and EVENT (vtgate accepts CREATE PROCEDURE), so
an export holding functions, triggers or events does not replay through it. In a sharded
keyspace, an AUTO_INCREMENT key needs a Vitess sequence.
Defining Models
A model is a plain Rust struct that maps to one table. Each instance is one row, and the struct carries the methods that read and write it.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub name: String, pub active: bool, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } }
That struct is ready to use: User::find(1), User::query(), user.save() and the rest are described in Reading and Writing.
#[tideorm::model] and #[derive(Model)]
#[tideorm::model(..)] is shorthand. It rewrites the struct to #[derive(tideorm::Model)] and moves its arguments into a #[tideorm(..)] attribute, so these two definitions are the same model:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts", soft_delete)] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub deleted_at: Option<DateTime<Utc>>, } }
#![allow(unused)] fn main() { use tideorm::prelude::*; #[derive(Model)] #[tideorm(table = "posts", soft_delete)] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub deleted_at: Option<DateTime<Utc>>, } }
Put the struct options in one place: inline in #[tideorm::model(..)], or in a #[tideorm(..)] attribute on a #[derive(Model)] struct. Giving them in both, or adding #[derive(Model)] to a struct that already has #[tideorm::model], is a compile error. Both forms apply only to structs with named fields, and a model cannot be generic: it maps one struct to one table.
Generated Implementations
Besides the TideORM traits, a model gets Debug, Clone, Default, Serialize and Deserialize.
You can derive any of these yourself, and TideORM then skips its own, as long as your derive is a separate #[derive(..)] attribute below #[tideorm::model(..)] (or below #[derive(Model)]). A derive above it, or in the same list as Model (#[derive(Model, Debug)]), is never shown to TideORM, and the two implementations fail with "conflicting implementations" (E0119). Move it below, or opt out of TideORM's implementation with a skip_* option.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub display_name: String, // serialized as "displayName" } }
Your derive then decides the JSON. to_json() and the hidden attributes follow its renames. Relation fields serialize as null until they are loaded, and a request body that leaves out a relation or a managed timestamp deserializes only if that field is #[serde(default)].
Do not put #[serde(flatten)] on a hidden field or on a typed relation. Flattening removes the boundary TideORM needs to filter that field's contents: try_to_json() returns a configuration error, to_json() logs it and returns {}, and an affected eager-loaded model renders as {}. Remove flatten, or mark the field skip_serializing. Public fields can still be flattened.
To write all of these impls yourself, use skip_derives:
#![allow(unused)] fn main() { use std::fmt; use tideorm::prelude::*; #[tideorm::model(table = "products", skip_derives)] #[derive(Clone, Default, serde::Serialize, serde::Deserialize)] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub sku: String, pub price: i64, } impl fmt::Debug for Product { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Product").field("sku", &self.sku).finish() } } }
Whatever you skip, implement yourself where your code needs it; every model must be Clone, Serialize and Deserialize.
Table and Column Names
Without table = "..", the table is the struct name in snake case, pluralized: User is users, BlogPost is blog_posts, Category is categories. A column is the field name in snake case (any r# prefix removed, so r#type is type) unless #[tideorm(column = "..")] names it.
The snake-case rules split words at _, at a lowercase letter followed by an uppercase one, between letters and digits, and before the last capital of an acronym:
| Name | Snake case |
|---|---|
UserProfile | user_profile |
HTTPRequest | http_request |
XMLParser | xml_parser |
sha256 | sha_256 |
S3Object | s_3_object (table s_3_objects) |
_private | _private |
Digits split off as their own word, so a field sha256 maps to the column sha_256. Use #[tideorm(column = "sha256")] when the column is named otherwise.
Pluralization adds es after s, x, z, ch and sh, turns a final y after a consonant into ies, and adds s otherwise. A short list of irregular words is recognised when the whole snake-case name is that word: person, man, woman, child, tooth, foot, mouse, goose, leaf, knife, life, wife, wolf, calf, half, loaf, self, shelf, thief, quiz and fez. So Person is people, but SalesPerson is sales_persons. Name the table explicitly when the generated one is not what you want.
Struct Options
| Option | Meaning |
|---|---|
table = "name" | The table name. |
schema = "name" | The schema the table lives in (a database, on MySQL and MariaDB). Every statement names the table as schema.table, and joins accept "schema.table" too. |
soft_delete | Deleting marks rows instead of removing them. See Soft Deletes and Scopes. |
deleted_at_column = "name" | The soft-delete field or column, when it is not deleted_at. Requires soft_delete. |
timestamps | Mark the model as timestamped. created_at and updated_at fields are managed either way; see Callbacks and Timestamps. |
hidden = "a,b" | Leave these out of to_json(). See Hidden Attributes. |
tokenize | Generate to_token() and from_token(). See Tokenization. |
encrypted = "a,b" | Store these fields encrypted. Requires the encrypted-fields feature; see Encrypted Fields. |
searchable = "a,b" | The columns searchable_fields() lists, to pass to a full-text search. See Full-Text Search. |
translatable = "a,b", languages = "en,fr", fallback_language = "en" | Translated fields. Requires the translations feature and a HasTranslations impl; see Translations. |
has_one_files = "a", has_many_files = "b" | File attachment slots. Requires the attachments feature and a HasAttachments impl; see File Attachments. |
skip_derives | Skip the generated Debug, Clone, Default, Serialize and Deserialize. |
skip_debug, skip_clone, skip_default, skip_serialize, skip_deserialize | Skip one of them. |
List options are one comma-separated string. An empty name in the list ("a,,b") is a compile error.
Hidden Attributes
hidden names fields, columns (which hide their field) or attachment relations. A name that is one field's name and another field's column hides both, and a name that matches nothing is a compile error. Without hidden, the soft-delete field (deleted_at by default) is hidden.
Hidden attributes are left out of to_json(), try_to_json() and to_hash_map(). Plain serde (serde_json::to_value(&user), a framework's Json(user)) and query().get_json() still include them. TideConfig::hidden_attributes([..]) hides names from to_json() for every model; see Configuration.
Indexes
Indexes are declared on the struct or on a field. Schema sync creates them, and ModelMeta::indexes() and unique_indexes() list them.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "products")] #[index("category")] #[index(name = "idx_price_category", columns = "price,category")] #[unique_index("sku")] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, pub sku: String, pub category: String, pub price: i64, #[index] pub active: bool, } }
| Form | Index |
|---|---|
#[index("col")], #[index("a,b")], #[index("a", "b")], #[index(a, b)] | On those columns, named idx_<table>_<columns> |
#[index(name = "idx", columns = "a,b")] | On those columns, under that name |
#[unique_index(..)] | The same forms, unique; a generated name ends in _unique |
#[index], #[unique_index] on a field | On that field's column |
A generated name longer than 63 bytes is shortened with a hash. Columns may be named by field or by column; a name the model does not declare is a compile error, and so is an index over an encrypted field.
Field Options
| Option | Meaning |
|---|---|
primary_key | Part of the primary key. Mark each field of a composite key. |
auto_increment | The database numbers this key. Only on a single-column integer primary key. |
column = "name" | The column name, when it is not the field name in snake case. Two fields cannot share a column; that is a compile error. |
nullable | The column accepts NULL. An Option field is nullable without it. |
default = "value" | The column's DEFAULT in tables that schema sync creates. Inserts send every field's value, so a model built with ..Default::default() stores the field's Rust default, not this one. |
skip | Not a column. It is never read or written, holds its Default on every model a query or write returns, and may be left out when deserializing. |
Every other field is a column, and its Rust type decides the column type (see Databases for the mappings). A field type TideORM cannot store fails to compile at that field. Relation fields (HasOne<T>, HasMany<T>, BelongsTo<T> and the rest) are not columns; their options are on the Relations page.
A skip field is useful for values a request carries but the table does not, such as a password confirmation checked by validation.
Primary Keys
Every model has a primary key; a struct without a #[tideorm(primary_key)] field is a compile error. A primary key field cannot be an Option.
auto_increment needs primary_key and an integer type. On such a key, 0 means "not saved yet": save() inserts a model whose key is 0, and the database assigns the key. See Reading and Writing for how save() treats other keys.
A Uuid primary key still at the nil UUID when the row is inserted gets a random (v4) key, whether through save(), create(), insert_all() or an upsert. Set the key yourself, in before_create for instance, to use another UUID version.
Composite Keys
Mark each field of the key. Methods that take a key take a tuple, in the order the fields are declared:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "user_roles")] pub struct UserRole { #[tideorm(primary_key)] pub user_id: i64, #[tideorm(primary_key)] pub role_id: i64, pub granted_by: String, } async fn load() -> tideorm::Result<Option<UserRole>> { UserRole::find((1_i64, 2_i64)).await } }
auto_incrementis refused on a composite key.tokenizeneeds exactly one key field.- A relation on a composite-key model needs an explicit
local_key = "..". BatchUpdateBuilder::limitis refused for a composite key on PostgreSQL and SQLite.
Generated Items
The derive also emits:
- A typed column constant per column (
User::EMAIL, aColumn<String>) and theUser::columnsstruct with one field per column (User::columns.email). See Typed Columns. - A constant per relation field holding its name (
User::POSTSis"posts"), for eager loading. ModelMeta, whose associated functions describe the model:table_name(),schema_name(),primary_key_names(),primary_key_name(),primary_key_auto_increment(),column_names(),field_names(),hidden_attributes(),searchable_fields(),translatable_fields(),encrypted_fields(),soft_delete_enabled(),deleted_at_column(),has_timestamps(),indexes()andunique_indexes(), among others.Validatefrom the#[validate(..)]rules (see Validation), andTokenizablewhentokenizeis set.- A registration that lets
TideConfig::auto_models()andmodels_matching(..)find the model (see Schema Sync and Export).
Reserved Names
params is reserved for presenter payloads: when a model's serialized params value is an object or an array, to_hash_map() leaves it out. Use another name for structured data you need in to_hash_map() output.
Compile-Time Checks
Mistakes in a model's declaration are compile errors at the model, field or attribute:
- a generic struct, or a struct with no primary key;
- an
Optionprimary key,auto_incrementon a non-integer, non-key or composite key, ortokenizewithout exactly one key; deleted_at_columnwithoutsoft_delete, or a soft-delete field whose type is notOption<DateTime<Utc>>;- a
hidden, index orsearchablename the model does not declare, or one that is ambiguous; - an encrypted primary key, or an index or
searchableentry over an encrypted field; - a relation option on a field whose type is not the matching wrapper, a wrapper inside
Option,Box,RcorArc, or a relation missing itsforeign_key; - a
#[validate(..)]rule on a relation field, or an unknown rule; - a field type TideORM cannot store.
Rules from your project's tideorm.toml add checks of their own; see Project Rules.
Choosing the Database a Call Uses
Model methods take no connection argument. They run on the database the surrounding code chooses:
| You want | Use |
|---|---|
| The application's database | nothing: User::find(id), User::query(), user.save() |
| One read from another database, such as a replica | User::query_with(&replica), User::find_with(id, &replica); eager loads of that query read there too |
| Every call in a piece of code on another database, such as a tenant's | tenant_db.scope(async { .. }) |
| Several writes that succeed or fail together | db.transaction(..) or db.atomically(..), see Transactions |
A call that names no database uses the innermost scope around it (a transaction is one), else the global database. A call that names one (query_with, find_with) joins the innermost enclosing transaction opened on that database's pool, and otherwise runs on that database's own connection, even inside another database's transaction: a replica read inside a primary's transaction goes to the replica, outside the transaction. Model writes (create, save, update, delete) name no database, so run them inside a scope or a transaction of the database they belong to.
That lets one service function serve every database, with the caller choosing where it runs:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn rename(id: i64, name: String) -> tideorm::Result<User> { let mut user = User::find_or_fail(id).await?; user.name = name; user.update().await } async fn examples(tenant_db: &Database, primary: &Database, replica: &Database) -> tideorm::Result<()> { let user = tenant_db.scope(rename(7, "Ada".into())).await?; // the tenant's database let user = primary.atomically(rename(7, "Ada".into())).await?; // in a transaction let total = Order::query_with(replica).count().await?; // a replica read Ok(()) } }
scope runs every call inside it on that database without opening a transaction:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn sign_up(tenant_db: &Database, user: User) -> tideorm::Result<User> { tenant_db .scope(async { let user = User::create(user).await?; Profile::create(Profile { user_id: user.id, ..Default::default() }).await?; Ok(user) }) .await } }
Database::current() returns the database a call naming none would use here. Databases covers connecting to several databases.
Reading and Writing
Every model has methods to insert, read, update and delete its rows, plus batch versions for many rows at once. This page uses the User model from Defining Models.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn example() -> tideorm::Result<()> { let user = User::create(User { email: "ada@example.com".into(), name: "Ada".into(), active: true, ..Default::default() }) .await?; let mut user = User::find_or_fail(user.id).await?; user.name = "Ada Lovelace".into(); let user = user.update().await?; user.delete().await?; Ok(()) } }
Every method runs on the database the surrounding code chooses; see Choosing the Database a Call Uses.
Create
Model::create(model) always inserts. model.save() inserts a new model and updates a saved one (see How save() Decides). Both return the row as stored, with its generated key and timestamps. An insert sends every field, so a column's database default never takes the place of a field's value.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn register(email: String, name: String) -> tideorm::Result<User> { let user = User { email, name, active: true, ..Default::default() }; let user = user.save().await?; println!("created user {}", user.id); Ok(user) } }
For an auto-increment key, 0 marks a model that is not saved yet, so you do not set the key when building a new model. create() and insert_all() let the database number a key still at 0 and write a key the model holds, as an upsert does; reset a loaded model's key to 0 before creating a copy of it.
After writing a key the model holds, TideORM moves PostgreSQL's sequence for the key past it, so the next key the database numbers does not collide with it. This needs UPDATE permission on the sequence; without it, the sequence is left alone. MySQL's AUTO_INCREMENT and SQLite's rowid move by themselves.
Read
| Call | Returns |
|---|---|
User::find(id) | Option<User> for that key |
User::find_or_fail(id) | the User, or Error::NotFound ("users with id = 7 not found") |
User::find_with(id, &db) | find on a specific database |
User::exists(id) | true when the key exists |
User::all() | every row. There is no limit, so use a query or paginate for tables that grow |
User::first() | one row, or None. No order is applied, so "first" is whichever row the database returns first |
User::last() | the row with the highest primary key |
User::count() | the number of rows |
User::exists_any() | true when the table has a row; cheaper than count() |
User::paginate(page, per_page) | one page and the total count (Paginated), pages numbered from 1, ordered by primary key |
User::query() | a query builder for everything else |
User::query_with(&db) | a query builder on a specific database |
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn reads() -> tideorm::Result<()> { let user = User::find(1).await?; // Option<User> let role = UserRole::find((1_i64, 2_i64)).await?; // composite key let active = User::query().where_eq(User::ACTIVE, true).get().await?; let page = User::paginate(1, 20).await?; Ok(()) } }
paginate returns a validation error when page or per_page is 0, or when per_page or the page's offset is past i64::MAX. For another order, use User::query().order_asc(..).paginate(page, per_page).
On a soft-delete model every read leaves trashed rows out, find(id) and exists(id) included.
model.reload() reads the row again and returns a fresh copy, leaving the one in hand unchanged. It reads a trashed row too, and returns Error::NotFound when the row is gone. model.is_new() says whether save() would insert.
Update
model.update() writes the model's columns to the row with its primary key and returns the row as stored. It returns Error::NotFound when no row has that key.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn rename(id: i64, name: String) -> tideorm::Result<User> { let mut user = User::find_or_fail(id).await?; user.name = name; user.update().await } }
update() writes every column of the model, not only the fields you changed, so two requests that each change one field of the same row undo each other's change. To write only some columns, name them in a batch update, which runs no hooks or validation and stamps no timestamp:
User::update_all()
.set(User::NAME, name)
.set(User::UPDATED_AT, Utc::now())
.where_eq(User::ID, id)
.execute()
.await?;
To refuse a write based on a stale read (optimistic concurrency), keep a version column and make the write conditional on it. Zero rows written means someone else wrote first:
let written = Document::update_all()
.set(Document::BODY, body)
.increment(Document::VERSION, 1)
.where_eq(Document::ID, id)
.where_eq(Document::VERSION, version_read)
.execute()
.await?;
if written == 0 {
// reload and show the newer version, or report a conflict
}
Or lock the row for the read-check-write, as Transactions shows.
How save() Decides
save() chooses between an insert and an update by the primary key:
- A key still at its default (
0, an empty string, a nil UUID, or any component of a composite key at its default) inserts. - A single auto-increment key that is set updates. A key no row holds is
Error::NotFound, not an insert: reset the key to0to insert a copy. - Any other key that is set (natural, UUID, composite) updates the row with that key, a trashed one included, and inserts when there is none.
For that last case, a model with callbacks first checks whether the row exists, so the right hooks run; a model without callbacks tries the update and inserts when it matched no row.
Delete
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn deletes() -> tideorm::Result<()> { if let Some(user) = User::find(1).await? { user.delete().await?; // this row } User::destroy(2).await?; // by key User::query() .where_eq(User::ACTIVE, false) .delete() .await?; // the rows a query matches Ok(()) } }
delete() and destroy(id) run the delete callbacks and return the number of rows deleted: 0 when the row was already gone. destroy(id) loads the row and deletes it, so its callbacks run too.
query().delete() needs at least one filter; an unfiltered delete, or a filter that is always true, is refused. To delete every row on purpose, use User::delete_all() (or User::query().delete_all(), which refuses filters). Query deletes run no callbacks.
On a soft-delete model, delete(), destroy(), query().delete() and delete_all() mark rows deleted instead of removing them, and force_delete() removes them. See Soft Deletes and Scopes.
Choosing a Write
| Call | Hooks | Validates | Timestamps | No row matches | Returns |
|---|---|---|---|---|---|
Model::create(m) | validation, save, create | yes | sets created_at and updated_at | always inserts | the stored row |
m.save() | those of the create or update it runs | yes | as create or update | see above | the stored row |
m.update() | validation, save, update | yes | sets updated_at | Error::NotFound | the stored row |
m.delete(), Model::destroy(id) | delete; after_delete only when a row went | no | none | Ok(0) | rows affected |
Model::insert_all(models) | none | yes, every model before any is written | as create | always inserts | the stored rows, in input order |
Model::on_conflict(..), insert_or_update(..) | none | yes | an insert sets both; an update refreshes updated_at only when it is in the update set | inserts | the stored row |
update_all()…execute() | none | no | none: set updated_at yourself | Ok(0) | rows affected |
query()…delete(), delete_all() | none | no | none | Ok(0) | rows affected |
The stored row is read back from the database, so it carries generated keys, defaults and stamped timestamps. Nested saves (save_with_many(..), see Relations) run each model's own save(), hooks included, in one transaction.
Dirty Tracking
Requires the dirty-tracking feature.
Models loaded or saved through TideORM keep a baseline of their last known stored column values. changed_fields() lists the fields that differ from it, and original_value(field) returns a field's value in it.
Both return an outer Option that separates "no baseline is known" (None) from "a baseline exists and nothing changed" (Some(vec![])). Treat None as unknown rather than unchanged; otherwise a model with no baseline silently skips its write.
let mut user = User::find(1).await?.unwrap();
user.name = "Jane Doe".to_string();
assert_eq!(user.changed_fields()?, Some(vec!["name"]));
// The inner `Option` is the column's own value, `None` for NULL.
assert_eq!(
user.original_value("name")?,
Some(Some(DbValue::from("John Doe")))
);
is_dirty() and is_field_dirty(field) answer the same question with a bool, None again meaning no baseline. The usual gate saves unless the model is known to be unchanged:
// Nothing to compare against (`None`): save rather than guess.
if user.is_dirty()? != Some(false) {
user = user.save().await?;
}
if user.is_field_dirty(User::columns.email)? == Some(true) {
send_confirmation(&user).await?;
}
original_value and is_field_dirty take a field name, a column name or a typed column, and return an error for a name the model does not have.
- Only stored fields are tracked, not relation wrappers.
- The baseline is refreshed by
find(), query results,reload(),save()andupdate(). Batch writes such asupdate_all()and query deletes forget the baselines of that model type in the task that runs them. - A model built by hand or deserialized from JSON has no baseline, and neither has one whose baseline was evicted from the bounded store.
Models are plain structs with no hidden tracking state, so baselines are kept per async task: each task (a request a server handles, a background job) compares a row with the copy it last read or wrote, and two tasks editing one row side by side never see each other's writes. A task that did not read the row itself, and code outside any task (the body of #[tokio::main] or block_on), compares with the latest baseline TideORM knows for the key. A baseline taken inside a transaction that then rolls back is withdrawn, and the one before it comes back, unless the row got a newer baseline from outside the transaction in the meantime. Copies of one row within one task share a baseline: if one of them saves first, reload the others before relying on their original values.
Each database keeps its own baselines, since two databases can hold different rows under one key (query_with(db), find_with(id, db)). A model does not record which database it came from, so when TideORM has read different rows for a key from two databases, both methods return None for that key rather than compare with the wrong row, until the row is read again.
Returning Models from an Endpoint
Render a model for an API response with try_to_json(). It drops hidden attributes (the model's hidden list and the global ones from TideConfig::hidden_attributes), turns attachment fields into URLs, resolves translatable fields to one language, and returns an error when a field cannot be rendered:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn show(id: i64) -> tideorm::Result<serde_json::Value> { let user = User::find_or_fail(id).await?; user.try_to_json(None) } async fn index() -> tideorm::Result<serde_json::Value> { let users = User::query().limit(50).get().await?; User::try_collection_to_json(&users, None) } }
The other ways to get JSON skip some of that:
| Call | Hidden fields | Attachments and translations | On failure |
|---|---|---|---|
model.try_to_json(options) | left out | URLs, one language | Err |
model.to_json(options) | left out | URLs, one language | logs it and returns {} |
serde_json::to_value(&model), a framework's Json(model) | included | as stored | serde's error |
query().get_json() | included: every selected column | as stored | Err |
Plain serde and get_json() are for internal use (caches, queues, admin exports). Never send them to a client unless the model has nothing to hide.
The options map understands one key, "language", which picks the translation to emit (by default the model's fallback language). to_json_in("fr") and try_to_json_in("fr") are shorthand for it. Model::collection_to_json(models, options) and Model::try_collection_to_json(models, options) render a Vec<Model>, &Vec<Model> or &[Model] as an array.
to_hash_map() flattens to_json(None) into a HashMap<String, String> for templates and forms: numbers and booleans become their text, null becomes "null", and nested objects and arrays become JSON text. A params field holding an object or array is left out.
Inserting Many Rows
Model::insert_all(models) inserts a Vec of models and returns them as stored, in input order:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn seed() -> tideorm::Result<Vec<User>> { User::insert_all(vec![ User { name: "John".into(), email: "john@example.com".into(), ..Default::default() }, User { name: "Jane".into(), email: "jane@example.com".into(), ..Default::default() }, ]) .await } }
Every model is validated before any is written; a failure names the model's position ("the batch's model at index 1"). No callbacks run, before_validation included, so each model is validated as it was built. Managed timestamps are stamped as create() stamps them. An empty Vec returns an empty Vec without touching the database.
How the rows are written depends on the backend:
| Backend | Statement |
|---|---|
| PostgreSQL | multi-row INSERT .. RETURNING, split into chunks inside a transaction when rows times columns pass 65,535 parameters |
| SQLite | multi-row INSERT .. RETURNING, in chunks of up to 32,766 parameters; the rows are put back in input order by key |
| MariaDB 10.5+ | multi-row INSERT .. RETURNING, in chunks of up to 1 MB of values |
| MySQL | models that set their own integer or Uuid key: multi-row INSERTs of up to 1 MB of values, each read back with one SELECT; other models one INSERT per row |
A batch that repeats a key, or an auto-increment batch that mixes set and unset keys, is inserted one row at a time.
Batch Updates
Model::update_all() starts a filtered UPDATE of many rows:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn deactivate_stale(cutoff: DateTime<Utc>) -> tideorm::Result<u64> { User::update_all() .set(User::ACTIVE, false) .set(User::UPDATED_AT, Utc::now()) .where_lt(User::UPDATED_AT, cutoff) .execute() .await } }
execute() runs one UPDATE and returns the number of rows changed. It runs no callbacks or validation and stamps no timestamps. It returns Ok(0) without touching the database when nothing is set, and an error when the builder has no filter. The model's query cache is invalidated on success.
query().update_all() updates the rows a query selects, keeping its scopes, filters and the database query_with names:
let affected = User::query()
.inactive() // a scope, see Soft Deletes and Scopes
.update_all()
.set("status", "dormant")
.execute()
.await?;
A query that joins, groups, pages or unions cannot become an UPDATE, and running one fails.
| Method | Writes |
|---|---|
set(col, value) | the value |
coalesce(col, value) | the value only where the column is NULL, so a backfill is safe to re-run |
increment(col, n), decrement(col, n) | col + n, col - n, computed by the database. Nothing clamps the result |
multiply(col, x), divide(col, x) | col * x, col / x. On an integer column the result is exact and rounded half away from zero. Zero divisors, non-finite factors and factors SQLite cannot apply exactly to integers are refused |
array_append(col, value) | the array with the value added: array_append on PostgreSQL, JSON_ARRAY_APPEND on MySQL and MariaDB, json_insert on SQLite |
array_remove(col, value) | the array without any element equal to the value. A non-array document or NULL stays as it is |
json_set(col, path, value) | the JSON document with one path set; path is $ followed by .key, ."any key", ['any key'] or [index] steps, and wildcards are refused |
set_value(col, UpdateValue) | an assignment chosen at run time, one UpdateValue variant per setter above |
set_trusted_raw(col, sql) | a raw SQL expression, unescaped. Only for text you wrote yourself, never user input; the forbid_raw_sql project rule covers it |
Values are bound as the column's type, as filter values are: text can name a UUID or a timestamp, a None writes NULL, and a JSON column takes the value as a document (serde_json::json!(..) for an object; text stays a JSON string). A typed column takes the values a filter on it takes, so .set(User::ACTIVE, "yes") does not compile; a column named by a string takes any value. Boolean, UUID and binary columns need a value of their own type. A NaN or infinite float, or a value the column cannot hold, fails the update before any row changes. Setting one column twice keeps the last value. A typed column must belong to the model being updated.
Other builder methods:
- The
where_*,or_where_*,whenandwhen_somefilters of the query builder. Allor_where_*calls form one OR group, ANDed with the rest. with_trashed()reaches soft-deleted rows, which are left out by default;without_trashed()goes back to the default.limit(n)caps the rows touched. MySQL and MariaDB putLIMITon theUPDATE; PostgreSQL and SQLite update the keys of a bounded subquery, which needs a single-column primary key, so a composite-key model fails there.execute_returning()returns the updated rows as models, on PostgreSQL and SQLite. MySQL and MariaDB refuse it before anything runs. The update and the decoding of its rows are not one unit: if a row fails to decode, the rows are written anyway, so run it in a transaction when that matters.
Upserts
Model::on_conflict(columns) inserts a model or, when it collides with the unique key those columns form, updates the stored row, and returns the row as stored:
let user = User::on_conflict(["email"])
.update_all_except(["role"])
.insert(user)
.await?;
let tag = Tag::on_conflict([Tag::columns.slug]).do_nothing().insert(tag).await?;
Model::insert_or_update(model, columns) is on_conflict(columns).insert(model) with the default update set. Columns are names or typed columns: ["email"], [User::columns.email], a Vec, or a tuple of typed columns of different types, (User::TENANT_ID, User::EMAIL).
| Builder method | On conflict |
|---|---|
| none (the default) | every column except the conflict columns and a managed created_at is overwritten |
update_columns([..]) | only these columns are written. Name updated_at to refresh it, and created_at only to overwrite it. Wins over update_all_except |
update_all_except([..]) | every column except these and a managed created_at |
do_nothing() | the stored row is kept and returned, so the call reads "insert unless it exists" |
The conflict columns must be covered by a unique constraint or unique index: the database, not TideORM, decides what counts as a conflict. insert(model) validates the model first and runs no callbacks. An encrypted column cannot be a conflict column.
| Backend | How it runs |
|---|---|
| PostgreSQL, SQLite | INSERT .. ON CONFLICT (columns) DO UPDATE .. RETURNING. A conflict on another unique key fails the statement, and whether NULLs conflict is the constraint's decision (NULLS NOT DISTINCT). do_nothing() sets the conflict columns to themselves so the kept row is returned |
| MySQL, MariaDB | ON DUPLICATE KEY UPDATE fires on any unique key, so TideORM instead locks the row the conflict columns name (SELECT .. FOR UPDATE) and updates or inserts it, in one transaction. Primary-key columns in update_columns are refused, and so is a conflict target covered only by a prefix index |
An upsert that writes an auto-increment key the model holds moves PostgreSQL's sequence past it, as create() does. A soft-deleted row is reached by an upsert, which writes the model's deleted_at back.
Validation
Declare rules on a model's fields with #[validate(..)], and TideORM checks them before every write. A model that breaks a rule is never sent to the database.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, #[validate(required, email)] pub email: String, #[validate(min_length = 3, max_length = 20, alphanumeric)] pub username: String, #[validate(range(18, 120))] pub age: i32, } fn check() { let user = User { email: "not-an-email".into(), username: "x".into(), age: 12, ..Default::default() }; if let Err(errors) = user.validate() { for (field, message) in errors.errors() { println!("{field}: {message}"); } } } }
create(), update(), save(), insert_all() and upserts check every rule first and fail with Error::Validation. For insert_all() the error names the failing model's position in the batch. Batch updates (update_all()) and query writes do not validate. Call validate() yourself to collect every failure at once; validated() returns the model itself on success, for call chains.
Rules
| Rule | Checks | Applies to |
|---|---|---|
required | the value is not empty: not None, not blank text, not an empty Vec, not JSON null | any field, usually an Option |
email | an email address | text |
url | an http or https URL with a host | text |
alpha | letters only | text |
alphanumeric | letters and digits only | text |
numeric | a finite number | text |
uuid | a UUID | text |
min_length = n, max_length = n, length = n | the length in characters, not bytes | text |
min = n, max = n | the lower or upper bound, inclusive | numbers, Decimal, numeric text |
range(min, max) | both bounds, inclusive | numbers, Decimal, numeric text |
regex = "pattern" | the text matches the pattern | text |
custom = "function" or custom = function | your own function, see Custom Rules | any field |
Text means String, &str and Text fields, optional or not. A rule on a field of a type it does not apply to is a compile error, and so is an unknown rule.
Details:
rangeis also writtenrange(min..=max)orrange = "min..max"; all three includemax. The half-openrange(min..max)is refused, since in Rust it would leavemaxout.min,maxandrangetake finite bounds only, rejectNaN, and compare anf32at its own precision, somin = 0.7accepts0.7_f32. An integer is compared exactly, even past 2^53.numericrefusesNaN,infand a value pastf64.alphaandalphanumericaccept Unicode letters and digits, not only ASCII.- A
regexpattern that does not compile fails every value, with an error naming the pattern. - Text rules pass a value that is not text, such as
None: onlyrequiredrejects a missing value. - Errors come out in the order the struct declares its fields.
The default messages read "The email must be a valid email address", "The username must be at least 3 characters", and so on.
Custom Rules
custom calls a function with a reference to the field. Return Ok(()) to pass, or an error of any type that implements Display, which becomes the field's message. It runs beside the field's other rules, wherever they run:
#![allow(unused)] fn main() { use tideorm::prelude::*; fn not_reserved(name: &str) -> Result<(), String> { match name { "admin" | "root" => Err(format!("'{name}' is reserved")), _ => Ok(()), } } #[tideorm::model(table = "accounts")] pub struct Account { #[tideorm(primary_key, auto_increment)] pub id: i64, #[validate(custom = "not_reserved", max_length = 32)] pub name: String, } }
Rules on Skip Fields
Rules on a #[tideorm(skip)] field run too, for a value that is checked but never stored, such as a password confirmation. A skip field holds its Default on every model a query returns, so make it an Option: None passes every rule except required.
#[validate] on a relation field is a compile error; put the rules on the related model's fields.
Validation and Callbacks
A single-model write runs before_validation, then the rules, then after_validation, and only then before_save. What before_save changes is therefore not validated; normalize input in before_validation when the result must pass the rules. insert_all() and upserts run no callbacks, so each model is validated as it was built. See Callbacks and Timestamps.
Handling Validation Errors
A failed create(), save() or update() returns Error::Validation. Its validation_errors() gives back every failure, field by field, to answer a form with:
match user.save().await {
Ok(user) => Ok(user),
Err(error) => match error.validation_errors() {
Some(errors) => Err(form_errors(errors.errors())), // Vec<(field, message)>
None => Err(error.into()),
},
}
ValidationErrors is the collection validate() returns:
| Method | Returns |
|---|---|
errors() | every failure as (field, message) pairs |
field_errors(field) | one field's messages, as a Vec<String> |
get(field) | one field's messages, or None |
first() | the first (field, message) |
messages() | every failure as "field: message" text |
iter() | (field, messages) pairs, in the order the fields failed |
all() | the underlying map of field to messages |
is_empty(), len() | whether there are failures, and how many fields failed |
add(field, message) | records a failure |
merge(other) | appends another collection's failures |
to_result() | Ok(()) when empty, otherwise Err(self) |
Its Display joins the failures with ; . It converts into tideorm::Error with ? or .into(); the error's own field and message are the first failure's, and validation_errors() keeps all of them. Error::validation(field, message) builds one with a single failure, for instance in a callback.
#![allow(unused)] fn main() { use tideorm::prelude::*; fn collect() -> tideorm::Result<()> { let mut errors = ValidationErrors::new(); errors.add("email", "Email is required"); errors.add("password", "Password must be at least 8 characters"); for message in errors.field_errors("email") { println!("email: {message}"); } println!("{errors}"); errors.to_result()?; Ok(()) } }
Applying Rules by Hand
The same rules are available outside models, through ValidationRule, Validator and ValidationBuilder (all in the prelude, and in tideorm::validation).
ValidationBuilder::new(field) collects rules for one field. validate(&value) checks a value against all of them, and build() returns the field name and the list of ValidationRules:
#![allow(unused)] fn main() { use tideorm::prelude::*; fn check_username(username: &str) { let username = username.to_string(); let result = ValidationBuilder::new("username") .required() .min_length(3) .max_length(20) .alphanumeric() .validate(&username); let (field, rules) = ValidationBuilder::new("role") .in_list(["admin", "editor", "viewer"]) .build(); } }
The builder has a method per rule: required, email, url, min_length, max_length, length, min, max, range, regex, alpha, alphanumeric, numeric, uuid, plus in_list(values) and not_in(values) for allow and deny lists. min, max and range keep their bounds as written, so min(18) compares an integer exactly and a "0.10" bound compares a Decimal without rounding.
Validator::validate_rule(&value, &rule, field) checks one value against one rule and returns the failure message, or None. rule.validate(&value) does the same with a Result<(), String>, and rule.message(field) gives the rule's default message. Validator::is_valid_email(text) and Validator::is_valid_url(text) are the checks behind email and url.
#![allow(unused)] fn main() { use tideorm::prelude::*; fn is_email(text: &str) -> bool { Validator::validate_rule(&text.to_string(), &ValidationRule::Email, "email").is_none() } }
ValidationRule lists every rule, including In(Vec<String>), NotIn(Vec<String>) and the MinExact, MaxExact and RangeExact forms that keep a bound's exact decimal spelling. It is #[non_exhaustive], so match it with a wildcard arm.
For a type that is not a model, such as a request body, implement Validate yourself. ValidationErrors::check(field, &value, &rules) applies a field's rules and records each failure under its name:
#![allow(unused)] fn main() { use tideorm::prelude::*; pub struct Signup { pub email: String, pub age: i32, } impl Validate for Signup { fn validate(&self) -> Result<(), ValidationErrors> { let mut errors = ValidationErrors::new(); errors .check("email", &self.email, &[ValidationRule::Required, ValidationRule::Email]) .check("age", &self.age, &[ValidationRule::MinExact("18".into())]); errors.to_result() } } }
Values are checked through the ValidatableValue trait, which TideORM implements for strings, numbers, Decimal, Options, Vecs, JSON values and the other common field types.
Callbacks and Timestamps
Callbacks run your code at fixed points of a model's writes: to normalize input, to refuse a write, or to queue follow-up work. Timestamps are the one piece of that TideORM does for you: created_at and updated_at fields are stamped on every write.
Callbacks
Implement the Callbacks trait on the model and override the hooks you need; the others do nothing.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub password_hash: String, } impl Callbacks for User { fn before_save(&mut self) -> tideorm::Result<()> { self.email = self.email.trim().to_lowercase(); Ok(()) } fn after_create(&self) -> tideorm::Result<()> { // Hooks cannot query: queue the welcome email here, and create // related records once `create()` has returned. println!("user {} created with id {}", self.email, self.id); Ok(()) } fn before_delete(&self) -> tideorm::Result<()> { if self.email == "admin@example.com" { return Err(tideorm::Error::validation("email", "Cannot delete admin account")); } Ok(()) } } }
Hooks must be in the impl Callbacks for User block. A method named before_save in an inherent impl User block is never called, and nothing warns about it.
Available Hooks
| Hook | Receives | Runs |
|---|---|---|
before_validation | &mut self | before the validation rules |
after_validation | &self | after the rules pass |
before_save | &mut self | before an insert or update |
before_create | &mut self | before an insert |
after_create | &self | after an insert |
before_update | &mut self | before an update |
after_update | &self | after an update |
after_save | &self | after an insert or update |
before_delete | &self | before a delete |
after_delete | &self | after a delete; not when no row matched |
Every hook returns tideorm::Result<()>.
Order
| Write | Hooks, in order |
|---|---|
create(), or save() of a new model | before_validation, validation, after_validation, before_save, before_create, INSERT, after_create, after_save |
update(), or save() of a stored model | before_validation, validation, after_validation, before_save, before_update, UPDATE, after_update, after_save |
delete(), destroy(id), force_delete() | before_delete, DELETE, after_delete |
before_save runs after validation, so what it changes is not validated: normalize in before_validation when the result must pass the rules. A managed created_at or updated_at is stamped after before_save, so a value the hook writes there is replaced. before_create is the place to set a key of your own, such as a UUID of a version other than v4.
On a soft-delete model, delete() marks the row and still runs the delete hooks.
Errors
An Err from a before_* hook stops the write before anything reaches the database, and is returned to the caller.
An after_* hook runs once the statement has succeeded. Its Err is returned from save(), update() or delete(), but the row is already written. Inside a transaction, propagating that error with ? rolls the write back with the rest of the transaction; outside one, the write stays.
Which Writes Run Hooks
Hooks run for single-model writes only: create(), save(), update(), delete(), destroy(id) and the SoftDelete methods. Nested saves run each model's own save(), hooks included.
These skip them: insert_all(), update_all(), upserts (on_conflict, insert_or_update) and the query writes (delete(), delete_all(), soft_delete(), force_delete(), restore() on a query).
Generic code still runs a model's hooks as long as it calls the model's own methods (M::create(m), m.save(), m.update(), m.delete()): the hook dispatch is generated into each model's methods.
Limits
Hooks are synchronous and cannot query the database. Work that needs the database, such as creating related records, belongs after the call returns:
let user = User::create(user).await?;
Profile::create(Profile { user_id: user.id, ..Default::default() }).await?;
Run both in db.transaction(..) or db.atomically(..) to make them succeed or fail together.
Timestamps
A model with created_at and updated_at fields gets them set on every write:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub content: String, pub created_at: DateTime<Utc>, // set on insert pub updated_at: DateTime<Utc>, // set on insert and update } async fn publish() -> tideorm::Result<Post> { let post = Post { title: "Hello".into(), content: "World".into(), ..Default::default() }; let mut post = post.save().await?; // created_at and updated_at are now set post.title = "Updated Title".into(); post.update().await // updated_at is refreshed, created_at stays } }
A field is managed when it is named created_at or updated_at, or mapped to such a column with #[tideorm(column = "..")], and holds a DateTime<Utc> or a NaiveDateTime, optional or not. A NaiveDateTime gets the current UTC time without its zone, which is what timestamps_naive() migration columns hold. The value you set on a managed field is replaced; a field of any other type, such as a String named created_at, keeps the value you set. Both fields of one write get the same instant, and a model with only created_at still has it stamped.
What each write does:
| Write | created_at | updated_at |
|---|---|---|
create(), save() of a new model, insert_all() | set | set |
update(), save() of a stored model | never written | set |
| upsert that inserts | set | set |
| upsert that finds the row | kept, unless named in update_columns | set when it is in the update set: by default it is, update_columns([..]) must name it, and do_nothing() writes nothing |
update_all(), query writes | not touched | not touched: set it yourself |
A request body can leave both fields out, so a model deserialized from {"title": ".."} saves with fresh timestamps, and a body that sends created_at cannot rewrite it.
The timestamps model option marks a model as timestamped (ModelMeta::has_timestamps()); a model with both fields counts as timestamped without it. The fields are managed either way.
To set updated_at in a batch update:
Post::update_all()
.set(Post::TITLE, title)
.set(Post::UPDATED_AT, Utc::now())
.where_eq(Post::ID, id)
.execute()
.await?;
Soft Deletes and Scopes
A soft-delete model keeps deleted rows in the table and marks them with a timestamp, so they can be restored or purged later. Scopes are named, reusable query conditions, such as "active users", that you chain like builder methods.
Soft Deletes
Add soft_delete to the model and a deleted_at: Option<DateTime<Utc>> field:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts", soft_delete)] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub deleted_at: Option<DateTime<Utc>>, } async fn trash(id: i64) -> tideorm::Result<()> { if let Some(post) = Post::find(id).await? { post.delete().await?; // sets deleted_at; the row stays } assert!(Post::find(id).await?.is_none()); // reads leave it out Ok(()) } }
When the field or column has another name, declare it with deleted_at_column:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts", soft_delete, deleted_at_column = "archived_on")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub archived_on: Option<DateTime<Utc>>, } }
The field must be an Option<DateTime<Utc>>; any other type is a compile error, and so is deleted_at_column without soft_delete. Unless the model sets hidden, the soft-delete field is left out of to_json(). ModelMeta::soft_delete_enabled() and deleted_at_column() report the setup.
Reading Trashed Rows
// Live rows only (the default)
let posts = Post::query().get().await?;
// Live and trashed rows
let all_posts = Post::query().with_trashed().get().await?;
// Trashed rows only
let trashed = Post::query().only_trashed().get().await?;
The scope applies to every read and filtered write: find(id), exists(id), all(), count(), every query terminal, update_all(), relation loads and full-text search leave trashed rows out. To reach them on purpose:
Post::query().with_trashed().find(id)reads a trashed row by key.post.reload()refreshes the record in hand even when it is trashed.Post::update_all().with_trashed()updates the trash too.
only_trashed() on a model without soft delete makes the query fail when it runs.
Writes of a model by its key are not scoped: update(), save() and upserts reach a trashed row and write the model's deleted_at back, so saving a stale copy of a trashed row restores it. That is how restore() works.
Deleting, Restoring and Purging
On a soft-delete model, the ordinary deletes mark rows instead of removing them: delete(), destroy(id), query().delete() and delete_all() set deleted_at to the current time. The stamp is Utc::now() from your application, bound as a value, not the database clock (MySQL and MariaDB read theirs in the session time zone). A row that is already trashed keeps its stamp.
The SoftDelete trait, in the prelude, adds methods to the model:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn lifecycle(post: Post) -> tideorm::Result<()> { let post = post.soft_delete().await?; // mark it, return it as stored assert!(post.is_deleted()); let post = post.restore().await?; // clear deleted_at and update() post.force_delete().await?; // remove the row for good Ok(()) } }
| Method | Does |
|---|---|
soft_delete() | delete(), then returns the row as stored. The delete callbacks run, so a before_delete that refuses stops it |
restore() | clears deleted_at and calls update(), with its validation and callbacks |
force_delete() | removes the row, running the delete callbacks; returns the rows deleted |
deleted_at(), set_deleted_at(..), is_deleted() | read or set the stamp in memory |
The same operations exist on a query, for many rows at once. They run no callbacks:
| Query method | Rows | Filter |
|---|---|---|
delete(), soft_delete() | marks the live rows it matches | required. Refused after only_trashed(), since those rows are deleted already |
delete_all() | marks every live row | refuses filters |
restore() | restores the trashed rows it matches | required, unless the query is only_trashed(), which restores the whole trash |
force_delete() | removes the rows it matches, trashed ones included | required, unless the query is only_trashed(), which empties the trash |
// Restore one post
Post::query().only_trashed().where_eq(Post::ID, id).restore().await?;
// Purge everything trashed more than 30 days ago
let cutoff = Utc::now() - tideorm::chrono::Duration::days(30);
Post::query().only_trashed().where_lt(Post::DELETED_AT, cutoff).force_delete().await?;
A filter that is always true (an empty NOT IN, a raw 1 = 1) counts as no filter. On a query, soft_delete() and restore() are errors for a model without soft delete; force_delete() works on any model.
Scopes
Declare a model's scopes in one #[tideorm::scopes] impl block. Each scope takes the query first, and may take more arguments:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::scopes] impl User { pub fn active(query: QueryBuilder<Self>) -> QueryBuilder<Self> { query.where_eq(User::columns.active, true) } pub fn verified(query: QueryBuilder<Self>) -> QueryBuilder<Self> { query.where_not_null(User::columns.verified_at) } pub fn role(query: QueryBuilder<Self>, role: &str) -> QueryBuilder<Self> { query.where_eq(User::columns.role, role) } } async fn admins() -> tideorm::Result<Vec<User>> { User::query().active().verified().role("admin").get().await } }
The block generates a UserQueryScopes trait implemented for QueryBuilder<User>, which is what makes .active() callable on a query; the functions also stay callable as User::active(query). A model takes one #[tideorm::scopes] block, so put every scope in it. To call the scopes from another module, import the trait:
use crate::models::UserQueryScopes as _;
Each scope must be a plain synchronous function with no self and no generic parameters, take QueryBuilder<Self> first and return it. Later parameters must be simple names; they can be mut and their types can name the model as Self. A scope cannot take the name of a QueryBuilder method (latest, limit, distinct, where_eq, with_trashed, ..): the builder's own method would answer the call, so such a name is a compile error. Doc comments and #[cfg] attributes carry over to the generated trait.
A scope adds to the query it is given, so scopes chain in any order and keep the filters, ordering, limit and values set before them. The or_where_* shorthand is the exception to watch: every or_where_* call on a query joins its one OR group, so two scopes that each use it OR their conditions together. A scope that offers alternatives should keep them in a group of its own, with where_any or begin_or() (see OR Conditions).
Scopes as Plain Functions
Ordinary functions over a QueryBuilder compose too, and can be generic over the model:
#![allow(unused)] fn main() { use tideorm::prelude::*; fn active<M: Model>(q: QueryBuilder<M>) -> QueryBuilder<M> { q.where_eq("active", true) } fn recent<M: Model>(q: QueryBuilder<M>) -> QueryBuilder<M> { q.order_desc("created_at").limit(10) } async fn recent_active_users() -> tideorm::Result<Vec<User>> { recent(active(User::query())).get().await } }
Conditional Scopes
when applies a closure when a condition holds, and when_some when an Option holds a value:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn search(include_trashed: bool, status: Option<&str>) -> tideorm::Result<Vec<Post>> { Post::query() .when(include_trashed, |q| q.with_trashed()) .when_some(status, |q, status| q.where_eq("status", status)) .get() .await } }
Batch updates have when and when_some too.
Saved Query Fragments
consolidate() captures a query's clauses as a QueryFragment, and apply(&fragment) adds them to another query. Use it to build a condition set once and reuse it:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn active_admins() -> tideorm::Result<Vec<User>> { let active = User::query().where_eq("status", "active").consolidate(); assert_eq!(active.condition_count(), 1); User::query().apply(&active).where_eq("role", "admin").get().await } }
A fragment holds the builder's clauses, not rendered SQL, so it keeps its bound values and works on any backend. apply replays it the way the matching builder calls would:
- WHERE conditions, OR groups, ORDER BY terms, selected expressions, GROUP BY columns, HAVING clauses, joins, unions, window functions and CTEs are appended. The fragment's
or_where_*conditions join the query's own OR group. limit,offset,selectand the cache options are last-wins: a value the fragment sets replaces the query's, and one it left unset keeps the query's.distinct()set in the fragment turns it on; otherwise the query's choice stays.with_trashed()oronly_trashed()in the fragment replaces the query's soft-delete scope; a fragment with neither leaves it alone.- If both carry an error from building, the query's own earlier error is the one reported.
Applying a fragment to an empty query reproduces the query it came from.
Typed Columns
Every model gets a typed constant for each of its columns. Use them instead of string names, and the compiler catches a misspelt column or a value of the wrong type.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub age: Option<i32>, pub active: bool, } async fn adults() -> tideorm::Result<Vec<User>> { User::query() .where_eq(User::ACTIVE, true) .where_gte(User::AGE, 18) .order_asc(User::NAME) .get() .await } }
User::query().where_eq(User::ACTIVE, "yes") does not compile, and neither does User::ACTVIE.
Two Spellings
The derive generates each column twice:
- an associated constant named after the field in upper case:
User::ID,User::NAME,User::AGE,User::ACTIVE; - a field of the
User::columnsstruct (typeUserColumns) named after the field:User::columns.id,User::columns.name.
Both are the same Column<T>, where T is the field's Rust type: User::AGE is a Column<Option<i32>>. The columns struct keeps the names apart from the model's own associated items and lists every column in your editor's completion. A field mapped with #[tideorm(column = "..")] keeps its field name here; the constant carries the column name.
Each relation field gets a constant holding its name too, for eager loading: User::POSTS is "posts".
Where They Work
Every method that takes a column name takes a typed column too, and string names keep working. Column lookups accept both the database column name and the Rust field name.
| Use | Methods |
|---|---|
| filters | where_eq, where_not, where_ne, where_gt, where_gte, where_lt, where_lte, where_like, where_not_like, where_in, where_not_in, where_null, where_not_null, where_between, where_not_between, and their or_where_* and and_where_* forms |
| ordering and grouping | order_by, order_asc, order_desc, group_by |
| aggregates | sum, avg, min, max, count_distinct |
| HAVING | having(Aggregate::sum(..).gt(..)), Aggregate::count().gte(..) and the rest |
| window functions | partition_by, order_by on the window builder |
| reads | pluck, value |
| writes | set, coalesce and the other setters of a batch update, upsert conflict columns (on_conflict, insert_or_update), is_field_dirty |
User::query().where_in(User::columns.role, ["admin", "moderator"]); // any list
User::query().where_not_in(User::columns.status, vec!["banned"]);
User::query().where_null(User::columns.deleted_at);
User::query().where_between(User::columns.age, 18, 65);
User::query()
.order_by(User::columns.created_at, Order::Desc)
.group_by(User::columns.role);
// All or_where_* calls form one OR group, ANDed with the rest of the query.
User::query()
.or_where_eq(User::columns.role, "admin")
.or_where_eq(User::columns.role, "moderator");
Aggregates read the result as the type you ask for:
let total: Decimal = Order::query().sum(Order::columns.amount).await?;
let average: Option<f64> = Product::query().avg(Product::columns.price).await?;
let oldest: Option<i32> = User::query().max(User::columns.age).await?;
pluck and value read a typed column as its field's type, with no annotation: User::query().pluck(User::ID) is a Vec<i64>, and value(User::AGE) an Option<Option<i32>>. A column named by a string reads as whatever type you ask for.
Which Values a Column Takes
A typed column takes the values a field of its type would hold:
| Column | Takes |
|---|---|
Column<T> | a T or a &T, so a borrowed list works in where_in |
Column<Option<T>> | a T, a &T or an Option<T> |
Column<String>, Column<Option<String>> | also a &str |
Column<i64> | also i8, i16, i32, u8, u16, u32 |
Column<i32> | also i8, i16, u8, u16 |
Column<f64> | also f32, i8, i16, i32, u8, u16, u32 |
Column<Decimal> | also every integer type up to i64 and u64 |
The widenings are the conversions that lose nothing. A column named by a string takes any value and binds it as the column's type, reading a serde_json::Value or text as that type (a UUID or timestamp written as text, for instance).
Ordering comparisons (where_gt and the rest, where_between) take numbers, Uuid, the chrono date and time types, Decimal, and &str on text columns, which compare in the column's collation.
Conditions From a Column
A typed column also builds a condition of its own, applied with where_col, or_where_col or and_where_col. The condition traits are in the prelude:
| Trait | Methods | Columns |
|---|---|---|
ColumnEq | eq, ne | any |
ColumnOrd | gt, gte, lt, lte, between | numbers, Uuid, chrono types, Decimal, text |
ColumnIn | is_in, not_in | any |
ColumnLike | like, not_like, contains, starts_with, ends_with | String, Option<String> |
ColumnNullable | is_null, is_not_null | any Option column |
User::query().where_col(User::columns.age.gte(18));
User::query().where_col(User::columns.email.ends_with("@example.com"));
User::query().where_col(User::columns.age.is_null());
See Query Builder for every filter.
Columns of Other Models
A typed column knows its model's table. In a query of another model it is written qualified, so User::columns.id in a Post query means users.id, not posts.id; this is what makes joins and subqueries with typed columns unambiguous. Column::name() returns the bare name and Column::table() the table.
A batch update refuses a typed column of another model.
Defining Columns by Hand
For a column no model field declares, such as a view's computed column, define a constant yourself:
use tideorm::prelude::*;
pub const FULL_NAME: Column<String> = Column::new("full_name");
let users = User::query().where_eq(FULL_NAME, "John Doe").get().await?;
Column::new(name) has no table and is never qualified. Column::of(table, name) and Column::of_schema(schema, table, name) name the table (and schema), as the generated constants do.
Methods that take several columns (partition_by, conflict columns) accept a list of names or typed columns, a Vec, or a tuple of up to 12 typed columns of different types, such as (User::TENANT_ID, User::EMAIL).
Encrypted Fields
Requires the
encrypted-fieldsfeature.
An encrypted field is stored encrypted in its column and holds plaintext in your model. Use it for values the database should not hold in the clear, such as phone numbers or document numbers, when you only read them back by row.
[dependencies]
tideorm = { version = "0.18.2", features = ["postgres", "encrypted-fields"] }
List the fields in the model's encrypted option, by field name or column name:
use tideorm::prelude::*;
#[tideorm::model(table = "customers", encrypted = "customer_phone_number, backup_phone")]
pub struct Customer {
#[tideorm(primary_key, auto_increment)]
pub id: i64,
pub name: String,
#[tideorm(column = "customer_phone_number")]
pub phone_number: String,
pub backup_phone: Option<String>,
}
async fn register() -> tideorm::Result<Customer> {
let customer = Customer::create(Customer {
name: "Ada".into(),
phone_number: "+44 20 7946 0000".into(),
..Default::default()
})
.await?; // the column holds ciphertext
Ok(Customer::find(customer.id).await?.unwrap()) // phone_number is plaintext again
}
Without the feature, encrypted = ".." fails to compile, with a note that the item it needs is gated behind encrypted-fields.
Setting the Key
Encryption needs a key, set once at startup. It is the same key tokenization uses:
let key = std::env::var("ENCRYPTION_KEY").expect("ENCRYPTION_KEY must be set");
TideConfig::init()
.database("postgres://localhost/mydb")
.encryption_key(&key)
.connect()
.await?;
// or, without TideConfig:
TokenConfig::set_encryption_key(&key);
- Without a key, every write of an encrypted field, and every read of a stored payload, fails with
Error::Configuration; nothing is stored in plaintext. - An empty or blank key is ignored with a warning and leaves no key set, so an unset environment variable read with
unwrap_or_default()fails the same way. - Changing the key makes every value written under the old one unreadable. There is no built-in key rotation.
Load the key from the environment or a secret manager, never from source.
What Is Encrypted
Every write that stores the model encrypts the field, and every read that builds a model or reads the column decrypts it:
| Encrypted on | Decrypted on |
|---|---|
create(), save(), update() | find(), all(), first() and the other model reads |
insert_all() | query builder reads (get(), first(), paginate()) |
upserts (on_conflict, insert_or_update) | eager-loaded relations |
| nested saves and entity manager flushes | raw SQL decoded into the model |
batch update_all().set(..) and coalesce(..) | pluck, value, get_json, get_as |
pluck, value, get_json and get_as decrypt columns of the query's model and of joined models, and keep decrypting a column read through an alias or a scalar subquery.
A model never holds ciphertext: a row decrypts as it is read, and a write encrypts a copy of the value.
Field Types and Columns
An encrypted field can be of any type that implements Serialize and Deserialize: String, numbers, Options, your own structs. The column stores the encrypted JSON of the value as text, so declare it TEXT whatever the field's type; schema sync and schema export already do.
None, and any value whose JSON isnull, is stored asNULL. AnOption<serde_json::Value>holding the JSONnullreads back asNone.- In a batch update,
set()andcoalesce()take any filter value, such asserde_json::to_value(&card)?for a struct field orNonefor anOptionfield, and refuse one the field's type cannot read ("cannot hold a JSON string") before anything is written. - The other batch setters (
increment,multiply, the array and JSON setters,set_trusted_raw) are refused on an encrypted field, since the database cannot compute on ciphertext.
Customer::update_all()
.set(Customer::BACKUP_PHONE, None::<String>)
.where_eq(Customer::ID, id)
.execute()
.await?;
Querying Encrypted Columns
Each write encrypts with a fresh random nonce, so the same value is stored differently every time, and the database cannot compare plaintext:
| Operation | Behaviour |
|---|---|
where_eq and the other filters | refused; where_null and where_not_null work, since None is stored as NULL |
DISTINCT, count_distinct, GROUP BY, ORDER BY | refused |
MIN, MAX, SUM, AVG, aggregates(), HAVING comparisons | refused |
window functions: MIN/MAX/SUM/AVG, PARTITION BY, ORDER BY | refused |
UNION | refused when a projection is encrypted, since deduplication would compare ciphertext |
UNION ALL | allowed with explicit columns or the default projection, when every operand has the same table and column at each encrypted position; refused for raw SQL or wildcard operands |
| full-text search | refused |
The refusals cover aliases, joined models' columns and scalar subquery outputs too, and fail when the query runs, with an error explaining that randomized ciphertext cannot compare plaintext values. Load the rows and compare or aggregate the values in Rust.
Typed unions also refuse operands whose output types differ at one position, such as a boolean and an integer, since every row is decoded the same way.
To look a row up by a protected value, keep a separate column the application can match, such as a keyed hash of the value, beside the encrypted one.
What Cannot Be Encrypted
These are compile errors:
- a primary key: its ciphertext changes on every write, so no lookup by the key could match it;
- an
#[index]or#[unique_index]covering an encrypted field: a unique index would never see two equal values; - a
searchable = ".."entry naming an encrypted field.
An upsert whose conflict columns include an encrypted field fails when it runs; conflict on a plaintext unique key instead.
Existing Data
An encrypted column must hold TideORM's encrypted payloads or NULL. Loading a row whose column holds plaintext fails with "Encrypted field '..' loaded plaintext data"; a payload written under another key or for another column fails to decrypt. Before listing an existing column in encrypted, migrate its data: read the rows with a model that does not encrypt the column, then write each value back through a model that does.
How It Works
- Values are sealed with XChaCha20-Poly1305 and stored as
enc::followed by base64url text. - Each column gets its own key, derived with Argon2id from the configured key, the table name and the column name, and cached after first use. A payload copied into another column or table does not decrypt there.
- Tampering with a stored payload makes its row fail to load.
ModelMeta::encrypted_fields() lists a model's encrypted fields as (field, column) pairs, and has_encrypted_fields() tells whether it has any.
With project rules, sensitive_fields flags any column whose name looks sensitive and that is neither hidden nor encrypted.
Password Hashes
Encryption is two-way: the application reads the value back. Store a password one-way instead. Hashed (in the prelude, and tideorm::types::Hashed) hashes a value with Argon2 under a fresh random salt and checks a candidate against the stored hash:
use tideorm::prelude::*;
// Hashed::new does the same and panics if Argon2 fails, which needs a 4 GiB input.
user.password_hash = Hashed::try_new(&password)?.hash().to_owned();
user.save().await?;
let matches = Hashed::from_hash(user.password_hash.clone()).verify(&attempt);
Hashed has no column mapping, so keep the hash in a String field and leave that field out of JSON with hidden = "password_hash" (see Hidden Attributes). Hashed itself never shows the hash: its Debug, Display and Serialize write ***HASHED***, and deserializing that placeholder fails.
Tokenization
Tokenization turns a record's primary key into an encrypted, URL-safe token, so URLs and API responses carry v2.iIBmdKYhJh4_vSKFlBTP.. instead of 42. A token decodes back to the key only with your application's key, and only for the model that issued it.
Add tokenize to the model and set an encryption key at startup:
use tideorm::prelude::*;
#[tideorm::model(table = "users", tokenize)]
pub struct User {
#[tideorm(primary_key, auto_increment)]
pub id: i64,
pub email: String,
pub name: String,
}
async fn example() -> tideorm::Result<()> {
let key = std::env::var("ENCRYPTION_KEY").expect("ENCRYPTION_KEY must be set");
TokenConfig::set_encryption_key(&key);
let user = User::find(1).await?.unwrap();
let token = user.to_token()?; // "v2.iIBmdKYhJh4_vSKFlBTP..."
let id = User::decode_token(&token)?; // 1, without a query
let same_user = User::from_token(&token).await?;
assert_eq!(user.id, same_user.id);
Ok(())
}
tokenize requires exactly one primary key field; on a model with a composite key it is a compile error.
Setting the Key
Tokens use the encryption key that encrypted fields use. Set it once at startup, through TideConfig or directly:
let key = std::env::var("ENCRYPTION_KEY").expect("ENCRYPTION_KEY must be set");
TideConfig::init()
.database("postgres://localhost/mydb")
.encryption_key(&key)
.connect()
.await?;
// or, without TideConfig:
TokenConfig::set_encryption_key(&key);
- Without a key, every method that encodes or decodes a default token fails with
Error::Tokenization("No encryption key configured"), even the forms that otherwise returnOk(None). - An empty or blank key is ignored with a warning and leaves no key set.
TokenConfig::has_encryption_key()tells whether one is set. - Use a high-entropy secret of 32 or more characters, kept in the environment or a secret manager, never in source.
- Changing the key invalidates every token issued under the old one.
Methods
A tokenize model implements the Tokenizable trait, which is in the prelude:
| Method | Returns |
|---|---|
user.to_token() | the record's token. Each call gives a different token, from a fresh random nonce; all of them decode to the same key |
User::tokenize_id(42) | the token for a key, without loading the record |
User::decode_token(&token) | the primary key, without a query. An invalid token is an Error::InvalidToken |
User::try_decode_token(&token) | the same, with Ok(None) for an invalid token |
User::from_token(&token).await | the record. An invalid token is an Error::InvalidToken, and a token whose row is gone an Error::NotFound |
User::find_by_token(&token).await | the same, with Ok(None) for an invalid token or a missing row |
from_token loads the record with find(), so on a soft-delete model a token for a trashed row is not found.
Reading Tokens From Requests
A token from a request may be garbled, forged, minted for another model, or name a row that has since been deleted. Use find_by_token and try_decode_token there: they answer all of those with Ok(None), and only a missing key stays an error.
match User::find_by_token(&token).await? {
Some(user) => respond_with(user),
None => not_found(),
}
let id: Option<i64> = User::try_decode_token(&token)?;
Error messages leave the decoded key out, since hiding it is the point of the token.
Tokens Belong to One Table
A token is bound to its model's schema and table, so a User token does not decode as a Product:
#[tideorm::model(table = "products", tokenize)]
pub struct Product {
#[tideorm(primary_key, auto_increment)]
pub id: i64,
}
let user_token = User::tokenize_id(1)?;
let product_token = Product::tokenize_id(1)?;
assert_ne!(user_token, product_token);
assert!(User::decode_token(&product_token).is_err());
The binding is to the table, not the struct name: two User structs in different modules, on different tables, cannot open each other's tokens, while two models over the same table can. Table-bound tokens start with v2.; a token issued by TideORM 0.15 or earlier, bound to the struct name, no longer decodes.
Tokens in API Responses
A model still carries its primary key, so returning it as it is puts the raw id back into the response. Hide the key and send the token in its place:
use tideorm::prelude::*;
#[tideorm::model(table = "users", tokenize, hidden = "id")]
pub struct User {
#[tideorm(primary_key, auto_increment)]
pub id: i64,
pub email: String,
}
async fn show_user(token: &str) -> tideorm::Result<Option<serde_json::Value>> {
let Some(user) = User::find_by_token(token).await? else {
return Ok(None);
};
let mut body = user.try_to_json(None)?; // `hidden` drops the raw id
body["token"] = serde_json::json!(user.to_token()?);
Ok(Some(body))
}
// GET /api/users/v2.iIBmdKYhJh4_vSKFlBTPgWRlbW8tZW5isZqLo_EU4YI
Tokens use the base64url alphabet (A-Z a-z 0-9 - _) plus the v2. prefix, so they need no escaping in a URL path.
Custom Token Formats
The default tokens suit most applications. When you need another format, override the encoder and decoder for one model or for all of them. TideORM picks, for each model, the model's own codec first, then the global one, then the default.
An encoder receives the serialized primary key (its JSON text, such as 42) and the model name, and returns the token. A decoder receives the token and the model name, and returns the serialized key, Ok(None) for a token it does not accept, or Err when it cannot decode at all. Pair every encoder with a decoder that accepts what it writes: a token the decoder rejects reads as invalid (Ok(None) from find_by_token), not as a configuration error, so a mismatched pair fails silently.
An override replaces the default encryption: the token's security is then yours. Overriding either codec also drops the table binding: an override receives the model name, and a default codec left on the other side binds to that name.
For One Model
Implement Tokenizable by hand instead of using tokenize:
use std::sync::Arc;
use tideorm::prelude::*;
#[tideorm::model(table = "documents")]
pub struct Document {
#[tideorm(primary_key)]
pub id: i64,
pub title: String,
}
#[async_trait] // from the prelude
impl Tokenizable for Document {
type TokenPrimaryKey = i64;
fn token_model_name() -> &'static str {
"Document"
}
fn token_primary_key(&self) -> i64 {
self.id
}
fn token_encoder() -> Option<TokenEncoder> {
Some(Arc::new(|id: &str, _model: &str| Ok(format!("DOC-{id}"))))
}
fn token_decoder() -> Option<TokenDecoder> {
Some(Arc::new(|token: &str, _model: &str| {
Ok(token.strip_prefix("DOC-").map(ToOwned::to_owned))
}))
}
async fn from_token(token: &str) -> tideorm::Result<Self> {
let id = Self::decode_token(token)?;
Self::find(id)
.await?
.ok_or_else(|| tideorm::Error::not_found("Document not found"))
}
}
token_model_name, token_primary_key and from_token are required; the rest have defaults. token_table() returns the schema and table to bind default tokens to: the derive returns the model's own, and a hand-written impl returns None by default, which binds them to token_model_name instead, so two hand-written impls with one name accept each other's tokens. Name them apart.
For Every Model
TokenConfig::set_encoder and TokenConfig::set_decoder install global codecs. They are closures, so they can capture what they need, such as a tenant prefix read at startup:
let tenant = std::env::var("TENANT").expect("TENANT must be set");
let prefix = format!("{tenant}-");
TokenConfig::set_encoder(move |id, model| {
Ok(format!("{tenant}-{}-{}", model.to_lowercase(), id))
});
TokenConfig::set_decoder(move |token, model| {
let model_prefix = format!("{}-", model.to_lowercase());
Ok(token
.strip_prefix(&prefix)
.and_then(|rest| rest.strip_prefix(&model_prefix))
.map(ToOwned::to_owned))
});
TideConfig::token_encoder(..) and TideConfig::token_decoder(..) take the same closures and install them on connect() or apply().
Setting a key, encoder or decoder again replaces the previous one. TokenConfig::reset() clears the key and both global codecs; TideConfig::reset() does the same along with the rest of the configuration. TokenConfig::get_encoder() and get_decoder() return the global codecs in effect, the default ones when none is set.
To build on the default format, wrap tideorm::tokenization::default_encode and default_decode, the codecs TideORM uses when nothing is overridden. They bind a token to the model name they are given, not to a table.
Security
- Default tokens are sealed with XChaCha20-Poly1305, under a key derived from yours with Argon2id.
- The table (or, without one, the model name) is authenticated with the token, so it opens only for that table.
- A modified or truncated token fails authentication and decodes as invalid. A token longer than 4096 characters is refused before it is decoded.
- The output is randomized: one record has many valid tokens, so tokens cannot be compared to find equal keys.
- A token hides the key; it is not a permission.
from_tokenloads whatever row the token names, so check that the caller may see that row as you would for a plain id. - Tokens are bound to the schema and table, not to the database: tenants that share an encryption key and a table name can open each other's tokens. Give each tenant its own key, or bind the tenant in with a custom format.
- For high-security applications, plan how you rotate the key: rotation invalidates outstanding tokens.
Query Builder
Model::query() starts a QueryBuilder for a model. Chain filters, ordering and paging onto it, then run it with a terminal such as get() or count(). Every value is bound as a parameter, every column name is checked before the statement runs, and the SQL is written for the backend the query runs on.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn adult_users() -> tideorm::Result<Vec<User>> { User::query() .where_eq(User::columns.active, true) .where_gte(User::columns.age, 18) .order_desc(User::columns.created_at) .limit(20) .get() .await } }
Joins, aggregates, grouping, unions, window functions, CTEs, subqueries, row locks and bulk updates are on Joins, Aggregates and Advanced SQL. JSON and array filters are on JSON and Arrays.
Filters
Every filter takes its column as a string, either the database column name or the Rust field name, or as a typed column: User::columns.active, or its constant form User::ACTIVE. The typed form is checked by the compiler and is the better default; see Typed Columns.
User::query().where_eq("active", true) // checked when the query runs
User::query().where_eq(User::columns.active, true) // checked at compile time
| Method | Keeps the rows where |
|---|---|
where_eq(col, value) | col = value |
where_not(col, value), where_ne(col, value) | col <> value; a NULL column never matches |
where_gt, where_gte, where_lt, where_lte | col >, >=, <, <= the value |
where_in(col, values) | col is one of values: a Vec, an array, &ids, a set |
where_not_in(col, values) | col is none of values; a NULL column never matches |
where_between(col, min, max) | col lies between min and max, inclusive |
where_not_between(col, min, max) | col lies outside them; a NULL column never matches |
where_like(col, pattern), where_not_like | col matches a LIKE pattern, used as written: % and _ stay wildcards |
where_contains(col, text) | col contains text literally; its % and _ are escaped |
where_starts_with, where_ends_with | col starts or ends with the text literally |
where_null(col), where_not_null(col) | col IS NULL, col IS NOT NULL |
where_column_eq(col, other) | col equals another column of the row; also _ne, _gt, _gte, _lt, _lte |
where_col(condition) | a typed column's condition holds, such as User::columns.age.gte(18) |
where_json_*, where_array_* | see JSON and Arrays |
where_raw(sql), where_raw_with(sql, values) | a trusted SQL fragment holds; see Raw SQL |
Each call is ANDed with the query's other filters:
User::query()
.where_eq(User::columns.status, "active")
.where_not(User::columns.role, "admin")
.where_in(User::columns.role, ["editor", "author"])
.where_in("id", &user_ids) // any list: a Vec, an array, a slice, a set
.where_between(User::columns.age, 18, 65)
.where_not_null(User::columns.email_verified_at)
.where_like(User::columns.name, "John%")
.where_contains(User::columns.bio, ¶ms.search)
// Two columns of the same row, or of a joined table
Order::query().where_column_gt("shipped_at", "ordered_at");
Post::query()
.inner_join("users", "posts.user_id", "users.id")
.where_column_lt("posts.created_at", "users.banned_at");
Conditional Filters
when(condition, f) applies f only when condition holds, and when_some(option, f) applies it with the value when the Option holds one, so a filter that depends on a request parameter does not break the chain:
User::query()
.when(params.only_active, |q| q.where_eq(User::columns.active, true))
.when_some(params.role, |q, role| q.where_eq(User::columns.role, role))
Typed Conditions
A typed column also builds a condition of its own, which where_col (and or_where_col, and_where_col) applies. The value must have the column's type, so a mismatch is a compile error. The conditions are eq, ne, gt, gte, lt, lte, like, not_like, contains, starts_with, ends_with, is_in, not_in, between, is_null and is_not_null:
User::query().where_col(User::columns.age.gte(18))
User::query().where_col(User::columns.role.is_in(["admin", "moderator"]))
User::query().where_col(User::columns.email.ends_with("@example.com"))
User::query().where_col(User::columns.deleted_at.is_null())
A typed column names its model's table, so in another model's query it means that model's column: Post::query().inner_join("users", ..).where_eq(User::columns.active, true) filters users.active.
Values
Values are any type a model field can hold (impl Into<DbValue>): numbers, text, bool, Uuid, chrono dates and timestamps, Decimal, bytes, serde_json::Value, an Option of one, or a reference to one. Each is bound as its own type, so pass the native value: where_eq("id", user_id), where_gt("created_at", since). A value of another type than the column's, such as a UUID or a timestamp written as text, or a serde_json::Value, is read as the column's type, so where_eq("id", "42") still compares an integer.
- NULL.
where_eq(col, None::<T>)isIS NULL.where_notandwhere_not_infollow SQL and never match a NULL column. ANoneinsidewhere_inalso matches NULL rows, and one insidewhere_not_inkeeps the non-NULL rows outside the list. - JSON
null. On a JSON column,where_eq(col, serde_json::Value::Null)(orSome(Value::Null)) matches the rows holding the JSONnulldocument, andNonethe SQL NULL ones; insidewhere_inandwhere_not_inthe two read the same way. - NaN and infinity. A filter value holding a NaN or infinite float fails the query, as does a
set()orhaving()given one: no SQL comparison can take it. Check a float parsed from a request withis_finite(). - Columns are identifiers. The column argument is a column,
table.column, or a typed column; anything else is rejected when the query runs. SQL expressions go throughwhere_raw(), whose SQL you vouch for; never pass user input to it. When the expression needs a value, write?for it and pass the value towhere_raw_with(), which binds it:where_raw_with("LOWER(email) = LOWER(?)", [email.into()]). The?works on every backend. - Long lists. A
where_in/where_not_inlist of more than 1,000 values that share a type is bound as one array on PostgreSQL (= ANY($1)), and a list of more than 1,000 strings as one JSON value on SQLite (IN (SELECT value FROM json_each(?))); anywhere else a list of more than 1,000 integers is written inline instead of bound. So a list of ids of any length works everywhere, and one of text on PostgreSQL and SQLite. Other long lists, such as text on MySQL and MariaDB or UUIDs and timestamps on SQLite and MySQL, are bound one parameter each, which caps them at the backend's limit: 32,766 on SQLite, 65,535 on PostgreSQL and MySQL. LIKEand case.where_contains,where_starts_withandwhere_ends_withescape%and_, so they are safe for user input;where_likeuses its pattern as written. Whether a match is case-sensitive is the backend's: PostgreSQL's is, MySQL's (with its default collations) and SQLite's (for ASCII) are not.- Text equality follows the collation. MySQL's default collation ignores case and accents, so there
where_eq("email", "ada@example.com")findsAda@Example.com,"cafe"findscafé, and a unique index refuses both spellings; MariaDB's default collations also ignore trailing spaces, so"a "finds"a". PostgreSQL and SQLite compare text exactly. Normalize the values you look up, such as lowercasing emails before saving, to get the same answer everywhere.
Where Each Filter Family Works
Every operator in the table above, the JSON, array, column-to-column, where_col and raw forms included, comes in several families. Which ones a builder offers:
| Builder | Families |
|---|---|
QueryBuilder (Model::query()) | where_*, or_where_*, both with the raw forms |
OrGroup (inside where_any/where_all) | where_*, with the raw forms |
OrBranchBuilder (after begin_or()) | or_where_*, and_where_*, both with the raw forms |
BatchUpdateBuilder (update_all()) | where_*, or_where_*, without the raw forms |
when and when_some work on all four.
OR Conditions
Write an OR as a group: where_any(|g| ..) ORs the conditions it adds, and where_all(|g| ..) ANDs them. Every group is written in parentheses and ANDed with the rest of the query, so the SQL reads the way the chain does. Each call adds a group of its own, and inside a group nested_or and nested_and add a group in turn:
// WHERE active = true AND (role = 'admin' OR role = 'moderator')
User::query()
.where_eq(User::columns.active, true)
.where_any(|g| g.where_eq(User::columns.role, "admin").where_eq(User::columns.role, "moderator"))
// WHERE (plan = 'pro' OR (plan = 'trial' AND verified = true))
User::query().where_any(|g| {
g.where_eq(User::columns.plan, "pro")
.nested_and(|t| t.where_eq(User::columns.plan, "trial").where_eq(User::columns.verified, true))
})
// WHERE (active = true AND (name = 'Ada' OR name = 'Grace'))
User::query().where_all(|g| {
g.where_eq(User::columns.active, true)
.nested_or(|o| o.where_eq(User::columns.name, "Ada").where_eq(User::columns.name, "Grace"))
})
An OR across what would otherwise be two filters goes in one group: where_any(|g| g.where_eq(User::columns.active, true).where_eq(User::columns.role, "admin")). A typed column inside a group is always written with its table.
The or_where_* Shorthand
All or_where_* calls on one query join one OR group, ANDed with the rest of the query. They never OR with a plain where_* filter:
// WHERE active = true AND (role = 'admin' OR role = 'moderator')
// not: active = true OR role = 'admin' OR role = 'moderator'
User::query()
.where_eq(User::columns.active, true)
.or_where_eq(User::columns.role, "admin")
.or_where_eq(User::columns.role, "moderator")
// WHERE (price > 1000 OR price < 50)
Product::query()
.or_where_gt(Product::columns.price, 1000.0)
.or_where_lt(Product::columns.price, 50.0)
Any operator works there: or_where_in, or_where_null, or_where_between, or_where_like and the rest. Use where_any or begin_or() for a second, separate OR group.
OR Branches With begin_or
begin_or() opens an OR group whose branches are ANDs: or_where_* starts a branch and and_where_* adds to the current one. end_or() closes the group and returns to the query. A group with no condition adds nothing.
// WHERE active = true AND rating >= 4.0
// AND ((category = 'Electronics' AND price < 1000) OR (category = 'Home' AND featured = true))
Product::query()
.where_eq("active", true)
.where_gte("rating", 4.0)
.begin_or()
.or_where_eq("category", "Electronics").and_where_lt("price", 1000.0)
.or_where_eq("category", "Home").and_where_eq("featured", true)
.end_or()
// Two groups: WHERE (category = 'Electronics' OR category = 'Home') AND (brand = 'Apple' OR brand = 'Samsung')
Product::query()
.begin_or()
.or_where_eq("category", "Electronics")
.or_where_eq("category", "Home")
.end_or()
.begin_or()
.or_where_eq("brand", "Apple")
.or_where_eq("brand", "Samsung")
.end_or()
Every operator has an and_where_* form there: and_where_not, and_where_in, and_where_null, and_where_between, and_where_contains, and_where_column_gt, and_where_json_contains, and_where_raw_with and so on.
To see the WHERE clause a chain builds, print the query's debug() (see Inspecting a Query).
Reusing Filters
consolidate() takes a snapshot of a query's clauses as a QueryFragment, and apply(&fragment) replays it onto another query:
let active = User::query().where_eq(User::columns.status, "active").consolidate();
let admins = User::query().apply(&active).where_eq(User::columns.role, "admin").get().await?;
The fragment holds clauses, not SQL, so its values stay bound and it renders for whichever backend the query runs on. Applying merges the way calling the setters again would: WHERE conditions, OR conditions, ordering, joins, grouping, HAVING, raw selects, unions, window functions and CTEs are appended; limit, offset, select and the cache settings are last-wins, a slot the fragment left unset keeping the query's own; distinct() turns on and stays on; a fragment that set neither with_trashed() nor only_trashed() leaves the soft-delete scope alone; and when both hold an error, the query's own is the one reported. QueryFragment::new() makes an empty fragment, and is_empty() and condition_count() describe one.
Ordering
User::query()
.order_by("created_at", Order::Desc)
.order_by(User::columns.name, Order::Asc)
User::query().order_asc(User::columns.name) // ORDER BY name ASC
User::query().order_desc(User::columns.created_at) // ORDER BY created_at DESC
User::query().latest() // ORDER BY created_at DESC
User::query().oldest() // ORDER BY created_at ASC
Post::query().latest_by(Post::columns.published_at) // ORDER BY published_at DESC
Post::query().oldest_by("published_at") // ORDER BY published_at ASC
Each call adds a sort key after the earlier ones. reorder(column, direction) replaces every order the query has so far, such as one a scope added.
order_by checks its column as a filter does, and takes one direction: order_by("name desc", Order::Asc) names two and fails the query. Take a request's sort string with sort(): terms separated by commas, each a column with an optional direction, as name, name desc, +name or -created_at for descending. Every column is checked as order_by checks one, so the string cannot smuggle an expression in. An empty string orders nothing; an empty term ("name,,id") fails the query.
// ?sort=-created_at,name
let posts = Post::query().sort(¶ms.sort).get().await?;
Order is Asc (the default) or Desc. It parses from "asc", "desc", "ascending" or "descending" in any case, through FromStr and serde, so a request can deserialize one; it serializes as "asc"/"desc", and reverse() gives the other direction. A model named Order shadows the prelude's Order enum; write SortOrder::Desc instead, the same enum under a second name.
order_by_raw(expression, direction) orders by a trusted SQL expression, such as COALESCE(nickname, name); it is checked for statement separators, comments and NUL characters, never escaped.
Where NULLs sort is the backend's: PostgreSQL puts them last in ascending order and first in descending order, MySQL and SQLite the other way round. Sort on IS NULL first to get one order everywhere:
User::query()
.order_by_raw("last_login_at IS NULL", Order::Asc) // NULLs last on every backend
.order_asc(User::columns.last_login_at)
Limit, Offset and Pages
User::query().order_asc(User::columns.id).limit(10).offset(20)
User::query().order_asc(User::columns.id).page(3, 25) // page 3, 25 per page
page(page, per_page) counts pages from 1. A page or page size of 0, or one whose offset passes i64::MAX, fails the query with a validation error naming page or per_page. offset() without limit() works on every backend: MySQL, MariaDB and SQLite get an open-ended LIMIT written for them.
Give a paged query a unique order, such as one ending in the primary key. Without one, PostgreSQL returns rows in storage order, which an UPDATE changes, so consecutive pages can repeat one row and skip another. Model::paginate(page, per_page) orders by the primary key for you (see Reading and Writing).
Pages With a Total
paginate(page, per_page) runs the query for one page and counts every matching row, and returns a Paginated<M>: the page's models in items, the count in total, and the page and per_page asked for. last_page() (1 when nothing matches), has_next_page() and has_previous_page() are worked out from them, and map(f) turns the items into another type, such as a view model. It serializes as {"items": .., "total": .., "page": .., "per_page": .., "last_page": ..}, ready to return from an API:
let page = Post::query()
.where_eq(Post::columns.published, true)
.order_desc(Post::columns.id)
.paginate(2, 20)
.await?;
println!("page {} of {} ({} posts)", page.page, page.last_page(), page.total);
Cursor Pagination
cursor_paginate(per_page, cursor) pages by the primary key instead, the way chunks() does: pass None for the first page and each page's next_cursor for the one after it. It returns a CursorPage<M>, serialized as {"items": .., "next_cursor": ..}, whose next_cursor is None once a page comes back short (a page that ends exactly at the last row is followed by an empty one). It counts nothing and skips no rows by OFFSET, so a deep page costs what the first does, and rows written between requests are neither repeated nor skipped.
let page = Post::query()
.where_eq(Post::columns.published, true)
.order_desc(Post::columns.id)
.cursor_paginate(20, params.cursor.as_deref())
.await?;
The query follows the rules of chunk() below, and refuses limit(). A cursor is opaque but not secret: it names the key to continue from, the query's filters still apply, and one that does not decode fails with Error::Validation on the field cursor.
Processing Large Results in Chunks
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn send_digest(_user: &User) -> tideorm::Result<()> { Ok(()) } async fn digest_everyone() -> tideorm::Result<()> { User::query() .where_eq(User::columns.active, true) .chunk(500, |batch| async move { for user in &batch { send_digest(user).await?; } Ok(()) }) .await?; // Or pull the batches yourself, holding any state across `.await`s let mut emails = Vec::new(); let mut batches = User::query().chunks(500)?; while let Some(batch) = batches.next().await? { emails.extend(batch.into_iter().map(|user| user.email)); } Ok(()) } }
chunk() and chunks() walk the query by a primary-key cursor instead of loading the whole result at once, so a callback may update or delete rows it has processed without a later batch skipping any. Each batch is one query, only one batch is held at a time, and the next is read when you ask for it; there is no row-by-row stream, so chunks() is how to read a result larger than memory. Filters, limit() and the cache settings stay in effect.
The rules, which cursor_paginate() shares:
- The model needs a single-column primary key, and the projection must keep it.
- The query may be ordered only by the primary key; order it descending with
order_descon the key to walk backwards. Any other order,offset(),GROUP BY/HAVING, a union or a window function fails, and so does a chunk size of 0. - On a join that repeats a key, the rows sharing it are handed over in one batch, so only a key repeated more often than the chunk size fails.
Running a Query
| Terminal | Returns |
|---|---|
get() | Vec<M>, every matching row |
first() | Option<M>, the first row; without an order the database picks it |
first_or_fail() | M, or a not-found error |
find(id), find_or_fail(id) | the row with that primary key among the rows the query matches |
count() | u64; ignores ordering, limit() and offset() |
exists() | bool; ignores ordering, limit() and offset() |
pluck(col) | Vec<T>, one column of every row |
value(col) | Option<T>, one column of the first row |
get_as::<T>() | Vec<T>, each row as a type of your own |
get_json() | Vec<serde_json::Value>, each row as a JSON object |
paginate(page, per_page) | Paginated<M> |
cursor_paginate(per_page, cursor) | CursorPage<M> |
chunk(size, f), chunks(size) | batches of M |
sum, avg, min, max, count_distinct, aggregates | see Aggregates |
delete(), update_all() and the other writes | see Bulk Updates and Deletes |
let users = User::query().where_eq(User::columns.active, true).get().await?;
let admin = User::query().where_eq(User::columns.email, "admin@example.com").first().await?;
let user = User::query().where_eq(User::columns.id, 1).first_or_fail().await?;
let active = User::query().where_eq(User::columns.active, true).count().await?;
let taken = User::query().where_eq(User::columns.email, email).exists().await?;
let mine = Post::query().where_eq(Post::columns.user_id, me).find(post_id).await?;
find(id) on a query looks the key up among the rows the query matches: its filters and soft-delete scope apply, so Post::query().where_eq("user_id", me).find(post_id) finds only my post. A composite key is passed as a tuple. It refuses limit()/offset() and a union, since the key would filter only the union's first query.
A query reads the model's columns by name rather than SELECT *, so a column added to the table while the application runs does not disturb it. get() builds complete models, so it refuses a select() that leaves model columns out: the missing ones would read as None or a default, and saving such a model would write those back over the stored values. Read a partial row with get_json(), get_as() or pluck(); selecting columns is covered under Selecting Columns.
Single Columns and Your Own Types
pluck reads one column of every row, value the column of the first row, and get_as each row as a type of your own (any Deserialize type) whose fields are the columns or their aliases: the shape of a join or a grouped select_raw() that no model has.
let emails: Vec<String> = User::query().where_eq(User::columns.active, true).pluck(User::columns.email).await?;
let newest: Option<String> = Post::query().latest().value("title").await?;
#[derive(serde::Deserialize)]
struct AuthorPosts { author: String, posts: i64 }
let rows: Vec<AuthorPosts> = Post::query()
.inner_join("users", "posts.user_id", "users.id")
.select_raw("users.name AS author, COUNT(*) AS posts")
.group_by("users.name")
.get_as()
.await?;
Given a typed column, pluck and value read the field's own type; given a name, they read whatever type you ask for. pluck replaces any select(), though distinct() still applies to it. On a union() the column is read off the union's rows, and an encrypted column comes back decrypted, as get() returns it. A model's enum column reads as its variants, not as the strings it stores. A JSON null read into an Option<serde_json::Value> comes back as None.
Rows as JSON
get_json() returns each row as a JSON object, which suits projections that are not a whole model:
let rows = User::query().select(["id", "email"]).get_json().await?;
The model's column types decode its columns on every backend: SQLite stores booleans as integers and JSON and dates as text, and the model's types are what put them back. Other columns (aliases, aggregates, window values) are decoded by the type the database declares: text comes back verbatim, binary as an array of bytes, NUMERIC/DECIMAL as a decimal string. A MySQL TIME is a signed duration, such as -01:30:00 or 100:00:00. PostgreSQL types with no Rust counterpart come back as the server prints them: an INTERVAL as its ISO 8601 duration, TIMETZ, INET, CIDR and the built-in ranges as their text, a MONEY as a decimal string; an array keeps its NULLs and dimensions. Floating-point NaN and infinities come back as the strings "NaN", "inf" and "-inf", inside PostgreSQL arrays too, apart from SQL NULL, which is JSON null. A value TideORM cannot read fails the call rather than reading as null.
SQLite declares no type for an expression, so one is read by what SQLite stores: a float sum or a running total is a number, and text is a string however it looks, unless a document-returning SQLite JSON function or -> computed an object or array.
- A single-path
json_extractreturns a string member as plain SQL text, so its text cannot tell"[2]"from[2]and stays a string. Read a document with->instead (doc -> '$.tags'), which always returns JSON, in any form: chained, after another call, or with a parameter as its path. With several paths,json_extractreturns a JSON array and is decoded as one. - Any other expression over a JSON value, such as
COALESCE,CASE,MAXor a scalar subquery reading a JSON column, reads as text. - SQLite JSON expressions are followed through subqueries, CTEs and the views a statement reads, renamed columns included. An inner alias does not change an unrelated outer text expression's type.
- If a
UNIONcombines a JSON expression with ordinary text in one output column, that column keeps SQLite's stored text rather than guessing which rows are documents. SQLite describes a compound's columns by its first arm, though, so aJSONtable column there makes the column a document for every row. - A table column is a document only when it is declared
JSONorJSONB: an untyped column, or one of a type SQLite's driver does not name, reads its text as a string however it looks.
Database::raw_json reads rows with no model behind them; see Raw SQL.
Soft-Deleted Rows
A query on a soft-delete model leaves trashed rows out. with_trashed() reads them too and only_trashed() reads nothing else; see Soft Deletes and Scopes.
Caching
cache(ttl) keeps the models a query reads in the process-wide query cache, which starts disabled; see Query Cache.
Inspecting a Query
debug() shows the statement a query will run, with its values written in, and validate() returns the error a terminal would fail with, without running anything; see Logging and Profiling.
Joins, Aggregates and Advanced SQL
This page covers the parts of the query builder that go past filtering a single table: choosing columns, joins, aggregates and grouping, filtering by related rows, subqueries, unions, window functions, CTEs, row locks, and updating or deleting many rows at once.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[derive(serde::Deserialize)] struct AuthorPosts { author: String, posts: i64, } async fn prolific_authors() -> tideorm::Result<Vec<AuthorPosts>> { Post::query() .inner_join("users", "posts.user_id", "users.id") .where_eq("users.active", true) .select_raw("users.name AS author, COUNT(*) AS posts") .group_by("users.name") .having(Aggregate::count().gte(10)) .get_as() .await } }
Selecting Columns
A query reads the model's own columns unless you choose others:
| Method | Effect |
|---|---|
select(columns) | the columns to read: names, field names or typed columns, as an array, a Vec, a slice, or a tuple of typed columns of different types ((User::ID, User::EMAIL)); a second call replaces the first |
add_select(column) | adds one column to the columns selected so far; on a query that selected none, the projection becomes that one column |
select_raw(expression) | adds a trusted SQL expression, such as COUNT(*) AS total |
select_subquery(query, alias) | adds a scalar subquery, its values still bound |
distinct() | SELECT DISTINCT |
The three kinds accumulate: typed columns come first, then raw expressions, then subqueries, and only a query that selected nothing reads the model's columns. Another model's typed column is written with its table, for a joined query.
get() builds complete models, so it refuses a select() that leaves model columns out. Read a partial projection with get_json(), get_as::<T>(), pluck() or value() (see Running a Query):
let rows = User::query()
.select((User::columns.id, User::columns.email))
.add_select(User::columns.name)
.select_subquery(Post::query().select(["id"]).where_raw("posts.user_id = users.id").limit(1), "latest_post")
.get_json()
.await?;
With distinct(), count() counts the deduplicated rows, and exists() is unaffected. A projection holding an encrypted column is refused, since its ciphertext differs for equal values. PostgreSQL requires every ORDER BY expression of a SELECT DISTINCT to be in the select list; TideORM checks that before sending the query, except for an order_by_raw() expression, which stays your responsibility.
Reading columns of a related table next to the model's (select_with_linked, select_also_linked) is covered on Relations.
Joins
Name both sides of a join as table.column (or alias.column); a bare column name invalidates the query, and the error surfaces when it runs. Everywhere else a bare name of one of the model's columns means the model's table: filters, select(), ordering and aggregates are written table.column once the query joins, so reach a joined table's column as table.column. The ON clause is one equality.
let posts = Post::query()
.inner_join("users", "posts.user_id", "users.id")
.where_eq("users.active", true)
.get()
.await?;
join::<R>(JoinType::Inner, left, right) joins model R's table with its columns typed, and join_as::<R>(join_type, alias, left, right) joins it under an alias, writing R's typed columns with the alias:
let posts = Post::query()
.join::<User>(JoinType::Inner, Post::columns.user_id, User::columns.id)
.where_eq(User::columns.active, true)
.get()
.await?;
| Method | Join |
|---|---|
inner_join(table, left, right), inner_join_as(table, alias, left, right) | INNER JOIN |
left_join, left_join_as | LEFT JOIN: keeps this model's rows with no match |
right_join, right_join_as | RIGHT JOIN: keeps the joined table's rows with no match (SQLite 3.39 or later) |
join::<R>(join_type, left, right), join_as::<R>(join_type, alias, left, right) | any JoinType (Inner, Left, Right) to a model's table |
An alias is how a table joins itself or joins the same table twice. A right join's unmatched rows have NULL in every model column, which get() cannot turn into models, so read such a query with get_json(). Two selected columns may not share an output name, since a row holds only one of them: alias one (tags.id AS tag_id).
A join gives a model once per matching joined row, and count() and paginate() count those rows, so a user with three posts appears, and counts, three times. Add distinct() to read and count each model once.
// Every user, with or without posts
let rows = Post::query()
.right_join("users", "posts.user_id", "users.id")
.select_raw("users.name AS author")
.select_raw("posts.title AS title")
.get_json()
.await?;
// Each employee with their manager, if any
let rows = Employee::query()
.left_join_as("employees", "manager", "employees.manager_id", "manager.id")
.select_raw("employees.name AS name")
.select_raw("manager.name AS manager")
.get_json()
.await?;
Grouping joined rows into parents with their children (JoinResultConsolidator) is covered on Relations.
Aggregates
sum, avg, min, max and count_distinct each run one statement and read the result as the type you ask for. sum returns that type, zero over no rows; avg, min and max return an Option, None over no rows; count_distinct returns a u64. A sum is never read through a float, so an integer total past 2^53 or a Decimal total stays exact, and min/max work on any column type: a number, text, a date. A model's enum column reads as its variants.
let revenue: Decimal = Order::query().where_eq("paid", true).sum("total").await?;
let average: Option<f64> = Product::query().avg(Product::columns.price).await?;
let first_signup: Option<DateTime<Utc>> = User::query().min("created_at").await?;
let oldest = User::query().max::<i32>("age").await?;
let countries = User::query().count_distinct(User::columns.country).await?;
aggregates() computes several over the same rows in one statement, read into a tuple with one type per aggregate (or a Vec), each typed as the single terminal would read it:
let (orders, revenue, largest): (u64, Decimal, Option<Decimal>) = Order::query()
.where_eq("region", "EU")
.aggregates(&[Aggregate::count(), Aggregate::sum("total"), Aggregate::max("total")])
.await?;
Aggregate offers count(), count_distinct(col), sum(col), avg(col), min(col) and max(col).
The aggregates honour joins, CTEs, unions and limit()/offset(), and refuse group_by(), having() and window functions, since a grouped aggregate has no single answer. count() is different: it ignores limit() and offset(), so a paged query counts its total across every page, while Aggregate::count() counts only the rows the limit and offset leave. count_distinct refuses an encrypted column.
Grouping and Having
group_by(column) groups the rows, and having(condition) keeps the groups whose aggregate passes a comparison, with the value bound. Build a condition from an Aggregate with gt, gte, lt, lte, eq or ne; several having calls must all hold. Read grouped rows with get_as() or get_json():
#[derive(serde::Deserialize)]
struct RegionTotal { region: String, revenue: Decimal }
let busy_regions: Vec<RegionTotal> = Order::query()
.select_raw("region, SUM(total) AS revenue")
.group_by("region")
.having(Aggregate::sum("total").gt(5_000))
.having(Aggregate::count().gte(3))
.get_as()
.await?;
having_raw(sql) takes a raw condition as trusted SQL, checked for statement separators and comments, never escaped. having_raw_with(sql, values) binds a value for each ?, on every backend, so the values may come from a request:
Order::query().group_by("rep").having_raw("COUNT(DISTINCT region) > 1");
Order::query().group_by("rep").having_raw_with("SUM(total) > ?", [params.min_revenue.into()]);
Filtering by Related Rows
where_has::<R>(foreign_key, local_key, |q| ..) keeps the rows with a related R row that the closure's query keeps. The closure receives R's own query, so R's soft-delete scope applies and any filter works; pass |q| q to ask only that a related row exists. where_doesnt_have::<R> keeps the rows with none, a row with no related rows at all included. The first key is R's column that holds the second, this model's:
// Users with a published post
User::query().where_has::<Post>(Post::columns.user_id, User::columns.id, |posts| {
posts.where_eq(Post::columns.published, true)
});
// Posts whose author is active: here the key sits on this side
Post::query().where_has::<User>(User::columns.id, Post::columns.user_id, |users| {
users.where_eq(User::columns.active, true)
});
// Users who never posted
User::query().where_doesnt_have::<Post>(Post::columns.user_id, User::columns.id, |posts| posts);
A related query that joins, pages or unions fails the query, since a correlated EXISTS cannot keep those. A model related to itself works the same way: Category::query().where_has::<Category>("parent_id", "id", |children| children.where_eq("active", true)) keeps the categories with an active child. The related rows are read under an alias of their own, so a nested where_has, a typed column or a qualified "categories.active" inside the closure names the child, not the outer row.
The has_* helpers do the same over a table named as text rather than a model. Every identifier must be a plain table or column name, and since the table is not modeled, its soft-deleted rows count:
| Method | Keeps the rows |
|---|---|
has_related(table, foreign_key, local_key, column, value) | with a related row whose column equals value |
has_no_related(table, foreign_key, local_key, column, value) | with no such related row; a row with no related rows at all passes |
has_any_related(table, foreign_key, local_key) | with any related row |
has_no_related_at_all(table, foreign_key, local_key) | with no related row |
User::query().has_related("posts", "user_id", "id", "title", "Hello");
Subqueries
Another model's query can be a subquery of this one. It keeps its values bound and is rendered with the outer query for the backend it runs on, and a model query applies that model's soft-delete scope:
| Method | Condition |
|---|---|
where_in_subquery(column, query) | column IN (subquery) |
where_not_in_subquery(column, query) | column NOT IN (subquery) |
where_exists(query) | EXISTS (subquery) |
where_not_exists(query) | NOT EXISTS (subquery) |
select_subquery(query, alias) | a scalar subquery in the projection |
let authors = User::query()
.where_in_subquery(User::columns.id, Post::query().select(["user_id"]).where_eq("published", true))
.get()
.await?;
let with_comments = Post::query()
.where_exists(Comment::query().where_raw("comments.post_id = posts.id"))
.get()
.await?;
Unions
// UNION: combines the rows and removes duplicates
let users = User::query()
.where_eq("active", true)
.union(User::query().where_eq("role", "admin"))
.get()
.await?;
// UNION ALL: keeps every row
let posts = Post::query()
.where_eq("status", "draft")
.union_all(Post::query().where_eq("status", "review"))
.union_all(Post::query().where_eq("status", "scheduled"))
.order_by("created_at", Order::Desc)
.get()
.await?;
// A raw operand, trusted SQL; `_with` binds a value for each `?` on every backend
let users = User::query()
.union_raw_with("SELECT * FROM archived_users WHERE year = ?", [year.into()])
.get()
.await?;
union_raw and union_all_raw take a raw operand with no values, union_raw_with and union_all_raw_with one with bound values; prefer a query builder operand whenever one can say it. A union's order_by sorts the combined rows, so a column is written by its bare output name there even when a query of the union joins another table.
An operand bound to a database must use the same database and transaction as the outer query. union() refuses a projection holding an encrypted column, since ciphertext cannot deduplicate plaintext; with union_all(), every operand must have the same encrypted table and column at each output position, so keep explicit columns or the model's default projection there.
Window Functions
A window function adds a computed column to each row. Window values are not model fields, so read the rows with get_json() or get_as(). Every shorthand takes the output column's alias, the function's own arguments, the PARTITION BY columns (one column, a tuple or array of them, or () for none), and the window's ORDER BY column and direction:
// ROW_NUMBER() OVER (PARTITION BY "category" ORDER BY "price" DESC) AS "row_num"
Product::query().row_number("row_num", "category", "price", Order::Desc)
// RANK with gaps for ties; DENSE_RANK without, over the whole result
Employee::query().rank("salary_rank", Employee::columns.department_id, Employee::columns.salary, Order::Desc)
Student::query().dense_rank("score_rank", (), "score", Order::Desc)
// A running total per region
Order::query().running_sum("running_total", "total", "region", "created_at", Order::Asc)
// The previous and next values in each partition (NULL where there is none)
Order::query().lag("prev_total", "total", 1, "user_id", "created_at", Order::Asc)
Appointment::query().lead("next_date", "date", 1, "patient_id", "date", Order::Asc)
// Four buckets per category and brand, and each category's cheapest price
Product::query().ntile("price_quartile", 4, ("category", "brand"), "price", Order::Asc)
Product::query().first_value("cheapest", "price", "category", "price", Order::Asc)
For anything else, build a WindowFunction and pass it to window():
let rows = Order::query()
.window(
WindowFunction::new(WindowFunctionType::sum("total"), "total_to_date")
.partition_by("region")
.order_by("created_at", Order::Asc)
.frame(FrameType::Rows, FrameBound::UnboundedPreceding, FrameBound::CurrentRow),
)
.get_json()
.await?;
// LAG with a value where there is no earlier row. The default is trusted SQL,
// written in as given, hence the `_raw` in the name.
let rows = Order::query()
.window(
WindowFunction::new(WindowFunctionType::lag_with_raw_default("total", 1, "0"), "prev_total")
.partition_by("user_id")
.order_by("created_at", Order::Asc),
)
.get_json()
.await?;
WindowFunctionType has RowNumber, Rank, DenseRank, Ntile(n) and Count(None) (COUNT(*)), and constructors sum, avg, min, max, count, first_value, last_value, nth_value(col, n), lag(col, offset), lead(col, offset), lag_with_raw_default and lead_with_raw_default, which take a column name or a typed column (Order::columns.total), written with its table. Custom(sql) is a function expression written as given: trusted SQL, checked for statement separators, comments and NUL characters.
FrameTypeisRows,RangeorGroups.Groupsneeds PostgreSQL 11 or SQLite 3.28 or later; MySQL and MariaDB do not have it, and a query framed by it fails before it runs there.Rangewith an offset bound needs exactly one ordering column of a type the offset can be added to.FrameBoundisUnboundedPreceding,Preceding(n),CurrentRow,Following(n)orUnboundedFollowing.last_valuereads the frame's last row, and the default frame ends at the current row, so give it a frame that ends atUnboundedFollowing.- MariaDB's
LAG/LEADtake no default, so on MySQL and MariaDB TideORM writes the default with aCASEaround the function. - Window functions are added to the projection after the other columns; they never replace the model's columns.
Common Table Expressions
A CTE names a result set the query can read. with_query builds the CTE from another query, its values bound; CTE::new and CTE::with_columns take trusted SQL, which is checked as a subquery but not sanitized:
// A CTE from another query, joined like a table
let active_users = User::query().where_eq("active", true).select(["id", "name", "email"]);
let posts = Post::query()
.with_query("active_users", active_users)
.inner_join("active_users", "posts.user_id", "active_users.id")
.get()
.await?;
// A CTE from trusted SQL
let orders = Order::query()
.with_cte(CTE::new("big_orders", "SELECT id FROM orders WHERE total > 1000"))
.where_raw("id IN (SELECT id FROM big_orders)")
.get()
.await?;
// Named columns
let orders = Order::query()
.with_cte(CTE::with_columns(
"daily",
["day", "revenue"],
"SELECT DATE(created_at), SUM(total) FROM orders GROUP BY DATE(created_at)",
))
.where_raw("DATE(created_at) IN (SELECT day FROM daily WHERE revenue > 10000)")
.get()
.await?;
// A recursive CTE: the base case, then the recursive step
let employees = Employee::query()
.with_recursive_cte(
"org_tree",
["id", "name", "manager_id", "level"],
"SELECT id, name, manager_id, 0 FROM employees WHERE manager_id IS NULL",
"SELECT e.id, e.name, e.manager_id, t.level + 1 FROM employees e INNER JOIN org_tree t ON e.manager_id = t.id",
)
.where_raw("id IN (SELECT id FROM org_tree)")
.get()
.await?;
with_query_columns(name, columns, query) names the columns of a query-built CTE. CTE::new(..).recursive() marks a hand-built CTE recursive; one recursive CTE makes the whole WITH a WITH RECURSIVE, as SQL requires.
Row Locks
lock_for_update() locks the rows a query reads until the transaction ends (SELECT .. FOR UPDATE). Use it for a read-check-write inside a transaction: a second transaction that locks the same rows waits until the first commits, then reads what it wrote. See Transactions.
let shipped = Database::current()?.atomically(async {
let mut item = Item::query()
.where_eq("id", id)
.lock_for_update()
.first_or_fail()
.await?;
if item.stock < quantity {
return Ok(false);
}
item.stock -= quantity;
item.update().await?;
Ok(true)
}).await?;
Outside a transaction the lock ends with the statement. count(), exists() and the aggregates lock the rows they read too, and a locked query never reads from the query cache. PostgreSQL refuses the lock on a query with DISTINCT, GROUP BY or a union. SQLite has no row locks and writes nothing: the first write of a transaction locks the whole database, so the second of two competing read-check-write transactions fails with a retryable LockNotAvailable error instead of racing.
lock_for_share() takes a shared lock instead (FOR SHARE; MariaDB's LOCK IN SHARE MODE): other transactions can still read and share-lock the rows, but not change them. A query with both locks takes lock_for_update()'s.
Two options change what a lock does when another transaction holds the row; each needs one of the two locks, and a query with only the option fails:
skip_locked()leaves locked rows out (SKIP LOCKED), so workers sharing a job table each take different rows instead of queueing behind one another. TiDB ignoresSKIP LOCKED, so there it fails the query (see Compatible Servers).nowait()fails at once with aLockNotAvailableerror (NOWAIT) instead of waiting. CockroachDB takes no shared lock underSERIALIZABLE, so withlock_for_share()it waits as a plain read does (see Compatible Servers).
// Each worker claims up to 10 pending jobs no other worker holds.
let jobs = Database::current()?.atomically(async {
let jobs = Job::query()
.where_eq("status", "pending")
.order_asc("id")
.limit(10)
.lock_for_update()
.skip_locked()
.get()
.await?;
for job in &jobs {
Job::update_all().set("status", "running").where_eq("id", job.id).execute().await?;
}
Ok(jobs)
}).await?;
MariaDB takes SKIP LOCKED from 10.6. SQLite writes neither option, as it writes no lock.
Bulk Updates and Deletes
A query can update or delete every row it matches in one statement. These statements skip model callbacks, validation and automatic timestamps, and load no rows:
| Terminal | Does |
|---|---|
update_all() | returns a BatchUpdateBuilder over the query's rows; .set(..) and the other setters, then .execute() |
delete() | deletes the matching rows; on a soft-delete model it marks them deleted instead |
delete_all() | deletes every row of the table, or marks every live row deleted on a soft-delete model; takes no filter |
soft_delete() | marks the live matching rows deleted (soft-delete models only) |
restore() | clears the mark on the matching trashed rows (soft-delete models only) |
force_delete() | removes the matching rows for good, trashed or not |
let affected = User::query()
.where_lt(User::columns.last_login_at, cutoff)
.update_all()
.set(User::columns.status, "dormant")
.execute()
.await?;
let removed = Post::query().where_eq(Post::columns.status, "spam").delete().await?;
let emptied = Post::query().only_trashed().force_delete().await?; // empties the trash
Each returns the number of rows affected. query().update_all() keeps the query's filters, its soft-delete scope (trashed rows stay out unless the query includes them) and the database named by query_with; the setters, set, coalesce, increment, json_set, array_append and the rest, are covered on Reading and Writing, and the JSON and array ones on JSON and Arrays. Trash handling is covered on Soft Deletes and Scopes: soft_delete() stamps deleted_at with the application's clock (Utc::now()), not the database's, leaves an already trashed row's stamp alone and refuses only_trashed(); delete() refuses only_trashed() too.
Safety Guards
An unfiltered bulk write is refused rather than run:
delete(),update_all(),soft_delete()andforce_delete()need at least one explicit filter that can exclude a row.restore()andforce_delete()also acceptonly_trashed()alone, so they can restore or empty the whole trash; anupdate_all()of the trash still needs a filter of its own.delete_all()is the explicit way to clear a table, and it refuses filters (usedelete()for those).- A filter that renders as matching every row is refused too, whatever it looks like: an empty
where_not_in, a raw1 = 1, or an OR group with such a branch. The default live-rows scope of a soft-delete model never counts as a filter. - An
UPDATEcannot keep a join, a union, a CTE,group_by(),having(), a window function,limit()oroffset(), so a query holding one fails instead of updating more rows than it shows. ADELETEand the trash writes also refuse aselect(),distinct()and an ordering.
JSON and Arrays
TideORM filters JSON documents and arrays, and updates a part of one in place, with the same methods on every backend. PostgreSQL's jsonb operators define what each filter means; MySQL, MariaDB and SQLite are given SQL that answers the same way.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub metadata: serde_json::Value, } async fn featured_posts() -> tideorm::Result<Vec<Post>> { Post::query() .where_json_contains("metadata", json!({"featured": true})) .where_json_path_exists("metadata", "$.cover.url") .get() .await } async fn feature(id: i64) -> tideorm::Result<u64> { Post::update_all() .where_eq("id", id) .json_set("metadata", "$.featured", true) .execute() .await } }
Columns
A serde_json::Value field is a JSON column (JsonValue in the prelude is the same type). In a migration, t.json(..) creates JSON and t.jsonb(..) creates JSONB on PostgreSQL and JSON elsewhere; SQLite stores either as text. See Migrations.
Only PostgreSQL has array columns: a Vec<T> field, or t.integer_array(..)/t.text_array(..) in a migration. MySQL, MariaDB and SQLite have none, so keep an array there in a JSON column (a serde_json::Value field holding an array); the array filters and setters below work on it as a JSON array. backend().supports_arrays() tells which kind you have:
if require_db()?.backend().supports_arrays() {
// PostgreSQL: native array columns
}
Filtering JSON
| Method | Keeps the rows whose JSON column |
|---|---|
where_json_contains(col, value) | contains value, as PostgreSQL's @> reads it |
where_json_contained_by(col, value) | is contained by value (<@) |
where_json_key_exists(col, key) | has the top-level key |
where_json_key_not_exists(col, key) | lacks the top-level key |
where_json_path_exists(col, path) | has a member at path |
where_json_path_not_exists(col, path) | has no member at path |
where_eq(col, value), where_not, where_in, where_not_in | equals the document value (or one of them) |
Every one has or_where_* and and_where_* forms, as other filters do (see Where Each Filter Family Works). The containment value is anything serde::Serialize, usually json!(..).
Post::query().where_json_contains("metadata", json!({"tags": ["rust"]}));
Post::query().where_json_contained_by("metadata", json!({"featured": true, "draft": false}));
Post::query().where_json_key_exists("metadata", "cover");
Post::query().where_json_path_not_exists("metadata", "authors[1].name");
Post::query().where_eq("metadata", json!({"featured": true, "draft": false}));
Containment
Containment follows PostgreSQL's @> on every backend: an object contains another when it has each of its keys holding a contained value, an array contains another when each element of the other is contained by some element of it (order and repeats do not count), and a scalar contains only an equal scalar. At the top level only, a scalar is contained by an array that holds it.
- PostgreSQL casts the column to
jsonb, since the operators exist only there. They work on ajsoncolumn (whatt.json(..)creates) too, and on ajsonbcolumn the cast is dropped at planning, so its GIN index still applies. - SQLite has no containment operators, so TideORM builds the test from
json_eachrows: an object matches key by key, an array element by element. - MySQL and MariaDB use
JSON_CONTAINS, which on its own lets a value match an array holding it at any depth:{"tags": "a"}would match{"tags": ["a", "b"]}. TideORM adds a type check for each path of the document you pass, so they follow PostgreSQL there too. Below an array the paths are not known in advance, so MySQL's reading stays there:[{"k": [1, 2]}]contains[{"k": 1}]on MySQL and MariaDB and not on PostgreSQL.
Keys and Paths
A key or path exists when there is a member there, one holding JSON null included. A NULL column matches neither a test nor its negation.
A path is $ followed by .key, ."quoted key", ['quoted key'] or [index] steps, or those steps alone, read from the root: a.b[0] is $.a.b[0]. A bare .key must be a plain identifier (an ASCII letter or _, then letters, digits or _); quote any other key. Every backend reads a path strictly:
- a key exists only in an object, never as a string element of an array;
- a step never looks inside an array it does not index;
- an index never reads a value that is not an array as an array of one (MySQL's and MariaDB's indexed steps check their parent is an array).
A path with other steps, such as a wildcard or a filter, fails the query, except on PostgreSQL (not CockroachDB), which reads it as the JSONPath written.
Equality
On a JSON column, where_eq, where_not, where_in and where_not_in compare documents, not their text: an object's key order does not count, numbers compare by value (1.0 is 1), and an array's order does. 1, "1" and true all differ. Text you pass is the JSON string, not a document parsed from it. serde_json::Value::Null matches the JSON null document and None the SQL NULL rows; see Values.
What Each Backend Runs
Every value and path is bound as a parameter (? below).
| Test | PostgreSQL | MySQL, MariaDB | SQLite |
|---|---|---|---|
| contains | (col)::jsonb @> ? | JSON_CONTAINS(col, ?) plus a JSON_TYPE check per path | a structural test over json_each(col) rows |
| contained by | (col)::jsonb <@ ? | JSON_CONTAINS(?, col) plus a JSON_TYPE check per path | a structural test over json_each(col) rows |
| key exists | jsonb_typeof((col)::jsonb) = 'object' AND (col)::jsonb ? ? | JSON_CONTAINS_PATH(col, 'one', ?) | json_type(col, ?) IS NOT NULL |
| path exists | jsonb_path_exists((col)::jsonb, 'strict <path>'); any other JSONPath with @? | JSON_CONTAINS_PATH(col, 'one', ?) plus an array check per index step | json_type(col, ?) IS NOT NULL |
| equality | (col)::jsonb = ? | MySQL col = CAST(? AS JSON), MariaDB JSON_EQUALS(col, ?) | a structural test over json_each(col) rows |
The negations wrap the same test so that a NULL column stays unmatched.
Filtering Arrays
| Method | Keeps the rows whose array column |
|---|---|
where_array_contains(col, values) | holds every one of values (@>) |
where_array_contained_by(col, values) | holds nothing but values (<@) |
where_array_overlaps(col, values) | holds at least one of values (&&) |
values is any list (a Vec, an array, a slice); each element is bound as the array's element type on PostgreSQL and as a JSON value elsewhere. They have or_where_* and and_where_* forms too.
// Posts tagged both "rust" and "orm"
Post::query().where_array_contains("tags", ["rust", "orm"]);
// Posts with no tag outside the list
Post::query().where_array_contained_by("tags", ["rust", "orm", "sql"]);
// Posts with either tag
Post::query().where_array_overlaps("tags", ["rust", "go"]);
- Order and repeats do not count.
- An empty list:
where_array_containskeeps every non-NULLarray,where_array_contained_byonly empty arrays, andwhere_array_overlapsnothing. - A
NULLin awhere_array_contained_bylist also allowsNULLelements. - A
NULLcolumn matches none of them. - On a JSON array (MySQL, MariaDB, SQLite), a column holding an object or a scalar matches none of them, and elements compare as JSON values:
1is nottrueor"1", and the string"{\"a\":1}"is not that object.
| Test | PostgreSQL (native array) | MySQL, MariaDB (JSON array) | SQLite (JSON array) |
|---|---|---|---|
| contains | (? = ANY(col) AND ? = ANY(col) ..) | JSON_CONTAINS(col, ?) of the whole list, with type checks | an EXISTS over json_each(col) per value, ANDed |
| contained by | col IS NOT NULL AND NOT EXISTS (..) over unnest(col) for an element outside the list | JSON_CONTAINS(?, col), with type checks | col IS NOT NULL AND NOT EXISTS (..) over json_each(col) |
| overlaps | (? = ANY(col) OR ? = ANY(col) ..) | JSON_CONTAINS(col, ?) per value, ORed | an EXISTS over json_each(col) per value, ORed |
On MySQL, MariaDB and SQLite every array test also checks that the column holds an array (JSON_TYPE(col) = 'ARRAY', json_type(col) = 'array'). To test an array inside a JSON document on PostgreSQL, use where_json_contains with the array: the array filters there need a native array column.
Updating JSON and Arrays
A bulk update (Model::update_all() or query().update_all()) changes part of a document or an array in the database, without reading it into Rust and writing it back, which would undo another writer's change to the rest of the document:
Post::update_all()
.where_eq("id", id)
.json_set("metadata", "$.cover.url", "https://cdn.example.com/1.png")
.array_append("tags", "rust")
.execute()
.await?;
Post::update_all()
.where_array_contains("tags", ["draft"])
.array_remove("tags", "draft")
.execute()
.await?;
| Setter | Writes | Column |
|---|---|---|
json_set(col, path, value) | the document with the member or element at path set to value | a JSON column, on every backend |
array_append(col, value) | the array with value added at the end | a native array on PostgreSQL; a JSON column on MySQL, MariaDB and SQLite |
array_remove(col, value) | the array without any element equal to value | as array_append |
A setter on a column of another type fails the update before it runs.
json_settakes$followed by at least one.key,."any key",['any key']or[index]step; a wildcard is refused. An existing member or element is replaced and a missing member of an existing object is added. A path whose parent is missing, or is not the object a key step needs or the array an index step needs, leaves the document as it is, and an index past an array's end appends the value. The same document comes out on every backend.array_appendstarts a new array in aNULLcolumn. On a JSON column it appends a JSON value, an object included, and a document that is not an array becomes the first element of a new one.array_removedrops every element equal to the value and keeps the others in their order, with their types. It compares as JSON equality does: an object's key order does not count,1.0is1, and1,"1"andtruediffer. ANULLcolumn, or a JSON document that is not an array, stays as it is. On MySQL and MariaDB it reads the array withJSON_TABLE, which TiDB lacks (see Compatible Servers).
Values are written as their JSON documents on a JSON column: json!(..) for an object, text as a JSON string, and a None as JSON null. A NaN or infinite float fails the update before any row changes. The other setters (set, coalesce, increment and the rest) are on Reading and Writing.
Reading JSON
A JSON field reads back as the document it holds on every backend, including SQLite, where it is stored as text. For JSON computed in a query, such as a -> expression read with get_json(), see Rows as JSON.
Full-Text Search
Full-text search finds the rows whose text columns hold the words of a search, ranked by how well they match. It uses each backend's own engine: tsvector/tsquery on PostgreSQL, FULLTEXT indexes on MySQL and MariaDB, and FTS5 on SQLite.
It requires the fulltext feature:
tideorm = { version = "0.18.2", features = ["postgres", "fulltext"] }
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, pub body: String, } async fn search_posts(text: &str) -> tideorm::Result<()> { let ranked = Post::search((Post::TITLE, Post::BODY), text) .limit(10) .get_ranked() .await?; for result in ranked { println!("{} ({:.2})", result.record.title, result.rank); } Ok(()) } }
The search types are in the prelude and in tideorm::fulltext.
Creating the Index
MySQL and MariaDB search only columns a FULLTEXT index covers, and SQLite searches the FTS5 table the index creates, so create the index before the first search. PostgreSQL searches without one, but reads every row. FullTextIndex writes the statements for each backend; run them in a migration:
#![allow(unused)] fn main() { use tideorm::prelude::*; use tideorm::fulltext::FullTextIndex; use tideorm::migration::*; struct AddPostSearch; #[async_trait] impl Migration for AddPostSearch { fn version(&self) -> &str { "20260301_001" } fn name(&self) -> &str { "add_post_search" } async fn up(&self, schema: &mut Schema) -> tideorm::Result<()> { let index = FullTextIndex::new("idx_posts_search", "posts", ["title", "body"]); for statement in index.to_sql(schema.database_type()) { schema.raw(&statement).await?; } Ok(()) } async fn down(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.raw("DROP INDEX idx_posts_search").await } } }
to_sql(db_type) returns the statements in the order to run them. Each backend also has its own method:
| Backend | Method | Statements |
|---|---|---|
| PostgreSQL | to_postgres_sql() | CREATE INDEX "idx_posts_search" ON "posts" USING GIN ((to_tsvector('english', ..))) |
| MySQL, MariaDB | to_mysql_sql() | CREATE FULLTEXT INDEX `idx_posts_search` ON `posts`(`title`, `body`) |
| SQLite | to_sqlite_sql() | the FTS5 table posts_fts, the triggers that keep it in step with posts, and a rebuild that fills it with the rows already there |
The down above suits PostgreSQL; MySQL and MariaDB write DROP INDEX idx_posts_search ON posts, and on SQLite you drop the posts_fts table and its triggers posts_ai, posts_ad and posts_au.
Options:
.language("english")sets the PostgreSQL text search configuration (englishby default). A search uses the index only when it names the same columns and language..pg_index_type(PgFullTextIndexType::GIN)orGiSTchooses the PostgreSQL index type (GIN by default).- The public
configfield is aFullTextIndexConfigwithlanguage,pg_index_typeandmysql_parser. Setindex.config.mysql_parser = Some("ngram".into())to add aWITH PARSERclause naming that parser to the MySQL statement.
SQLite Indexes
- A table has one full-text index, the
<table>_ftstable its searches read, whatever the index is named. - Applying the same index again changes nothing. One over a column the existing index does not hold fails with
no such columninstead of keeping the old columns; drop<table>_ftsand its triggers to index other columns. A trigger of another definition under one of those names is refused too. - A table named with its attached database (
tenant.posts) gets its index in that database. - The index follows the table's rowid, which
VACUUMkeeps only for a table with anINTEGER PRIMARY KEY. After vacuuming a table keyed another way (a UUID or text key), runindex.sqlite_rebuild_sql()before anything else touches it, or searches return other rows. - A table that declares a column named
rowidis supported only when that column is itsINTEGER PRIMARY KEY; otherwise the index, the rebuild and every search fail. - The statements check these rules through
tideorm_raise, a function TideORM's SQLite connections define, so run them through TideORM (a migration orDatabase::execute), not another SQLite client.
Searching
Model::search(columns, text) starts a search. The columns are names (["title", "body"]) or typed columns ((Post::TITLE, Post::BODY)), as for select.
| Method | Returns |
|---|---|
get() | Vec<Post>, the matching rows |
get_ranked() | Vec<SearchResult<Post>>, best match first |
first() | Option<Post>, the first match |
count() | u64, the number of matching rows |
let posts = Post::search(["title", "body"], "rust programming").get().await?;
let total = Post::search(["title", "body"], "rust").count().await?;
let first = Post::search(["title"], "rust").first().await?;
let page_two = Post::search(["title", "body"], "rust").limit(20).offset(20).get().await?;
A SearchResult holds the record, its rank (an f64) and the highlights described below.
A search on a soft-delete model leaves trashed rows out, as a query does. with_trashed() reads them too and only_trashed() reads nothing else:
let binned = Post::search(["title"], "rust").only_trashed().get().await?;
#[tideorm(searchable = "title,body")] on a model records a column list in Post::searchable_fields(). A search does not read it on its own; pass it as the columns: Post::search(Post::searchable_fields(), text).
Search Modes
Every mode builds the backend's syntax from the words of the search text, so an operator a user types is never read as syntax.
use tideorm::fulltext::SearchMode;
// Natural language (the default)
Post::search(["body"], "learn rust programming").get().await?;
// Every term required, "-term" excluded
Post::search(["body"], "+rust +async -javascript").mode(SearchMode::Boolean).get().await?;
// The words in order
Post::search(["body"], "async await").mode(SearchMode::Phrase).get().await?;
// Words beginning with each search word, for autocomplete
Post::search(["title"], "prog").mode(SearchMode::Prefix).get().await?;
// The words within 5 words of each other, in either order
Post::search(["body"], "borrow checker").mode(SearchMode::Proximity(5)).get().await?;
| Mode | Matches |
|---|---|
Natural | the words as the backend's natural-language search reads them: PostgreSQL and SQLite require every word, MySQL and MariaDB rank rows holding any of them |
Boolean | every term; a term written -term or -"a phrase" is left out, and a quoted phrase matches as a phrase. MySQL and MariaDB also read their ~ < > * operators, and there a term without + is optional. On SQLite a search of exclusions only matches nothing, since FTS5's NOT needs something to subtract from |
Phrase | the words, in order, as one phrase |
Prefix | words beginning with each search word, all of them required |
Proximity(n) | the words within n words of each other, in either order; at most 64 on PostgreSQL |
A search with no word left to search for matches nothing on every backend.
| Mode | PostgreSQL | MySQL, MariaDB | SQLite (FTS5) |
|---|---|---|---|
Natural | plainto_tsquery | MATCH (..) AGAINST (?) | each word quoted |
Boolean | to_tsquery of the terms | IN BOOLEAN MODE, the terms sanitized | AND and NOT |
Phrase | phraseto_tsquery | IN BOOLEAN MODE, "the words" | one phrase |
Prefix | to_tsquery with :* prefixes | IN BOOLEAN MODE, +word* for each word | word* for each word |
Proximity(n) | to_tsquery with the <n> distances, both orders | IN BOOLEAN MODE, "the words" @n | NEAR(.., n - 1) |
On PostgreSQL a to_tsquery mode that leaves no word after sanitizing falls back to plainto_tsquery. On SQLite the search reads only the named columns of the FTS5 table, through a column filter.
Configuration
FullTextConfig sets the mode, the language, term filters and weights together:
use tideorm::fulltext::{FullTextConfig, SearchMode};
let config = FullTextConfig::new()
.language("english")
.mode(SearchMode::Boolean)
.stop_words(["the", "a", "of"])
.min_word_length(3);
// Searches for "rust" and "ownership" only
let posts = Post::search(["body"], "the rust of ownership").config(config).get().await?;
The builder also takes .mode(..) and .language(..) directly.
languageis the PostgreSQL text search configuration (englishby default). It is written into the statement as a constant, the wayFullTextIndexwrites it into the index, so a search can use that index; a name that is not a configuration name (identifiers separated by dots) fails the search. MySQL, MariaDB and SQLite ignore it.stop_words,min_word_lengthandmax_word_lengthleave terms out of the search text before it is sent, on every backend; the index is untouched. Stop words compare without regard to case, and the operators around a term (+,-,*, quotes, parentheses) count toward neither its length nor its stop-word match. A quoted phrase, and aPhrasesearch, is sent as written. A search whose every term is left out matches nothing.weightsare PostgreSQL's rank weights; see Ranking.
Ranking
get_ranked() ranks on every backend and returns the best match first. A higher rank is a better match everywhere, but the numbers mean different things per backend, so compare ranks only within one backend:
| Backend | Rank |
|---|---|
| PostgreSQL | ts_rank_cd(weights, tsvector, tsquery) |
| MySQL, MariaDB | the MATCH (..) AGAINST (..) relevance |
| SQLite | -bm25(<table>_fts), the negated FTS5 score |
min_rank(rank)drops results scoring belowrank. Onlyget_ranked()applies it.with_ranking()ordersget()andfirst()by relevance on PostgreSQL. MySQL, MariaDB and SQLite ignore it; useget_ranked()there.SearchWeights::new(a, b, c, d)(default1.0, 0.4, 0.2, 0.1) sets PostgreSQL's weights for the four label categories. TideORM builds thetsvectorwithoutsetweight, so every word carries theDlabel: onlydcounts, and it scales every rank by the same factor. It moves the scoremin_rankcompares against, not the order.
let strong = Post::search(["title", "body"], "rust async")
.min_rank(0.1)
.limit(10)
.get_ranked()
.await?;
Highlighting
highlight(config) marks the whole-word matches in the searched columns of each get_ranked() result, without regard to case. The record's text is HTML-escaped around the tags, so a stored <script> reaches the page as text:
use tideorm::fulltext::HighlightConfig;
let ranked = Post::search((Post::TITLE, Post::BODY), "rust async")
.highlight(HighlightConfig::default())
.get_ranked()
.await?;
for field in &ranked[0].highlights {
println!("{}: {} ({} matches)", field.field, field.highlighted, field.match_count);
}
Each HighlightedField holds the column (field), the marked text (highlighted), the text as stored (original) and the number of matches (match_count). A term a Boolean search excludes is not marked.
HighlightConfig | Default | Effect |
|---|---|---|
.tags(start, end) | <mark>, </mark> | the tags around each match |
.fragment_words(n) | 10 | keep n words on each side of the first match |
.whole_text() | off | mark the whole text instead of a fragment |
.max_length(chars) | none | cut the result to chars characters, followed by ... |
.escape_html(bool) | true | turn escaping off for tags that are not HTML |
HighlightConfig::highlight(text, query) marks any text the same way, escaping it as a search does:
let marked = HighlightConfig::default().whole_text().highlight("a <script> about the fox", "fox");
assert_eq!(marked, "a <script> about the <mark>fox</mark>");
highlight_text and generate_snippet mark text without escaping it, so keep them for text that is not HTML:
use tideorm::fulltext::{generate_snippet, highlight_text};
let text = "The quick brown fox jumps over the lazy dog.";
let marked = highlight_text(text, "fox lazy", "<mark>", "</mark>");
// "The quick brown <mark>fox</mark> jumps over the <mark>lazy</mark> dog."
let snippet = generate_snippet(text, "fox", 2, "<b>", "</b>");
// "...quick brown <b>fox</b> jumps over..."
generate_snippet(text, query, fragment_words, start, end) keeps fragment_words words on each side of the first match, with ... where it cut; with no match it keeps the opening words.
PostgreSQL Headlines
pg_headline_sql(column, query, language, start_tag, end_tag) returns a ts_headline expression for the server to mark the matches, and the language, search text and options it binds as $1 to $3:
use tideorm::fulltext::pg_headline_sql;
let (headline, params) = pg_headline_sql("body", "search query", "english", "<b>", "</b>");
// ts_headline($1::regconfig, "body", plainto_tsquery($1::regconfig, $2), $3)
let rows = Database::raw_json_with_params(
&format!("SELECT id, {headline} AS headline FROM posts"),
params,
)
.await?;
The options are StartSel, StopSel, MaxWords=35 and MinWords=15; the tags are double-quoted inside them, so a tag cannot add an option of its own. The text is not escaped: ts_headline returns the column as stored. See Raw SQL for raw_json_with_params.
MySQL and MariaDB Operators
MySQL's boolean-mode operators (+ - < > ( ) ~ * " @) are sanitized before the text reaches MATCH .. AGAINST. In Boolean mode each term keeps one leading + - ~ < > and a trailing *, and a quoted phrase stays a phrase; in the other modes the operator characters become spaces before TideORM writes its own. A search left with no searchable term matches nothing instead of failing with a syntax error.
Limits
- An encrypted field cannot be searched: an index over randomized ciphertext matches no search text. A search naming one fails, and so does a
searchablelist naming one, at compile time. get()andget_ranked()are held to themax_rowsproject rule: with the rule set, a search needs alimit()within it.
Raw SQL
When the query builder cannot express a statement, run your own SQL. Its values are bound as parameters, never written into the text, and its rows can be read as models, as a struct of your own or as JSON.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[derive(FromQueryResult)] struct CountryTotal { country: String, users: i64, } async fn busy_countries(min: i64) -> tideorm::Result<Vec<CountryTotal>> { // PostgreSQL markers; MySQL, MariaDB and SQLite take `?` Database::raw_as_with_params( "SELECT country, COUNT(*) AS users FROM users GROUP BY country HAVING COUNT(*) >= $1", [min.into()], ) .await } }
Running Statements
These are associated functions on Database: they run inside the enclosing transaction, or on the global connection when there is none.
| Function | Returns |
|---|---|
Database::raw::<M>(sql), raw_with_params::<M>(sql, params) | Vec<M>, each row read as the model M |
Database::raw_as::<T>(sql), raw_as_with_params::<T>(sql, params) | Vec<T>, each row read as a FromQueryResult type |
Database::raw_json(sql), raw_json_with_params(sql, params) | Vec<serde_json::Value>, each row as a JSON object |
Database::execute(sql), execute_with_params(sql, params) | u64, the rows affected |
let adults: Vec<User> = Database::raw::<User>("SELECT * FROM users WHERE age > 18").await?;
let active: Vec<User> = Database::raw_with_params::<User>(
"SELECT * FROM users WHERE age > $1 AND status = $2",
vec![18.into(), "active".into()],
)
.await?;
let affected = Database::execute(
"UPDATE users SET active = false WHERE last_login < NOW() - INTERVAL '1 year'",
)
.await?;
let removed = Database::execute_with_params(
"DELETE FROM users WHERE status = $1",
vec!["banned".into()],
)
.await?;
execute(sql) sends its text unprepared, so it may hold several statements separated by ;, such as a script. The _with_params forms prepare one statement.
Parameters
Parameters are DbValues (in the prelude), usually built with .into() from a Rust value. params takes a Vec, an array or any iterator of them. Bind SQL NULL as a typed None:
let params: Vec<DbValue> = vec![true.into(), "alice".into(), None::<String>.into()];
The SQL is sent as you wrote it, so write the backend's own markers:
| Backend | Markers |
|---|---|
| PostgreSQL | $1, $2, .. |
| MySQL, MariaDB | ? |
| SQLite | ?, ?NNN or $NNN, numbered from 1 |
SQLite refuses named parameters (:name, @name), ?0 and $0, and a statement whose markers take more values than you passed or leave some unused.
Never format a value into the SQL text yourself; bind it. Identifiers cannot be bound, so a table or column name in raw SQL must be one you wrote, not one taken from a request.
Reading Rows
As Models
raw::<M> reads each row the way a query does: through the model's own columns, with encrypted fields decrypted, relations attached to the database the row came from, and dirty tracking started. The statement must return the model's columns. Nothing else is added: no soft-delete scope, no default projection, no limit.
As Your Own Type
#[derive(FromQueryResult)] (in the prelude) reads a row of any shape, such as a report or a join:
#[derive(FromQueryResult)]
struct Totals {
country: String,
users: i64,
last_signup: Option<chrono::DateTime<chrono::Utc>>,
}
let totals: Vec<Totals> = Database::raw_as(
"SELECT country, COUNT(*) AS users, MAX(created_at) AS last_signup FROM users GROUP BY country",
)
.await?;
- Each field is read from the column of its name, as the field's type, the way a model reads its columns, so alias a computed column to its field (
AS users). A raw identifier field (r#type) reads the columntype. - An
Optionfield takes SQLNULL, and a column the row does not have, asNone; any other field fails on either, so a misspelt alias empties anOptionfield silently. - A name two result columns share, such as a join's two
ids, fails the row rather than read either: alias them (p.id AS post_id). The same holds forraw_jsonkeys. - The derive takes structs with named fields and no attributes.
- A row that does not read fails the call with a conversion error naming the type:
raw_as() could not read a row as ...
A query builder's get_as::<T>() uses serde instead, so a Deserialize type works there; raw_as needs FromQueryResult.
As JSON
raw_json returns each row as a JSON object, with each column decoded by the type the database declares for it. Rows as JSON describes how each type reads, including SQLite's expressions.
let rows = Database::raw_json("SELECT id, email, created_at FROM users LIMIT 10").await?;
On a Specific Database
Every function has an instance form on a Database handle, for an application with several databases (see Databases):
| Associated function | On a handle |
|---|---|
Database::raw::<M> | db.query_raw::<M>(sql), db.query_raw_with_params::<M>(sql, params) |
Database::raw_as::<T> | db.query_raw_as::<T>(sql), db.query_raw_as_with_params::<T>(sql, params) |
Database::raw_json | db.query_raw_json(sql), db.query_raw_json_with_params(sql, params) |
Database::execute | db.exec_raw(sql), db.exec_raw_with_params(sql, params) |
let reporting = Database::connect(&reporting_url).await?;
let rows = reporting.query_raw_json("SELECT * FROM daily_totals").await?;
A transaction opened on the handle's own pool still wins: inside Database::transaction, db.exec_raw(..) joins that transaction rather than running beside it. A transaction on another database does not take it: the statement runs on the handle's own database.
Raw Fragments in a Query
The query builder takes raw SQL for the parts it cannot express, and checks each fragment before the query runs:
| Method | Fragment |
|---|---|
where_raw(sql), or_where_raw, and_where_raw | a condition |
where_raw_with(sql, params), or_where_raw_with, and_where_raw_with | a condition with bound values |
having_raw(sql), having_raw_with(sql, params) | a HAVING condition |
select_raw(sql) | a projection |
order_by_raw(sql, Order::Asc) | an ordering expression |
union_raw(sql), union_all_raw(sql), union_raw_with(sql, params), union_all_raw_with(sql, params) | a union operand |
CTE::new(name, sql), with_recursive_cte(..) | a CTE body |
let users = User::query()
.where_raw_with("LOWER(email) = LOWER(?)", [email.into()])
.order_by_raw("COALESCE(nickname, name)", Order::Asc)
.get()
.await?;
let busy = Post::query()
.select_raw("user_id, COUNT(*) AS posts")
.group_by("user_id")
.having_raw_with("COUNT(*) > ?", [10_i64.into()])
.get_json()
.await?;
The _with forms take ? as the marker on every backend, whatever the backend's own: TideORM writes the backend's markers when the statement renders. A ? inside a quoted literal is text, and a count of ? other than the number of values fails the query. The values may come from a request. A value no backend can bind as given (a u64 past i64::MAX) is bound as an exact decimal.
Which filter families take the *_raw forms is listed under Where Each Filter Family Works; unions, CTEs and window functions under Joins, Aggregates and Advanced SQL.
What Is Checked
A fragment is trusted SQL: it is checked for constructs that would change the statement around it, never escaped. Every fragment is refused when it is empty or holds:
- a statement separator (
;); - a comment (
--,/* */, or#, which MySQL and MariaDB read as one); - a NUL byte;
- an unterminated string literal or quoted identifier, or a dollar-quoted string;
- a backslash right before a quote inside a literal, which MySQL reads as an escape and PostgreSQL and SQLite do not;
- a quote inside square brackets, which SQLite reads as a quoted identifier.
Some fragments are held to more:
having_rawrefuses subqueries, joins, set operators, data-changing and DDL keywords,EXISTS,INTO,LIMIT,OFFSET,WINDOWandOVER, and any character other than an operator,.,,,?,:or balanced parentheses.LEFT(..)andRIGHT(..)are functions there, not joins.union_rawand a CTE body must begin withSELECTorWITH, aWITHmust end in aSELECT, and they refuseINSERT,UPDATE,DELETE,DROP,ALTER,CREATE,TRUNCATE,RETURNING,MERGE,REPLACE,UPSERT,GRANT,REVOKE,CALL,EXECUTEandVALUESat their top level (a function of that name, such asREPLACE(..), is fine). A union operand may not hold aUNION,INTERSECTorEXCEPTof its own; useunion()with a query for that. ACTE::newbody may; each half ofwith_recursive_ctemay not.
A refused fragment does not fail the builder call: the query fails when it runs, and validate() reports it without running anything.
The checks catch mistakes, not every injection. Never format a request's text into a fragment; bind it with a _with form.
A batch update's set_trusted_raw(col, expression) is the one fragment that is not checked at all; reach for the computed setters on Reading and Writing first.
Forbidding Raw SQL
The forbid_raw_sql project rule refuses raw SQL: the fragments above, set_trusted_raw, and every statement on this page. Database::raw::<M> is held to M's rules; execute, raw_as and raw_json name no model, so they are refused whenever the project forbids raw SQL. Migrations may still run raw SQL through Schema::raw.
Prepared Statements
Each connection prepares a parameterized statement once and reuses it, keeping up to 100 by default (see Configuration for statement_cache_capacity). db.cached_statements() reports how many statements one of the handle's connections holds.
Name the columns in raw SQL rather than SELECT * when the table can change under a running application. After a column is added, PostgreSQL rejects a cached SELECT * (cached plan must not change result type) and SQLite can report the old column list, until the connection is replaced. The query builder is not affected: it always names the model's columns.
Caching and Logging
TideORM cannot tell which tables a raw statement writes: a SELECT can write through a function, a view or a trigger. So every raw statement drops the query cache's cached reads of its database once it has run, reads included, and so does one that fails, since a statement before the failing one may already have committed. Query builder reads keep their targeted invalidation.
Raw statements reach the query logger and the profiler like any other; see Logging and Profiling.
Query Cache
The query cache keeps the models a query read, in memory, for a time you choose, and drops them when TideORM writes to their database. It is one cache per process, it starts disabled, and a query uses it only when you ask.
#![allow(unused)] fn main() { use std::time::Duration; use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub active: bool, } async fn active_users() -> tideorm::Result<Vec<User>> { User::query() .where_eq(User::columns.active, true) .cache(Duration::from_secs(60)) .get() .await } fn enable_cache() { // Once at startup QueryCache::init_global(CacheConfig::default().enabled(true)); } }
The cache types are in the prelude and in tideorm::cache.
Turning It On
QueryCache::init_global(config) configures the process-wide cache and returns it. It can run after the cache already exists (any model write creates it with the defaults): the configuration then replaces the live one and the cached entries stay. QueryCache::global().enable() and .disable() switch it at any time, and is_enabled() tells which it is.
While the cache is disabled, cache(ttl) does nothing; the first query that asks for it logs a warning saying so, once per process.
Caching a Query
| Method | Effect |
|---|---|
cache(ttl) | keep this query's models for ttl |
cache_with_key(key, ttl) | the same, with key as part of the entry's identity |
no_cache() | do not cache this query, undoing an earlier cache |
cache stores what get() returns, so it serves everything that reads through get(): first(), first_or_fail(), a query's find(id) and find_or_fail(id), the items of each paginate() page (its total count is read every time) and each batch of chunk(). Other terminals (count(), exists(), pluck(), get_json(), aggregates) always read the database. A hit returns models as a read does: relations attached to the database and dirty tracking started.
An entry is found by the query's SQL and values, the database handle it runs on, and the cache_with_key key if given. Two queries share an entry only when all of them match: User::query_with(&tenant_a) and User::query_with(&tenant_b) never do, and neither do first() and get() of one query.
cache_with_key is for rows that depend on something the SQL does not show, such as a session setting or a row-level security role: give each value its own key, so reads under different values never share an entry.
let posts = Post::query()
.where_eq(Post::columns.published, true)
.cache_with_key(&format!("role:{role}"), Duration::from_secs(30))
.get()
.await?;
A query asking for the cache reads the database instead, and stores nothing, when:
- it runs inside a transaction, where a stored copy could outlive a rollback and a hit would hide the transaction's own writes;
- it locks its rows (
lock_for_update()); - its model's own serde derives would not read every stored field back, such as a
#[serde(skip)]on a column or no serde at all; - a row holds a value JSON cannot keep exactly: a NaN or infinite float, or a JSON
nullin anOptionfield (entries are stored as JSON); - a write to its database landed while it ran, so the rows it read may already be replaced;
- the result is empty and
cache_empty_resultsis off.
Invalidation
Every write TideORM makes drops the cached reads of the database it wrote to, not only of its table, since foreign-key actions and triggers can change any table there. That covers model writes, bulk updates and deletes, the entity manager's flushes and every raw statement, reads included.
- Transactions. A write inside a transaction drops the reads as it runs and again when the transaction commits, since other requests read, and may cache, the old rows until then. A commit that fails or is cancelled drops them again too, since it may have committed.
- Outside writes. Writes TideORM does not make, from another process or another program, are seen only once the TTL runs out. To share invalidations between your own processes, see Several Processes.
Which pools count as one database:
| Backend | One database is |
|---|---|
| SQLite | one file; a shared in-memory database by its name; a private in-memory database is its own |
| PostgreSQL | one socket or host, port and database |
| MySQL, MariaDB | one socket or host and port: the whole server, since triggers and foreign keys can cross databases there |
Hosts are compared as the URL writes them, ignoring case, so localhost and 127.0.0.1 are two databases. A SQLite pool that uses ATTACH, and a connection whose database cannot be identified, drop every entry on each write.
To drop entries yourself:
let cache = QueryCache::global();
cache.invalidate("my-key"); // one entry; returns whether it was there
cache.invalidate_model("users"); // every entry that reads the table, compared without case
cache.clear(); // everything
Configuration
CacheConfig starts from CacheConfig::default(); its fields are public to read and assign.
| Setting | Default | Meaning |
|---|---|---|
.enabled(bool) | false | whether the cache serves and stores |
.max_entries(n) | 1000 | entries kept before evicting |
.max_size_bytes(n) | 64 MiB | total size of the stored JSON; 0 for no byte limit |
.default_ttl(duration) | 60 s | the TTL of a manual entry set without one |
.strategy(CacheStrategy) | LRU | which entry to evict first |
.cache_empty_results(bool) | true | whether an empty result is stored |
.key_prefix(prefix) | none | a prefix on every key, to keep namespaces apart |
CacheStrategy | Evicts first |
|---|---|
LRU | the entry read least recently |
FIFO | the entry stored first |
TTL | the entry closest to expiring |
Whatever the strategy, every entry also expires at its TTL. An entry larger than the whole byte limit is never stored.
The live cache takes set_max_entries, set_max_size_bytes, set_default_ttl, set_strategy and set_cache_empty_results; lowering a limit evicts at once. config() returns the current configuration and apply_config(config) replaces it, keeping the entries. QueryCache::new() and QueryCache::with_config(config) build a separate cache of your own, which model writes do not invalidate.
Manual Entries
The cache also holds values of your own, stored as JSON:
let cache = QueryCache::global();
cache.set("stats:users", &totals, Some(Duration::from_secs(300)), "users")?;
cache.set_tagged("report:orders", &report, None, ["orders", "users"])?;
let totals: Option<Vec<Totals>> = cache.get("stats:users");
set(key, &value, ttl, table)tags the entry with one table andset_tagged(key, &value, ttl, tables)with several, soinvalidate_modelon any of them drops it. ANoneTTL takesdefault_ttl; a zero TTL stores nothing.- A manual entry belongs to no database, so a write to any database drops it.
- A value JSON cannot keep exactly (a NaN or infinite float, or
Someof a JSONnull) is not stored, and replacing an entry with one removes the old entry. A serialization error is returned and leaves the old entry in place. get::<T>(key)returnsNonewhile the cache is disabled, and for a missing or expired entry or one that does not read asT(which it removes).
CacheKeyBuilder builds keys from parts, escaping its separators so that two different lists of parts never build one key:
let key = CacheKeyBuilder::new()
.table("posts")
.condition("user_id", 42)
.order("created_at", "DESC")
.limit(20)
.offset(40)
.raw("v2")
.build();
build_hash() returns a 64-bit hash of the key instead, which can collide: keep the full key wherever the wrong entry would be a bug. cache.generate_key(table, hash) builds the key table:hash, after the key_prefix when one is set.
Statistics
let stats = QueryCache::global().stats();
println!("{} hits, {} misses, {:.0}% hit rate", stats.hits, stats.misses, stats.hit_ratio() * 100.0);
CacheStats holds hits, misses, entries, size_bytes, evictions and invalidations. reset_stats() restarts the counters but not the entry count or size. len(), is_empty() and contains(key) describe the cache, and evict_expired() drops expired entries now rather than as they are next touched.
Several Processes
The cache lives in one process. To keep several processes' caches in step, give the cache a hook: it is called with a CacheInvalidation after each invalidation, a write's (once as it runs and again when its transaction commits), invalidate_model's and clear's, but not a single key's invalidate or an expiry. Publish each event on a channel of your own, such as Redis or NATS, and hand what the other processes publish to apply_invalidation, which drops the same entries without calling the hook again.
The hook runs on the writing task, so hand the event off rather than wait on the network:
use tideorm::prelude::*;
let (events, mut outgoing) = tokio::sync::mpsc::unbounded_channel::<CacheInvalidation>();
QueryCache::global().set_invalidation_hook(move |event| {
let _ = events.send(event.clone());
});
tokio::spawn(async move {
while let Some(event) = outgoing.recv().await {
publish(serde_json::to_string(&event)?).await; // your broker
}
Ok::<_, serde_json::Error>(())
});
// In the task subscribed to the other processes:
let event: CacheInvalidation = serde_json::from_str(&message)?;
QueryCache::global().apply_invalidation(&event);
CacheInvalidation is Database(name), Table(name) or All, and serializes as {"Database": ".."}, {"Table": ".."} or "All". A database's name is built from the connection's socket, host, port and database, so connect every process the same way. clear_invalidation_hook() removes the hook.
Relations
Relations connect a model to the rows of other models. You declare each one as a struct field, then load it on demand from one model or eagerly for a whole query, which avoids one query per row (the N+1 problem).
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub email: String, #[tideorm(has_one = "Profile", foreign_key = "user_id")] pub profile: HasOne<Profile>, #[tideorm(has_many = "Post", foreign_key = "user_id")] pub posts: HasMany<Post>, } #[tideorm::model(table = "profiles")] pub struct Profile { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub bio: String, #[tideorm(belongs_to = "User", foreign_key = "user_id")] pub user: BelongsTo<User>, } #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub title: String, pub content: String, #[tideorm(belongs_to = "User", foreign_key = "user_id")] pub author: BelongsTo<User>, #[tideorm(has_many = "Comment", foreign_key = "post_id")] pub comments: HasMany<Comment>, } async fn show(id: i64) -> tideorm::Result<()> { let user = User::find_or_fail(id).await?; let posts: Vec<Post> = user.posts.load().await?; println!("{} wrote {} posts", user.name, posts.len()); Ok(()) } }
Relation fields are not columns. The derive wires each wrapper from the model's own key fields when a row loads, when a model deserializes, and when you build one with Default.
Relation Types
The field's wrapper type decides the kind of relation:
| Wrapper | Attribute | Relation | Required keys |
|---|---|---|---|
HasOne<T> | has_one | One-to-one (a user has one profile) | foreign_key |
HasMany<T> | has_many | One-to-many (a user has many posts) | foreign_key |
BelongsTo<T> | belongs_to | The inverse side (a post belongs to a user) | foreign_key |
HasManyThrough<T, P> | has_many_through | Many-to-many through the pivot model P | foreign_key, related_key |
MorphOne<T> | none | Polymorphic one-to-one | morph_name |
MorphMany<T> | none | Polymorphic one-to-many | morph_name |
MorphTo<T> | none | The inverse of a polymorphic relation | morph_name |
SelfRef<T> | none | The parent row in the same table | none |
SelfRefMany<T> | none | The child rows in the same table | none |
The has_one/has_many/belongs_to/has_many_through attribute may be left out; when present it must name the same kind as the wrapper. A mismatch or a missing required key is a compile-time error, and the message suggests the conventional key (foreign_key = "user_id"). Keys are never assumed, since a model with two relations to one model would silently join both on the same key.
Relation Attributes
| Attribute | Meaning | Default |
|---|---|---|
foreign_key | The column holding the key: on the related table for HasOne/HasMany/HasManyThrough's pivot, on this model for BelongsTo and SelfRef | Required, except SelfRef/SelfRefMany: parent_id |
local_key | The column on this model the foreign key matches | The primary key, whatever its column is called |
owner_key | The column on the owner a BelongsTo foreign key matches | id |
related_key | The pivot column holding the related model's key (HasManyThrough) | Required |
pivot | The pivot table (HasManyThrough) | The pivot model's table |
morph_name | The prefix of the <name>_type and <name>_id columns (polymorphic relations) | Required |
The derive emits a constant per relation, named after the field in upper case (User::POSTS == "posts"). Use it wherever a relation name is a string, such as with(User::POSTS).
Loading a Relation
Each wrapper queries the related rows when you ask:
#![allow(unused)] fn main() { let user = User::find_or_fail(1).await?; let profile: Option<Profile> = user.profile.load().await?; let posts: Vec<Post> = user.posts.load().await?; let post = Post::find_or_fail(1).await?; let author: Option<User> = post.author.load().await?; let has_profile: bool = user.profile.exists().await?; let has_posts: bool = user.posts.exists().await?; let post_count: u64 = user.posts.count().await?; }
load() returns rows in no particular order. To order, filter or page them, use load_with, whose closure gets the relation's query already filtered and adds to it:
#![allow(unused)] fn main() { let recent_posts = user.posts.load_with(|query| { query .where_eq("published", true) .where_gt("views", 100) .order_desc("created_at") .limit(10) }).await?; let profile = user.profile.load_with(|query| query.where_not_null("avatar")).await?; }
| Wrapper | load | load_with | exists | count |
|---|---|---|---|---|
HasOne, BelongsTo, MorphOne, SelfRef | Option<T> | Option<T> | yes | no |
HasMany, HasManyThrough, MorphMany, SelfRefMany | Vec<T> | Vec<T> | yes | u64 |
A few rules hold for every wrapper:
- An owner whose key is NULL (an unset nullable
local_key) has no related rows:load()returns none,count()zero, andattach,detachandsyncrefuse it, rather than matching every row whose foreign key is NULL. - A model may hold several relations to one model, such as an
authorand aneditorthat are bothBelongsTo<User>. Each loads by its own keys, eagerly too. - A relation matches one key column. For a composite-key model, set
local_keywhere needed, and write your own query when the relation must match several columns. - A model read through
User::query_with(&db)orUser::find_with(id, &db)keeps that database, and its relations query there.
load() and get_cached()
A wrapper also holds a cache: the rows an eager load, an entity manager load or deserialization put there.
load()queries whenever a connection is reachable, even with rows cached, so a deserialized payload cannot pass itself off as database state. It serves the cache only when there is nothing to query through. It does not store what it reads.get_cached()never queries. It returnsOption<&T>for a single-row wrapper andOption<&[T]>for a list.is_loaded()tells a relation that was loaded and has no rows from one that was never loaded.as_mut()edits the cached rows in place.load()does not see such edits; save the rows themselves to persist them.clear()drops the cached rows and marks the relation loaded and empty.
Under an entity manager the manager's cache wins instead; see Entity Manager.
Eager Loading
When you know which relations you need, call with() (or with_many()) on a query. TideORM loads each requested relation for all rows with set-based queries, not one per row:
#![allow(unused)] fn main() { let users = User::query() .where_eq("active", true) .with(User::PROFILE) .with(User::POSTS) .get() .await?; for user in &users { let profile = user.profile.get_cached(); let posts = user.posts.get_cached().unwrap_or_default(); println!("{} has {} posts", user.name, posts.len()); } }
Name a nested relation with a dot: with("posts.comments") loads every user's posts and every post's comments. Calls accumulate, and shared prefixes load once. A relation name is checked when the query runs; a typo is an "Unknown relation" error.
with() keeps the query's filters, ordering, pagination, cache settings and database handle. Filter the query before with(), or reach any query method after it through query(|q| ..). That closure shapes the root query only; constrain a relation with load_with instead:
#![allow(unused)] fn main() { let users = User::query() .with(User::POSTS) .query(|q| q.where_gt("age", 18).where_null("banned_at").order_desc("id")) .get() .await?; }
The eager builder runs with get(), first(), first_or_fail(), find(id), find_or_fail(id), paginate(page, per_page) and count(). Each returns the models themselves, each requested relation's rows in its wrapper. User::query_with(&db).with(..) reads the relations from db as well.
Eager loading works for HasOne, HasMany, BelongsTo, HasManyThrough, MorphOne and MorphMany. MorphTo, SelfRef and SelfRefMany have no eager path, and with() on one is an error that points you at the lazy load().
Keys match by value, as the database matches them: an i64 key finds the rows of an i32 foreign key or of a text *_id column holding it. Where the column's collation matches keys that differ in case or accents (SQLite NOCASE, MySQL's default collations), each row goes to the parent whose key it holds byte for byte.
Hidden Attributes in Eager-Loaded Payloads
to_json() writes a cached relation inline, and filters each payload by the target model's hidden list, at any depth. A User that declares hidden = "password_hash" keeps it out of post.to_json(None), though the call was made on Post:
#![allow(unused)] fn main() { #[tideorm::model(table = "users", hidden = "password_hash")] pub struct User { /* ... */ } let post = Post::query().with(Post::AUTHOR).first().await?.unwrap(); // {"id": 1, "title": "…", "author": {"id": 7, "email": "…"}}: no password_hash let body = post.to_json(None); }
The owning model's hidden list is not applied to a relation payload, so a column one model hides and another does not keeps its value in the payload that does not hide it. Two payloads fall back to the owning model's list, because their type is not known statically: attachment blobs and MorphTo relations.
Relations and Serde
TideORM's generated serde writes a relation's cached rows when they are loaded, and leaves the wrappers out of the stored columns. Deserializing a model rebuilds its wrappers from its own key fields and keeps the cached payload, so a JSON round trip keeps loaded relations. A wrapper deserialized on its own, outside a model, carries only its cache, not the keys it would query by. MorphTo keeps no cache: it serializes nothing and ignores a payload.
Many-to-Many
HasManyThrough<T, P> reaches T through rows of the pivot model P:
#![allow(unused)] fn main() { #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, #[tideorm(has_many_through = "Role", pivot = "user_roles", foreign_key = "user_id", related_key = "role_id")] pub roles: HasManyThrough<Role, UserRole>, } #[tideorm::model(table = "roles")] pub struct Role { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, } #[tideorm::model(table = "user_roles")] pub struct UserRole { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub role_id: i64, } async fn manage_roles(user: &User, role_id: i64) -> tideorm::Result<()> { let roles: Vec<Role> = user.roles.load().await?; user.roles.attach(role_id).await?; user.roles.attach_many([4_i64, 5]).await?; // all or none, in one transaction let removed: u64 = user.roles.detach(role_id).await?; let removed: u64 = user.roles.detach_many([4_i64, 5]).await?; let removed: u64 = user.roles.detach_all().await?; // Replace the whole set user.roles.sync([1_i64, 2, 3]).await?; Ok(()) } }
foreign_key names the pivot column holding this model's key and related_key the one holding the related key. Both may name the pivot model's fields or their renamed columns, and a pivot key need not share the owner's integer type. pivot names the pivot model's own table: the relation reads, deletes and loads pivot rows through that model, so a relation naming another table is refused. Leave it out and it is the pivot model's table.
Reading:
load(),count()and eager loading return each related row once, however many pivot rows link it.load_with()joins the pivot table, so its closure can order by or read a pivot column, and it returns a row per pivot row that links it.
Writing:
attach()writes only the two key columns. A pivot table with otherNOT NULLcolumns and no defaults needs a directUserRole::createinstead.attach()of a pair already linked succeeds without a second row, even when two calls race. When another unique key of the pivot keeps the pair out, such as one onrole_idalone,attach()andsync()return an error rather than report a link they did not make.sync()deletes every pivot row of the owner and inserts the wanted ids afresh, in one transaction (a savepoint inside yours), so extra columns on a pivot row are lost. Duplicate ids are collapsed and every id is checked before anything runs. An empty list detaches everything.- When the pivot model has soft deletes, a trashed pivot row no longer links its pair: reads leave it out,
attach()restores it, andsync()deletes it with the live rows.
| Backend | How attach() inserts a missing pair |
|---|---|
| PostgreSQL, SQLite | One INSERT .. SELECT .. WHERE NOT EXISTS .. ON CONFLICT DO NOTHING |
| MySQL, MariaDB | A read, then a plain INSERT (InnoDB's locks for an INSERT .. SELECT let two concurrent attaches deadlock); a duplicate counts as not written |
On every backend, a pair that was not written is read back, which catches a conflict on another unique key of the pivot.
Polymorphic Relations
A polymorphic relation links rows through a (type, id) column pair instead of a foreign key to one table. Here an image belongs to a post or a video:
#![allow(unused)] fn main() { #[tideorm::model(table = "images")] pub struct Image { #[tideorm(primary_key, auto_increment)] pub id: i64, pub path: String, pub imageable_type: String, // "posts" or "videos" pub imageable_id: i64, #[tideorm(morph_name = "imageable")] pub imageable: MorphTo<Post>, } #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub title: String, #[tideorm(morph_name = "imageable")] pub images: MorphMany<Image>, } }
morph_name = "imageable" names the imageable_type and imageable_id columns, which the child model must declare; the derive fails if either is missing. The type column holds the owner's table name ("posts"), not the struct name. It is the name without its schema, so two owners whose tables share a name in different schemas write the same type, and each would read the other's children: give owner tables distinct names. An owner that keys its children by another column names it with local_key, as #[tideorm(morph_name = "imageable", local_key = "uuid")].
MorphOne and MorphMany load like HasOne and HasMany, eagerly too (with("images")). MorphTo<T> loads the owner:
#![allow(unused)] fn main() { let image = Image::find_or_fail(1).await?; // The default target, T: an error when the row names another table let post: Option<Post> = image.imageable.load().await?; // Owners of several types if image.imageable.is_type::<Video>() { let video: Option<Video> = image.imageable.load_as::<Video>().await?; } let table: Option<&str> = image.imageable.type_value(); }
load_as::<U>() returns Ok(None) when the type column names another table, so you can try each type it may hold. It finds the owner by the local_key its MorphOne/MorphMany declares, else by its primary key. MorphTo always queries and has no eager path.
Self-Referencing Relations
SelfRef and SelfRefMany model a hierarchy inside one table, such as an org chart, categories or a comment thread:
#![allow(unused)] fn main() { #[tideorm::model(table = "employees")] pub struct Employee { #[tideorm(primary_key)] pub id: i64, pub name: String, pub manager_id: Option<i64>, #[tideorm(foreign_key = "manager_id")] pub manager: SelfRef<Employee>, #[tideorm(foreign_key = "manager_id")] pub reports: SelfRefMany<Employee>, } async fn org_chart(id: i64) -> tideorm::Result<()> { let employee = Employee::find_or_fail(id).await?; let manager: Option<Employee> = employee.manager.load().await?; let has_manager = employee.manager.exists().await?; let reports: Vec<Employee> = employee.reports.load().await?; let report_count = employee.reports.count().await?; // The whole subtree, three levels deep, in one recursive query let tree: Vec<Employee> = employee.reports.load_tree(3).await?; Ok(()) } }
foreign_key defaults to parent_id. local_key defaults to the primary key, whatever its column is called, and can be set explicitly.
load_tree(max_depth) fetches the subtree below the row with one recursive CTE query, which avoids one SELECT per node on a large hierarchy. It respects the configured local_key. Rows come back flat, ordered by depth (direct children first); rebuild the structure from their foreign keys. A node appears once even when the keys form a cycle, at the shallowest depth it was reached. Soft deletes apply at every level, so a trashed node also prunes its descendants. load_tree(0) returns nothing without querying, and load_tree(1) equals load(). It always needs a live connection.
Nested Save
The NestedSave methods save a parent and its children together, setting each child's foreign key to the parent's key:
#![allow(unused)] fn main() { // The profile's user_id is set to user.id let (user, profile) = user.save_with_one(profile, "user_id").await?; // Each post's user_id is set; a new post is inserted, a stored one updated let (user, posts) = user.save_with_many(posts, "user_id").await?; // Update parent and children, all already stored; no key is set let (user, profile) = user.update_with_one(profile).await?; let (user, posts) = user.update_with_many(posts).await?; // Delete the children first, then the parent; returns the total row count let deleted = user.delete_with_many(posts).await?; let deleted = user.delete_with_one(profile).await?; }
For several kinds of children at once, use NestedSaveBuilder:
#![allow(unused)] fn main() { let (user, saved) = NestedSaveBuilder::new(user) .with_one(profile, "user_id") .with_many(posts, "user_id") .with_many(comments, "author_id") .save() .await?; let profile: Option<&Profile> = saved[0].as_one(); let posts: Option<&[Post]> = saved[1].as_many(); }
save() returns one SavedRelation per with_one/with_many, in the order you added them, holding the children as stored. as_one/as_many borrow them (None for another shape or model type), into_one/into_many take them and fail instead, and is_one/is_many report the shape.
Each nested operation runs in one transaction (a savepoint inside yours), so a child that fails also rolls back the parent's write. Children are written one at a time through each model's own create, update or delete, so their callbacks and validation run as usual. The foreign key may be the Rust field name, the column name or a typed column (Post::USER_ID), and the children may come in any list, a Vec or an array. NestedSaveBuilder is Send, so you can hold it across await points or move it into a spawned task before calling save().
Join Result Consolidation
JoinResultConsolidator turns flat tuples, such as rows of a join read as (Order, LineItem), into nested ones:
#![allow(unused)] fn main() { use tideorm::prelude::JoinResultConsolidator; // [(order1, item1), (order1, item2), (order2, item3)] let flat: Vec<(Order, LineItem)> = orders_with_items; // [(order1, [item1, item2]), (order2, [item3])] let nested: Vec<(Order, Vec<LineItem>)> = JoinResultConsolidator::consolidate_two(flat, |o| o.id); // LEFT JOIN rows, Vec<(Order, Option<LineItem>)>: a parent with no child gets an empty list let nested = JoinResultConsolidator::consolidate_two_optional(flat_optional, |o| o.id); // Three levels: Vec<(Order, Vec<(LineItem, Vec<Product>)>)> let nested3 = JoinResultConsolidator::consolidate_three(flat3, |o| o.id, |i| i.id); // Three levels where only the innermost may be absent: Vec<(Order, LineItem, Option<Product>)> let nested3 = JoinResultConsolidator::consolidate_three_optional(flat3_optional, |o| o.id, |i| i.id); }
Linked Partial Select
select_with_linked left-joins another table and selects columns from both; select_also_linked selects every model column plus the linked ones. Read the rows into a struct of your own with get_as(), whose fields are the column names:
#![allow(unused)] fn main() { #[derive(serde::Deserialize)] struct UserBio { id: i64, name: String, bio: Option<String>, } // users.id = profiles.user_id let rows: Vec<UserBio> = User::query() .select_with_linked(vec!["id", "name"], "profiles", "id", "user_id", vec!["bio"]) .get_as() .await?; // Every user column, plus the profile's bio let rows: Vec<serde_json::Value> = User::query() .select_also_linked("profiles", "id", "user_id", vec!["bio"]) .get_json() .await?; }
The arguments are the model's columns, the linked table, the model's join column, the linked table's join column and the linked columns. A linked column that shares a name with a selected one must be aliased: two outputs cannot share a name.
Relations Under an Entity Manager
With the entity-manager feature, entity_manager.load(&mut relation) loads a HasOne, HasMany, BelongsTo or HasManyThrough relation inside the manager's identity map, and entity_manager.save(&model) writes the loaded relations back. Every relation of a model the manager loaded, polymorphic and self-referencing ones included, queries through the manager's database, even with no global database. See Entity Manager.
File Attachments
Requires the attachments feature.
File attachments keep references to files, such as a product's thumbnail or its gallery, in a JSON column of the model. TideORM stores each file's key, name, timestamp and metadata; the file bytes live wherever you store them (a bucket, a CDN, a disk).
[dependencies]
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio", "attachments"] }
Model Setup
Name the attachment slots on the model, and implement HasAttachments to say which column holds them:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model( table = "products", has_one_files = "thumbnail", has_many_files = "images,documents" )] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub files: Option<JsonValue>, // JSON or JSONB column holding the attachments } impl HasAttachments for Product { fn has_one_files() -> Vec<&'static str> { vec!["thumbnail"] } fn has_many_files() -> Vec<&'static str> { vec!["images", "documents"] } fn get_files_data(&self) -> Result<FilesData, AttachmentError> { Ok(self.files.as_ref().map(FilesData::from_json).unwrap_or_default()) } fn set_files_data(&mut self, data: FilesData) -> Result<(), AttachmentError> { self.files = Some(data.to_json()); Ok(()) } } }
Every option goes inside the one #[tideorm::model(..)] attribute; combining it with a separate #[tideorm(..)] on the struct is a compile error. The attribute records the slot names on the model, which to_json() uses. The derive does not generate HasAttachments, because only you know which column holds the payload. Once your impl exists, the methods below are available on Product with tideorm::prelude::* in scope.
Name the column field files: to_json() renders attachments from the field named files (by its serialized name, if your serde derive renames it).
| Slot kind | Holds | Typical use |
|---|---|---|
has_one_files | One file; attaching replaces it | Avatar, thumbnail, profile picture |
has_many_files | A list of files; attaching appends | Gallery images, documents, media |
Every method changes the model in memory only. Save the model afterwards (product.update().await?) or nothing is stored.
Attaching Files
#![allow(unused)] fn main() { // hasOne: replaces any existing file product.attach("thumbnail", "uploads/thumb.jpg")?; // hasMany: appends product.attach("images", "uploads/img1.jpg")?; product.attach("images", "uploads/img2.jpg")?; // Several at once (hasMany only) product.attach_many("images", ["uploads/img3.jpg", "uploads/img4.jpg"])?; // With metadata let attachment = FileAttachment::with_metadata( "uploads/document.pdf", Some("My Document.pdf"), // original filename Some(1024 * 1024), // size in bytes Some("application/pdf"), // MIME type ); product.attach_with_metadata("documents", attachment)?; // With custom metadata let attachment = FileAttachment::new("uploads/photo.jpg") .add_metadata("width", 1920) .add_metadata("height", 1080) .add_metadata("photographer", "John Doe"); product.attach_with_metadata("images", attachment)?; product.update().await?; }
Custom metadata sits beside the attachment's own fields in its JSON. An entry named like a field that is set (key, size, ..) is left out, since the field owns that name. One named like an unset optional field is kept, and reads back as metadata when it is not that field's type, so add_metadata("size", "12KB") round-trips.
A slot name that the model does not declare is an AttachmentError::InvalidRelation ("Unknown file relation"), and attach_many/detach_many on a hasOne slot is refused the same way.
Detaching Files
#![allow(unused)] fn main() { // hasOne: remove the thumbnail product.detach("thumbnail", None)?; // hasOne: remove the thumbnail only while it is this file product.detach("thumbnail", Some("uploads/old-thumb.jpg"))?; // hasMany: remove one file product.detach("images", Some("uploads/img1.jpg"))?; // hasMany: remove every file product.detach("images", None)?; // hasMany: remove several files product.detach_many("images", ["uploads/img2.jpg", "uploads/img3.jpg"])?; product.update().await?; }
Syncing Files
sync replaces a slot's contents:
#![allow(unused)] fn main() { product.sync("images", ["uploads/new1.jpg", "uploads/new2.jpg"])?; // An empty list clears the slot product.sync("images", Vec::<&str>::new())?; // With metadata let attachments = vec![ FileAttachment::with_metadata("img1.jpg", Some("Photo 1"), Some(1024), Some("image/jpeg")), FileAttachment::with_metadata("img2.jpg", Some("Photo 2"), Some(2048), Some("image/jpeg")), ]; product.sync_with_metadata("images", attachments)?; product.update().await?; }
On a hasOne slot, sync keeps the first file, or clears the slot when the list is empty.
Reading Files
#![allow(unused)] fn main() { // hasOne if let Some(thumb) = product.get_file("thumbnail")? { println!("Thumbnail: {} ({}), attached {}", thumb.key, thumb.filename, thumb.created_at); if let Some(size) = thumb.size { println!("Size: {size} bytes"); } } // hasMany for image in product.get_files("images")? { println!("Image: {} ({})", image.filename, image.key); } if product.has_files("images")? { let count = product.count_files("images")?; println!("Product has {count} images"); } }
A stored entry that does not read as an attachment makes get_file/get_files return AttachmentError::InvalidData. all_file_relations(), is_has_one_relation(name), is_has_many_relation(name) and validate_relation(name) answer questions about the slots themselves.
AttachmentError converts into tideorm::Error with ?: an unknown slot becomes a validation error, malformed data a conversion error.
FileAttachment
Each attachment holds:
| Field | Type | Description |
|---|---|---|
key | String | The storage key or path, such as uploads/2024/01/image.jpg |
filename | String | The last segment of the key (/ and \ both separate) |
created_at | String | When it was attached, as an RFC 3339 timestamp |
original_filename | Option<String> | The upload's own name, if different |
size | Option<u64> | Size in bytes |
mime_type | Option<String> | MIME type |
metadata | HashMap<String, serde_json::Value> | Custom fields |
Build one with FileAttachment::new(key) or FileAttachment::with_metadata(key, original_filename, size, mime_type), add fields with add_metadata(name, value), and render it with to_json().
FilesData is the whole column's content, which your HasAttachments impl converts with FilesData::from_json (anything other than a JSON object reads as empty) and to_json(). Its methods (set_one, get_one, try_get_one, remove_one, add_many, get_many, try_get_many, remove_from_many, remove_many, clear_many, has_files, count_files) are what the trait's methods are built on; the try_ forms report malformed data instead of treating it as absent.
Storage Format
The column holds one JSON object, a member per slot:
{
"thumbnail": {
"key": "uploads/thumb.jpg",
"filename": "thumb.jpg",
"created_at": "2024-01-15T10:30:00+00:00"
},
"images": [
{
"key": "uploads/img1.jpg",
"filename": "img1.jpg",
"created_at": "2024-01-15T10:30:00+00:00",
"size": 1048576,
"mime_type": "image/jpeg"
},
{
"key": "uploads/img2.jpg",
"filename": "img2.jpg",
"created_at": "2024-01-15T10:31:00+00:00"
}
]
}
Keys Are Untrusted Input
TideORM stores a key as opaque text and never opens, reads or writes the file it names. attach("avatar", "../../etc/passwd") is stored verbatim, and the default URL generator joins it onto the base URL verbatim. Validating keys is your job: screen a key that arrives from a client with FileAttachment::is_safe_key before attaching it, or generate keys on the server and never accept them from the client.
#![allow(unused)] fn main() { if !FileAttachment::is_safe_key(&upload_key) { return Err(tideorm::Error::validation("avatar", "invalid file key")); } user.attach("avatar", &upload_key)?; }
is_safe_key rejects a key that is empty or whitespace, contains a NUL byte, is absolute (/x or \x), contains // (URLs with a scheme or protocol-relative ones), contains : (Windows drive prefixes, alternate data streams, URL schemes) or has a .. segment. Both / and \ count as separators. A key that passes is only shaped like a safe key: your storage backend still confines it to its prefix and authorizes the access. attach() does not call it for you, because existing applications store keys it rejects.
File URLs
to_json() removes the files column from the output and writes each slot as a top-level member, each file with a url member added:
{
"id": 1,
"name": "Headphones",
"thumbnail": {
"key": "products/123/thumb.jpg",
"filename": "thumb.jpg",
"created_at": "2024-01-15T10:30:00+00:00",
"url": "https://cdn.example.com/uploads/products/123/thumb.jpg"
}
}
A slot named in the model's or the global hidden attributes stays out of the output, and the model's hidden attribute names are removed inside each file too.
Base URLs
Prefix every key with a base URL, or give one slot a base of its own:
#![allow(unused)] fn main() { TideConfig::init() .database("postgres://localhost/mydb") .file_base_url("https://cdn.example.com/uploads") .file_base_url_for("avatar", "https://avatars.example.com") .connect() .await?; }
The default generator joins the base and the key with one /, tolerating a slash on either side, and returns the bare key when no base applies.
Custom URL Generator
For signed URLs, image transformations or routing by type, install a generator. It receives the slot name and the whole FileAttachment, and may capture what it needs:
#![allow(unused)] fn main() { use tideorm::attachments::FileAttachment; fn smart_url_generator(field_name: &str, file: &FileAttachment) -> String { match field_name { "thumbnail" => { let quality = if file.size.unwrap_or(0) > 500_000 { "60" } else { "auto" }; return format!("https://thumbs.example.com/q_{}/{}", quality, file.key); } "avatar" => return format!("https://avatars.example.com/w_200,h_200/{}", file.key), _ => {} } match file.mime_type.as_deref() { Some(m) if m.starts_with("video/") => format!("https://stream.example.com/{}", file.key), Some(m) if m.starts_with("image/") => { let quality = if file.size.unwrap_or(0) > 1_000_000 { "80" } else { "auto" }; format!("https://images.example.com/q_{}/{}", quality, file.key) } _ => format!("https://cdn.example.com/{}", file.key), } } TideConfig::init() .database("postgres://localhost/mydb") .file_url_generator(smart_url_generator) .connect() .await?; }
The generator replaces the base-URL settings unless it reads them itself (Config::get_file_base_url_for(field), or by calling Config::default_file_url_generator). Like the other settings it is installed by connect() or apply(), and one of them without a generator puts the default back.
There is no per-model generator: every model renders its attachments with the one generator. Route per model inside it, by slot name or by something you stored in metadata at attach time.
The order in which a URL is decided:
- The custom generator, if
file_url_generator()installed one. - The slot's base URL (
file_base_url_for), else the global one (file_base_url). - The key unchanged.
Building URLs Yourself
#![allow(unused)] fn main() { use tideorm::attachments::FileAttachment; // Through the installed generator let url = FileAttachment::new("uploads/image.jpg").url("thumbnail"); if let Some(thumb) = product.get_file("thumbnail")? { let url = thumb.url("thumbnail"); // A one-off generator for this call only let url = thumb.url_with_generator("thumbnail", |field_name, file| { format!("https://custom-cdn.com/{}/{}", field_name, file.key) }); } }
Config::get_file_url_generator() returns the installed generator (or the default) as a FileUrlGenerator, an Arc<dyn Fn(&str, &FileAttachment) -> String + Send + Sync>.
With Translations
A model can use attachments and translations together, each with its own impl:
#![allow(unused)] fn main() { #[tideorm::model( table = "products", translatable = "name,description", has_one_files = "thumbnail", has_many_files = "images" )] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub description: String, pub price: f64, pub translations: Option<JsonValue>, pub files: Option<JsonValue>, } product.set_translation("name", "ar", "اسم المنتج")?; product.attach("thumbnail", "uploads/thumb.jpg")?; product.attach_many("images", ["img1.jpg", "img2.jpg"])?; product.update().await?; }
Translations
Requires the translations feature.
Translations keep per-language values of a model's fields in a JSON column. The struct's own field holds the default value, and the translations override it per language.
[dependencies]
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio", "translations"] }
Model Setup
List the translatable fields on the model, and implement HasTranslations to say which column holds the translations:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "products", translatable = "name,description")] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, // Default values pub name: String, pub description: String, pub price: f64, // JSON or JSONB column holding the translations pub translations: Option<JsonValue>, } impl HasTranslations for Product { fn translatable_fields() -> Vec<&'static str> { vec!["name", "description"] } fn allowed_languages() -> Vec<String> { vec!["en".to_string(), "ar".to_string(), "fr".to_string(), "de".to_string()] } fn fallback_language() -> String { "en".to_string() } fn get_translations_data(&self) -> Result<TranslationsData, TranslationError> { match &self.translations { Some(json) => Ok(TranslationsData::from_json(json)), None => Ok(TranslationsData::new()), } } fn set_translations_data(&mut self, data: TranslationsData) -> Result<(), TranslationError> { self.translations = Some(data.to_json()); Ok(()) } fn get_default_value(&self, field: &str) -> Result<serde_json::Value, TranslationError> { match field { "name" => Ok(serde_json::json!(self.name)), "description" => Ok(serde_json::json!(self.description)), _ => Err(TranslationError::InvalidField(format!("Unknown field: {field}"))), } } } }
The translatable attribute records the fields on the model, which to_json() uses. The derive does not generate HasTranslations, because only you know which column holds the payload. Once your impl exists, the methods below are available on Product with tideorm::prelude::* in scope. get_translated() falls back to what your get_default_value() returns.
Name the column field translations: Model::to_json() reads the translations from the field named translations.
Languages
HasTranslations declares its own allowed_languages() and fallback_language(), so a plain struct can implement it with a fixed policy. A model also has languages of its own, which Model::to_json() uses:
- the model attributes
languages = "en,ar,fr"andfallback_language = "en", or else - the configured
TideConfig::languages(["en", "ar"])andTideConfig::fallback_language("en"), whose defaults are["en"]and"en".
To keep one policy, return the model's from your impl, as <Self as ModelMeta>::allowed_languages() and <Self as ModelMeta>::fallback_language(); the fully qualified form is needed because both traits name these methods.
Setting Translations
#![allow(unused)] fn main() { product.set_translation("name", "ar", "اسم المنتج")?; product.set_translation("name", "fr", "Nom du produit")?; product.set_translation("description", "ar", "وصف المنتج")?; // Several languages of one field: a HashMap or any (language, value) pairs product.set_translations("name", [ ("en", "Product Name"), ("ar", "اسم المنتج"), ("fr", "Nom du produit"), ])?; // Replace every translation of a field product.sync_translations("name", [("en", "New Product Name"), ("de", "Neuer Produktname")])?; product.update().await?; }
Every method changes the model in memory only; save the model afterwards. A field that is not translatable is a TranslationError::InvalidField, and a language that is not allowed a TranslationError::InvalidLanguage; set_translations and sync_translations set nothing when either is rejected.
From a Request
TranslationInput reads a request or form payload shaped {"field": {"lang": "value"}}, and apply_translations stores it:
#![allow(unused)] fn main() { let input = TranslationInput::from_json(&body["translations"])?; product.apply_translations(input)?; product.update().await?; }
from_json only reshapes the payload (anything other than a JSON object is a TranslationError::ParseError). apply_translations checks every field against translatable_fields() and every language against allowed_languages(), as set_translation does, and writes nothing unless the whole batch passes, since such keys usually come from a client. Build one by hand with TranslationInput::new() and add(field, lang, value).
Reading Translations
#![allow(unused)] fn main() { // One stored translation, or None if let Some(name) = product.get_translation("name", "ar")? { println!("Arabic name: {name}"); } // With the fallback chain: requested language, fallback language, default value let name = product.get_translated("name", "ar")?; // Every language of one field for (lang, value) in product.get_all_translations("name")? { println!("{lang}: {value}"); } // Every field in one language: {"name": "اسم المنتج", "description": "وصف المنتج"} let arabic = product.get_translations_for_language("ar")?; }
Values are serde_json::Values.
Checking Translations
#![allow(unused)] fn main() { if product.has_translation("name", "ar")? { println!("Arabic name available"); } if product.has_any_translation("name")? { println!("Name has translations"); } let languages = product.available_languages("name")?; println!("Name available in: {languages:?}"); }
validate_field(field) and validate_language(lang) run the same checks the setters do.
Removing Translations
#![allow(unused)] fn main() { product.remove_translation("name", "fr")?; // one language of one field product.remove_field_translations("name")?; // every language of one field product.clear_translations()?; // everything product.update().await?; }
JSON Output
#![allow(unused)] fn main() { // Translatable fields in Arabic; the raw translations column is removed let json = product.to_translated_json_in("ar"); // {"id": 1, "name": "اسم المنتج", "description": "وصف المنتج", "price": 99.99} // In the fallback language, or the one an options map names under "language" let json = product.to_translated_json(None); // Model::to_json with its translatable fields in one language, with hidden // attributes and attachment URLs applied as for any to_json let json = product.to_json_in("ar"); // The whole model, raw translations included (for admin interfaces) let json = product.to_json_with_all_translations(); }
A field with no translation in the requested language takes the fallback language's, and then keeps the model's own value. A stored translation counts even when it is an empty string or null, so remove one rather than blanking it to fall back. Language codes match exactly: en-US and en-us are two languages, and only the spelling in the allowed list can be written. The plain forms log a failure and return {}; try_to_translated_json, try_to_translated_json_in, try_to_json_with_all_translations and Model::try_to_json_in return it instead.
Model::to_json() itself renders translatable fields in the language its options name ("language"), else in the model's fallback language, and removes the raw translations column. A malformed field in the stored payload is skipped rather than failing the whole model, and a field that is both hidden and translatable stays hidden.
If your model's serde derive renames fields (rename_all = "camelCase"), tell HasTranslations where each field lands, so the translation replaces it there:
#![allow(unused)] fn main() { fn serialized_key(field: &'static str) -> &'static str { <Self as ModelMeta>::serialized_name(field) } }
There is no load_all_translations() that writes every translation onto the struct's fields; it was removed because it was lossy. Use get_all_translations() per field, get_translations_for_language() per language, or to_json_with_all_translations() for the full payload.
Errors
TranslationError has three variants, InvalidField, InvalidLanguage and ParseError, and is #[non_exhaustive], so match it with a wildcard arm. It converts into tideorm::Error with ?: a rejected field or language becomes a validation error naming field or language, and a parse failure a conversion error.
Storage Format
The column holds one JSON object, a member per field, each holding a member per language:
{
"name": {
"en": "Wireless Headphones",
"ar": "سماعات لاسلكية",
"fr": "Écouteurs sans fil"
},
"description": {
"en": "High-quality wireless headphones",
"ar": "سماعات لاسلكية عالية الجودة",
"fr": "Écouteurs sans fil de haute qualité"
}
}
TranslationsData::from_json skips a member that is not such an object, so one malformed field cannot hide, or once saved back erase, the others. TranslationsData and FieldTranslations also offer direct access (get, set, remove, remove_field, has_translations, fields; all, has, languages).
To use translations together with file attachments, see File Attachments.
Entity Manager
Requires the entity-manager feature.
An EntityManager is an explicit persistence context: one database handle, an identity map that hands out one instance per loaded row, and a set of managed entities whose changes it writes back together. Use it when you load an aggregate (a user and its posts), change the graph, and want to write it back as a unit, or when you want to stage inserts, updates and deletes and write them all in one transaction.
[dependencies]
tideorm = { version = "0.18.2", default-features = false, features = ["postgres", "runtime-tokio", "entity-manager"] }
Use the backend feature you need (postgres, mysql or sqlite) alongside entity-manager.
Create one manager per request or unit of work. Its identity map keeps every model it has loaded until the manager is dropped or clear()ed, and find answers from that map without asking the database again, so a manager shared for the life of a process grows without bound and keeps serving rows other connections have since changed. Managers are independent of each other: each has its own identity map.
The manager is explicit: it does not replace TideORM's global database APIs. Everything it does goes through its own database handle, so it works without any global connection.
Aggregate Workflow
Load a root with find, load its relations with load, change the graph, and write it back with save:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, #[tideorm(has_many = "Post", foreign_key = "user_id")] pub posts: HasMany<Post>, } #[tideorm::model(table = "posts")] pub struct Post { #[tideorm(primary_key, auto_increment)] pub id: i64, pub user_id: i64, pub title: String, } async fn add_draft(db: Database) -> tideorm::Result<()> { let entity_manager = EntityManager::new(db); let mut user = entity_manager .find::<User>(1) .await? .expect("user should exist"); entity_manager.load(&mut user.posts).await?; user.posts .as_mut() .expect("posts should be loaded") .push(Post { id: 0, user_id: 0, title: "Draft".to_string(), }); let user = entity_manager.save(&user).await?; assert!(user.posts.get_cached().is_some()); Ok(()) } }
EntityManager::new takes a Database or an Arc<Database> and returns an Arc<EntityManager>. database() returns the handle it reads and writes through.
find::<T>(pk) serves the row from the identity map when the manager already holds it, and otherwise reads it through the manager's database (Model::find_with). load(&mut relation) loads a HasOne, HasMany, BelongsTo or HasManyThrough relation inside the context: its rows come from the identity map when it holds them, so two relations reaching one row share its instance, and the manager records what the relation held, which a later save() compares against.
save(&entity) writes the root and its loaded relations in one transaction and returns the saved aggregate.
What a Save Writes
- The root is written through the manager's database handle.
- Loaded
HasOne<T>,HasMany<T>andHasManyThrough<T, P>relations are synchronized with the saved aggregate: new related models are inserted, changed ones updated,HasOne/HasManychildren removed from the relation are deleted by the child model's own primary key, andHasManyThroughpivot rows are attached or detached as needed. - Both
foreign_keyandlocal_keyare honoured, so relations keyed by a column other thanidwork. - Nested loaded child graphs continue through the same context.
- Relations that were not loaded are left untouched.
BelongsTo<T>takes part in manager-aware loads and identity reuse, but a save does not cascade updates through it.
Managed Lifecycle Workflow
find_managed, persist and merge hand out Managed<T> handles. flush() writes every pending insert, update and delete in one transaction:
#![allow(unused)] fn main() { async fn managed_example(db: Database) -> tideorm::Result<()> { let entity_manager = EntityManager::new(db); let user = entity_manager .find_managed::<User>(1) .await? .expect("user should exist"); user.edit(|user| user.name = "Updated".to_string()); entity_manager.flush().await?; let inserted = entity_manager.persist(User { id: 0, name: "New User".to_string(), posts: Default::default(), }); entity_manager.flush().await?; assert!(inserted.get().id > 0); entity_manager.remove(&user); entity_manager.flush().await?; Ok(()) } }
| Method | What it does |
|---|---|
find_managed::<T>(pk) | Loads the row as a managed, clean entity; one the context already manages comes back as the same handle |
persist(entity) | Schedules an insert. An entity with a client-assigned key that the context already manages is replaced in place, and its handle returned |
merge(entity) | Attaches a detached instance: a managed one takes on its values, otherwise a new entry is created, clean against what the identity map holds. An entity with no primary key yet is persisted instead |
remove(&managed) | Schedules a delete; an entity never inserted is simply dropped |
detach(&managed) | Stops managing it: later flushes ignore it, while the handle keeps its value |
clear() | Detaches every managed entity and empties the identity map |
flush() | Writes inserts, then updates, then deletes, in one transaction |
Persisting or merging an entity the context was about to remove takes the removal back and writes it; merging one a persist() has not flushed keeps it an insert.
A Managed<T> handle exposes:
get(): a copy of the entity as it is now.read(|entity| ..): runs a closure on the entity without copying it.edit(|entity| ..): changes the entity in place; the next flush writes what changed.replace(entity): puts a new value in place of the tracked one.state():EntityState::New,Managed,RemovedorDetached.
Clones of a handle share one entity. The entity is locked while read or edit runs, so calling edit from inside read, or reading from inside edit, through this or another handle, waits forever.
register(entity) files a copy of a model you loaded elsewhere in the identity map, without the relations it loaded, and returns the instance for its row: the model itself, unless the context already tracks that row, in which case the tracked instance wins. A model with no primary key yet is handed straight back.
Flush Order
A flush orders writes by table so a parent row exists before the child that references it: referenced rows insert first and delete last. Within one table, rows that reference each other through a declared self-reference are ordered the same way.
Saves and Managed Entities
When the context saves a row it also holds as a managed entity, through save() or a relation sync, the managed entity moves onto what was stored: the fields it has not changed take the stored values, the ones it changed keep its edits, so a later flush does not write the values it loaded back over the newer save. A relation copy of the row, loaded before, is not moved; reload it.
A managed entity keeps the primary key it was loaded or saved with: a flush refuses one whose key was changed, rather than write it over the row holding the new key. Detach it and persist a new entity instead.
Concurrency and Failure
A manager runs one flush() or save() at a time: a second one waits for the first, so an entity waiting to be inserted is inserted once. A flush or save called inside another, such as from a callback, joins it instead. Another manager runs its own.
An edit made to a managed entity's columns while a flush writes it stays over the row as stored, and the entity stays dirty for the next flush. An edit to its relations cannot be merged with the rows the flush wrote for them: the flush fails and rolls back instead, which keeps the edit, and the next flush writes it.
A flush that fails, is cancelled part way, or runs inside a transaction that later rolls back leaves the context as it was before the flush, since none of what it wrote was committed. The one outcome no client can know is a flush cancelled while its COMMIT is on the wire: the database may have committed it. The context is restored then too, so reload what the flush wrote before flushing it again.
Relations of a Model the Manager Loaded
When a model was loaded through find or find_managed, every relation it holds, the polymorphic and self-referencing ones included, queries through the manager's database: load(), load_with(..), count() and exists() work even with no global database configured.
Use entity_manager.load(&mut relation) when the relation should also be tracked, so that save() synchronizes it. See Relations for the relation types themselves.
Primary Keys
Identity tracking works with the same primary-key shapes as the generated model APIs:
- Auto-increment numeric keys:
entity_manager.find::<User>(1). - Natural keys:
entity_manager.find::<ApiKey>("api-key-1".to_string()). - Composite keys:
entity_manager.find::<Membership>((team_id, member_id)).
HasOne and HasMany synchronization updates and deletes children by the related model's own primary key, so natural-key and composite-key children work as numeric-key children do.
Generic Code
Generic code names one bound for the models a manager handles, ManagedModel, which every model derives with this feature on:
#![allow(unused)] fn main() { use std::sync::Arc; fn track<M: ManagedModel>(entity_manager: &Arc<EntityManager>, model: M) -> Managed<M> { entity_manager.persist(model) } }
Reuse one manager for aggregate loads, managed edits and flushes when you want one consistent persistence context.
Transactions
A transaction runs several statements so that they all take effect or none do. TideORM's transactions are ambient: every TideORM call made inside one joins it, so you pass no handle around.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn sign_up(db: &Database, user: User, profile: Profile) -> tideorm::Result<User> { db.transaction(async move |_tx| { let user = User::create(user).await?; Profile::create(Profile { user_id: user.id, ..profile }).await?; // Ok commits, Err rolls back Ok(user) }) .await } }
When the closure returns Ok, the transaction commits. When it returns Err or panics, the transaction rolls back. It has always ended, one way or the other, when transaction returns.
Opening a Transaction
| Method | Takes | Use it for |
|---|---|---|
transaction | An async closure handed the transaction | The usual case |
transaction_with | TransactionOptions, then an async closure | An isolation level, an access mode or a SQLite BEGIN mode |
atomically | A plain future | Work that needs no handle; the future may borrow local variables |
atomically is the same transaction for a future instead of a closure. Every TideORM call inside it joins the transaction anyway:
#![allow(unused)] fn main() { let order = require_db()?.atomically(async { let order = Order::create(order).await?; Item::update_all().decrement("stock", 1).where_eq("id", item_id).execute().await?; Ok(order) }).await?; }
Use require_db()? for the global database. Database::current()? is the database the surrounding code runs on: the enclosing transaction's, else a scope's, else the global one. Database::current()?.transaction(..) therefore opens a savepoint inside an enclosing transaction. Inside a transaction, Database::current() returns the transaction's handle: drop it before the transaction ends, or the commit fails (see Leaked Handles).
Scopes
scope runs a future with a database as the ambient connection without opening a transaction, so model calls that name no handle (create, save, update, delete, find, insert_all, Model::query(), Database::raw and the rest) use a replica or a tenant's database instead of the global one:
#![allow(unused)] fn main() { let user = tenant_db.scope(async { let user = User::create(user).await?; Profile::create(Profile { user_id: user.id, ..Default::default() }).await?; Ok(user) }).await?; }
Inside a transaction opened on the same database's pool, the calls in a scope join that transaction.
Choosing the Database a Call Uses
| You want | Use |
|---|---|
| The application's database | Nothing: User::find(id), User::query(), user.save() |
| One read from another database, such as a replica | User::query_with(&replica), User::find_with(id, &replica); eager loads of that query read there too |
| Every call in a piece of code on another database, such as a tenant's | tenant_db.scope(async { .. }) |
| Several writes that succeed or fail together | db.transaction(..) or db.atomically(..) |
A call that names no database uses the innermost scope around it (a transaction is one), else the global database. A call that names one (query_with, find_with) joins the innermost enclosing transaction opened on that database's pool, and otherwise runs on that database's own connection, even inside another database's transaction: a replica read inside a primary's transaction goes to the replica, outside the transaction. Model writes (create, save, update, delete) name no database, so run them inside a scope or a transaction of the database they belong to.
That lets one service function serve every database, the caller choosing where it runs:
#![allow(unused)] fn main() { async fn rename(id: i64, name: String) -> tideorm::Result<User> { let mut user = User::find_or_fail(id).await?; user.name = name; user.update().await } let user = tenant_db.scope(rename(7, "Ada".into())).await?; // the tenant's database let user = primary.atomically(rename(7, "Ada".into())).await?; // in a transaction let total = Order::query_with(&replica).count().await?; // a replica read }
Nested Transactions
A transaction opened inside another one is a savepoint of it. When the inner closure returns Err, only the inner work rolls back; the outer transaction can catch the error and go on, or return it and roll back everything:
#![allow(unused)] fn main() { db.transaction(async move |_tx| { let order = Order::create(order).await?; // Optional work: if it fails, the order is still placed let gift = require_db()?.transaction(async move |_tx| { let card = GiftCard::create(card).await?; Ledger::record(&card).await?; Ok(card) }).await; if let Err(error) = gift { eprintln!("gift card skipped: {error}"); } Ok(order) }).await?; }
An inner commit only ends the savepoint: its rows are written for good when the outermost transaction commits, and are rolled back with it. Code that opens its own transaction can therefore be called both on its own and inside a caller's transaction.
A transaction ends only its own level. Rolling one back first rolls back the levels nested in it; committing one while a level nested in it is still open is refused and rolls both back; and a nested transaction whose enclosing one has already ended refuses its statements. A rolled-back savepoint is also released, so retries in a loop do not stack savepoints.
Two nested transactions run side by side with join! take turns, one savepoint at a time.
Transactions and Concurrent Tasks
A transaction, like a scope, follows the future it was given: it is installed each time that future is polled. So:
- calls awaited in the closure join it;
- futures run together inside it with
join!,try_join!orselect!join it too, since they are polled as part of its future. They share its one connection, so their statements run one after another; - a task started with
tokio::spawn(orasync_std::task::spawn) does not. It is polled on its own, so its calls run on the global database, outside the transaction: they commit on their own and stay if the transaction rolls back, they cannot see its uncommitted rows, and they can wait on locks it holds.
#![allow(unused)] fn main() { let user = db.transaction(async move |_tx| { let (user, settings) = tokio::try_join!( User::create(user), // both in the transaction Settings::create(settings), )?; Ok(user) }).await?; // Work that must not be part of the transaction starts after it, on purpose, // and names its database when it is not the global one let db = tenant_db.clone(); tokio::spawn(async move { db.scope(send_welcome(&user)).await }); }
Isolation Level and Access Mode
transaction_with begins the transaction with TransactionOptions:
#![allow(unused)] fn main() { let report = db.transaction_with( TransactionOptions { isolation_level: Some(IsolationLevel::Serializable), access_mode: Some(AccessMode::ReadOnly), ..TransactionOptions::default() }, async move |_tx| Report::build().await, ).await?; }
| Field | Values | Backends |
|---|---|---|
isolation_level | IsolationLevel::ReadUncommitted, ReadCommitted, RepeatableRead, Serializable | PostgreSQL, MySQL, MariaDB |
access_mode | AccessMode::ReadOnly, ReadWrite | PostgreSQL, MySQL, MariaDB; SQLite refuses ReadOnly with an error as the transaction begins, since it cannot keep a transaction from writing |
sqlite_transaction_mode | SqliteTransactionMode::Deferred (SQLite's default), Immediate, Exclusive | SQLite |
A read-only transaction refuses writes. On SQLite, Immediate takes the write lock as the transaction begins, so two competing writers queue at BEGIN (up to the busy timeout) instead of the second failing at its first write; Exclusive also keeps other connections from reading, outside WAL mode.
Options set a transaction up as it begins, so a transaction_with inside another transaction, which opens a savepoint, returns an error when given any.
Concurrent Updates
A transaction does not stop two requests from reading the same row at the same time. update() writes every column of the model it was given, so in a read-check-write the last writer wins and silently undoes the other: two orders of 3 against a stock of 4 both pass the check, and both ship.
Lock the rows you are about to change with lock_for_update() (SELECT .. FOR UPDATE). A second transaction that locks the same row waits until the first commits, then reads what it wrote:
#![allow(unused)] fn main() { let shipped = Database::current()?.atomically(async { let mut item = Item::query() .where_eq("id", id) .lock_for_update() .first_or_fail() .await?; if item.stock < quantity { return Ok(false); } item.stock -= quantity; item.update().await?; Ok(true) }).await?; }
Outside a transaction the lock ends with the statement. count(), exists() and the aggregates lock the rows they read too, and a locked query never reads from the query cache. PostgreSQL rejects the lock on a query with DISTINCT, GROUP BY or a UNION.
For a plain counter, a single conditional statement needs no lock: Item::update_all().decrement("stock", quantity).where_eq("id", id).where_gte("stock", quantity).execute() returns 0 when the stock ran out.
SQLite has no row locks, so lock_for_update() adds nothing there: the first write of a transaction locks the whole database, and the second of two competing transactions fails with a retryable LockNotAvailable error instead.
Failed Statements and Automatic Rollback
What happens after a statement fails inside a transaction depends on the failure:
- PostgreSQL aborts the whole transaction on any failed statement: the server refuses the statements after it, and would answer the
COMMITwith a silent rollback. TideORM refuses that commit with anError::Transactioninstead. To catch a failure and carry on, run the statement in a nested transaction: only its savepoint rolls back. - MySQL, MariaDB and SQLite keep a transaction going after an ordinary failed statement, such as a constraint violation, so the closure can catch the error and continue.
- SQLite rolls a transaction back by itself after some failed statements (a constraint's
ON CONFLICT ROLLBACK, a trigger'sRAISE(ROLLBACK)), and every database rolls back the whole transaction a deadlock hits, savepoints included.
In the last case TideORM refuses the transaction's later statements, nested transactions and its commit at every savepoint depth, even when the closure caught the error, so nothing runs outside it; rolling back stays safe. Retry the whole transaction: its earlier writes were rolled back too.
A connection goes back to the pool with no transaction open: one left open is rolled back, and a connection that cannot be brought back to that state is closed.
Retrying
Error::is_retryable() says whether running the work again can plausibly succeed. It reads the failure's classification, Error::failure_kind(), whatever the backend's message said:
DbFailureKind | Typically |
|---|---|
Deadlock | SQLSTATE 40P01, MySQL 1213 |
SerializationFailure | SQLSTATE 40001, under SERIALIZABLE, and on CockroachDB, which runs every transaction SERIALIZABLE; TiDB's write conflict (9007) |
LockNotAvailable | SQLSTATE 55P03, a MySQL lock wait timeout, SQLite's busy or locked database |
StatementTimeout | SQLSTATE 57014 |
ConnectionTimeout, ConnectionClosed, ConnectionRefused | No connection, or a lost one |
Retry the whole transaction, never the one statement that failed. transaction_retrying runs the closure again in a new transaction after a deadlock, a serialization failure or a lock it could not take, up to the given number of runs in all, with a short random wait between them:
#![allow(unused)] fn main() { async fn transfer_with_retry(db: &Database, from: i64, to: i64, amount: i64) -> tideorm::Result<()> { db.transaction_retrying(TransactionOptions::default(), 4, async |_tx| { transfer(from, to, amount).await }) .await } }
The closure can run more than once, so send emails and other effects outside the database after it returns. Inside another transaction on the same pool it runs once, as a savepoint that ignores options (the enclosing transaction began with its own): a deadlock or a serialization failure aborts the enclosing transaction, so retry that one. It never retries a lost connection: one lost while the COMMIT is on the wire leaves the outcome unknown, and the database may have committed. Make retried work safe to repeat, or check for its effect first. Errors has the details. See Compatible Servers for the transaction behaviour of CockroachDB, TiDB and Vitess.
Leaked Handles
Do not move the transaction handle, or a Database taken from Database::current() inside it, into a spawned task or anywhere it outlives the closure. A clone still alive when the closure returns fails the commit with "transaction handle leaked outside the transaction scope". TideORM then rolls the transaction (or the savepoint) back through the shared handle, which ends its locks at once and refuses the stray handle's statements afterwards. The error says whether that rollback succeeded, and carries the closure's own error when it had already failed.
Pinned Sessions
A pool hands each statement whichever connection is free, so what one statement sets for its session (SET, PRAGMA, MySQL's GET_LOCK) may not hold for the next, and stays on that connection for whatever statement takes it later. pin_session() returns a handle on one connection of its own:
#![allow(unused)] fn main() { let session = db.pin_session().await?; session.exec_raw("SET statement_timeout = '5s'").await?; // Every statement through `session` runs on that connection, with that setting let rows = User::query_with(&session).get().await?; session.transaction(async move |_tx| { /* runs there too */ Ok(()) }).await?; session.close().await?; }
- The connection is opened with the pool's settings but outside the pool, so it takes none of the pool's connections.
- Transactions begun on the session run on its connection. A second one begun there waits until the first ends; nest through the transaction instead.
- It closes with
close()or when the last clone of the handle drops, and is never replaced: once it is lost, the handle's statements fail. pin_session()on a session opens another one.- It fails on a transaction's handle, which belongs to its scope, and on a private SQLite database (in memory without a shared cache, or a temporary one), where a new connection would open an empty database.
Migrations
Migrations change a database's schema in versioned, reversible steps. Use them for every deployed environment; schema sync is for local development only.
#![allow(unused)] fn main() { use tideorm::prelude::*; use tideorm::migration::*; struct CreateUsersTable; #[async_trait] impl Migration for CreateUsersTable { fn version(&self) -> &str { "20260115_001" } fn name(&self) -> &str { "create_users_table" } async fn up(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.create_table("users", |t| { t.id(); // id BIGSERIAL PRIMARY KEY t.string("email").unique().not_null(); // email VARCHAR(255) UNIQUE NOT NULL t.string("name").not_null(); // name VARCHAR(255) NOT NULL t.text("bio").nullable(); // bio TEXT NULL t.boolean("active").default(true); // active BOOLEAN DEFAULT TRUE t.date("birth_date").nullable(); // birth_date DATE NULL t.decimal_with("balance", 12, 2) // balance DECIMAL(12, 2) DEFAULT '0.00' .default("0.00"); t.jsonb("preferences").nullable(); // preferences JSONB NULL t.timestamptz("email_verified_at") // email_verified_at TIMESTAMPTZ NULL .nullable(); t.timestamps(); // created_at, updated_at TIMESTAMPTZ t.soft_deletes(); // deleted_at TIMESTAMPTZ NULL t.index(&["name"]); // idx_users_name t.unique_index_named("users_email_key", &["email", "deleted_at"]); }).await?; schema.create_index("users", "idx_users_email_active", &["email", "active"]).await?; Ok(()) } async fn down(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.drop_table("users").await } } }
The comments show PostgreSQL's SQL; see Column Types for the other backends. The model that matches this table:
#![allow(unused)] fn main() { use chrono::{DateTime, NaiveDate, Utc}; use rust_decimal::Decimal; #[tideorm::model(table = "users", soft_delete)] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub name: String, pub bio: Option<String>, pub active: bool, pub birth_date: Option<NaiveDate>, pub balance: Decimal, pub preferences: Option<serde_json::Value>, pub email_verified_at: Option<DateTime<Utc>>, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub deleted_at: Option<DateTime<Utc>>, } }
A migration's version orders it: migrations run in the lexicographic order of their versions, so use a sortable form such as YYYYMMDD_NNN. Its name is for people, and for picking one migration out by name.
Running Migrations
At startup, register the migrations on TideConfig and turn running them on:
#![allow(unused)] fn main() { TideConfig::init() .database("postgres://localhost/mydb") .migration(CreateUsersTable) .migration(CreatePostsTable) .run_migrations(true) .connect() .await?; }
Registering is not running: migrations run only with run_migrations(true), which is off by default, and only from connect(). They run in version order, whatever order they were registered in. connect_only() skips them.
For more control, use a Migrator:
#![allow(unused)] fn main() { let migrator = Migrator::new() .add(CreateUsersTable) .add(CreatePostsTable); let result = migrator.run().await?; // apply pending migrations migrator.run_steps(2).await?; // apply the next two migrator.rollback().await?; // undo the last one migrator.rollback_steps(3).await?; // undo the last three migrator.reset().await?; // undo every one migrator.refresh().await?; // reset, then run migrator.run_one("20240101_create_posts").await?; // one migration, by version or name, migrator.rollback_one("create_posts").await?; // out of turn migrator.mark("20240101_create_posts", true).await?; // record it without running it let sql = migrator.pretend("create_posts", true).await?; // the statements its up() would run for status in migrator.status().await? { /* registered migrations, applied or not */ } for applied in migrator.applied().await? { /* the ledger: version, name, applied_at */ } let strays = migrator.unregistered().await?; // applied, but registered nowhere here // Another database than the global one: a tenant's, or a test's own Migrator::new().add(CreateUsersTable).database(&tenant_db).run().await?; }
add_boxed(Box<dyn Migration>) registers a boxed migration. A version registered twice is refused before anything runs. With database(&db) the migrations, their ledger and their lock all run on db.
Results and Failures
The batch commands (run, run_steps, rollback, rollback_steps, reset, refresh) return a MigrationResult, whose applied, skipped and rolled_back list each migration's version and name (has_applied() says whether anything was applied). It displays as a readable report.
Each migration commits on its own, so a failing one stops a batch command with the earlier ones still applied or rolled back. The error, a MigrationFailure, holds those in its result beside the error, and ? turns it into that tideorm::Error:
#![allow(unused)] fn main() { match migrator.run().await { Ok(result) => println!("{result}"), Err(failure) => { eprintln!("applied before the failure: {:?}", failure.result.applied); return Err(failure.error); } } }
On backends with transactional DDL (PostgreSQL, SQLite, CockroachDB), a migration and its ledger row commit together, so a statement failing halfway cannot leave an applied change with no ledger row. A rollback reverts a migration and removes its row in one transaction where the backend allows it.
Rollback Order and the Ledger
The ledger, _migrations by default, records which migrations ran and when. A rollback undoes the migration applied most recently, by its ledger entry, not the one with the highest version; after a long-lived branch merges, those are often different migrations. Every entry counts, registered or not: an entry this migrator has no migration for stops the rollback rather than being skipped over.
status()returns oneMigrationStatusper registered migration:version,name,appliedandapplied_at.applied()returns everyAppliedMigrationthe ledger records, in the order they were applied, withapplied_atas the database stamped it (in the session's time zone on PostgreSQL, MySQL and MariaDB, in UTC on SQLite).unregistered()lists the ledger's entries that no registered migration matches.reset()refuses to run while it lists anything, since it could not undo those migrations.
migrations_table("schema_versions") records the ledger in another table. Its name may only hold ASCII letters, digits and underscores; an invalid one is reported the first time the ledger is touched. The CLI passes the [migration] table setting of tideorm.toml here, and an application migrating at startup must use the same table, or each keeps its own ledger and the migrations the CLI applied run a second time. TideConfig always uses _migrations, so with another table run a Migrator yourself.
One Migration at a Time
run_one(name)runs a pending migration, by version or else by name, even when pending migrations come before it.rollback_one(name)reverts an applied one wherever it is in the ledger. Both hold the same lock asrun.mark(name, applied)records a migration as applied without running it, or withfalseremoves its record. The MySQL family and YugabyteDB commit DDL as it runs, so a migration whose ledger write failed there leaves its change unrecorded and every later run fails on it; marking it applied reconciles the ledger, and unmarking covers a rollback that dropped the change but kept the row.pretend(name, apply)returns the statements the migration'sup()(or withfalseitsdown()) would run, without running them. The migration runs with aSchemathat collects its statements, inside a transaction that is rolled back, so what it runs past the schema (a data backfill) changes nothing, except DDL on the MySQL family and YugabyteDB, which commits as it runs. The schema still reads the database where it must (has_table, MySQL'salter_table) and sees it before the migrations it pretends. It takes no lock and writes no ledger row.
run_one, rollback_one and mark refuse a migration already in the state they would put it in, and a name two migrations share is ambiguous.
The Migration Lock
Concurrent migrators are serialized with a lock, so replicas booting together apply each migration once instead of racing. The lock is held on a connection of its own, while the migrations run on the pool, so even a one-connection pool works, and a cancelled run() closes that connection and releases the lock.
| Backend | Lock |
|---|---|
| PostgreSQL | A session advisory lock (pg_advisory_lock), its session's idle and transaction timeouts turned off |
| CockroachDB | A transaction-scoped advisory lock (pg_advisory_xact_lock), released by a rollback |
| MySQL, MariaDB | GET_LOCK('tideorm_migrations:<database>', 300); a name past 64 characters uses a hash of the database name. Waiting longer than 300 seconds fails with an Error::Transaction naming the lock. Vitess holds it on a reserved connection |
| SQLite | An OS lock on a sidecar file, <database file>.tideorm-migrations.lock, which must not be deleted; an in-memory database uses an in-process lock |
Seeds take a lock of their own the same way; see Seeding.
From the CLI
tideorm migrate runs a project's migrations through the project's own Migrator, registered in src/migrations/mod.rs, so everything on this page holds there too. A migration not registered there is invisible to the CLI.
Schema Builder
Schema is what up() and down() receive. Every method is async and returns tideorm::Result:
| Method | Does |
|---|---|
create_table(name, closure) | Creates a table; the closure declares its columns on a TableBuilder |
create_table_if_not_exists(name, closure) | The same, doing nothing for a table that exists |
alter_table(name, closure) | Changes a table through an AlterTableBuilder |
drop_table(name), drop_table_if_exists(name) | Drops a table |
rename_table(from, to) | Renames a table |
has_table(name), has_column(table, column) | Reads the catalog |
create_index(table, name, &columns), create_unique_index(..) | Creates an index |
create_index_if_not_exists(..), create_unique_index_if_not_exists(..) | The same, doing nothing for an index that exists |
drop_index(table, name), drop_index_if_exists(table, name) | Drops an index |
raw(sql) | Runs a statement as written |
database_type() returns the backend the migration runs on, for a step only one backend takes.
create_table_if_not_exists can run again after a half-applied migration: on MySQL, which has no CREATE INDEX IF NOT EXISTS, it skips the indexes the table already has.
Column Types
| Method | PostgreSQL | MySQL, MariaDB | SQLite |
|---|---|---|---|
small_integer | SMALLINT | SMALLINT | INTEGER |
integer | INT4 | INT | INTEGER |
big_integer, foreign_id | BIGINT | BIGINT | INTEGER |
float | REAL | FLOAT | REAL |
double | DOUBLE PRECISION | DOUBLE | REAL |
decimal | DECIMAL(10, 2) | DECIMAL(10, 2) | REAL |
decimal_with(name, p, s) | DECIMAL(p, s) | DECIMAL(p, s) | REAL |
string | VARCHAR(255) | VARCHAR(255) | TEXT |
string_with(name, n) | VARCHAR(n) | VARCHAR(n) | TEXT |
text | TEXT | LONGTEXT | TEXT |
boolean | BOOLEAN | TINYINT(1) | INTEGER |
date | DATE | DATE | TEXT |
time | TIME | TIME(6) | TEXT |
datetime, timestamp | TIMESTAMP | DATETIME(6) | TEXT |
timestamptz | TIMESTAMPTZ | DATETIME(6) | TEXT |
uuid | UUID | BINARY(16) | TEXT |
json | JSON | JSON | TEXT |
jsonb | JSONB | JSON | TEXT |
binary | BYTEA | LONGBLOB | BLOB |
integer_array | INT4[] | JSON | TEXT |
text_array | TEXT[] | JSON | TEXT |
string_with takes a length of at least 1: up to 10,485,760 on PostgreSQL, and up to 16,383 on MySQL and MariaDB (utf8mb4), or 768 for a column that is indexed or unique. SQLite ignores the length.
Convenience methods:
#![allow(unused)] fn main() { t.id(); // big_increments("id") t.big_increments("id"); // BIGINT auto-increment primary key (BIGSERIAL on PostgreSQL) t.increments("id"); // integer auto-increment primary key (SERIAL4 on PostgreSQL) t.timestamps(); // created_at, updated_at: TIMESTAMPTZ NOT NULL DEFAULT now t.timestamps_naive(); // the same without a time zone (TIMESTAMP) t.soft_deletes(); // deleted_at: nullable TIMESTAMPTZ }
Any Column Type
t.column(name, column_type) takes any ColumnType, the type a model field's Rust type maps to, which schema sync creates, so a migration can declare the column a field gets:
#![allow(unused)] fn main() { use std::sync::Arc; t.column("visits", ColumnType::Unsigned); // BIGINT / INT UNSIGNED / INTEGER t.column("code", ColumnType::String(StringLen::N(12))); // VARCHAR(12) t.column("ratios", ColumnType::Array(Arc::new(ColumnType::Double))); // DOUBLE PRECISION[] / JSON / TEXT t.column("amount", ColumnType::custom("NUMERIC(20,0)")); // written as given }
tideorm::migration::column_type_sql(&column_type, db_type) returns the SQL a type renders to. A few mappings to know: an unsigned or one-byte integer has no unsigned type on PostgreSQL and takes a wider signed one; ColumnType::Enum is the quoted type name on PostgreSQL (create the type yourself) and ENUM(..) on MySQL and MariaDB; a type with no equivalent on a backend falls back to TEXT on SQLite and VARCHAR(255) on MySQL and MariaDB for network and interval types.
Column Modifiers
Every typed method returns a column builder, which adds the column when it is dropped:
| Modifier | Does |
|---|---|
not_null(), nullable() | Sets nullability |
default(value) | Sets a default |
default_now() | Defaults to CURRENT_TIMESTAMP |
unique() | Adds a UNIQUE constraint on the column |
check(expr) | Adds a CHECK constraint, as .check("email LIKE '%@%'") |
references(table, column) | Adds a foreign key; see Foreign Keys |
on_delete(action), on_update(action) | Sets the actions of the key references declared |
primary_key() | Makes the column the primary key |
extra(sql) | Appends SQL to the column definition as written |
default takes a DefaultValue, or anything that converts to one: &str and String (a string literal), the integer types, f32/f64, bool (TRUE/FALSE), Decimal (its exact digits) and Uuid (text on PostgreSQL, bytes on MySQL, MariaDB and SQLite). DefaultValue::Raw("..") writes an expression as given, and DefaultValue::Null a NULL.
A string default is escaped the way the backend reads a literal, so default(r"C:\temp\") stores those backslashes on MySQL and MariaDB too. A current-time default may be spelled now(), CURRENT_TIMESTAMP or LOCALTIMESTAMP on any backend.
Indexes and Table Constraints
#![allow(unused)] fn main() { schema.create_table("user_roles", |t| { t.foreign_id("user_id").not_null(); t.foreign_id("role_id").not_null(); t.big_integer("tenant_id").not_null(); t.string("email"); t.primary_key(&["user_id", "role_id"]); // a composite primary key t.unique(&["user_id", "tenant_id"]); // a UNIQUE constraint, named by the database t.unique_named("uq_email_tenant", &["email", "tenant_id"]); t.index(&["tenant_id"]); // idx_user_roles_tenant_id t.unique_index(&["email"]); // idx_user_roles_email_unique t.index_named("idx_roles_by_tenant", &["tenant_id", "role_id"]); }).await?; }
index and unique_index name an index after its table and columns (idx_<table>_<columns>, with _unique for a unique one); index_named and unique_index_named take the name. A generated name past 63 bytes is shortened with a hash, since PostgreSQL would otherwise cut two names that share a prefix to one and MySQL refuses them; a model's #[index] names are shortened the same way. primary_key(&columns) wins over a column declared as the primary key.
Foreign Keys
#![allow(unused)] fn main() { schema.create_table("posts", |t| { t.id(); t.foreign_id("user_id") .not_null() .references("users", "id") .on_delete(ForeignKeyAction::Cascade); t.big_integer("tenant_id").not_null(); t.big_integer("editor_id"); // A key over several columns t.foreign(&["tenant_id", "editor_id"], "tenant_users", &["tenant_id", "id"]) .name("fk_posts_editor") .on_delete(ForeignKeyAction::SetNull); }).await?; }
A key is written as a table constraint, because MySQL and MariaDB ignore a REFERENCES written on a column. Unnamed, it is fk_<table>_<columns>, shortened with a hash past 63 bytes like an index name, and that name is what drop_foreign_key takes. on_delete and on_update apply to the key references declares, so they follow it. The actions are Cascade, Restrict, SetNull, SetDefault (which MySQL's InnoDB refuses) and NoAction, the default.
Altering a Table
#![allow(unused)] fn main() { schema.alter_table("users", |t| { t.string("nickname"); // every typed column method adds a column t.add_column("rank", ColumnType::Integer); // or any type t.foreign_id("team_id").references("teams", "id"); t.rename_column("name", "full_name"); t.alter_column("email").not_null(); t.alter_column("score").set_type(ColumnType::BigInteger).default(0); t.change_column("age", ColumnType::BigInteger); // alter_column("age").set_type(..) t.alter_column("bio").drop_default(); t.add_index(&["full_name"]); t.add_unique_index(&["nickname"]); // add_index_named / add_unique_index_named take a name t.drop_index("idx_users_legacy"); t.add_foreign_key(&["manager_id"], "users", &["id"]).on_delete(ForeignKeyAction::SetNull); t.drop_foreign_key("fk_users_legacy_id"); t.drop_column("legacy"); }).await?; }
alter_column(name) changes a column with set_type, nullable, not_null, default and drop_default. The changes run in the order they were made.
| Backend | How a column changes |
|---|---|
| PostgreSQL | In place: its type, nullability or default |
| MySQL, MariaDB | MODIFY COLUMN restates the column whole, so alter_table first reads the table's SHOW CREATE TABLE and keeps what the change leaves alone: its nullability, default, AUTO_INCREMENT, comment and, for a column that still holds text, its character set and collation. A change of default alone runs ALTER COLUMN .. SET DEFAULT |
| SQLite | It cannot change a column, or add or drop a foreign key on a table it has, so such an alteration fails before any of its statements runs (see Rebuilding a SQLite Table). A column added with references takes its key along, which then wants the column to default to NULL |
Renaming a Table
#![allow(unused)] fn main() { async fn up(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.rename_table("posts", "articles").await } async fn down(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.rename_table("articles", "posts").await } }
MySQL and MariaDB run RENAME TABLE, PostgreSQL and SQLite ALTER TABLE .. RENAME TO. The rows, columns and indexes move with the table, and foreign keys in other tables follow it.
Tables in Another Schema
Every table name the schema builder takes may be written schema.table: a PostgreSQL schema, or a MySQL or MariaDB database. SQLite keeps the tables in its main database, as schema sync does, and ignores the schema part.
#![allow(unused)] fn main() { schema.create_table("billing.invoices", |t| { t.id(); t.foreign_id("account_id").references("billing.accounts", "id"); t.index(&["account_id"]); }).await?; }
Index and foreign key names derive from the table alone (idx_invoices_account_id, fk_invoices_account_id), and has_table/has_column look in the schema the name gives. MySQL and MariaDB move a table to another database when rename_table's new name names one; PostgreSQL renames a table within its schema only, and moving one is ALTER TABLE .. SET SCHEMA through raw.
Indexes and Introspection
#![allow(unused)] fn main() { schema.create_index("posts", "idx_posts_published", &["published_at"]).await?; schema.create_unique_index("posts", "idx_posts_slug", &["slug"]).await?; schema.create_index_if_not_exists("posts", "idx_posts_author", &["author_id"]).await?; schema.drop_index_if_exists("posts", "idx_posts_old").await?; if !schema.has_column("posts", "summary").await? { schema.alter_table("posts", |t| { t.text("summary"); }).await?; } if schema.database_type() == DatabaseType::Postgres { schema.raw("CREATE EXTENSION IF NOT EXISTS pg_trgm").await?; } }
MySQL has no CREATE INDEX IF NOT EXISTS, and neither MySQL nor MariaDB takes DROP INDEX IF EXISTS on a table, so there the if forms ask the catalog first. has_table and has_column look in the connection's current schema on PostgreSQL, its database on MySQL and MariaDB, and the main database on SQLite; a migration running in a transaction sees what it has created.
MySQL and MariaDB
Every timestamp method renders DATETIME(6) there: TIMESTAMP only spans 1970 to 2038, and a column without fractional digits drops microseconds; a CURRENT_TIMESTAMP default is raised to CURRENT_TIMESTAMP(6) to match. text() and binary() render LONGTEXT/LONGBLOB, because TEXT and BLOB stop at 64 KB, and a default on one of them, or on a JSON column, is written as the parenthesized expression MySQL requires. MySQL cannot index a TEXT column without a prefix length, so give an indexed or unique string column string() (VARCHAR(255)). Tables are created DEFAULT CHARSET=utf8mb4, whatever the database's own default is.
MySQL and MariaDB commit DDL as it runs, so a failed migration can leave part of its change applied; mark reconciles the ledger afterwards.
Rebuilding a SQLite Table
SQLite cannot change a column's type, so the change is a rebuild: create the new table, copy the rows, drop the old one and rename the new one. With foreign keys enforced, which is the driver's default, the DROP TABLE deletes the rows of other tables that point at the table with ON DELETE CASCADE, or fails on them. SQLite only turns enforcement off outside a transaction, and every migration runs in one, so PRAGMA foreign_keys = OFF inside it is refused. Ask for it instead:
#![allow(unused)] fn main() { fn foreign_keys_off(&self) -> bool { true } async fn up(&self, schema: &mut Schema) -> tideorm::Result<()> { schema.raw("CREATE TABLE users_new (id INTEGER PRIMARY KEY, age INTEGER NOT NULL)").await?; schema.raw("INSERT INTO users_new SELECT id, CAST(age AS INTEGER) FROM users").await?; schema.raw("DROP TABLE users").await?; schema.raw("ALTER TABLE users_new RENAME TO users").await } }
The migration then runs on a connection of its own with enforcement off, and before it commits TideORM runs PRAGMA foreign_key_check: a row whose foreign key matches no row fails the migration, which rolls back. The check runs before the migration as well, so a database that already has such rows is refused with the first of them named, rather than the migration being blamed for them. It cannot run inside a transaction of yours, nor on an in-memory database with a private cache. Other backends ignore foreign_keys_off(). A migration that cascades on purpose keeps the default.
Seeding
Seeds fill a database with the rows an application needs to start, such as roles, categories or a first admin user, or with sample data for development. TideORM records each seed it runs, so running the seeds again skips the ones already done.
#![allow(unused)] fn main() { use tideorm::prelude::*; struct RoleSeeder; #[async_trait] impl Seed for RoleSeeder { fn name(&self) -> &str { "role_seeder" } async fn run(&self, _db: &Database) -> tideorm::Result<()> { for name in ["admin", "editor", "viewer"] { Role::create(Role { id: 0, name: name.to_string() }).await?; } Ok(()) } async fn rollback(&self, _db: &Database) -> tideorm::Result<()> { Role::query().where_in("name", ["admin", "editor", "viewer"]).delete().await?; Ok(()) } } async fn seed_database() -> tideorm::Result<()> { let result = Seeder::new().add(RoleSeeder).run().await?; println!("ran {} seeds", result.executed.len()); Ok(()) } }
Writing a Seed
The Seed trait has two required methods and three optional ones:
| Method | Default | Meaning |
|---|---|---|
name() | Required | A unique name, stored in the ledger; use a descriptive snake_case name such as user_seeder |
run(db) | Required | Inserts the seed's rows |
rollback(db) | Does nothing | Removes what run inserted |
priority() | 100 | Lower runs first |
depends_on() | None | Names of seeds that must run before this one |
Each seed runs in one transaction with its ledger entry, so a seed that fails part way leaves neither rows nor an entry behind, and can be fixed and run again without duplicating what it wrote. Model calls inside run that name no database join that transaction. A rollback reverts the seed and removes its entry in one transaction too.
Running Seeds
At startup, register seeds on TideConfig and turn running them on:
#![allow(unused)] fn main() { TideConfig::init() .database("postgres://localhost/mydb") .seed(RoleSeeder) .seed(AdminUserSeeder) .run_seeds(true) .connect() .await?; }
Seeds run only with run_seeds(true), which is off by default. They run after migrations and schema sync, so they can fill the tables either creates, and a force_sync does not drop what they wrote. If seeding fails, what already ran is not rolled back: connect() returns the error with the database partially initialized. connect_only() skips seeds.
For more control, use a Seeder:
#![allow(unused)] fn main() { let seeder = Seeder::new() .add(RoleSeeder) .add(AdminUserSeeder); seeder.run().await?; // every pending seed seeder.run_seed("role_seeder").await?; // one seed, even if it already ran seeder.rollback().await?; // undo the last seed seeder.rollback_steps(2).await?; // undo the last two seeder.rollback_seed("role_seeder").await?; // undo one seed by name seeder.reset().await?; // undo every seed seeder.refresh().await?; // reset, then run for status in seeder.status().await? { println!("{} (priority {}): {}", status.name, status.priority, status.executed); } let names: Vec<&str> = seeder.names().collect(); // needs no database // Another database than the global one: a tenant's, or a test's own Seeder::new().add(RoleSeeder).database(&tenant_db).run().await?; }
With database(&db), the seeds, their ledger and their lock all run on db, and so do the model calls a seed makes. add_boxed(Box<dyn Seed>) registers a boxed seed.
| Method | Returns | Notes |
|---|---|---|
run() | Result<SeedResult, SeedFailure> | Skips seeds the ledger records |
run_seed(name) | Result<SeedResult> | Runs a seed again even if it already ran, once every seed it depends on has run; a re-run keeps its original ledger entry |
rollback(), rollback_steps(n) | Result<SeedResult, SeedFailure> | Newest first |
rollback_seed(name) | Result<SeedResult> | Fails with Seed '<name>' has not run when the ledger does not record it |
reset() | Result<SeedResult, SeedFailure> | Creates the ledger first, so on a fresh database it returns an empty result: "reset, then run" works as a bootstrap |
refresh() | Result<SeedResult, SeedFailure> | reset(), then run() |
status() | Result<Vec<SeedStatus>> | name, executed and priority of each registered seed |
A SeedResult lists the seeds it executed, skipped and rolled_back by name; has_executed() says whether anything ran.
A failing seed stops a batch command (run, rollback, rollback_steps, reset, refresh); the seeds it ran or rolled back before stay so. The error, a SeedFailure, holds them in its result beside the error, and ? turns it into that tideorm::Error.
Order and Dependencies
#![allow(unused)] fn main() { struct AdminUserSeeder; #[async_trait] impl Seed for AdminUserSeeder { fn name(&self) -> &str { "admin_user_seeder" } fn depends_on(&self) -> Vec<&str> { vec!["role_seeder"] } async fn run(&self, _db: &Database) -> tideorm::Result<()> { let admin = Role::query().where_eq("name", "admin").first_or_fail().await?; User::create(User { id: 0, role_id: admin.id, ..Default::default() }).await?; Ok(()) } } }
Each seed runs after the seeds it depends on. Among the seeds whose dependencies have all run, the lowest priority() goes next, and equal priorities keep the order they were added in.
- A dependency must have run, in this run or an earlier one.
run()fails on a seed whose dependency the ledger does not record and this seeder does not run first;run_seed()refuses one whose dependency has not run. - A dependency on a seed this seeder does not hold orders nothing; it only has to be in the ledger already.
- A dependency cycle is a configuration error naming the seeds on it.
The Ledger
Seeds that ran are recorded in the _seeds table, which TideORM creates when it first needs it and no migration owns. A rollback undoes the seed the ledger recorded last. When that seed is no longer registered (renamed or removed since it ran), the rollback fails rather than skip it, and the error says to register it again or delete its _seeds row.
The Seed Lock
Complete seed operations take a database lock before reading the ledger, so concurrent runners, such as replicas booting together, never run one pending seed twice. The lock works as the migration lock does, under its own name: pg_advisory_lock with a key of its own on PostgreSQL, GET_LOCK('tideorm_seeds:<database>', 300) on MySQL and MariaDB, and a <database file>.tideorm-seeds.lock sidecar file on SQLite.
- A seed's own code must not start another mutating seed operation: it already holds the lock.
- Inside a transaction of yours, the lock stays held until that transaction ends, across savepoints and sequential seed operations.
- Inside a SQLite transaction whose read snapshot is out of date, a seed operation fails before any seed runs; restart that transaction to see the committed ledger.
Logging
Set TIDE_LOG_SEEDS=1 (or TIDE_LOG_QUERIES=1) to log each seed as it runs, completes and rolls back. Only 1 and true turn either on.
From the CLI
tideorm db seed runs a project's seeders through the project's own runner, the <package>-seed binary the CLI scaffolds, which connects with connect_only() and runs the Seeder that src/seeders/mod.rs builds. Everything on this page holds there too.
Schema Sync and Export
TideORM can create your tables from your models while you develop (schema sync), write a connected database's schema to a SQL file (schema export), and read a database's tables, columns, indexes and foreign keys (the catalog). For the schema of a deployed database, use migrations.
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tideorm::model(table = "users")] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub active: bool, } async fn connect_for_development() -> tideorm::Result<()> { TideConfig::init() .database("postgres://localhost/mydb") .auto_models() .sync(true) .schema_file("schema.sql") .connect() .await?; Ok(()) } }
Schema Sync
Sync is for local development and tests. Do not enable it in production: a schema change that is not additive can still fail or damage data there. Deployed databases change through migrations.
sync(true) makes connect() bring the database in line with the registered models: it creates the tables that are missing and adds the columns an existing table lacks. It never drops or changes a table or a column.
Registering Models
Sync works on the models you register. Register them on TideConfig:
| Method | Registers |
|---|---|
auto_models() | Every model linked into the program |
models::<User>() | One model |
models::<(User, Post)>() | Each model of a tuple (up to 16) |
models_matching("src/models/*") | Every model whose source file matches the pattern |
models_matching matches the path of the file each #[tideorm::model] is written in. * matches within one path segment and ** crosses directories, so src/models/*, src/models/*.model.rs and src/models/**/*.rs all work. A pattern that matches no model logs a warning.
#![allow(unused)] fn main() { TideConfig::init() .database("postgres://localhost/mydb") .models_matching("src/models/*.model.rs") .sync(true) .connect() .await?; }
Every model registers itself at link time, but only when its file is compiled: a file no mod declaration reaches registers nothing, whatever the pattern says. Discovery itself does not connect or change any table.
With sync on and no model registered, connect() fails with No models registered for schema sync; call auto_models() or models::<YourModel>(), followed by the tables of the models the program does compile.
What Sync Creates
A missing table is created with a column per field, typed by the field's Rust type: the type's ValueType::column_type(), which a model's Column::def() reports too, rendered as migrations render it (a String is TEXT, LONGTEXT on MySQL; a u32 is BIGINT on PostgreSQL). An encrypted field's column is text whatever the field's type. A field type with no ValueType does not compile: derive DeriveValueType on a newtype or DeriveActiveEnum on an enum, or mark a field that is not a column #[tideorm(skip)]. A field marked auto_increment whose type cannot auto-increment gets a column without it, and sync logs a warning.
Sync also creates the indexes a model declares with #[index] and #[unique_index]:
- On a new table, a failing index fails the sync.
- On an existing table, sync adds the indexes that are missing; a failure there, such as a unique index over rows that repeat a value, is logged as a warning rather than stopping startup.
- An index name that another table already owns is an error: sync does not reuse that name.
Sync creates no foreign keys and no enum types. Declare those in a migration.
Existing Tables
On an existing table sync only adds:
- It adds the columns the table lacks and never drops or changes one.
- It logs a warning naming the columns the model no longer declares. Remove them with a migration.
- A new non-
Optionfield without a#[tideorm(default = "..")]can be added only while the table is empty, since its rows would otherwise holdNULL. With rows present, sync fails and names the column. Give the field a default, make it anOption, or add it with a migration that fills it in.
SQLite adds columns under its own limits, and sync logs a warning for each:
- It cannot add a
NOT NULLcolumn without a default at all, so sync adds such a column to an empty table as nullable. - It cannot add a column whose default is the current time (
CURRENT_TIMESTAMP,CURRENT_DATE,CURRENT_TIME) or a parenthesized expression to an existing table, so sync adds it without the default. A migration that rebuilds the table keeps it.
Tables in Another Schema
A model's #[tideorm(schema = "..")] qualifies every statement sync issues:
| Backend | schema = "analytics" means |
|---|---|
| PostgreSQL | The analytics schema, which must exist before sync runs |
| MySQL, MariaDB | The analytics database |
| SQLite | Nothing; it is ignored |
Two models of one table (in one schema) share it: the second one adds the columns and indexes the first lacks, and a column both declare keeps the first model's definition.
Force Sync
force_sync(true) drops and recreates the table of every registered model on each connect, deleting all of its rows. It works only together with sync(true).
#![allow(unused)] fn main() { TideConfig::init() .database("sqlite://./test.db?mode=rwc") .auto_models() .sync(true) .force_sync(true) .connect() .await?; }
- It drops every table before creating any, each one before the registered tables its foreign keys reference. The recreated tables have no foreign keys.
- On PostgreSQL the drop is
CASCADE, which drops the keys other tables hold on a table (not those tables), so a reference cycle or an unregistered table referencing a registered one is left to it. MySQL, MariaDB and SQLite (while the referencing table has rows) refuse to drop a referenced table, and report it. - Seeds run after sync, so
force_syncdoes not drop what seeding wrote at startup.
force_sync is for throwaway development and test databases only. In a process whose TIDEORM_ENV is production (in any case), it fails with Error::Configuration before dropping anything, unless TIDEORM_ALLOW_FORCE_SYNC is 1 or true. Set that variable only for a database you mean to empty, such as a staging one.
Running Sync Yourself
connect() runs sync between migrations and seeds. To sync a database at another time, or a database other than the global one:
#![allow(unused)] fn main() { use tideorm::prelude::*; use tideorm::sync::{SyncRegistry, sync_database_with}; async fn rebuild_test_schema(db: &Database) -> tideorm::Result<()> { SyncRegistry::register_all_models(); sync_database_with(db, SyncMode::Recreate).await?; // what force_sync(true) does Ok(()) } }
| Call | Does |
|---|---|
db.sync() | Additive sync of db |
tideorm::sync::sync_database(&db) | The same |
sync_database_with(&db, SyncMode::Additive) | What sync(true) does |
sync_database_with(&db, SyncMode::Recreate) | What force_sync(true) does, with the same production guard |
The registry is global to the process: TideConfig::auto_models(), models() and models_matching() fill the same one that SyncRegistry exposes.
SyncRegistry method | Does |
|---|---|
register_all_models() | Registers every linked model; returns how many |
register_models_matching(pattern) | Registers the models whose source path matches; returns how many |
register_schema(ModelSchema) | Registers one table description |
schema_count() | The number of registered tables |
get_all_schemas() | The registered ModelSchemas |
clear() | Forgets every registration, for tests |
A single model registers with User::register_for_sync() (the SyncModel trait, in the prelude).
Previewing the SQL
SchemaGenerator renders the CREATE TABLE and CREATE INDEX statements sync would run for a model, for a backend you name, without connecting:
#![allow(unused)] fn main() { use tideorm::prelude::*; fn users_ddl() -> String { SchemaGenerator::new(DatabaseType::Postgres) .add_model::<User>() .generate() } }
It also renders tables you describe yourself, each column's SQL type written as you give it:
#![allow(unused)] fn main() { use tideorm::prelude::*; fn audit_log_ddl() -> String { let audit_log = TableSchemaBuilder::new("audit_log") .column(ColumnSchema::new("id", "BIGINT").primary_key()) .column(ColumnSchema::new("action", "TEXT").not_null()) .column(ColumnSchema::new("created_at", "TIMESTAMPTZ").not_null().default("now()")) .index(IndexDefinition::new("idx_audit_log_action", vec!["action".to_string()], false)) .build(); SchemaGenerator::new(DatabaseType::Postgres) .add_table(audit_log) .generate() } }
ColumnSchema::new(name, sql_type)is nullable untilnot_null()orprimary_key();auto_increment()anddefault(expression)complete it.TableSchemaBuildertakesschema(name)for a qualified table, andindexorindexesforIndexDefinitions.- The output starts with a comment naming the backend and the time it was generated, and writes
IF NOT EXISTSon each statement (MySQL has none for an index).
Schema Export
schema_file(path) makes connect() write the connected database's schema to path as SQL. The file is a readable dump of the schema, meant to be committed and reviewed in diffs:
#![allow(unused)] fn main() { TideConfig::init() .database("postgres://localhost/mydb") .schema_file("schema.sql") .connect() .await?; }
- It is written once per
connect(), after migrations, sync and seeds; nothing rewrites it in between. - It describes every table of the database, not only the registered models.
- A failed export fails
connect().connect_only()skips it. TideConfig::schema_file_path()returns the configured path.
SchemaWriter does the same at any time:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn export(db: &Database) -> tideorm::Result<()> { SchemaWriter::write_schema("schema.sql").await?; // the global database SchemaWriter::write_schema_for(db, "schema.sql").await?; // another one let sql: String = SchemaWriter::schema_sql(db).await?; // the script, not written println!("{sql}"); Ok(()) } }
write_schema_for writes nothing when the export fails. Keep the schema stable while it runs.
PostgreSQL
- Schemas, extensions and collations come first.
- Each base table is read from the catalog with its columns and primary key. Generated columns are written with their expression.
- Every secondary index is written as PostgreSQL defines it, so ordering, collations, operator classes, full-text, expression and partial indexes,
INCLUDEcolumns andNULLS NOT DISTINCTall survive. CHECKconstraints that call no routine are declared before inheriting tables are created. Checks that call a routine, foreign keys andEXCLUDEconstraints come after every table.- Tables, views, functions and the types they reference follow their catalog dependencies.
- Domain checks, column defaults, rules and triggers follow the tables, with their enabled state.
- Partition column overrides, replica identities and table storage options are kept.
- Ownership, grantor chains, column grants and default privileges are kept.
- Unsupported types, custom aggregates, operators, foreign tables and servers, and text search objects fail the export, rather than producing a file that cannot recreate them.
CockroachDB
CockroachDB's file is what its own SHOW CREATE ALL statements write, because its pg_catalog lacks what the PostgreSQL export reads: schemas, types, tables, sequences and views, with foreign keys after every table, then routines and triggers. Indexes and defaults are inside each CREATE TABLE. A table or view that calls a routine of its own database comes before that routine, so such a file cannot be replayed as written. See Compatible Servers.
MySQL and MariaDB
- Tables, views, stored routines, triggers and events keep the definitions the server wrote (
SHOW CREATE), and MariaDB sequences their own DDL. - Foreign keys are moved out of each
CREATE TABLEand added after every table exists, so tables that reference each other restore. - Views are created through temporary stand-in tables that each view then replaces, as
mysqldumpdoes, so any view dependency graph resolves. No rows are inserted. - Replay the file with the
mysqlormariadbclient on one connection: it usesDELIMITERfor stored program bodies, and sets the SQL modes, collations and event time zones they were created under, restoring your session's settings at the end. - Replaying needs
ALTERon the destination database: its default collation is restored from the source, while each stored program is created under its own original database collation. - References to the exported database are rebound to the destination. Explicit references to other databases, and dynamic SQL strings, keep their text.
- An object whose definition
SHOW CREATEdoes not disclose to your account fails the export, naming it; grant more privileges and run it again.
SQLite
SQLite keeps the statement that created each table, view, index and trigger, so the file is those statements, with generated columns, collations, constraints and AUTOINCREMENT included. An FTS5 table's shadow tables are left out, since the FTS5 table recreates them.
Compatible Servers
| Server | Difference |
|---|---|
| Vitess | Leaves out the ALTER DATABASE COLLATE statements written for MySQL, since Vitess manages a keyspace's collation; each table names its own. Vitess does not accept CREATE FUNCTION, TRIGGER or EVENT, so a file holding them does not replay through it |
| YugabyteDB | A GIN index is written as ybgin, and tables keep YugabyteDB's REPLICA IDENTITY CHANGE |
| TiDB | TiDB has no stored routines, triggers or events, so there are none to write |
What an Export Leaves Out
An export holds schema, not row data, current sequence values, database accounts or replication subscriptions. The roles and definers it names must exist where you replay it, and the replaying connection needs permission to restore their ownership and grants.
Reading the Catalog
db.catalog() reads what a connected database holds. It is the reader sync, migrations and the schema export use themselves.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn describe(db: &Database) -> tideorm::Result<()> { let catalog = db.catalog(); for table in catalog.tables().await? { println!("{table}"); for column in catalog.columns(&table).await? { let null = if column.nullable { "NULL" } else { "NOT NULL" }; println!(" {} {} {null}", column.name, column.data_type); } for index in catalog.indexes(&table).await? { println!(" index {} on {:?} (unique: {})", index.name, index.columns, index.unique); } for key in catalog.foreign_keys(&table).await? { println!(" {} -> {}.{}", key.column, key.references_table, key.references_column); } } Ok(()) } }
| Method | Returns |
|---|---|
tables() | Base tables by name, PostgreSQL's partitioned tables and MariaDB's system-versioned ones included |
views() | Views by name |
sequences() | Sequences by name, on PostgreSQL and MariaDB; MySQL and SQLite have none |
enum_types() | PostgreSQL's enum types by name; the other backends declare an enum on its column |
columns(table) | The columns of a table or view, in order; empty when there is no such table |
indexes(table) | The table's indexes; SQLite has none for an INTEGER PRIMARY KEY, which is the row id |
foreign_keys(table) | The table's foreign keys, one entry per key column |
Each returns a tideorm::Result. The catalog reads the connection's current schema on PostgreSQL, its database on MySQL and MariaDB, and the main database on SQLite. On PostgreSQL a table in another schema is listed as schema.name, and a table passed that way is read from that schema; schemas named pg_* and information_schema, and what an extension installed, are left out. Inside a transaction the catalog reads on that transaction, so it sees the tables the transaction created.
The types are in tideorm::schema: Catalog, ColumnInfo, IndexInfo and ForeignKeyInfo.
ColumnInfo field | Meaning |
|---|---|
name | The column's name |
data_type | Its type as the database writes it: character varying(255) on PostgreSQL, int unsigned on MySQL, the declared type on SQLite |
nullable | Whether it accepts NULL |
default | Its default expression as the catalog writes it, if any |
primary_key | Whether it is part of the primary key |
unique | Whether a unique index other than the primary key holds this column alone |
foreign_key | Whether it is part of a foreign key |
extra | What else the catalog says, if anything: MySQL's auto_increment, PostgreSQL's identity, a generated column's expression |
IndexInfo field | Meaning |
|---|---|
name | The index's name |
columns | Its key columns in order. PostgreSQL writes an expression key as its expression; MySQL and SQLite leave one out |
unique | Whether it is unique |
primary | Whether it is the primary key's |
whole_columns | Whether every key part is a whole column: false for an expression, or on MySQL and MariaDB for a column prefix |
ForeignKeyInfo field | Meaning |
|---|---|
column | The referencing column |
references_table | The referenced table, written as tables() writes it |
references_column | The referenced column |
SQLite names no referenced column for a foreign key to a parent table without a primary key, a key it does not enforce, so foreign_keys leaves such a key out.
Errors
Every fallible TideORM call returns tideorm::Result<T>, whose error is tideorm::Error. The error says what kind of failure it was, what the database reported independent of backend and wording, whether retrying can succeed, and what status and stable code to answer a client with.
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn register(user: User) -> tideorm::Result<Option<User>> { match User::create(user).await { Ok(user) => Ok(Some(user)), // a unique index on users.email Err(e) if e.is_unique_violation() => Ok(None), Err(e) => Err(e), } } }
tideorm::Result is not in the prelude (it would shadow std's Result), so write it out. Error and DbFailureKind are in the prelude; ErrorContext and DbFailure are in tideorm::error.
The Error Type
Error is an enum grouped by where the failure came from. It is #[non_exhaustive], so a match on it needs a wildcard arm.
| Variant | Raised when | code() | http_status() |
|---|---|---|---|
NotFound | A record that must exist does not (find_or_fail, first_or_fail, ..) | TIDE_NOT_FOUND | 404 |
Connection | A connection cannot be opened or used: refused, timed out, bad credentials, unknown database, no database configured | TIDE_CONNECTION | 503 |
Query | A statement fails on the server, or the query builder refuses a query before sending it | TIDE_QUERY | 400 |
Validation | A model fails its #[validate] rules; nothing was written | TIDE_VALIDATION | 422 |
Conversion | A value cannot be converted, such as a column that does not decode into its field | TIDE_CONVERSION | 400 |
Transaction | A transaction cannot continue or commit: it was aborted by an earlier failure, or its handle leaked out of its closure | TIDE_TRANSACTION | 409 |
Configuration | The setup is wrong: no URL, a backend feature not compiled in, a bad pool setting | TIDE_CONFIG | 500 |
Internal | Something unexpected, such as an I/O error | TIDE_INTERNAL | 500 |
BackendNotSupported | The backend cannot do what was asked, such as execute_returning() on MySQL | TIDE_BACKEND_NOT_SUPPORTED | 501 |
PrimaryKeyNotSet | An operation needs a primary key the model does not hold | TIDE_PRIMARY_KEY_NOT_SET | 400 |
Tokenization | Tokens cannot be made, usually because no encryption key is configured | TIDE_TOKENIZATION | 400 |
InvalidToken | decode_token was given a token that is invalid, tampered or for another model | TIDE_INVALID_TOKEN | 401 |
AccessDenied, Rbac | Your own access checks, built with Error::access_denied(permission, resource) and Error::rbac(..) | TIDE_ACCESS_DENIED, TIDE_RBAC | 403, 500 |
code() does not change between releases, so it is what an API response or an alert should key on; the Display text may.
Classifying Database Failures
A duplicate key and a deadlock are both Error::Query. failure_kind() tells them apart: it is the driver's classification of what the database reported (PostgreSQL's SQLSTATE, MySQL's error number, SQLite's result code), never a reading of the message. is_retryable() says whether running the operation again can succeed.
#![allow(unused)] fn main() { use tideorm::prelude::*; match User::create(user).await { Ok(user) => { /* created */ } Err(e) if e.failure_kind() == DbFailureKind::UniqueViolation => { /* email taken */ } Err(e) if e.is_retryable() => { /* deadlock, lock timeout, dropped connection: retry */ } Err(e) => return Err(e), } }
is_unique_violation(), is_foreign_key_violation() and is_not_null_violation() ask the same about one kind.
DbFailureKind | Database report | Retryable |
|---|---|---|
UniqueViolation | SQLSTATE 23505 | No |
ForeignKeyViolation | 23503 | No |
NotNullViolation | 23502 | No |
CheckViolation | 23514 | No |
ExclusionViolation | 23P01 (PostgreSQL EXCLUDE constraints) | No |
InvalidValue | Class 22: a value too long, out of range or invalid for its type | No |
SyntaxError | 42601, MySQL 42000 | No |
UndefinedColumn | 42703, MySQL 42S22 | No |
UndefinedTable | 42P01, MySQL 42S02 | No |
InsufficientPrivilege | 42501 | No |
Deadlock | 40P01, MySQL 1213 | Yes |
SerializationFailure | 40001, such as CockroachDB's "restart transaction" | Yes |
LockNotAvailable | 55P03, MySQL's lock wait timeout, a busy or locked SQLite database | Yes |
StatementTimeout | 57014 | Yes |
ConnectionTimeout | 53300, or no pooled connection within acquire_timeout | Yes |
ConnectionClosed | Class 08 but 08P01, and the server's own session timeouts (57P05, 25P03, 25P04, MySQL 4031): the server closed the connection | Yes |
ConnectionRefused | Nothing listens at the host and port, or the server is not up yet | Yes |
AuthenticationFailed | 28P01, 28000, MySQL 1045 | No |
UnknownDatabase | 3D000, MySQL 1049 | No |
TlsFailed | The TLS handshake failed | No |
InvalidConfiguration | A bad URL or connection option | No |
NotConnected | No connection is set up: a model used before connecting | No |
Unclassified | Anything else, and every error that did not come from the database | No |
DbFailureKind is #[non_exhaustive]; as_str() gives a readable name, and is_constraint_violation() is true for the five constraint kinds, which the caller fixes by changing the data rather than retrying.
A few cases worth knowing:
- SQLite checks neither text length nor type, so a string longer than its
VARCHAR(255)is stored there and refused (InvalidValue) by PostgreSQL and MySQL.#[validate(max_length = 255)]keeps the backends in step. - A connection the server closes under a statement (a restart, a failover, MySQL's
KILL) isConnectionClosed. The pool replaces it, so the next call gets a fresh one. - A statement refused on a transaction that a failure already aborted reports that failure's kind, so the refusals after a deadlock are retryable too.
- An error with no classified failure, such as one built with
Error::query(..), is not retryable, whatever its message says.
Constraint and Driver Details
The Connection, Query and Transaction variants carry the driver's report when there was one:
#![allow(unused)] fn main() { if let Some(failure) = e.db_failure() { println!("{:?} {:?}", failure.kind(), failure.code()); // UniqueViolation Some("23505") println!("{:?} {:?}", failure.constraint(), failure.table()); } }
| Method | Returns |
|---|---|
e.db_failure() | The DbFailure, or None for failures that never reached a driver (query-builder misuse, validation, configuration) |
e.sqlstate() | The SQLSTATE, or the driver's native code where the backend has none (SQLite) |
e.constraint() | The violated constraint's name; only PostgreSQL reports it, MySQL and SQLite name it inside the message |
failure.table() | The table the statement was writing, when the backend reports it |
An error that came from a driver keeps the driver's error as its source(), so {:#} chains and anyhow reach the backend's own error. From<std::io::Error> gives an Internal error and From<serde_json::Error> a Conversion error, each keeping its source, so ? works on both inside a function returning tideorm::Result.
Connection Errors
Every failure to open or use a connection is an Error::Connection, which http_status() answers with 503: a refused connection, a timeout waiting for a pooled connection, bad credentials, an unknown database, a failed TLS handshake, or a model used before any connection was set up (NotConnected). The kinds in the table above tell them apart.
Only ConnectionRefused and the timeouts are retryable. AuthenticationFailed, UnknownDatabase, TlsFailed and InvalidConfiguration are deployment faults that a retry will not fix, and belong in an alert as well as a 503. A URL for a backend whose Cargo feature is not compiled in is an Error::Configuration naming the feature to enable (see Installation).
db() panics when no global connection is set; require_db() returns the same failure as an Err. See Configuration for connecting.
Transaction Errors
Error::Transaction means the transaction cannot go on:
- A statement failed inside it and the transaction was aborted. Later statements on it are refused, and its commit rolls back and fails instead of committing. The refusal reports the original failure's kind, so
is_retryable()is true after a deadlock or serialization failure. - A clone of the transaction handle escaped the closure, so the commit fails with "transaction handle leaked outside the transaction scope" and the transaction is rolled back.
- A nested transaction whose enclosing one already ended refuses its statements.
See Transactions for how transactions and savepoints behave.
Validation Errors
Error::Validation comes from a model's #[validate] rules before anything is written. Its field and message are the first failure; validation_errors() returns every failure, field by field:
#![allow(unused)] fn main() { use tideorm::prelude::*; if let Err(e) = User::create(user).await { if let Some(errors) = e.validation_errors() { for (field, messages) in errors.all() { println!("{field}: {}", messages.join(", ")); } } } }
ValidationErrors also has get(field), first(), messages(), iter(), len() and is_empty(). Validation messages are written for users, so they can go out to a client as they are. See Validation for the rules.
Error Context
Errors from query-builder reads, batch inserts, catalog reads and migration schema reads carry an ErrorContext: the table, the column, the conditions, how they were combined, and the SQL. context() returns it for NotFound and Query errors:
#![allow(unused)] fn main() { if let Some(ctx) = e.context() { println!("table: {:?}", ctx.table); println!("conditions: {:?}", ctx.conditions); // values are shown as `?` println!("query: {:?}", ctx.query); } }
The conditions show ? for the values you filtered by, so the context is safe to log. Call debug() on the query to see the values (see Logging and Profiling). A NotFound from Model::find_or_fail(id) carries no context; its message names the table and the key, such as users with id = 7 not found.
with_context(ErrorContext) attaches context to a NotFound or Query error you build or pass on, keeping the database failure it carries; other variants come back unchanged:
#![allow(unused)] fn main() { use tideorm::error::ErrorContext; let err = Error::query("order total is negative") .with_context(ErrorContext::new().table("orders").column("total")); }
Presenting an Error
| Method | Gives |
|---|---|
code() | The stable code, such as TIDE_VALIDATION |
http_status() | A status for the variant (see The Error Type) |
suggestion() | A next step, per database failure kind where there is one (an UndefinedTable suggests running migrations), otherwise per variant |
log_format() | [CODE] message, then indented Table:, Conditions:, Query:, Database: and Suggestion: lines |
Display | One line starting with the variant, such as Record not found: .. or Validation error: email - .. |
Answering a Request
http_status() answers 400 for every Error::Query, a duplicate key and a deadlock included, so an endpoint looks at failure_kind() first:
#![allow(unused)] fn main() { use tideorm::prelude::*; /// The status and body an endpoint answers a TideORM error with. The body /// carries the stable `code()`, never the error's text. fn error_response(e: &Error) -> (u16, JsonValue) { if let Some(errors) = e.validation_errors() { // 422 with every failure, field by field: {"email": ["..."]} return (422, json!({ "code": e.code(), "errors": errors.all() })); } let status = match e.failure_kind() { DbFailureKind::UniqueViolation => 409, // deadlock, lock or statement timeout, dropped connection _ if e.is_retryable() => 503, // NotFound 404, Connection 503, Transaction 409, Configuration 500, .. _ => e.http_status(), }; if status >= 500 { tracing::error!("{}", e.log_format()); } (status, json!({ "code": e.code() })) } }
An error's Display text can hold the server's message, table, column and constraint names, and SQL; log_format() adds the query and its context. Send code() to the client and keep the rest in your logs.
Retrying a Transaction
Retry the whole transaction, never one statement inside it: after a deadlock or a serialization failure the server has already rolled the whole transaction back. transaction_retrying does that:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn place_order_with_retry(db: &Database, cart: &Cart) -> tideorm::Result<Order> { db.transaction_retrying(TransactionOptions::default(), 4, async |_tx| place_order(cart).await) .await } }
It runs the closure in a new transaction after a Deadlock, a SerializationFailure or a LockNotAvailable, up to the given number of runs in all, waiting 10 ms before the second, doubling up to 1 s, each wait shortened by a random part so competing transactions spread out. Any other failure, and the last attempt's, comes back as it is. It never retries a lost connection, whose commit may have gone through. Inside another transaction on the same pool it runs the closure once, as a savepoint that ignores the options the enclosing transaction began with its own: a deadlock or a serialization failure aborts the enclosing transaction, so that is the one to retry. The closure can run more than once, so do what happens outside the database, such as sending an email, after it returns.
CockroachDB runs every transaction at SERIALIZABLE and asks clients to retry with SQLSTATE 40001 ("restart transaction"), which is SerializationFailure, as is TiDB's write conflict (error 9007), so the same call serves them (see Compatible Servers). PostgreSQL's SERIALIZABLE and REPEATABLE READ isolation levels report the same code.
To retry on other failures too, such as a statement timeout, write the loop yourself around is_retryable().
Retryable means a new attempt can succeed, not that the failed one wrote nothing. A ConnectionClosed that cuts off the COMMIT leaves it unknown whether the transaction committed, and the retry then writes it a second time. The same holds for a single create() retried outside a transaction. Make a retried write idempotent: insert with a key the request carries (a client-chosen UUID, an idempotency key under a unique index) or use an upsert, so a second run finds the first one's row instead of adding another.
Creating Your Own Errors
Each variant has a constructor, so your own code can return tideorm::Error alongside TideORM's:
| Constructor | Variant |
|---|---|
Error::not_found(msg) | NotFound |
Error::connection(msg) | Connection |
Error::query(msg) | Query |
Error::validation(field, msg) | Validation |
Error::conversion(msg) | Conversion |
Error::transaction(msg) | Transaction |
Error::configuration(msg) | Configuration |
Error::internal(msg) | Internal |
Error::access_denied(permission, resource) | AccessDenied |
Error::rbac(msg) | Rbac |
Error::backend_not_supported(msg, backend) | BackendNotSupported |
Error::primary_key_not_set(msg, model) | PrimaryKeyNotSet |
Error::tokenization(msg) | Tokenization |
Error::invalid_token(msg) | InvalidToken |
An error you build carries no database failure, so failure_kind() is Unclassified and is_retryable() is false whatever the message says. Returning an Err from a Database::transaction closure rolls the transaction back, which is how a check inside it cancels the work:
#![allow(unused)] fn main() { use tideorm::prelude::*; db.transaction(async |_tx| { let order = Order::find_or_fail(order_id).await?; if order.total < 0 { return Err(Error::validation("total", "must not be negative")); } order.update().await }) .await?; }
Logging and Profiling
TideORM gives you three ways to see what your queries do: print a query before it runs, log the statements as they run, and time them. The types are in tideorm::logging and tideorm::profiling, and the common ones are also in the prelude.
| You want to | Use |
|---|---|
| See the SQL one query will run | debug(), build_sql_preview() |
| Check a query is valid without running it | validate() |
| Print every statement while developing | TIDE_LOG_QUERIES=true |
| Record statements, slow ones and counts in-process, or send them to your logs | QueryLogger |
| Count and time every statement | GlobalProfiler |
| Build a report from statements you choose | Profiler, QueryAnalyzer |
Inspecting a Query Before It Runs
Print debug() on a query-builder query to see the statement with its values written in, the parameterized statement with its parameters, and the clauses it was built from:
#![allow(unused)] fn main() { use tideorm::prelude::*; let query = Post::query() .where_eq(Post::PUBLISHED, true) .order_by(params.sort.as_str(), Order::Asc) .limit(20); println!("{}", query.debug()); query.validate()?; }
A query that a terminal method would refuse (an unsafe order_by taken from a request, a bad raw fragment, a zero page) shows the reason on an Invalid: line. validate() returns the same error without running anything, so a handler can answer 400 before touching the database.
| Method | Returns |
|---|---|
debug() | A QueryDebugInfo: table, operation, select list, conditions, joins, order, group, limit and offset, the SQL, the parameters, and any error. Display prints it as a block |
debug_for(DatabaseType::MySQL) | The same in another backend's dialect, with its markers ($1 or ?) and quoting |
build_sql_preview() | The statement get() would run, values written in as literals, under a banner marking it display-only |
build_sql_preview_for(DatabaseType::SQLite) | The preview in another backend's dialect |
validate() | Ok(()), or the error the query would fail with |
debug() and build_sql_preview() use the dialect of the database the query would run on, or PostgreSQL's when no database is connected. The preview inlines values for reading only: never run it, run the query.
Printing Every Statement
Set TIDE_LOG_QUERIES to 1 or true while developing:
TIDE_LOG_QUERIES=true cargo run
Every statement is then printed to stderr as [TideORM DEBUG] Query: <sql>. Query-builder statements print before they run; typed CRUD (find, save, update, delete, upserts), raw SQL and migration DDL print once they complete. Bound values are never printed: a statement appears with its markers ($1, ?). The variable is read once, when the first statement runs; any other value, false and 0 included, leaves it off.
TIDE_LOG_QUERIES also turns on the QueryLogger's history and statistics (below), so QueryLogger::history() has the statements too.
The Query Logger
QueryLogger is a process-wide structured logger. While it is enabled it records each statement as a QueryLogEntry, keeps a bounded history and counters, and prints entries according to its level.
#![allow(unused)] fn main() { use std::time::Duration; use tideorm::prelude::*; QueryLogger::global() .level(LogLevel::Debug) .slow_query_threshold(Duration::from_millis(50)) .history_limit(200) .enable(); }
QueryLogger::global() returns a builder; nothing changes until enable(), disable() or apply() ends it (apply() keeps the current on/off state). The builder's settings:
| Builder method | Default |
|---|---|
level(LogLevel) | TIDE_LOG_LEVEL, else Off |
slow_query_threshold(Duration) | TIDE_SLOW_QUERY_MS, else 100 ms |
history_limit(usize) | 100 entries; 0 keeps none |
timing(bool) | true: printed entries show their duration |
The level decides only what is printed; an enabled logger keeps its history and statistics at any level, Off included.
LogLevel | Prints |
|---|---|
Off | Nothing |
Error | Failed statements |
Warn | Failed and slow statements |
Info | Failed and slow statements, and a one-line summary of every other |
Debug | Every statement with its timing |
Trace | Every statement with timing, row count and any parameters attached to the entry |
The level also governs TideORM's own status lines ([TideORM] ..) and warnings ([TideORM WARN] ..), which print unless the level is set to Off or Error.
What the logger records: query-builder statements, tagged with their table, and every statement the engine runs (typed CRUD, raw SQL, migration DDL), once it completes, with its duration, row count and error. Bound values are never recorded.
Reading the History and Statistics
#![allow(unused)] fn main() { use tideorm::prelude::*; for entry in QueryLogger::slow_queries() { println!("{:?} {} {:?}", entry.table, entry.sql, entry.duration); } let stats = QueryLogger::stats(); println!("{stats}"); // total, slow count and share, total and average time }
| Function | Returns |
|---|---|
QueryLogger::history() | The recorded entries, oldest first |
QueryLogger::slow_queries() | The entries at or above the slow-query threshold |
QueryLogger::stats() | A QueryStats: total_queries, slow_queries, total_time(), avg_query_time(), slow_percentage() |
QueryLogger::clear_history(), reset_stats() | Empty the history, zero the counters |
is_enabled(), level(), slow_query_threshold() | The current settings |
enable(), disable(), set_level(LogLevel) | Change them without the builder |
A QueryLogEntry has sql, params, operation (a QueryOperation: Select, Insert, Update, Delete, Transaction or Unknown), table, duration, rows, success, error and timestamp. QueryLogger::log(entry) records an entry of your own.
Sending Log Output Elsewhere
By default the logger prints to stderr. set_sink hands each printed line, with its entry, to your function instead, such as tracing; clear_sink() goes back to stderr:
#![allow(unused)] fn main() { use tideorm::prelude::*; QueryLogger::set_sink(|entry, text| { if entry.success { tracing::debug!("{text}"); } else { tracing::warn!("{text}"); } }); }
A sink runs on the task that ran the statement, so one that writes to a file or the network should hand the text off and return. A bounded channel keeps that from holding up queries, dropping lines instead of waiting when the writer falls behind:
#![allow(unused)] fn main() { let (lines, mut pending) = tokio::sync::mpsc::channel::<String>(1024); QueryLogger::set_sink(move |_entry, text| { let _ = lines.try_send(text.to_owned()); }); tokio::spawn(async move { while let Some(text) = pending.recv().await { write_log_line(&text).await; // your writer } }); }
Environment Variables
The logger reads these once, the first time it is used. Settings made in code afterwards take precedence.
| Variable | Effect |
|---|---|
TIDE_LOG_QUERIES | 1 or true: print every statement and enable the logger |
TIDE_LOG_LEVEL | off, error, warn, info, debug or trace: set the level, and enable the logger for any level but off. An unknown value means off |
TIDE_SLOW_QUERY_MS | The slow-query threshold in milliseconds, for both the logger and GlobalProfiler (default 100) |
QueryLogger::reset() puts the logger back as the environment configures it: TIDE_LOG_LEVEL and TIDE_SLOW_QUERY_MS read again, counters and history emptied, the history limit at 100, timing shown, output on stderr. Call it in tests that change the global logger.
Global Profiling
GlobalProfiler counts and times every statement the engine runs while it is enabled: typed CRUD, query-builder reads and writes, raw SQL and migration statements, each timed around the driver call. Transaction control (BEGIN, COMMIT, savepoints) is not counted. It is off by default and keeps no SQL text, only counters.
#![allow(unused)] fn main() { use std::time::Duration; use tideorm::prelude::*; GlobalProfiler::enable(); GlobalProfiler::reset(); GlobalProfiler::set_slow_threshold(Duration::from_millis(200)); let users = User::query().where_eq(User::ACTIVE, true).limit(25).get().await?; let stats = GlobalProfiler::stats(); println!("{} queries, {} slow, avg {:?}", stats.total_queries, stats.slow_queries, stats.avg_query_time()); GlobalProfiler::disable(); }
GlobalStats is the same type as the logger's QueryStats, with its own counters and threshold. GlobalProfiler::is_enabled() and slow_threshold() read the settings, and record(duration) adds a duration of your own while it is enabled.
The profiler is process-wide, so reset it between tests that assert on its counts.
Manual Profile Reports
When you need SQL text, tables, row counts and the slowest statements, build a report with Profiler. It records only what you hand it; it does not subscribe to TideORM's statements.
#![allow(unused)] fn main() { use std::time::Duration; use tideorm::prelude::*; let mut profiler = Profiler::start(); profiler.record("SELECT id, email FROM users WHERE active = true", Duration::from_millis(12)); profiler.record_full( ProfiledQuery::new("SELECT * FROM posts WHERE user_id = 42", Duration::from_millis(37)) .with_table("posts") .with_rows(8), ); let report = profiler.stop(); println!("{report}"); for hint in report.suggestions() { println!("{hint}"); } }
This is useful when you instrument a benchmark, compare two shapes of a query, or build a focused performance report in a test.
| Item | Gives |
|---|---|
Profiler::query_count(), elapsed() | The statements recorded so far and the time since start() |
ProfiledQuery::cached() | Marks a statement served from a cache, which the N+1 count skips |
ProfiledQuery::operation_kind() | Its QueryOperation, read from the SQL |
ProfileReport fields | total_duration, query_duration, queries, operations (count per operation), slowest, tables (count per table) |
report.query_count(), avg_query_time(), query_time_percentage() | Totals, and the share of the session's time spent in statements |
report.queries_slower_than(duration) | The statements at or above a duration |
report.suggestions() | Hints: more than 10 uncached reads of one table (a likely N+1), slow statements, SELECT * |
report.suggestions_with(duration) | The same hints with your own slow threshold |
suggestions() counts a statement slow at GlobalProfiler::slow_threshold().
Query Analysis
QueryAnalyzer::analyze(sql) reads a statement and returns suggestions for its shape: SELECT *, an UPDATE or DELETE with no WHERE, a LIKE with a leading wildcard, OR conditions, ORDER BY without LIMIT, NOT IN, a function applied to a column in WHERE, and an ID column compared with a quoted number.
#![allow(unused)] fn main() { use tideorm::prelude::*; for suggestion in QueryAnalyzer::analyze("SELECT * FROM users WHERE LOWER(email) = 'ada@example.com'") { println!("[{}] {}: {}", suggestion.level.label(), suggestion.title, suggestion.suggestion); } let complexity = QueryAnalyzer::estimate_complexity("SELECT u.id FROM users u JOIN posts p ON p.user_id = u.id"); println!("{complexity:?}: {}", complexity.description()); }
A QuerySuggestion has a level (SuggestionLevel::Info, Warning or Critical), a title, an explanation and a suggestion, and prints all of them through Display. estimate_complexity returns a QueryComplexity: Simple, Moderate, Complex or VeryComplex.
The analyzer reads text; it does not ask the database for a plan. Run EXPLAIN through Raw SQL for that.
Tracing Spans
Every statement runs inside a tracing span named db.query (transaction control, BEGIN, COMMIT, ROLLBACK and savepoints, does not, nor does the wait for a pool connection), at DEBUG under the target tideorm::query, so any subscriber sees it, and through tracing-opentelemetry it becomes a client span of your traces. Its fields follow OpenTelemetry's database conventions:
| Field | Holds |
|---|---|
otel.kind | client |
db.system.name | The server: postgresql, mysql, mariadb, sqlite, cockroachdb, yugabytedb, tidb or vitess |
db.query.text | The statement with markers ($1, ?) for its bound values; what is written into the SQL itself stays (a raw statement's literals, a LIMIT, an integer IN list of more than 1,000 values). Empty for unprepared SQL (exec_raw, Database::execute, migration DDL), whose text can hold values |
db.response.returned_rows | The rows a statement returned or changed, once it succeeded |
otel.status_code | ERROR when it failed |
A span opened by your code around the call, such as a request's, is its parent. Enable the target in the subscriber's filter, for instance RUST_LOG=tideorm::query=debug with tracing_subscriber::EnvFilter.
Slow-Query Thresholds
The logger and GlobalProfiler each keep their own slow-query threshold. Both start at TIDE_SLOW_QUERY_MS, or 100 ms, and a statement counts as slow at or above it. Change the logger's with the builder's slow_query_threshold, the profiler's with GlobalProfiler::set_slow_threshold. ProfileReport::suggestions() follows the profiler's.
Related Pages
- Errors:
log_format()writes an error with its query context for your logs. - Benchmarking: TideORM's own Criterion benchmarks.
- Query Cache: the cache keeps its own hit and miss statistics.
Project Rules
Project rules let a team write down the shape its models and queries must keep, such as "no model over 20 columns", "at most 2 JSON columns per model" or "no raw SQL", and have TideORM refuse whatever breaks them. Model rules fail the build; query rules fail the query before it is sent.
Nothing is enforced by default. Without a [rules] table every model and query is allowed.
Writing Rules
Rules go in a [rules] table of tideorm.toml, the file the CLI already reads:
[rules]
max_columns = 20
max_json_columns = 2
max_relation_depth = 3
sensitive_fields = ["password", "token", "secret"]
require_foreign_key_index = true
max_rows = 1000
forbid_raw_sql = true
[rules.allow]
# Exceptions: each model named here is exempt from the rules listed.
LegacyOrder = ["max_columns", "max_json_columns"]
Report = ["forbid_raw_sql"]
A rule left out of [rules], or set to false, is off.
[rules.allow] keys are model struct names without their module path, so two structs of one name share their exceptions; a key naming no model exempts nothing.
TideORM uses the first tideorm.toml it finds, starting in the directory of the crate that declares the models and walking up, so one file at a workspace root covers every member crate. A dependency fetched from crates.io, git or a vendor directory reads none: the rules hold your own models. When crates of one binary read different files, a raw statement that names no model is refused if any of them forbids raw SQL.
Model Rules
Model rules are checked as the models compile, so cargo check, like every build, fails on a model that breaks one. Each broken rule is an error of its own at the model, field or relation that breaks it, naming the rule:
error: Account has 6 columns, over the limit of 5 (max_columns in tideorm.toml)
--> src/models/account.rs:7:12
|
7 | pub struct Account {
| ^^^^^^^
The rules that read a field's type (max_json_columns, primary_key_types, forbid_float_columns) or other models (max_relation_depth, forbid_relation_cycles, require_foreign_key_index) are checked by the compiler as it evaluates constants, so their errors read error[E0080]: evaluation panicked: .. with the same message. Nothing is checked when the application starts.
| Rule | Value | Refuses |
|---|---|---|
max_columns | number | A model with more columns |
max_relations | number | A model declaring more relations |
max_json_columns | number | More JSON/JSONB columns in one model |
max_nullable_columns | number | More nullable columns in one model |
max_indexes | number | More declared indexes, unique ones included |
max_identifier_length | number | A table, column or index name longer than this many bytes (PostgreSQL cuts names at 63) |
snake_case_names | true | A table or column name that is not lowercase snake_case |
avoid_reserved_words | true | A table or column named by an SQL reserved word (order, user, group, ..) |
primary_key_types | list of "integer", "bigint", "uuid", "string" | A primary key column of any other type |
forbid_composite_primary_keys | true | A primary key of several columns |
require_timestamps | true | A model without created_at/updated_at |
require_soft_delete | true | A model without soft delete |
require_foreign_key_index | true | A relation's foreign key column that does not lead an index (or the primary key) of its table |
sensitive_fields | list of words | A column whose name contains one of the words (any case) and that is neither hidden nor encrypted |
forbid_float_columns | true | f32/f64 columns, which round money and counts; use a decimal or an integer |
max_relation_depth | number | A longer chain of owned relations from the model |
forbid_relation_cycles | true | A model that its owned relations lead back to |
Relation depth and cycles follow owned relations only: has_one, has_many, morph_one and morph_many. A belongs_to, has_many_through, morph_to or self-reference points at rows the model does not own, so it adds no depth and closes no cycle; nor does an owned relation to the model's own table (a tree's children), whose depth is in the data. A relation leads to the struct it names, not to other structs reading the same table, and a foreign key must lead an index (or the primary key) that the struct holding the key declares.
Query Rules
Query rules are checked as each query runs, and by validate(). A broken one fails the query with Error::Query before anything is sent.
| Rule | Value | Refuses |
|---|---|---|
max_rows | number, 1 or more | A read of more rows: get(), all(), get_json() or pluck() without a limit() within it, paginate() with a larger page, chunk() with a larger batch, a full-text search() without such a limit(). count(), exists() and aggregates are not limited |
max_joins | number | A query with more joins |
max_in_values | number | A where_in/where_not_in listing more values |
max_eager_depth | number | with("a.b.c") nesting deeper (that one is 3) |
max_eager_relations | number | One eager load resolving more relations, at every level |
forbid_raw_sql | true | Raw SQL: where_raw, select_raw, order_by_raw, having_raw, union_raw, a CTE written as SQL, lag_with_raw_default/lead_with_raw_default, a WindowFunctionType::Custom window function, a batch update's set_trusted_raw, and the raw statements of Database (execute, raw, raw_json, raw_as, their _with_params forms, and the handle forms exec_raw, query_raw, query_raw_json and query_raw_as) |
A query is held to the rules of its own model. A subquery, union operand or CTE is held to its own model's rules too, so where_exists(Report::query().where_raw(..)) runs only if Report may use raw SQL.
To find out whether a query passes before running it, call validate() (see Logging and Profiling).
What the Rules Leave Alone
- TideORM's own statements. The lookups TideORM writes itself (eager loading's key queries, existence checks, pivot reads) are not held to the query rules. A relation's
load()reads all of the relation's rows, and refuses only raw SQL aload_withclosure adds. - Migrations. A migration's statements,
Schema::rawincluded, may be raw SQL. - Raw statements that name no model.
Database::execute,raw_jsonandraw_ashave no model to exempt, so they are refused whenever the project forbids raw SQL, even when some models are exempt.Database::raw::<T>is held toT's rules.
When Rules Change
The rules are read while the models compile and are built into the binary, so changing them needs a rebuild. Cargo rebuilds by itself when an existing tideorm.toml changes. When you create the file for the first time, touch a source file (or run cargo clean -p your-crate) so the models compile again and read it.
A mistake in [rules] (an unknown rule, a wrong value, an exception naming an unknown rule, invalid TOML) is a compile error on each model, naming the file and listing the valid rules.
Testing
This page shows how to test an application built on TideORM: a database per test, fixtures, rolling a test back, running one body on several backends, and code that uses the global database. Testing TideORM Itself at the end lists the commands for working on TideORM.
A Database for Each Test
Give each test its own database and run the code under test inside scope. A call that names no database (User::create, User::query(), user.update()) then uses that database instead of the global one, so tests that run side by side never see each other's rows and need no global setup:
#![allow(unused)] fn main() { use tideorm::prelude::*; /// A fresh in-memory SQLite database with the application's migrations applied. async fn test_db() -> tideorm::Result<Database> { let db = Database::builder().url("sqlite::memory:").build().await?; migrations::all().database(&db).run().await?; // the project's `Migrator` registry Ok(db) } #[tokio::test] async fn renames_a_user() -> tideorm::Result<()> { let db = test_db().await?; db.scope(async { let user = User::create(User { email: "ada@example.com".into(), ..Default::default() }) .await?; let renamed = rename(user.id, "Ada".into()).await?; assert_eq!(renamed.name, "Ada"); Ok(()) }) .await } }
Every connection of a sqlite::memory: pool shares one in-memory database, and each Database built from that URL gets a database of its own, gone when the pool closes. Running the migrations gives the test the same schema as production; Schema Sync and Export is an alternative for a quick test without migrations.
Work the test starts with tokio::spawn runs outside the scope, on the global database: await it inside the scope instead, or give the spawned task the database (db.scope(..) inside it). Several Databases at Once has the rules for which database a call uses.
Seeding Fixtures
Create rows inside the scope, with the model's own API or in one statement with insert_all:
#![allow(unused)] fn main() { db.scope(async { User::insert_all(vec![ User { email: "a@example.com".into(), ..Default::default() }, User { email: "b@example.com".into(), ..Default::default() }, ]) .await?; // ... Ok(()) }) .await?; }
insert_all validates every model but runs no callbacks. A project scaffolded by tideorm init can run its seeders the same way: seeders::all().database(&db).run().await? (see Seeding).
Rolling a Test Back
On a server database every test shares, run the test in test_transaction, which always rolls back everything it wrote and returns what the test returned. Every TideORM call inside joins it, and code under test that opens its own transaction runs as a savepoint inside it, whose commit the rollback undoes too:
#![allow(unused)] fn main() { use tideorm::prelude::*; #[tokio::test] async fn ships_an_order() -> tideorm::Result<()> { let db = Database::builder() .url(std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL")) .build() .await?; db.test_transaction(async { let order = Order::create(Order { quantity: 2, ..Default::default() }).await?; assert!(ship(order.id).await?); Ok(()) }) .await } }
A failed assertion panics, which rolls the transaction back too. A task the test spawns does not join the transaction. See Transactions for savepoints and how calls join the transaction.
The Same Test on Several Backends
Write the body once, taking the database, and call it from one test per backend. Skip a server backend when its URL is not set:
#![allow(unused)] fn main() { use tideorm::prelude::*; async fn creates_users(db: &Database) -> tideorm::Result<()> { db.scope(async { User::create(User { email: "ada@example.com".into(), ..Default::default() }).await?; assert_eq!(User::query().count().await?, 1); Ok(()) }) .await } #[tokio::test] async fn creates_users_on_sqlite() -> tideorm::Result<()> { creates_users(&test_db().await?).await } #[tokio::test] async fn creates_users_on_postgres() -> tideorm::Result<()> { let Ok(url) = std::env::var("TEST_POSTGRES_URL") else { return Ok(()); }; let db = Database::builder().url(url).build().await?; migrations::all().database(&db).run().await?; creates_users(&db).await } }
Each backend's feature must be enabled for its URL to connect (see Installation). Databases lists what differs between them.
Code That Uses the Global Database
Code that calls db() or require_db() itself, or startup code built on TideConfig, needs the global database. Tests of it share one global slot, so run them one at a time (a shared lock, or --test-threads=1) and reset it between tests:
#![allow(unused)] fn main() { Database::reset_global(); TideConfig::reset(); // the tokenization settings too; TokenConfig::reset() clears only those TideConfig::init() .database("sqlite::memory:") .connect() .await?; }
The query logger and the global profiler are process-wide too: call QueryLogger::reset() and GlobalProfiler::reset() in tests that assert on them (see Logging and Profiling).
Checking Migrations in CI
tideorm migrate status --check exits with an error while a migration is pending, so a deploy step can refuse to start an application whose database is behind its code.
Testing TideORM Itself
The commands below test TideORM, not your application. Run them from the tideorm repository and use the smallest one that covers your change:
# Unit tests, default features (PostgreSQL driver, Tokio)
cargo test --lib
# Default features, every target
cargo test --features postgres
# Broad compatibility pass
cargo test --all-features
# SQLite integration suite and smoke test
cargo test --test sqlite_integration_tests --features "sqlite runtime-tokio" --no-default-features
cargo test --test sqlite_ci_smoke_test --features "sqlite runtime-tokio" --no-default-features
# Server integration suites
cargo test --test postgres_integration_tests
cargo test --test mysql_integration_tests --features mysql
cargo test --test mariadb_integration_tests --features mysql
# Compile-fail tests for the derive
cargo test --test relation_compile_fail
# Rebuild the book after documentation changes
mdbook build
The backend suites decide whether to run from the environment, and each backend decides differently:
| Backend | Runs when | Skipped by |
|---|---|---|
| SQLite | Always (in memory) | SKIP_SQLITE_TESTS |
| PostgreSQL | TEST_DATABASE_URL, POSTGRESQL_DATABASE_URL (read in that order) or RUN_POSTGRES_TESTS is set | SKIP_POSTGRES_TESTS |
| MySQL | MYSQL_DATABASE_URL or RUN_MYSQL_TESTS is set | SKIP_MYSQL_TESTS |
| MariaDB | MARIADB_DATABASE_URL or RUN_MARIADB_TESTS is set | SKIP_MARIADB_TESTS |
A backend that is enabled but cannot connect fails its suite instead of passing quietly. The suites create and drop fixed-name tables, so run them one at a time against a shared server. CONTRIBUTING.md has the full list of variables and their default URLs.
Benchmarking
TideORM's own performance is measured with Criterion benchmarks under benches/ in the tideorm repository. This page is for working on TideORM; to measure your application's queries, use Logging and Profiling.
Benchmark one target at a time. A bare cargo bench runs every target the default features allow and takes long, and the ones that need other features or a server are skipped.
Benchmark Targets
| Target | Measures | Needs |
|---|---|---|
validation_benchmarks | Validation rules | Nothing |
stability_benchmarks | Query building and debug() rendering | Nothing |
relations_benchmarks | Eager-load path parsing and relation trees | Nothing |
tokenization_benchmarks | Token encoding and decoding | Nothing |
attachments_translations_benchmarks | File attachment and translation data handling | --features "attachments translations" |
fulltext_benchmarks | Full-text index and query generation for each backend | --features fulltext |
cache_benchmarks | The query cache under realistic workloads, on SQLite | --features sqlite |
crud_benchmarks | Inserts, finds, updates and deletes | A PostgreSQL server |
query_benchmarks | Query-builder reads and subqueries | A PostgreSQL server |
or_clause_benchmarks | OR groups against IN lists | A PostgreSQL server |
A target whose features are not enabled is skipped. The three PostgreSQL targets need the default features (postgres and runtime-tokio).
Running a Benchmark
Targets that need no database:
cargo bench --bench validation_benchmarks
cargo bench --bench stability_benchmarks
cargo bench --bench relations_benchmarks
cargo bench --bench tokenization_benchmarks
cargo bench --bench attachments_translations_benchmarks --features "attachments translations"
cargo bench --bench fulltext_benchmarks --features fulltext
The cache benchmarks open SQLite databases, in memory and in a file under target/:
cargo bench --bench cache_benchmarks --features sqlite
The PostgreSQL targets:
cargo bench --bench crud_benchmarks
cargo bench --bench query_benchmarks
cargo bench --bench or_clause_benchmarks
To type-check every target without running any:
cargo bench --no-run --features "sqlite attachments translations fulltext"
PostgreSQL Benchmarks
The PostgreSQL targets are opt-in, like the PostgreSQL test suites. They run when TEST_DATABASE_URL, POSTGRESQL_DATABASE_URL or RUN_POSTGRES_TESTS is set, and otherwise print Skipping PostgreSQL benchmarks: set POSTGRESQL_DATABASE_URL, TEST_DATABASE_URL or RUN_POSTGRES_TESTS and measure nothing. SKIP_POSTGRES_TESTS turns them off again.
POSTGRESQL_DATABASE_URL=postgres://postgres:postgres@localhost:5432/test_tide_orm \
cargo bench --bench query_benchmarks
The URL is TEST_DATABASE_URL, then POSTGRESQL_DATABASE_URL, then postgres://postgres:postgres@localhost:5432/test_tide_orm when only RUN_POSTGRES_TESTS is set. A .env file in the repository is read too. Once enabled, a benchmark aborts the run if it cannot reach the server.
The benchmarks create their own tables. Keep the server otherwise idle while measuring: other activity swamps small improvements.
Comparing Against a Baseline
Criterion keeps saved baselines, so a performance change can be measured against the code before it on the same target and workload. Save a baseline before the change:
cargo bench --bench query_benchmarks -- --save-baseline before-change
Then run the changed code against it:
cargo bench --bench query_benchmarks -- --baseline before-change
The HTML and raw reports are under target/criterion/. Criterion draws its plots with plotters; installing gnuplot is optional.
Workflow Notes
- Benchmark the smallest relevant target first, and avoid running unrelated targets while narrowing a regression.
- Use
cargo bench --no-runwhen changing shared benchmark support or feature wiring. - When a change affects query shape or SQL generation, pair the benchmark with
debug()and the profiling tools in Logging and Profiling.
Troubleshooting
Common mistakes, what they look like, and the fix.
"Global database connection not initialized"
A model call ran before Database::init, Database::set_global or TideConfig::init()..connect(), or after Database::reset_global(). Connect at startup, before serving requests. db() panics in this case; require_db() returns this error instead, so prefer it outside main. A test can run its code on a database of its own with db.scope(..) and skip the global one (see Testing).
A before_save (or Other Hook) Never Runs
Callbacks are found through the Callbacks trait. A method with the same name in a plain impl User { .. } block compiles and is never called. Move it into impl Callbacks for User { .. } (see Callbacks and Timestamps). Hooks also run only for single-model writes: insert_all, update_all, upserts and query writes (query().delete()) skip them.
conflicting implementations of trait Serialize (E0119)
A #[derive(Serialize, Deserialize)] written above #[tideorm::model], or in the same #[derive(..)] list as Model, conflicts with the serde impls TideORM generates. Put your own derive below the model attribute; TideORM then reads its #[serde(..)] renames and writes JSON keys the way serde would (see Defining Models).
A Model Is Missing from sync, auto_models() or models_matching(..)
Models register themselves when their file is compiled. A file no mod declaration reaches is not compiled, so its models register nothing, and a models_matching pattern that matches no compiled model only logs a warning. Add the mod line.
"requires at least one explicit filter" / "matches every row"
update_all(), query().delete() and the other bulk writes refuse to run without a filter, so a forgotten where_* cannot touch the whole table. A filter that cannot exclude a row (an empty where_not_in, a % pattern, a raw 1 = 1) is refused the same way. Add the filter you meant. To delete every row on purpose, call delete_all().
get() Refuses a select(..)
A query that loads models must select every model column: an unselected Option field would read as None and look like data. Select every column, or read the columns you want with pluck, get_json() or a #[derive(FromQueryResult)] struct through raw_as.
A Spawned Task Does Not See the Transaction's Rows
A transaction follows the future it was given. Work started with tokio::spawn (or async_std::task::spawn) inside it runs on the global database, outside the transaction: it cannot see uncommitted rows and can wait on the transaction's own locks. Await the work inside the transaction, or start it after the transaction ends. See Transactions.
"transaction handle leaked outside the transaction scope"
A clone of the transaction handle outlived the closure, usually by being moved into a spawned task or stored somewhere. The transaction is rolled back. Do not keep the handle: calls inside the closure join the transaction without it.
A DATE or TIMESTAMP Column Fails to Decode on PostgreSQL
PostgreSQL's infinity and -infinity dates and TIME '24:00:00' have no Rust date or time, so a typed read of such a row fails with an error naming the column. Read it with get_json(), which returns them as text, or keep them out of the column.
force_sync Refuses to Run
With TIDEORM_ENV=production, force_sync(true) is refused, because it drops and recreates every registered table. Use migrations in production. To run it anyway, for example against a staging database you mean to empty, set TIDEORM_ALLOW_FORCE_SYNC=true.
The CLI Connects to the Wrong Database
The CLI reads DATABASE_URL from the process environment before the project's env file, so a DATABASE_URL exported in your shell wins over .env. tideorm db status shows where the URL it uses came from. Unset the shell variable, or set the one you mean.
A Query Fails on One Backend Only
Check the SQL TideORM will run, in the backend's own dialect, before running it:
#![allow(unused)] fn main() { let query = User::query().where_eq(User::ACTIVE, true).order_desc(User::ID); println!("{}", query.debug()); println!("{}", query.build_sql_preview_for(DatabaseType::MySQL)); }
Some features exist only on some backends. A query that uses one where it is missing fails when it runs, rather than running without it: a window frame of GROUPS on MySQL or MariaDB is an Error::Query naming the frame, and execute_returning() on MySQL or MariaDB is an Error::BackendNotSupported. Backend Differences lists them. Errors explains how to tell a backend's refusal from a failure worth retrying.
A Query Is Refused by a Project Rule
A tideorm.toml with a [rules] table can refuse raw SQL, unbounded reads, long IN lists and deep eager loads, and fail the build on models that break its model rules. The error names the rule. Exempt the model in [rules.allow] or change the query (see Project Rules).
Statements Are Slow or There Are Too Many
Set TIDE_LOG_QUERIES=true to print every statement, or enable QueryLogger to collect slow ones, and look for one read per row of a list, the sign of a relation loaded in a loop: load it with with(..) instead. See Logging and Profiling.