I'm having a compilation error related to lifetimes, and I'm unsure about how to solve it though there are already similar questions.
I'm seeking some guidance or assistance in this matter. I am not experienced in Rust at all so please bear in mind that the code I've written might be quite naive.
I defined Transaction trait for a custom transaction mechanism. This trait has a method execute
that takes an operation (op
) as an argument, which is a closure encapsulating whatever database operation to be executed within the transaction.
I also defined a struct SeaOrmTransaction
that implements the trait for SeaORM transaction
Here is the code I wrote. (I wanted to put a reproduction code in Rust playground but I did not know how to make Sea ORM crate available there)
use sea_orm::{DatabaseConnection, TransactionTrait, DbErr};
use std::sync::Arc;
use anyhow::Result;
use futures_util::future::BoxFuture;
pub type Op<'a> = Box<dyn 'a + Send + FnOnce() -> BoxFuture<'a, Result<()>>>;
#[async_trait]
pub trait Transaction {
async fn execute(&self, op: Op<'_>) -> Result<()>;
}
pub struct SeaOrmTransaction {
pub db: Arc<DatabaseConnection>,
}
#[async_trait]
impl Transaction for SeaOrmTransaction {
async fn execute(&self, op: Op<'_>) -> Result<()> {
self.db.transaction::<_, (), DbErr>(|tx| {
let c = async move {
let res = op().await;
if let Err(_) = res {
return Err(DbErr::Custom(String::from("error")));
}
Ok(())
};
Box::pin(c)
})
.await?;
Ok(())
}
}
When I tried building the code below, I got following error.
Why does life1 have to outlive 'static?
error: lifetime may not live long enough
--> src/domain/test.rs:28:13
|
19 | async fn execute(&self, op: Op<'_>) -> Result<()> {
| -- lifetime `'life1` defined here
...
28 | Box::pin(c)
| ^^^^^^^^^^^ returning this value requires that `'life1` must outlive `'static`