I encountered some issues using SQLite in Rust. I wrote some methods involving SQL operations, and I want to write some test cases for this code. I don’t want the test cases to affect my normal logic, so I encapsulated a method:
pub fn with_connection<F, T>(op: F) -> Result<T>
where
F: FnOnce(&mut Database) -> Result<T>,
{
#[cfg(test)]
{
}
#[cfg(not(test))]
{
let pool = get_pool()?;
let mut conn = Database::PooledConnection(pool.get().map_err(|e| AppError::Other(format!("get conn failed: {}", e)))?);
op(&mut conn)
}
}
This way, when performing some operations (such as deletion), we can directly use:
pub fn delete_data_from_db(table_name: String) -> Result<usize> {
with_connection(|conn| {
let sql = format!("DELETE FROM {}", table_name);
let deleted_count = conn.execute(&sql, params![])?;
Ok(deleted_count)
})
}
Now the only issue is how I should return an SQLite connection in the with_connection
method during testing that does not affect the normal data. I first thought of using sqlite::Connection::open_in_memory()
to create an in-memory database for subsequent operations. This requires us to be able to get the same SQLite instance for each call. I am not sure if there is a better solution. I am a beginner, and I would appreciate any help anyone can provide!