Thread safety and Connection pooling in duckdb-rs
mainA Connection in duckdb-rs is Send but not Sync. This means you can move a connection between threads, but you cannot share a single connection across multiple threads simultaneously.
To handle multi-threaded applications, you should provide each thread with its own connection. The recommended way to do this is using a connection pool via the r2d2 feature.
Example using r2d2:
use duckdb::{DuckdbConnectionManager, params};
let manager = DuckdbConnectionManager::file("file.db")?;
let pool = r2d2::Pool::new(manager)?;
// Each worker checks out its own connection from the pool.
let conn = pool.get()?;
conn.execute("INSERT INTO foo (bar) VALUES (?)", params![1])?;use duckdb::{DuckdbConnectionManager, params};
let manager = DuckdbConnectionManager::file("file.db")?;
let pool = r2d2::Pool::new(manager)?;
let conn = pool.get()?;
conn.execute("INSERT INTO foo (bar) VALUES (?)", params![1])?;