use async_trait::async_trait;
use crate::error::Result;
pub trait Row: Send {
fn i64_at(&self, idx: usize) -> Option<i64>;
fn str_at(&self, idx: usize) -> Option<String>;
}
#[async_trait]
pub trait Db: Send + Sync {
async fn query_bool(&self, sql: &str) -> Result<bool>;
async fn execute(&self, sql: &str) -> Result<()>;
async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>>;
async fn begin(&self) -> Result<()>;
async fn commit(&self) -> Result<()>;
async fn rollback(&self) -> Result<()>;
}
pub async fn with_transaction<F, Fut, T>(db: &dyn Db, body: F) -> Result<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
db.begin().await?;
match body().await {
Ok(value) => {
db.commit().await?;
Ok(value)
}
Err(err) => {
let _ = db.rollback().await;
Err(err)
}
}
}