Diesel
Diesel is a type-safe ORM and query builder that catches many SQL mistakes at compile time through schema codegen.
Busca en todas las páginas de la documentación
Diesel is a type-safe ORM and query builder that catches many SQL mistakes at compile time through schema codegen.
Quick-reference recipe card - copy-paste ready.
use diesel::prelude::*;
#[derive(Queryable, Selectable)]
#[diesel(table_name = users)]
struct User { id: i64, email: String }
let results = users::table
.filter(users::active.eq(true))
.select(User::as_select())
.load(&mut conn)?;When to reach for this: You want compile-time schema alignment, a rich query builder, and migrations integrated with the ORM - often in sync or spawn_blocking architectures.
use diesel::prelude::*;
use diesel::pg::PgConnection;
diesel::table! {
items (id) {
id -> Int8,
name -> Text,
}
}
#[derive(Queryable, Selectable, Insertable)]
#[diesel(table_name = items)]
struct Item { id: i64, name: String }
#[derive(Insertable)]
#[diesel(table_name = items)]
struct NewItem<'a> { name: &'a str }
fn main() -> QueryResult<()> {
let mut conn = PgConnection::establish(&std::env::var("DATABASE_URL").unwrap())?;
let new = NewItem { name: "widget" };
let inserted: Item = diesel::insert_into(items::table)
.values(&new)
.get_result(&mut conn)?;
let all: Vec<Item> = items::table.load(&mut conn)?;
println!("{:?} {:?}", inserted, all);
Ok(())
}What this demonstrates:
table! macro defines schema at compile time.NewItem for inserts without id.insert_into(...).get_result returns inserted row on PostgreSQL.Queryable + Selectable for reads.diesel print-schema generates schema.rs from live database.spawn_blocking in async Axum handlers or diesel-async for native async.| Topic | Diesel | sqlx |
|---|---|---|
| SQL style | Builder + types | Raw SQL strings |
| Async | diesel-async addon | Native |
| Compile checks | Schema + queries | query! macro |
| Learning curve | Steeper | SQL-first |
// Async with diesel-async (conceptual)
// let users = users::table.load(&mut async_conn).await?;PgConnection in async handler blocks Tokio. Fix: tokio::task::spawn_blocking or diesel-async.diesel migration run and regenerate schema. Fix: Automate in CI.sql_query with bind params.r2d2 pool with Diesel.join or belonging_to loads.
| Alternative | Use When | Don't Use When |
|---|---|---|
| sqlx | Async-first, raw SQL | You want ORM-level type safety |
| SeaORM | Async ORM with Diesel-like ergonomics | Minimal dependency tree |
tokio-postgres | Low-level control | Type-safe queries without macros |
diesel-async provides async connections for PostgreSQL/MySQL.
diesel migration generate + diesel migration run - parallel to sqlx migrate.
Supported for dev/tests; PostgreSQL common in production.
belonging_to, has_many macros with explicit joins.
on_conflict DSL on PostgreSQL and SQLite.
sql_query with bind for escape hatch.
BoxedQuery for dynamic filters in search endpoints.
Map Queryable models to API DTOs at handler boundary.
In-memory SQLite or testcontainers PostgreSQL.
sqlx for async microservices; Diesel for schema-heavy domains with sync tolerance.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026