Rust Eloquent π
An Active Record ORM for Rust, inspired by Laravel's Eloquent.
Built on top of sqlx and procedural macros, rust-eloquent aims to bring the delightful and simplistic syntax of Laravel directly to the high-performance Rust ecosystem. It supports PostgreSQL, MySQL, and SQLite universally out of the box using dynamic driver loading!
π Why Rust Eloquent?
In traditional Rust database handling, you have to write raw SQL queries, manage connection pools manually across every function, and bind variables repetitively. Rust Eloquent solves this by abstracting the heavy lifting behind a single #[derive(Eloquent)] macro.
Rust Eloquent v0.2 brings a massive array of enterprise-grade features:
- Constrained Eager Loading for fetching deep relationships safely.
- Global Lifecycle Observers to intercept operations before/after they happen.
- Subqueries & Advanced Joins with multi-constraint
ONclauses. - Artisan Migrations CLI for auto-generating, mapping, and rolling back database schemas.
- Dynamic STDOUT Query Logging for rapid debugging.
- Model Field Serialization & Hiding to strip out secrets.
π οΈ Installation
Add the library to your Cargo.toml:
[]
= "0.2.0"
= { = "1.0", = ["full"] }
π Quick Start
use ;
// 1. Just add the Eloquent macro to your struct!
// Optional: specifies a custom table name
async
β¨ Available Query Builder Methods
The #[derive(Eloquent)] macro injects an entire Query Builder into your model, allowing you to chain methods endlessly.
π Active Record Methods
These methods are called directly on your model instance or struct:
Model::query()-> Starts a new Query Builder instance.Model::find(id: i32)-> Find a single record by its Primary Key (returnsOption).Model::find_or_fail(id: i32)-> Find a single record or throwRowNotFound.Model::all()-> Retrieve an array containing all records.model.save()-> Automatically runs anINSERTorUPDATEdepending on if theidis0.model.delete()-> Deletes the record from the database.
βοΈ Query Filters (Chainable)
You can chain these methods after calling Model::query() to filter your data. All values are automatically bound to prevent SQL Injection:
AND Filters:
.where_eq(column, value).where_not_eq(column, value).where_gt(column, value)/.where_lt(column, value).where_like(column, value)/.where_not_like(column, value).where_null(column)/.where_not_null(column).where_in(column, vec_of_values).where_between(column, min, max)
OR Filters:
.or_where(column, value).or_where_not_eq(column, value).or_where_like(column, value).or_where_in(column, vec_of_values)
π’ Selection & Aggregation
.select_raw("users.*, posts.title")-> Choose specific columns or aliases.group_by(column)-> Add GROUP BY clause.order_by(column)/.order_by_desc(column).limit(value: usize)/.offset(value: usize)
β‘ Executors (Terminal Methods)
End your Query Builder chain with one of these to execute the SQL query asynchronously:
.get().await?-> Returns aVec<Model>matching your filters..first().await?-> ReturnsOption<Model>(automatically appliesLIMIT 1)..paginate(page, per_page).await?-> ReturnsPaginationResult<Model>..count().await?-> Returns ani64representing the number of rows..delete_all().await?-> Deletes all rows matching your filters.
π Advanced Subqueries & Joins
Rust Eloquent provides powerful primitives for complex SQL joins and subqueries, maintaining sqlx binding safety!
Constrained Joins
You can join tables and apply multiple exact matches inside the join clause:
let posts_with_users = query
.join_constrained
.where_eq
.get
.await?;
Subqueries (where_exists)
Inject nested WHERE EXISTS queries natively by passing another query builder:
let active_users = query
.where_exists
.get
.await?;
π‘οΈ Global Lifecycle Observers
You can hook into your modelsβ lifecycle without cluttering your structs! Create an observer and register it globally:
;
// Register your observer once globally:
observe;
Supported Events: saving, saved, creating, created, updating, updated, deleting, deleted.
π Rust Artisan CLI (Migrations & Seeding)
Ship your applications with an integrated database migration architecture running within Rust!
// In your application's CLI entry point:
run_artisan.await;
Commands provided natively:
make:migration create_users_table-> Scaffolds a.rsmigration file using a fluentBlueprintgenerator.migrate-> Executes un-run migrations sequentially against the database.migrate:rollback-> Undoes the previous batch of executed migrations.db:seed-> Iterates through your database Seeders.
π Query Debug Logging
Ever wondered what SQL queries are running under the hood? Toggle STDOUT query logging dynamically at any point!
enable_query_log;
// All queries, limits, offsets, and parameter bindings will print to STDOUT
disable_query_log;
βοΈ Compile-Time Magic Methods
The macro intelligently inspects your struct fields at compile time and generates exclusive methods for each field. If your struct has an email field, you automatically unlock:
.where_email(value).or_where_email(value).where_not_email(value).order_by_email().order_by_email_desc()
This provides an incredible developer experience identical to Laravel!