Module diesel::r2d2

source ·
Available on crate feature r2d2 only.
Expand description

Connection pooling via r2d2.

Note: This module requires enabling the r2d2 feature


The below snippet is a contrived example emulating a web application, where one would first initialize the pool in the main() function (at the start of a long-running process). One would then pass this pool struct around as shared state, which, here, we’ve emulated using threads instead of routes.

use diesel::prelude::*;
use diesel::r2d2::ConnectionManager;
use diesel::r2d2::Pool;
use diesel::result::Error;
use std::thread;

pub fn get_connection_pool() -> Pool<ConnectionManager<DbConnection>> {
    let url = database_url_for_env();
    let manager = ConnectionManager::<DbConnection>::new(url);
    // Refer to the `r2d2` documentation for more methods to use
    // when building a connection pool
        .expect("Could not build connection pool")

pub fn create_user(conn: &mut DbConnection, user_name: &str) -> Result<usize, Error> {
    use schema::users::dsl::*;


fn main() {
    let pool = get_connection_pool();
    let mut threads = vec![];
    let max_users_to_create = 1;

    for i in 0..max_users_to_create {
        let pool = pool.clone();
            move || {
                let conn = &mut pool.get().unwrap();
                let name = format!("Person {}", i);
                create_user(conn, &name).unwrap();

    for handle in threads {

§A note on error handling

When used inside a pool, if an individual connection becomes broken (as determined by the R2D2Connection::is_broken method) then, when the connection goes out of scope, r2d2 will close and return the connection to the DB.

diesel determines broken connections by whether or not the current thread is panicking or if individual Connection structs are broken (determined by the is_broken() method). Generically, these are left to individual backends to implement themselves.

For SQLite, PG, and MySQL backends is_broken() is determined by whether or not the TransactionManagerStatus (as a part of the AnsiTransactionManager struct) is in an InError state or contains an open transaction when the connection goes out of scope.


  • Event subscriptions.



  • The error used when managing connections with r2d2.


  • A trait which allows for customization of connections.
  • A trait which handles errors reported by the ManageConnection.
  • A trait which is provided with information about events in a connection pool.
  • A trait which provides connection-specific functionality.
  • A trait indicating a connection could be used inside a r2d2 pool

Type Aliases§