-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using a connection retrieved from Acquire
more than once not possible because of lifetimes
#1635
Comments
@johannescpk Were you able to solve this? |
@mehcode Not sure how I would apply this in the example given by @johannescpk. Also, would this work with PgPool, PgConnection and transactions? |
With the following use sqlx::{self, pool::PoolConnection, Executor, Pool, Postgres, 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> {}
impl<'c> Queryer<'c> for &'c mut PoolConnection<Postgres> {} I'm able to create a function that accepts &PgPool, &mut PoolConnection and &mut Transaction pub async fn foo<'c, C: Queryer<'c>>(db: C, val: i32) -> Result<i32, sqlx::Error> {
let foo = sqlx::query!("SELECT $1::int4 as foo FROM items", val)
.fetch_one(db)
.await
.unwrap();
Ok(foo.foo.unwrap())
} However, like @johannescpk, I also am unable to execute multiple queries in the same function:
@mehcode How do you suggest I proceed here? |
Unfortunately not, had to resort to only accept @mehcode Sadly that doesn't help with multiple |
This is far from from obvious, but it is possible: pub async fn save<'a, A>(conn: A) -> Result<(), sqlx::Error>
where
A: Acquire<'a, Database = Postgres>,
{
let mut conn = conn.acquire().await?;
sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;
Ok(())
}
|
Thanks @jplatte, that actually solves it. |
With this method, can I just pass in Pool when transaction is not needed, and pass in Transaction when transaction is needed? |
As per #1441
works fine.
However, if one would want to do more than one query with the acquired connection, it would require the
conn
to be&mut
, which looks like thisBut that fails with
Reason for that seems to be the lifetime on the executing methods, like
fetch_one
here. Any way around this or am I missing something?The text was updated successfully, but these errors were encountered: