Skip to content
Proyek

Tentang

Async ActiveRecord ORM for Rust: your structs are the models, relations are fields, and typed queries catch mistakes at compile time. PostgreSQL, MySQL, MariaDB, SQLite, CockroachDB, YugabyteDB, TiDB and Vitess.

Data dan analisis

Cara angka ini diukur

Yang dapat Anda lakukan

  • Clean Model Definitions - Simple #[tideorm::model(table = "...")] attribute macro
  • Field-Declared Relations - HasOne, HasMany, BelongsTo, and HasManyThrough relations are defined directly on the model
  • Eager Loading - Batch relation loading with query().with(...) and nested eager paths to avoid N+1 lookups
  • Chunked Reads - Process large result sets with query().chunk(...) instead of loading every row at once, and page an API by key with cursor_paginate()

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
0
dalam 15 hari
0
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

TideORM

Database code for Rust without the boilerplate. A TideORM model is your own struct: one attribute maps it to a table, its relations are fields, and its typed columns turn a misspelled column or a wrong-typed value into a compile error. The same code runs on PostgreSQL, MySQL, MariaDB and SQLite, and on CockroachDB, YugabyteDB, TiDB and Vitess.

CI Website Rust License

#[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>,
}

// Active users and their posts: one query for the users, one for all their posts
let users = User::query()
    .where_eq(User::ACTIVE, true)
    .with(User::POSTS)
    .order_desc(User::ID)
    .limit(10)
    .get()
    .await?;

Why TideORM

  • Models are plain structs. No separate entity, active-model or column types to write and keep in step.
  • Relations are fields. HasOne, HasMany, BelongsTo and HasManyThrough load lazily, or in batches with with(..) so a list never costs a query per row.
  • Mistakes fail to compile. Typed columns check column names and value types, and opt-in project rules in tideorm.toml check your models as they compile.
  • Updates write what changed. Loaded models track their changes, and update() sends only those columns.
  • Everything around the queries. Migrations, seeding, validation, callbacks, soft deletes, transactions, and the tideorm CLI that scaffolds them.
  • One codebase, many databases. The dialect comes from the connection URL.

The Quick Start is a complete program; Features lists everything else.

Quick Start

[dependencies]
tideorm = { version = "0.19.0", default-features = false, features = ["sqlite", "runtime-tokio"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
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,

    // Relations are struct fields, not columns
    #[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::model(table = "posts")]
pub struct Post {
    #[tideorm(primary_key, auto_increment)]
    pub id: i64,
    pub user_id: i64,
    pub title: String,

    #[tideorm(belongs_to = "User", foreign_key = "user_id")]
    pub author: BelongsTo<User>,
}

#[tokio::main]
async fn main() -> tideorm::Result<()> {
    // An in-memory SQLite database; sync(true) creates the tables (development only)
    TideConfig::init()
        .database("sqlite::memory:")
        .max_connections(1)
        .models::<(User, Profile, Post)>()
        .sync(true)
        .connect()
        .await?;

    // Create: a key of 0 is numbered by the database
    let user = User {
        email: "[email protected]".into(),
        name: "Jane".into(),
        active: true,
        ..Default::default()
    }
    .save()
    .await?;
    let bio = "Writes about Rust".to_string();
    Profile::create(Profile { user_id: user.id, bio, ..Default::default() }).await?;
    for title in ["Hello", "Typed columns"] {
        let title = title.to_string();
        Post::create(Post { user_id: user.id, title, ..Default::default() }).await?;
    }

    // Query with the generated typed columns: a misspelled column or a value
    // of the wrong type is a compile error
    let found = User::query()
        .where_eq(User::ACTIVE, true)
        .where_any(|any| {
            any.where_contains(User::NAME, "Jane")
                .where_ends_with(User::EMAIL, "@example.org")
        }) // active = true AND (name LIKE '%Jane%' OR email LIKE '%@example.org')
        .order_desc(User::ID)
        .limit(10)
        .get()
        .await?;
    println!("found {} user(s)", found.len());

    // Load a relation lazily...
    let posts = user.posts.load().await?;
    println!("{} wrote {} posts", user.name, posts.len());

    // ...or batch-load relations with the query
    let users = User::query().with(User::PROFILE).with(User::POSTS).get().await?;
    let profile = users[0].profile.get_cached();
    println!("bio: {:?}", profile.map(|profile| profile.bio.as_str()));

    // Update writes the columns that changed
    let mut user = User::find(user.id).await?.expect("Jane exists");
    user.name = "Jane Doe".into();
    let user = user.update().await?;

    // One column, read as its field's type (Vec<String>)
    let titles = Post::query()
        .where_eq(Post::USER_ID, user.id)
        .order_asc(Post::ID)
        .pluck(Post::TITLE)
        .await?;
    println!("titles: {titles:?}");

    // Delete
    Post::query().where_eq(Post::USER_ID, user.id).delete().await?;
    Profile::query().where_eq(Profile::USER_ID, user.id).delete().await?;
    user.delete().await?;
    println!("users left: {}", User::query().count().await?);
    Ok(())
}

It prints:

found 1 user(s)
Jane wrote 2 posts
bio: Some("Writes about Rust")
titles: ["Hello", "Typed columns"]
users left: 0

Swap the sqlite feature and the URL for postgres (postgres://user:pass@localhost/app) or mysql to run the same program on another backend; Installation lists the feature sets.

The global connection the quick start sets up is a default, not a limit. Database::connect(url) opens another database, User::query_with(&replica) reads from it, and tenant_db.scope(async { .. }) runs every model call inside the block on it, so no handle has to be threaded through your code; see Several Databases at Once.

Relation helper fields like HasOne<T> and HasMany<T> are runtime-only wrappers, not persisted columns. TideORM's generated serde support serializes their cached payloads when present and rebuilds the runtime wrappers on deserialize, so round-tripped JSON can preserve loaded relations without turning the wrappers themselves into stored schema fields.

Composite primary keys are supported by marking multiple fields with #[tideorm(primary_key)]. Composite keys are used as tuples in CRUD APIs, for example UserRole::find((user_id, role_id)). auto_increment and tokenization remain single-primary-key features.

For batch inserts, use Model::insert_all(...). It is TideORM's single bulk-insert API and returns the inserted models with database-generated values populated when the active backend supports or emulates that behavior. Every model is validated before any is written, and a batch too large for one statement's bind parameters is split across several inside a transaction.

For tests and reconfiguration-heavy workflows, TideORM's global state is resettable. Use Database::reset_global() and TideConfig::reset() (which also clears the tokenization settings) before applying a fresh setup.

For aggregate workflows with an explicit persistence context, enable the entity-manager feature and see docs/entity-manager.md.

Features

  • Clean Model Definitions - Simple #[tideorm::model(table = "...")] attribute macro
  • Field-Declared Relations - HasOne, HasMany, BelongsTo, and HasManyThrough relations are defined directly on the model
  • Eager Loading - Batch relation loading with query().with(...) and nested eager paths to avoid N+1 lookups
  • Chunked Reads - Process large result sets with query().chunk(...) instead of loading every row at once, and page an API by key with cursor_paginate()
  • Named Query Scopes - Declare model-local #[tideorm::scopes] methods for chains like User::query().active().verified()
  • Dirty Tracking - Loaded models report changed_fields() and original_value(), and update() writes only the columns that changed
  • Async-First - Built for modern async/await workflows
  • Auto Schema Sync - Automatic table management during development
  • Multi-Database - PostgreSQL, MySQL, MariaDB and SQLite, plus CockroachDB, YugabyteDB, TiDB and Vitess through the PostgreSQL and MySQL drivers (Compatible Servers)
  • Several Databases at Once - The global connection is only the default: Database::connect(url) opens more, and db.scope(async { .. }) runs every model call inside it on that database, for tenants and replicas
  • Query Builder - Fluent filtering, OR groups, joins, unions, CTEs, and window functions
  • Typed Results - Aggregates read as the type you ask for (sum::<Decimal>, min::<DateTime<Utc>>), pluck/value read one column, get_as::<T>() reads rows into your own struct, and paginate() returns a page with its total
  • Project Rules - Opt-in limits in tideorm.toml (max_columns = 20, max_json_columns = 2, forbid_raw_sql = true, ..) that every model (as cargo check compiles it) and query is held to, with per-model exceptions
  • Profiling & Logging - Built-in query logging plus execution counters and slow-query stats
  • Data Lifecycle Tools - Migrations, seeding, validation, callbacks, soft deletes, and transactions
  • Entity Manager - Optional persistence context for aggregate workflows and managed entity lifecycles
  • Optional Modules - Attachments, translations, and full-text search are available behind feature flags
  • Field Encryption - Optional encrypted-fields feature for model-level encrypted columns that automatically encrypt on write and decrypt on load using TideORM's configured encryption key
  • Tokenization - Secure record ID encoding/decoding helpers

Encrypted Fields

Enable the encrypted-fields Cargo feature before using model-level auto-encryption.

Use model-level encrypted fields when you want selected persisted columns, such as phone numbers or other sensitive values, to be stored encrypted in the database while keeping their own plaintext type in Rust.

[dependencies]
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "encrypted-fields"] }
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>,
}

TideConfig::init()
    .database("sqlite://./app.db")
    .encryption_key("replace-with-a-long-random-secret")
    .connect()
    .await?;

Encrypted field notes:

  • encrypted = "..." is separate from #[tideorm(tokenize)]; it uses the same configured encryption key and crypto primitives, but it protects normal model columns instead of record IDs.
  • Each encrypted field uses a scoped key derived from the configured encryption secret plus the model table and column name, so ciphertext from one attribute does not decrypt under another attribute's context.
  • TideORM encrypts these fields before create(), save(), update(), insert_all(), nested saves, and batch update_all().set(...) writes.
  • TideORM decrypts these fields automatically when loading models through normal queries, eager loads, and raw model hydration.
  • Encrypted columns must contain TideORM encrypted payloads or NULL. Plaintext legacy rows and older global-scope payloads are rejected on load; migrate that data explicitly before enabling the feature.
  • Query predicates are not rewritten yet. Filters such as where_eq("customer_phone_number", "...") still compare against the stored database value, so plaintext lookups on encrypted columns are not currently transparent.
  • An encrypted field can have any type that implements Serialize and Deserialize; its column stores the encrypted JSON of the value as text (TEXT, whatever the field's type), and None as NULL.

Installation

Every snippet below sets default-features = false and names its backend and runtime explicitly. The default feature set is ["postgres", "runtime-tokio"], so a MySQL- or SQLite-only project that leaves the defaults on still compiles the whole PostgreSQL driver stack.

[dependencies]
# PostgreSQL
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio"] }

# MySQL / MariaDB
tideorm = { version = "0.19.0", default-features = false, features = ["mysql", "runtime-tokio"] }

# SQLite
tideorm = { version = "0.19.0", default-features = false, features = ["sqlite", "runtime-tokio"] }

# Enable attachments support explicitly
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "attachments"] }

# Enable translations support explicitly
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "translations"] }

# Enable full-text search support explicitly
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "fulltext"] }

# Enable the entity manager explicitly
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "entity-manager"] }

# Enable model encrypted fields explicitly
tideorm = { version = "0.19.0", default-features = false, features = ["postgres", "runtime-tokio", "encrypted-fields"] }

Swap runtime-tokio for runtime-async-std if you run on async-std.

What else your crate needs

Nothing, for the models themselves: the code #[tideorm::model] generates reaches serde, serde_json and chrono through TideORM. Add serde if your own code derives Serialize/Deserialize, and chrono if you spell a column type with an explicit chrono:: path — the DateTime<Utc> re-exported from tideorm::prelude works without it.

Feature Flags

Feature Description
postgres PostgreSQL support (default)
mysql MySQL/MariaDB support
sqlite SQLite support
mariadb, tidb, vitess The same as mysql, named after the server you use
cockroachdb, yugabytedb The same as postgres, named after the server you use
runtime-tokio Tokio runtime (default)
runtime-async-std async-std runtime
attachments Compile-time-only feature gate for the attachments API and attachment-specific benchmarks/tests; adds no extra dependencies
translations Compile-time-only feature gate for the translations API and translation-specific benchmarks/tests; adds no extra dependencies
fulltext Compile-time-only feature gate for the full-text search API and fulltext-specific benchmarks/tests; adds no extra dependencies
entity-manager Enables the EntityManager facade (find, find_managed, load, save, persist, merge, remove, detach, flush), entity-manager-aware relation loads, and aggregate synchronization for loaded HasOne, HasMany, and HasManyThrough relations
encrypted-fields Enables #[tideorm(encrypted = "...")] model auto-encrypt/decrypt hooks for persisted columns of any serializable type

Attachments are opt-in. Enable the attachments feature when you want to use tideorm::attachments, HasAttachments, or attachment URL generation helpers. This is a compile-time API gate only; it does not pull in additional crates.

Translations are opt-in. Enable the translations feature when you want to use tideorm::translations, HasTranslations, or ApplyTranslations. This is a compile-time API gate only; it does not pull in additional crates.

Full-text search is opt-in. Enable the fulltext feature when you want to use tideorm::fulltext, FullTextSearch, or the highlighting helpers. This is a compile-time API gate only; it does not pull in additional crates.

The entity manager is opt-in. Enable the entity-manager feature when you want an explicit persistence context for aggregate workflows: entity_manager.find::<Model>(...), entity_manager.find_managed::<Model>(...), entity_manager.load(&mut relation), entity_manager.save(&model), and managed lifecycle operations such as persist, merge, remove, detach, and flush. See docs/entity-manager.md for the full workflow.

Model encrypted fields are opt-in. Enable the encrypted-fields feature when you want #[tideorm(encrypted = "...")] to automatically encrypt configured columns on writes and decrypt them on model loads.

Schema sync can also register compiled models by source path with glob-style patterns such as models_matching("src/models/*") or models_matching("src/models/*.model.rs"). The matching files still need to be part of the crate through normal Rust mod declarations because TideORM filters compiled model metadata rather than loading source files dynamically.

Documentation

#[tideorm::model] generates typed constants such as User::ACTIVE and relation names such as User::POSTS. where_eq(User::ACTIVE, true) checks the value's Rust type; passing "yes" fails to compile. String column names remain supported. with(User::relations.posts.then(Post::relations.comments)) loads a typed relation path, and a relation of another model fails to compile. Use .auto_models() to discover linked models without depending on file layout, or .models::<User>() / .models::<(User, Post)>() to select a subset for schema sync.

Rust 1.94 is the minimum supported version, declared in the rust-version of every TideORM crate (macros, engine, SQL builder and drivers included) and verified in CI. Select the toolchain with cargo +1.94.0.

The docs now ship as an mdBook.

Core chapters:

  • Installation - Cargo features for backends, runtimes and optional modules
  • Quick Start - A complete SQLite program, migrations, and the runnable examples
  • Configuration - Connecting, pool and driver options, pinned sessions, and environment variables
  • Databases - Backend detection, several databases at once, type mappings, and backend differences
  • Models - Model definition and attributes, with CRUD, validation, callbacks, soft deletes, typed columns, encrypted fields and tokenization in the pages under it
  • Queries - The query builder, with advanced SQL, JSON and arrays, full-text search, raw SQL and the query cache in the pages under it
  • Relations - Field-declared relations, attachments, translations, and runtime relation wrappers
  • Entity Manager - Persistence-context identity map, aggregate synchronization helpers, and managed entity lifecycle operations
  • Transactions - Transactions, savepoints, and how model calls join them
  • Migrations - Schema builder column types and migration authoring, with seeding and schema sync on their own pages
  • Errors - Error variants, database failure kinds, retries, and answering a request
  • Logging and Profiling - Query debugging, query logging, global timing, manual reports, and query analysis
  • Project Rules - Opt-in limits on models and queries, written in tideorm.toml, with per-model exceptions
  • Testing - Testing an application built on TideORM, and TideORM's own suites
  • Benchmarking - Benchmark target matrix, PostgreSQL setup, feature-gated bench commands, and Criterion baseline workflow

Ecosystem

This repository is the core TideORM library. Related projects live separately:

Examples

For a runnable example of each feature, see tideorm-examples.

Testing

Start with the smallest command that covers your change. CI also runs formatting, linting, library tests, and backend-specific checks.

Common local commands:

# Fast library validation
cargo test --lib

# Full suite for a backend feature set
cargo test --features postgres

# Cross-backend compile/test coverage
cargo test --all-features

# SQLite smoke test
cargo test --test sqlite_ci_smoke_test --features "sqlite runtime-tokio" --no-default-features

The backends do not share gate semantics: SQLite is opt-out (SKIP_SQLITE_TESTS), MySQL is opt-in (RUN_MYSQL_TESTS or MYSQL_DATABASE_URL, overridden by SKIP_MYSQL_TESTS), so is MariaDB (the same with MARIADB), and PostgreSQL is opt-in as well (TEST_DATABASE_URL, POSTGRESQL_DATABASE_URL or RUN_POSTGRES_TESTS, overridden by SKIP_POSTGRES_TESTS). See CONTRIBUTING.md for the full variable table.

See docs/testing.md for more.

Benchmarking

Always run a single Criterion target; a bare cargo bench is not usable because several targets need a database. query_benchmarks, crud_benchmarks, and or_clause_benchmarks need a live PostgreSQL server and are opt-in like the PostgreSQL tests: they run nothing unless TEST_DATABASE_URL, POSTGRESQL_DATABASE_URL or RUN_POSTGRES_TESTS is set, then connect to the first URL set, falling back to postgres://postgres:postgres@localhost:5432/test_tide_orm, and abort the run if it is unreachable.

Common local commands:

# No database required
cargo bench --bench validation_benchmarks
cargo bench --bench attachments_translations_benchmarks --features "attachments translations"
cargo bench --bench fulltext_benchmarks --features fulltext

# SQLite driver required
cargo bench --bench cache_benchmarks --features sqlite

# Live PostgreSQL server required
cargo bench --bench query_benchmarks
cargo bench --bench crud_benchmarks
cargo bench --bench or_clause_benchmarks

# Compile every bench without running any
cargo bench --no-run --features "sqlite attachments translations fulltext"

See docs/benchmarking.md for the full benchmark matrix and Criterion baseline workflow.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Please review the Contributing Guidelines before opening a pull request.

Please review the Code of Conduct before participating in project discussions or reviews.

Support

If you need usage help or troubleshooting guidance, please review SUPPORT.md and open the appropriate issue type.

Security

If you need to report a suspected vulnerability, please use the private reporting process described in the Security Policy instead of opening a public issue.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Jelajahi proyek terkait

Memuat…