64 lines
1.7 KiB
Rust
64 lines
1.7 KiB
Rust
use rustorm::{DbError, EntityManager, ToValue};
|
|
use rustorm::dao::{ToTableName, ToColumnNames, ToDao, FromDao};
|
|
|
|
use super::schema::SqlResult;
|
|
|
|
pub struct Transaction {
|
|
em: EntityManager,
|
|
committed: bool,
|
|
}
|
|
|
|
impl Transaction {
|
|
pub fn new(em: EntityManager) -> Result<Self, DbError> {
|
|
let tx = Transaction {
|
|
em,
|
|
committed: false,
|
|
};
|
|
tx.exec("BEGIN", &[])?;
|
|
Ok(tx)
|
|
}
|
|
|
|
pub fn commit(mut self) -> Result<(), DbError> {
|
|
self.exec("COMMIT", &[])?;
|
|
self.committed = true;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn exec<'a>(&self, sql: &str, params: &[&'a dyn ToValue]) -> Result<(), DbError> {
|
|
let _: Option<SqlResult> = self.em.execute_sql_with_maybe_one_return(sql, params)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn insert<T>(&self, entities: &[&T]) -> Result<(), DbError>
|
|
where
|
|
T: ToTableName + ToColumnNames + ToDao + FromDao,
|
|
{
|
|
let _: Vec<T> = self.em.insert(entities)?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl Drop for Transaction {
|
|
fn drop(&mut self) {
|
|
if !self.committed {
|
|
self.exec("ROLLBACK", &[]).unwrap();
|
|
}
|
|
}
|
|
}
|
|
|
|
pub trait QuerySql<R> {
|
|
fn query<'a>(&self, sql: &str, params: &[&'a dyn ToValue]) -> Result<R, DbError>;
|
|
}
|
|
|
|
impl<R: FromDao> QuerySql<Vec<R>> for Transaction {
|
|
fn query<'a>(&self, sql: &str, params: &[&'a dyn ToValue]) -> Result<Vec<R>, DbError> {
|
|
self.em.execute_sql_with_return(sql, params)
|
|
}
|
|
}
|
|
|
|
impl<R: FromDao> QuerySql<Option<R>> for Transaction {
|
|
fn query<'a>(&self, sql: &str, params: &[&'a dyn ToValue]) -> Result<Option<R>, DbError> {
|
|
self.em.execute_sql_with_maybe_one_return(sql, params)
|
|
}
|
|
}
|