5

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):

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62

1 Answers1

4

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();
        // ...
    });
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62