sqlorm
An ergonomic, lightweight SQL ORM for Rust with type-safe query building and powerful entity relationships.
Sqlorm is a modern ORM built on top of sqlx that provides compile-time safety, powerful macro-generated APIs, and an intuitive query builder. It's designed for developers who want the performance of sqlx with the convenience of an ORM.
โจ Key Features
- ** Type-Safe **: All queries are checked at compile-time
- ** Zero-Cost Abstraction**: Minimal overhead over raw sqlx
- ** Macro-Powered**: Rich APIs generated from simple struct definitions
- ** Relationships**: Support for
belongs_to
andhas_many
relations with eager/lazy loading - ** Automatic Timestamps**: Built-in
created_at
/updated_at
handling - ** Multi-Database**: PostgreSQL and SQLite support
- ** Powerful Querying**: Fluent query builder with comprehensive filtering
๐ Quick Start
Installation
Add to your Cargo.toml
:
[]
= { = "0.4", = ["postgres", "uuid" ] }
# Or for SQLite:
# sqlorm = { version = "0.4", features = ["sqlite", "uuid" ] }
= { = "0.8", = ["postgres", "runtime-tokio-rustls"] }
= { = "1.0", = ["full"] }
= { = "0.4", = ["serde"] }
= { = "1.0", = ["v4", "serde"] }
= { = "1.0", = ["derive"] }
Database Support
Choose one feature:
postgres
- PostgreSQL supportsqlite
- SQLite support
Optional features:
uuid
- UUID supportextra-traits
- Additional trait derivations
Your First Entity
use *;
use ;
๐ Usage Examples
Basic CRUD Operations
use *;
async
Advanced Querying
SQLOrm provides a powerful, type-safe query builder:
// Simple filtering
let active_users = query
.filter
.fetch_all
.await?;
// Comparison operators
let recent_users = query
.filter
.filter
.fetch_all
.await?;
// Pattern matching
let rust_developers = query
.filter
.fetch_all
.await?;
// Multiple conditions
let specific_users = query
.filter
.filter
.fetch_all
.await?;
// Range queries
let mid_range_users = query
.filter
.fetch_one // Get first result
.await?;
// NULL checks
let users_without_bio = query
.filter
.fetch_all
.await?;
Selective Field Queries
Optimize your queries by selecting only needed fields:
// Select specific fields as tuple
let : = query
.filter
.select
.fetch_one_as
.await?;
// Select multiple fields
let user_summaries: = query
.select
.fetch_all_as
.await?;
Relationships
Define and work with entity relationships:
// Lazy loading - fetch related data when needed
let user = find_by_id.await?.expect;
let user_posts = user.posts.await?; // Separate query
let post = find_by_id.await?.expect;
let author = post.author.await?.expect;
// Eager loading - fetch related data in one query
let user_with_posts = query
.filter
.with_posts // JOIN posts in single query
.fetch_one
.await?;
let posts = user_with_posts.posts.expect;
let post_with_author = query
.filter
.with_author
.fetch_one
.await?;
let author = post_with_author.author.expect;
Automatic Timestamps
SQLOrm automatically handles timestamp fields:
// Custom timestamp functions
pub created_at: i64, // Unix timestamp
Multiple Primary Key Types
SQLOrm supports various primary key types:
use Uuid;
// Auto-incrementing integer
// UUID primary key
// Custom primary key
Working with Options and Different Types
๐๏ธ Architecture
SQLOrm is built with a modular architecture:
โโโโโโโโโโโโโโโโโโโ
โ sqlorm โ โ Main crate (user-facing API)
โโโโโโโโโโโโโโโโโโโ
โ
โโโโโโดโโโโโโฌโโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโผโโโโ โโโโโโผโโโโโ โโโโโโโโโโโผโโโ
โ core โ โ macros โ โ sqlx โ
โโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโ
sqlorm
: Main crate with public APIsqlorm-core
: Query builder and core traitssqlorm-macros
: Procedural macros for code generationsqlx
: Underlying database driver
๐ง Generated API Reference
The #[table]
macro generates extensive APIs for each entity:
Core Methods
save()
- Insert or update (smart detection)insert()
- Force insertupdate()
- Force updatefind_by_id()
- Find by primary keyfind_by_<unique_field>()
- Find by unique fields
Query Builder
query()
- Start query builderfilter()
- Add WHERE conditionsselect()
- Specify columns to fetchfetch_one()
- Get single resultfetch_all()
- Get all resultsfetch_one_as()
- Get result as tuple/custom typefetch_all_as()
- Get results as Vec of tuples/custom type
Filter Operators
eq()
/ne()
- Equality / Not equalgt()
/ge()
- Greater than / Greater equallt()
/le()
- Less than / Less equallike()
- Pattern matchingin_()
/not_in()
- List membershipbetween()
/not_between()
- Range queriesis_null()
/is_not_null()
- NULL checks
Relationships (when defined)
<relation_name>()
- Lazy load related entitieswith_<relation_name>()
- Eager load in query builder
๐ Attribute Reference
Table Attributes
// Use struct name as table name
// Custom table name
Field Attributes
// Primary key
// Unique constraint
// Auto timestamp
// Belongs to
// Has many
๐งช Testing
# Test with PostgreSQL
# Test with SQLite
# Run examples
๐ More Examples
Check the examples/
directory for complete working examples:
basic
: Simple CRUD operationscrud
: Comprehensive CRUD with multiple entitiesrelations
: Working with entity relationships
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request. Make sure to:
- Run tests with both database features
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
๐ License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
๐ Acknowledgments
Built on the excellent sqlx crate. Inspired by Rails Active Record and Laravel Eloquent.