sql-orm
What is sql-orm?
sql-orm is a code-first ORM for Rust applications that use Microsoft SQL Server.
It lets you define your database model using Rust structs, derive metadata from those structs, build typed queries, generate SQL Server-specific SQL, run migrations, and execute everything through Tiberius.
Rust structs
↓
Entity metadata
↓
Query AST
↓
SQL Server SQL
↓
Tiberius
↓
Entity / DTO
The goal is to keep application code strongly typed, expressive, and close to your domain while still producing real parameterized SQL Server SQL.
Table of Contents
- Highlights
- When Should You Use It?
- Installation
- Quick Example
- Query Builder
- DTO Projections
- Relationships
- Entity Policies
- Raw SQL
- Migrations
- Architecture
- Current Limits
- Documentation
- Local Validation
Highlights
| Feature | Description |
|---|---|
| Code-first models | Rust structs define database metadata, schema snapshots, and migrations |
| SQL Server-first | Designed specifically for SQL Server syntax, parameters, DDL, and rowversion |
| Typed queries | Build filters, ordering, pagination, joins, includes, and projections safely |
| Derive-based API | Use Entity, Insertable, Changeset, DbContext, and FromRow |
| Safe raw SQL | Execute manual SQL using parameters and typed result mapping |
| Migrations | Generate reviewable SQL from Rust metadata snapshots |
| Entity policies | Declare audit, soft delete, and tenant behavior from model metadata |
| Layered design | Clear separation between metadata, AST, SQL generation, execution, and migrations |
When Should You Use It?
Use sql-orm if you want:
- A Rust-first development experience for SQL Server.
- Code-first schema metadata.
- Typed query construction instead of scattered SQL strings.
- SQL Server-specific behavior instead of a generic multi-database abstraction.
- A clean public API over Tiberius.
- Reviewable migrations generated from model snapshots.
[!NOTE] SQL Server is currently the only supported backend.
[!WARNING] This project is still
0.1.0. Some APIs are experimental or intentionally limited. See Current Limits.
Installation
Use the public root crate:
[]
= "0.1.0"
With optional bb8 pooling support:
[]
= { = "0.1.0", = ["pool-bb8"] }
Import the prelude:
use *;
The prelude exposes the normal user-facing API:
- Public derives
DbContextDbSet- Query extensions
- Error types
- Metadata contracts
- Common SQL values
- Mapping traits
Quick Example
1. Define an entity
use *;
2. Define write models
3. Define a context
4. Insert, find, update, and delete
let db = connect.await?;
let saved = db
.users
.insert
.await?;
let found = db.users.find.await?;
let updated = db
.users
.update
.await?;
let deleted = db.users.delete.await?;
The ORM reads the generated entity metadata, builds the SQL Server statement, binds parameters safely, executes it through Tiberius, and materializes the result back into your Rust type.
Query Builder
Generated columns are typed query symbols.
let active_users = db
.users
.query
.filter
.order_by
.take
.all
.await?;
The query builder produces a neutral AST. SQL Server SQL is generated only by sql-orm-sqlserver.
flowchart LR
A[Typed Rust Query] --> B[Query AST]
B --> C[SQL Server Compiler]
C --> D[Parameterized SQL]
D --> E[Tiberius Execution]
E --> F[Entity / DTO]
DTO Projections
Use DTO projections when you do not need full entities.
use *;
let summaries = db
.users
.query
.select
.
.await?;
DTO projections can use:
- Entity columns
- Aliased expressions
- Explicit joins
- Selected subsets of columns
- Custom
FromRowmappings
Relationships
Relationships are explicit and metadata-driven.
use *;
Include a related entity:
let posts = db
.posts
.query
.?
.all
.await?;
let author = posts.user.as_ref;
Include a collection:
let users = db
.users
.query
.?
.max_joined_rows
.all
.await?;
let posts = users.posts.as_slice;
[!IMPORTANT] Navigation fields do not trigger hidden database I/O when accessed. Lazy wrappers represent loaded or not-loaded state, but they do not store context or execute SQL by themselves.
Entity Policies
Entity policies let you declare cross-cutting behavior from metadata.
flowchart TD
A[Entity Metadata] --> B[Audit Policy]
A --> C[Soft Delete Policy]
A --> D[Tenant Policy]
B --> E[Runtime Inserts / Updates]
C --> F[Query Filters / Delete Behavior]
D --> G[Fail-Closed Tenant Scope]
Auditing
use ;
use *;
Audit columns are part of schema metadata. They do not need to appear as fields on the entity itself.
Soft Delete
#[orm(soft_delete = SoftDelete)] converts public delete operations into logical-delete updates.
Normal queries hide deleted rows by default.
Tenant Scoping
#[orm(tenant = CurrentTenant)] enables fail-closed tenant filters for opt-in entities.
Reads and writes on the root entity apply tenant scoping automatically.
[!CAUTION] Raw SQL and manual joins require explicit tenant and visibility predicates.
Raw SQL
Use raw SQL when the query builder does not model the statement you need yet.
let rows = db
.
.param
.all
.await?;
Execute a command:
let result = db
.raw_exec
.params
.execute
.await?;
| API | Purpose |
|---|---|
raw<T>() |
Query rows and map them into a typed result |
raw_exec() |
Execute commands such as UPDATE, DELETE, or custom SQL |
.param(...) |
Bind a single parameter |
.params(...) |
Bind multiple parameters |
Migrations
The migration flow is based on snapshots and reviewable SQL.
sequenceDiagram
participant Dev as Developer
participant Model as Rust Entities
participant Snapshot as Model Snapshot
participant Diff as Migration Diff
participant SQL as up.sql / down.sql
participant DB as SQL Server
Dev->>Model: Change entities
Model->>Snapshot: Export metadata snapshot
Snapshot->>Diff: Compare previous/current model
Diff->>SQL: Generate migration SQL
Dev->>SQL: Review migration files
SQL->>DB: Apply database update
Create a migration:
Apply pending migrations:
Generated artifacts:
| File | Purpose |
|---|---|
up.sql |
SQL applied when migrating forward |
down.sql |
SQL used to manually review rollback intent |
model_snapshot.json |
Captured model metadata after the migration |
[!NOTE]
migration.rsis not part of the current MVP.
Transactions and Pooling
db.transaction(...) is available on contexts created from a direct connection.
With the optional pool-bb8 feature, transactions from pooled contexts are currently blocked until the runtime can pin a single physical connection for the full transactional closure.
The Tiberius layer exposes configuration for:
- Timeouts
- Retry
- Tracing
- Slow-query logging
- Health checks
- Optional pooling
Architecture
The workspace is split by responsibility.
| Crate | Responsibility |
|---|---|
sql-orm-core |
Contracts, metadata, SQL values, errors, and neutral rows |
sql-orm-macros |
Derives and metadata generation |
sql-orm-query |
Query AST and query-builder primitives |
sql-orm-sqlserver |
SQL Server query and DDL compilation |
sql-orm-tiberius |
Connections, execution, transactions, rows, and pooling |
sql-orm-migrate |
Snapshots, diffs, operations, and migration helpers |
sql-orm-cli |
Migration and database commands |
sql-orm |
Public facade for applications |
flowchart TB
A[sql-orm] --> B[sql-orm-core]
A --> C[sql-orm-macros]
A --> D[sql-orm-query]
D --> E[sql-orm-sqlserver]
E --> F[sql-orm-tiberius]
B --> G[sql-orm-migrate]
G --> H[sql-orm-cli]
This separation keeps each layer focused:
core -> contracts and metadata
query -> AST only
sqlserver -> SQL generation
tiberius -> execution
migrate -> schema evolution
sql-orm -> public API
Current Limits
See docs/stability-audit.md for the updated stability boundaries.
| Area | Current status |
|---|---|
| Backend support | SQL Server only |
Tracked<T> |
Experimental |
save_changes() |
Experimental |
| Composite primary keys | Metadata exists, public persistence support is limited |
| Tracking ownership | Current tracker still depends on live Tracked<T> wrappers |
| Relationship graph persistence | Not implemented; persist dependents or explicit join entities directly |
| Many-to-many navigation | Use an explicit join entity |
| Lazy loading | No automatic I/O from field access |
include_many(...).split_query() |
API exists, execution returns not implemented |
| Raw SQL filters | Tenant and soft-delete filters must be written manually |
database downgrade |
Not implemented yet |
migration.rs |
Deferred |
| Pooled transactions | Blocked until connection pinning is implemented |
Documentation
| Guide | Description |
|---|---|
| Core concepts | Mental model and end-to-end flow |
| Quickstart | Connection, CRUD, and query builder |
| Code-first guide | Entities, derives, DbContext, and metadata |
| Public API | Public surface exported from the root crate |
| Query builder | Filters, ordering, pagination, joins, includes, and projections |
| Navigation properties | belongs_to, has_one, has_many, includes, and limits |
| Typed projections | select(...), all_as::<T>(), aliases, and DTOs |
| Typed raw SQL | raw<T>(), raw_exec(), parameters, and security |
| Relationships | Foreign keys, joins, navigation, and loading |
| Transactions | Runtime behavior and pool limits |
| Migrations | Snapshots, diffs, migration add, and database update |
| Entity policies | Audit, soft delete, tenant, and limits |
| Tracking stability | Stabilization criteria for tracking APIs |
| Use from another project | Use from crates.io or directly from Git |
Examples
[!NOTE] Real SQL Server validation depends on a current
SQL_ORM_TEST_CONNECTION_STRINGorDATABASE_URL; rerun the integration tests and smoke flow before treating a release candidate as freshly validated.
Local Validation
Run standard checks:
Tests against a real SQL Server instance require: