FAQ - Help and questions

How do I give each test its own in-memory SQLite database with sqlx?

#sqlx#sqlite#testing#databasepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Open a pool with "sqlite::memory:" in every test: each pool gets its own separate database, and the connections inside one pool share it. The data exists only while a connection stays open, so do not let idle connections close, or the tables disappear between queries.

Checked with rustc 1.93.0, sqlx 0.8.6 (SQLite), tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

sqlite::memory: is the connection string for a database that lives in memory. This program tests three facts about it with sqlx 0.8.6:

src/main.rsrust
use sqlx::sqlite::SqlitePoolOptions;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    // Two pools, each opened with "sqlite::memory:", are two separate databases: handy for tests.
    let one = SqlitePoolOptions::new().connect("sqlite::memory:").await?;
    let two = SqlitePoolOptions::new().connect("sqlite::memory:").await?;
    sqlx::query("CREATE TABLE t (x INTEGER)").execute(&one).await?;
    println!("pool two sees the table of pool one: {}", sqlx::query("SELECT 1 FROM t").fetch_optional(&two).await.is_ok());

    // Inside one pool the connections share the database ...
    let pool = SqlitePoolOptions::new().max_connections(2).connect("sqlite::memory:").await?;
    let mut a = pool.acquire().await?;
    let mut b = pool.acquire().await?;
    sqlx::query("CREATE TABLE t (x INTEGER)").execute(&mut *a).await?;
    println!("second connection of the same pool sees it: {}", sqlx::query("SELECT 1 FROM t").fetch_optional(&mut *b).await.is_ok());
    drop((a, b));

    // ... but the data lives only as long as at least one connection stays open.
    let idle = SqlitePoolOptions::new()
        .min_connections(0)
        .idle_timeout(Duration::from_millis(50))
        .connect("sqlite::memory:").await?;
    sqlx::query("CREATE TABLE t (x INTEGER)").execute(&idle).await?;
    tokio::time::sleep(Duration::from_millis(1500)).await;
    match sqlx::query("SELECT 1 FROM t").fetch_optional(&idle).await {
        Ok(_) => println!("after the idle timeout the table is still there"),
        Err(e) => println!("after the idle timeout: {e}"),
    }
    Ok(())
}
text
pool two sees the table of pool one: false
second connection of the same pool sees it: true
after the idle timeout: error returned from database: (code: 1) no such table: t
  1. Two pools are two databases. The table made through pool one was not visible through pool two. That is what makes it good for tests: run each test against its own pool and tests cannot disturb each other.
  2. Connections of one pool share the database. With max_connections(2), a table made on one connection was visible on the other, so a pool of several connections behaves like one database.
  3. It lives only while a connection is open. With a very short idle timeout, the pool closed its idle connections, and after the wait the table was gone (no such table: t).

Fix for the vanishing table#

Keep one connection checked out for as long as the test needs the data. A connection that is in use is never idle, so the pool does not close it:

src/main.rsrust
use sqlx::sqlite::SqlitePoolOptions;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool = SqlitePoolOptions::new()
        .idle_timeout(Duration::from_millis(50)) // an aggressive timeout, to show the effect
        .connect("sqlite::memory:").await?;
    let _keep_alive = pool.acquire().await?; // a connection that stays checked out is never idle
    sqlx::query("CREATE TABLE t (x INTEGER)").execute(&pool).await?;
    tokio::time::sleep(Duration::from_millis(1500)).await;
    match sqlx::query("SELECT 1 FROM t").fetch_optional(&pool).await {
        Ok(_) => println!("after the idle timeout the table is still there"),
        Err(e) => println!("after the idle timeout: {e}"),
    }
    Ok(())
}
text
after the idle timeout the table is still there

(In this run, min_connections(1) alone did not keep the table alive, so do not rely on it for this.) The idle timeout of 50 ms is deliberately tiny, to show the effect in a short program. Alternatively use a database file in a temporary folder when the test must outlive its connections.

Common mistakes#

  • Creating the schema on a pool and then building a second pool for the code under test. The second one is empty.
  • Sharing one pool between tests that run in parallel, and getting rows from other tests.

Should tests use SQLite when production uses another database?#

SQL dialects and types differ, so SQLite tests cover your logic but not database-specific behaviour. Run some tests against the real kind of database too.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet