Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

diesel

> 数据库
Open source

A safe, extensible ORM and Query Builder for Rust

14.1K stars0 likes0 views
WebsiteGitHub

About

A safe, extensible ORM and Query Builder for Rust

A safe, extensible ORM and Query Builder for Rust

API Documentation: latest release – main branch

Homepage

Diesel gets rid of the boilerplate for database interaction and eliminates runtime errors without sacrificing performance. It takes full advantage of Rust's type system to create a low overhead query builder that "feels like Rust."

Supported databases:

  1. PostgreSQL
  2. MySQL
  3. SQLite
  4. MariaDB

You can configure the database backend in Cargo.toml:

toml
[dependencies]
diesel = { version = "<version>", features = ["<postgres|mysql|sqlite>"] }

Getting Started

Find our extensive Getting Started tutorial at https://diesel.rs/guides/getting-started. Guides on more specific features are coming soon.

Getting help

If you run into problems, you can come ask for help at in our GitHub Discussions forum. This is also the right place to propose new features or show your applications.

Usage

Simple queries

Simple queries are a complete breeze. Loading all users from a database:

rust
users::table.load(&mut connection)

Executed SQL:

sql
SELECT * FROM users;

Loading all the posts for a user:

rust
Post::belonging_to(user).load(&mut connection)

Executed SQL:

sql
SELECT * FROM posts WHERE user_id = 1;

Complex queries

Diesel's powerful query builder helps you construct queries as simple or complex as you need, at zero cost.

rust
let versions = Version::belonging_to(krate)
  .select(id)
  .order(num.desc())
  .limit(5);
let downloads = version_downloads
  .filter(date.gt(now - 90.days()))
  .filter(version_id.eq_any(versions))
  .order(date)
  .load::<Download>(&mut conn)?;

Executed SQL:

sql
SELECT version_downloads.* FROM version_downloads
  WHERE date > (NOW() - '90 days')
    AND version_id = ANY(
      SELECT id FROM versions
        WHERE crate_id = 1
        ORDER BY num DESC
        LIMIT 5
    )
  ORDER BY date

Less boilerplate

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:

rust
#[derive(Queryable, Selectable)]
#[diesel(table_name = downloads)]
pub struct Download {
    id: i32,
    version_id: i32,
    downloads: i32,
    counted: i32,
    date: SystemTime,
}

Instead of this without Diesel:

rust
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"),
        }
    }
}

Inserting data

It's not just about reading data. Diesel makes it easy to use structs for new records.

rust
#[derive(Insertable)]
#[diesel(table_name = users)]
struct NewUser<'a> {
    name: &'a str,
    hair_color: Option<&'a str>,
}

let new_users = vec![
    NewUser { name: "Sean", hair_color: Some("Black") },
    NewUser { name: "Gordon", hair_color: None },
];

insert_into(users)
    .values(&new_users)
    .execute(&mut connection);

Executed SQL:

sql
INSERT INTO users (name, hair_color) VALUES
  ('Sean', 'Black'),
  ('Gordon', DEFAULT)

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.

rust
let new_users = vec![
    NewUser { name: "Sean", hair_color: Some("Black") },
    NewUser { name: "Gordon", hair_color: None },
];

let inserted_users = insert_into(users)
    .values(&new_users)
    .get_results::<User>(&mut connection);

Executed SQL:

sql
INSERT INTO users (name, hair_color) VALUES
  ('Sean', 'Black'),
  ('Gordon', DEFAULT)
  RETURNING *

Updating data

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.

Modifying a struct:

rust
post.published = true;
post.save_changes(&mut connection);

One-off batch changes:

rust
update(users.filter(email.like("%@spammer.com")))
    .set(banned.eq(true))
    .execute(&mut connection)

Using a struct for encapsulation:

rust
update(Settings::belonging_to(current_user))
    .set(&settings_form)
    .execute(&mut connection)

Raw SQL

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.

rust
#[derive(QueryableByName)]
#[diesel(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>(&mut conn)?;

Code of conduct

Anyone who interacts with Diesel in any space, including but not limited to this GitHub repository, must follow our code of conduct.

License

Licensed under either of these:

  • Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
  • MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)

Contributing

Before contributing, please read the contributors guide for useful information about setting up Diesel locally, coding style and common abbreviations.

Unless you explicitly state otherwise, any contribution you intentionally submit for inclusion in the work, as defined in the Apache-2.0 license, shall be dual-licensed as above, without any additional terms or conditions.

Notable Sponsors and Supporters

We would like to thank all of the sponsors supporting the work on Diesel. Notable large sponsors are:

    <br/>
    <sub><b>NLNet Foundation</b></sub>
  </a>
</td>
<td align="center" width="33%">
  <a href="https://www.prototypefund.de/projects/diesel-databaseviews">
    
    <br/>
    <sub><b>Prototype Fund</b></sub>
  </a>
</td>
<td align="center" width="33%">
  <a href="https://github.blog/open-source/maintainers/securing-the-supply-chain-at-scale-starting-with-71-important-open-source-projects/">
    
    <br/>
    <sub><b>GitHub Secure Open Source Fund</b></sub>
  </a>
</td>
    <br/>
    <sub><b>NGI Zero Core</b></sub>
  </a>
</td>
<td align="center" width="33%">
  <a href="https://www.prototypefund.de/projects/diesel-databaseviews">
    
    <br/>
    <sub><b>Federal Ministry of Research, Technology and Space (Germany)</b></sub>
  </a>
</td>
<td align="center" width="33%">
  <a href="https://giga-infosystems.com/">
    
    <br/>
    <sub><b>GiGa Infosystems GmbH</b></sub>
  </a>
</td>
    <br/>
    <sub><b>Bytebase - Open-source Database DevSecOps</b></sub>
  </a>
</td>

Additionally we would like to thank all persons sponsoring the project on GitHub. Without them developing Diesel wouldn't be possible.

Issues· 167 open

View all issuesOpen on GitHub
  • #5224

    Run (some of) the tests via Miri

    enhancementhelp wantedsqlitemysqlpostgresUpdated Sep 30, 2026
  • #5253

    Cannot filter by an outer column inside EXCEPT

    bughole in apiUpdated Sep 26, 2026
  • #5236

    Refine the fuzzer corpus

    help wantedCIUpdated Sep 24, 2026
  • #2099

    [diesel_cli] index out of bounds when running migrations on windows 10 WSL

    bugcliUpdated Sep 24, 2026
  • #3201

    diesel_cli: joinable vanishes when a partition is added in a migration even on a fresh database (no redo)

    bugcliUpdated Sep 24, 2026
  • #3674

    diesel-cli stack overflow when running migration with copy stdin statement.

    bugcliUpdated Sep 24, 2026
  • #5223

    Fuzzing Diesel DSL

    enhancementhelp wantedsqlitemysqlpostgresUpdated Sep 23, 2026
  • #5235

    Error wrappers do not expose consistent source chains

    bughelp wantedUpdated Sep 22, 2026
  • #5221

    Extending fuzzing of the code base

    enhancementhelp wantedsqlitemysqlpostgresUpdated Sep 22, 2026
  • #5219

    Harden SQLite test setup

    enhancementhelp wantedsqliteCIUpdated Sep 18, 2026

> Tags

Rustmysqlormpostgresqlquery-builder

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库