Hello fellow Rustaceans
I'm trying to make a function generic over both sqlx
Transaction
and PoolConnection
. Unfortunately, the Executor
trait requires a generic lifetime parameter.
use anyhow::Result;
use std::time::Duration;
use sqlx::{self, postgres::PgPoolOptions, Executor, Pool, Postgres, PgExecutor, Transaction};
pub type DB = Pool<Postgres>;
pub trait Queryer<'c>: Executor<'c, Database = sqlx::Postgres> {}
impl<'c> Queryer<'c> for &Pool<Postgres> {}
impl<'c> Queryer<'c> for &'c mut Transaction<'_, Postgres> {}
async fn do_something_generic(
db: impl Queryer<'_>,
param: String,
) -> Result<()> {
return Ok(());
}
#[tokio:main]
async fn main() -> Result<()> {
let db = PgPoolOptions::new()
.connect(&database.url)
.await?;
let mut tx = db.begin().await?;
do_something_generic(&mut tx, "hello".to_string()).await?;
return Ok(());
}
Any idea how I could remove the <'_>
from the do_something_generic
function, whether it be a type alias, a new trait or a complete refactoring?
I find it very ugly.
Any help is appreciated