riftenlabs-indexer/src/utiltest.rs
Dagur Valberg Johannsson f421327a5d
Switch to tokio and sqlx
This makes the application fully async; freeing web server threads to
handle new connections when waiting on SQL queries.

Additionally sqlx will allow easier move to a different database if
needed in the future.

Includes some SQL optimizations as well (slow queries more easliy identifiable
with sqlx).
2026-02-18 10:16:51 +01:00

49 lines
1.7 KiB
Rust

// Copyright (C) 2024-2026 Whiterun LLC
//
// This software is licensed under the GNU Affero General Public License (AGPL), version 3.0 or later.
// A copy of the license can be found in the LICENSE file or at https://www.gnu.org/licenses/agpl-3.0.html
#[allow(clippy::items_after_test_module)]
#[cfg(test)]
mod test_utils {
use crate::db::DB;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::SqlitePool;
use std::sync::atomic::{AtomicU64, Ordering};
static DB_COUNTER: AtomicU64 = AtomicU64::new(0);
/// Create an in-memory SqlitePool-based DB for tests.
/// The setup function receives a `SqlitePool` to create tables and seed data.
/// Foreign keys are disabled to match the old rusqlite test behavior.
/// Each call gets a unique shared-cache in-memory database so multiple pool
/// connections share the same data without interfering with other tests.
pub async fn mock_db_pool<F, Fut>(setup_fn: F) -> DB
where
F: FnOnce(SqlitePool) -> Fut,
Fut: std::future::Future<Output = ()>,
{
let id = DB_COUNTER.fetch_add(1, Ordering::SeqCst);
let uri = format!("file:testdb_{}?mode=memory&cache=shared", id);
let opts = SqliteConnectOptions::new()
.filename(&uri)
.foreign_keys(false);
let pool = SqlitePool::connect_with(opts).await.unwrap();
setup_fn(pool.clone()).await;
DB {
cauldron_w: pool.clone(),
cauldron_r: pool.clone(),
bcmr_w: pool.clone(),
bcmr_r: pool.clone(),
crc20_w: pool.clone(),
crc20_r: pool.clone(),
oracle_w: pool.clone(),
oracle_r: pool.clone(),
}
}
}
#[cfg(test)]
pub use test_utils::mock_db_pool;