Expand description
SQLModel Rust - SQL databases in Rust, designed to be intuitive and type-safe.
sqlmodel is the facade crate for the entire SQLModel Rust ecosystem. It re-exports
the core traits, macros, query builders, schema/migration tooling, session layer, pooling,
and optional console integration so most applications only need a single dependency.
§Role In The Architecture
- One-stop import:
use sqlmodel::prelude::*;gives youModel,Connection,Expr, and the query macros. - Facade over sub-crates: wraps
sqlmodel-core,sqlmodel-macros,sqlmodel-query,sqlmodel-schema,sqlmodel-session, andsqlmodel-pool. - Optional console: feature-gated integration with
sqlmodel-consolefor rich output.
§When To Use This Crate
Use sqlmodel for nearly all application code. Reach for the sub-crates directly only
if you’re extending internals or building an alternative facade.
§Quick Start
ⓘ
use sqlmodel::prelude::*;
#[derive(Model, Debug)]
#[sqlmodel(table = "heroes")]
struct Hero {
#[sqlmodel(primary_key, auto_increment)]
id: Option<i64>,
name: String,
secret_name: String,
age: Option<i32>,
}
async fn main_example(cx: &Cx, conn: &impl Connection) -> Outcome<(), Error> {
let hero = Hero {
id: None,
name: "Spider-Man".to_string(),
secret_name: "Peter Parker".to_string(),
age: Some(25),
};
let _id = match insert!(hero).execute(cx, conn).await {
Outcome::Ok(v) => v,
Outcome::Err(e) => return Outcome::Err(e),
Outcome::Cancelled(r) => return Outcome::Cancelled(r),
Outcome::Panicked(p) => return Outcome::Panicked(p),
};
let heroes = match select!(Hero)
.filter(Expr::col("age").gt(18))
.all(cx, conn)
.await
{
Outcome::Ok(v) => v,
Outcome::Err(e) => return Outcome::Err(e),
Outcome::Cancelled(r) => return Outcome::Cancelled(r),
Outcome::Panicked(p) => return Outcome::Panicked(p),
};
let Some(mut hero) = heroes.into_iter().next() else {
return Outcome::Ok(());
};
hero.age = Some(26);
match update!(hero).execute(cx, conn).await {
Outcome::Ok(_) => {}
Outcome::Err(e) => return Outcome::Err(e),
Outcome::Cancelled(r) => return Outcome::Cancelled(r),
Outcome::Panicked(p) => return Outcome::Panicked(p),
};
match delete!(Hero)
.filter(Expr::col("name").eq("Spider-Man"))
.execute(cx, conn)
.await
{
Outcome::Ok(_) => Outcome::Ok(()),
Outcome::Err(e) => Outcome::Err(e),
Outcome::Cancelled(r) => Outcome::Cancelled(r),
Outcome::Panicked(p) => Outcome::Panicked(p),
}
}§Features
- Zero-cost abstractions: Compile-time code generation, no runtime reflection
- Structured concurrency: Built on asupersync for cancel-correct operations
- Type safety: SQL types mapped to Rust types with compile-time checks
- Fluent API: Chainable query builder methods
- Connection pooling: Efficient connection reuse
- Migrations: Version-controlled schema changes
consolefeature: Enable rich terminal output viasqlmodel-console
Re-exports§
pub use connection_session::ConnectionSession;pub use connection_session::ConnectionSessionBuilder;
Modules§
- connection_
session - Connection session management for SQLModel Rust.
- prelude
- Prelude module for convenient imports.
- select
- SELECT query builder.
- session
- ORM session re-exports.
Macros§
- delete
- Create a DELETE query for a model.
- insert
- Create an INSERT query for a model.
- select
- Create a SELECT query for a model.
- tracked
- Wrap a model struct literal and track which fields were explicitly provided.
- update
- Create an UPDATE query for a model.
Structs§
- Budget
- A budget constraining resource usage for a task or region.
- Connection
Config - Configuration for database connections.
- Create
Table - Builder for CREATE TABLE statements.
- Cx
- The capability context for a task.
- Dump
Options - Options for model_dump() and model_dump_json().
- Field
- A field reference for type-safe column access.
- Field
Info - Metadata about a model field/column.
- Fields
Set - A compact bitset representing “field is set” for indices
0..len. - GetOptions
- Options for
Session::get_with_options(). - Hybrid
- A hybrid property wrapper.
- Inheritance
Info - Inheritance metadata for a model.
- Join
- A JOIN clause.
- Limit
- LIMIT clause.
- Migration
- A database migration.
- Migration
Runner - Migration runner for executing migrations.
- Object
Key - Unique key for an object in the identity map.
- Offset
- OFFSET clause.
- OrderBy
- ORDER BY clause.
- Polymorphic
Joined Select - A polymorphic SELECT for joined-table inheritance base + single child.
- Polymorphic
Joined Select2 - A polymorphic SELECT for joined-table inheritance base + two children.
- Polymorphic
Joined Select3 - A polymorphic SELECT for joined-table inheritance base + three children.
- Pool
- A connection pool for database connections.
- Pool
Config - Connection pool configuration.
- Pool
Stats - Pool statistics.
- Pooled
Connection - A connection borrowed from the pool.
- Query
Builder - Query builder for raw SQL with type-safe parameter binding.
- Region
Id - A unique identifier for a region in the runtime.
- Replica
Pool - A pool that routes reads to replicas and writes to a primary.
- Row
- A single row returned from a database query.
- Schema
Builder - Builder for multiple schema operations.
- Select
- A SELECT query builder.
- Session
- The Session is the central unit-of-work manager.
- Session
Config - Configuration for Session behavior.
- Session
Debug Info - Debug information about session state.
- TaskId
- A unique identifier for a task in the runtime.
- Tracked
Model - A model instance with explicit “fields set” tracking.
- Transaction
- A database transaction (concrete implementation).
- Validate
Options - Options for model_validate().
- Where
- WHERE clause.
Enums§
- Binary
Op - Binary operators.
- Dump
Mode - Output mode for model_dump().
- Error
- The primary error type for all SQLModel operations.
- Expr
- A SQL expression that can be used in WHERE, HAVING, etc.
- Inheritance
Strategy - Table inheritance strategy.
- Join
Type - Types of SQL joins.
- Migration
Status - Status of a migration.
- Object
State - State of a tracked object in the session.
- Outcome
- The four-valued outcome of a concurrent operation.
- Polymorphic
Joined - Output of a joined-table inheritance polymorphic query with a single child type.
- Polymorphic
Joined2 - Output of a joined-table inheritance polymorphic query with two child types.
- Polymorphic
Joined3 - Output of a joined-table inheritance polymorphic query with three child types.
- Replica
Strategy - Strategy for selecting which replica to use for reads.
- SqlType
- SQL data types supported by SQLModel.
- SslMode
- SSL connection mode.
- UnaryOp
- Unary operators.
- Validate
Input - Input types for model_validate().
- Value
- A dynamically-typed SQL value.
Traits§
- Connection
- Model
- Trait for types that can be mapped to database tables.
- Model
Dump - Trait for models that support model_dump().
- SqlEnum
- Trait for Rust enums that map to SQL enum types.
- SqlModel
Dump - Model-aware dump that supports field aliases and computed field exclusion.
- SqlModel
Validate - Model-aware validation that supports field aliases.
- Type
Info - Trait for types that have a corresponding SQL type.
Functions§
- create_
all - Create all tables for the given models.
- create_
table - Create a table for a model type.
- drop_
table - Drop a table.
- raw_
execute - Raw SQL statement execution.
- raw_
query - Raw SQL query execution.
Type Aliases§
- Dump
Result - Result type for model_dump operations.
- Result
- Result type alias for SQLModel operations.
- Validate
Result - Result type for model_validate operations.