Reputation: 10256
There are a number of articles explaining the problem of multi-threaded access with SQLite but I couldn't find any easy solutions. How does one access SQLite from e.g. a web server where multiple threads work concurrently?
Sources (that still don't explain any easy work-around):
Upvotes: 6
Views: 4536
Reputation: 10256
You can use r2d2-sqlite
connection pooling + std::sync::Arc
to have multi-threaded access to SQLite. Example:
[dependencies]
r2d2_sqlite = "0.16.0"
r2d2 = "0.8.8"
And in Rust:
fn main() {
let sqlite_file = "my.db";
let sqlite_connection_manager = SqliteConnectionManager::file(sqlite_file);
let sqlite_pool = r2d2::Pool::new(sqlite_connection_manager)
.expect("Failed to create r2d2 SQLite connection pool");
let pool_arc = Arc::new(sqlite_pool);
let pool = pool_arc.clone();
whatever.method(move || {
let connection = pool.get();
// ...
});
let pool = pool_arc.clone();
whatever.method(move || {
let connection = pool.get();
// ...
});
}
Upvotes: 5