Diesel,
a database ORM in Rust, provides compile-time type checks for its database operations, seamlessly integrating with blazingly fast, robust API applications built with
Axum.
As always, when working with a new technology, some of the details are difficult to remember (assuming you’re not vibe coding the entire app). For example, is it load(&mut conn) or execute(&mut conn) for a select query? This article showcases a few simple queries. It doesn’t try to be a comprehensive tutorial. In the following, upper-case text is meant as a placeholder. The code assumes an auto-generated schema.rs file and a hand-written models.rs file with Rust representations of database data structures.
Select
let values: Vec<SELECTED_TYPE> = schema::TABLE::table
// .inner_join(schema::OTHER_TABLE::table)
.filter(schema::TABLE::FIELD.eq(VALUE))
.select(schema::TABLE::FIELD)
// or .select((schema::TABLE::FIELD, …) )
// or .select(model::TABLE.as_select())
// .offset(OFFSET)
// .limit(LIMIT)
.load(&mut conn)
// .first(&mut conn)
.await?;
Insert
let report_id: i32 = VALUES_OBJECT
.insert_into(schema::TABLE::table)
.returning(schema::TABLE::FIELD)
.get_result(&mut conn)
// or without returning
// .execute(&mut conn)
.await?;
Update
diesel::update(schema::TABLE::table)
.filter(schema::TABLE::FIELD.eq(VALUE))
.set(schema::TABLE::FIELD.eq(VALUE))
.execute(&mut conn)
.await?
This might also interest you