VasiliNovikov
VasiliNovikov

Reputation: 10256

How to use SQLite via rusqlite from multiple threads?

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

Answers (1)

VasiliNovikov
VasiliNovikov

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

Related Questions