Why did we make Diesel?
Preventing Runtime Errors
We don’t want to waste time tracking down runtime errors. We achieve this by having Diesel eliminate the possibility of incorrect database interactions at compile time.
Built for Performance
Diesel offers a high level query builder and lets you think about your problems in Rust, not SQL. Our focus on zero-cost abstractions allows Diesel to run your query and load your data even faster than C.
Productive and Extensible
Unlike Active Record and other ORMs, Diesel is designed to be abstracted over. Diesel enables you to write reusable code and think in terms of your problem domain and not SQL.
See some examples
Simple queries are a complete breeze. Loading all users from a database:
Loading all the posts for a user:
Diesel’s powerful query builder helps you construct queries as simple or complex as you need, at zero cost.
Diesel codegen generates boilerplate for you. It lets you focus on your business logic, not mapping to and from SQL rows.
That means you can write this:
Instead of this:
pub struct Download {
id: i32,
version_id: i32,
downloads: i32,
counted: i32,
date: SystemTime,
}
impl Download {
fn from_row(row: &Row) -> Download {
Download {
id: row.get("id"),
version_id: row.get("version_id"),
downloads: row.get("downloads"),
counted: row.get("counted"),
date: row.get("date"),
}
}
}
It’s not just about reading data. Diesel makes it easy to use structs for new records.
If you need data from the rows you inserted, just change execute
to get_result
or get_results
. Diesel will take care of the rest.
Diesel’s codegen can generate several ways to update a row, letting you encapsulate your logic in the way that makes sense for your app.
There will always be certain queries that are just easier to write as raw SQL, or can’t be expressed with the query builder. Even in these cases, Diesel provides an easy to use API for writing raw SQL.
#[derive(QueryableByName)]
#[table_name = "users"]
struct User {
id: i32,
name: String,
organization_id: i32,
}
// Using `include_str!` allows us to keep the SQL in a
// separate file, where our editor can give us SQL specific
// syntax highlighting.
sql_query(include_str!("complex_users_by_organization.sql"))
.bind::<Integer, _>(organization_id)
.bind::<BigInt, _>(offset)
.bind::<BigInt, _>(limit)
.load::<User>(conn)?;