How to Use Connection Pooling in Rust

Use the `diesel::r2d2::Pool` struct to manage a fixed number of database connections that are reused across requests. Add the `r2d2` feature to your `diesel` dependency, define a `Connection` type alias, and instantiate the pool with your database URL and a maximum size limit.

How to Use Connection Pooling in Rust

Use the diesel::r2d2::Pool struct to manage a fixed number of database connections that are reused across requests. Add the r2d2 feature to your diesel dependency, define a Connection type alias, and instantiate the pool with your database URL and a maximum size limit.

use diesel::r2d2::{ConnectionManager, PooledConnection};
use diesel::r2d2::Pool;
use diesel::SqliteConnection;

type DbPool = Pool<ConnectionManager<SqliteConnection>>;

fn establish_pool(database_url: &str) -> DbPool {
    let manager = ConnectionManager::<SqliteConnection>::new(database_url);
    Pool::builder()
        .max_size(10)
        .build(manager)
        .expect("Failed to create pool")
}

fn get_connection(pool: &DbPool) -> PooledConnection<ConnectionManager<SqliteConnection>> {
    pool.get().expect("Failed to get connection from pool")
}

fn main() {
    let database_url = "file:example.db?mode=memory";
    let pool = establish_pool(database_url);
    
    let _conn = get_connection(&pool);
    println!("Connection acquired successfully!");
}