expression

Database integration tests: isolate state

A test against a real database engine checks behavior a fake cannot, including constraints and SQL execution. Each independent in-memory SQLite pool has its own database here. Keep one connection per pool to avoid confusing independent in-memory connections; SQLite does not replace tests against the production engine. Uses a disposable in-memory SQLite database, with no external database. Expected stdout (not executed): second database: 0 Common mistake: Reusing one persistent test database across concurrent tests without isolation.

Formal Syntax & Structure

rust syntaxrust
SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    use sqlx::sqlite::SqlitePoolOptions;    let a = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?;    let b = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?;    for pool in [&a, &b] {        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY)").execute(pool).await?;    }    sqlx::query("INSERT INTO items VALUES (1)").execute(&a).await?;    let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM items").fetch_one(&b).await?;    println!("second database: {count}");    a.close().await;    b.close().await;    Ok(())}
Rust Reference