Skip to main content

Crate sqlmodel

Crate sqlmodel 

Source
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 you Model, Connection, Expr, and the query macros.
  • Facade over sub-crates: wraps sqlmodel-core, sqlmodel-macros, sqlmodel-query, sqlmodel-schema, sqlmodel-session, and sqlmodel-pool.
  • Optional console: feature-gated integration with sqlmodel-console for 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
  • console feature: Enable rich terminal output via sqlmodel-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.
ConnectionConfig
Configuration for database connections.
CreateTable
Builder for CREATE TABLE statements.
Cx
The capability context for a task.
DumpOptions
Options for model_dump() and model_dump_json().
Field
A field reference for type-safe column access.
FieldInfo
Metadata about a model field/column.
FieldsSet
A compact bitset representing “field is set” for indices 0..len.
GetOptions
Options for Session::get_with_options().
Hybrid
A hybrid property wrapper.
InheritanceInfo
Inheritance metadata for a model.
Join
A JOIN clause.
Limit
LIMIT clause.
Migration
A database migration.
MigrationRunner
Migration runner for executing migrations.
ObjectKey
Unique key for an object in the identity map.
Offset
OFFSET clause.
OrderBy
ORDER BY clause.
PolymorphicJoinedSelect
A polymorphic SELECT for joined-table inheritance base + single child.
PolymorphicJoinedSelect2
A polymorphic SELECT for joined-table inheritance base + two children.
PolymorphicJoinedSelect3
A polymorphic SELECT for joined-table inheritance base + three children.
Pool
A connection pool for database connections.
PoolConfig
Connection pool configuration.
PoolStats
Pool statistics.
PooledConnection
A connection borrowed from the pool.
QueryBuilder
Query builder for raw SQL with type-safe parameter binding.
RegionId
A unique identifier for a region in the runtime.
ReplicaPool
A pool that routes reads to replicas and writes to a primary.
Row
A single row returned from a database query.
SchemaBuilder
Builder for multiple schema operations.
Select
A SELECT query builder.
Session
The Session is the central unit-of-work manager.
SessionConfig
Configuration for Session behavior.
SessionDebugInfo
Debug information about session state.
TaskId
A unique identifier for a task in the runtime.
TrackedModel
A model instance with explicit “fields set” tracking.
Transaction
A database transaction (concrete implementation).
ValidateOptions
Options for model_validate().
Where
WHERE clause.

Enums§

BinaryOp
Binary operators.
DumpMode
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.
InheritanceStrategy
Table inheritance strategy.
JoinType
Types of SQL joins.
MigrationStatus
Status of a migration.
ObjectState
State of a tracked object in the session.
Outcome
The four-valued outcome of a concurrent operation.
PolymorphicJoined
Output of a joined-table inheritance polymorphic query with a single child type.
PolymorphicJoined2
Output of a joined-table inheritance polymorphic query with two child types.
PolymorphicJoined3
Output of a joined-table inheritance polymorphic query with three child types.
ReplicaStrategy
Strategy for selecting which replica to use for reads.
SqlType
SQL data types supported by SQLModel.
SslMode
SSL connection mode.
UnaryOp
Unary operators.
ValidateInput
Input types for model_validate().
Value
A dynamically-typed SQL value.

Traits§

Connection
Model
Trait for types that can be mapped to database tables.
ModelDump
Trait for models that support model_dump().
SqlEnum
Trait for Rust enums that map to SQL enum types.
SqlModelDump
Model-aware dump that supports field aliases and computed field exclusion.
SqlModelValidate
Model-aware validation that supports field aliases.
TypeInfo
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§

DumpResult
Result type for model_dump operations.
Result
Result type alias for SQLModel operations.
ValidateResult
Result type for model_validate operations.

Derive Macros§

Model
Derive macro for the Model trait.
SqlEnum
Derive macro for SQL enum types.
Validate
Derive macro for field validation.