Skip to content

Using a connection retrieved from Acquire more than once not possible because of lifetimes #1635

Closed
@johannescpk

Description

@johannescpk

As per #1441

pub async fn query<'a, A>(conn: A) -> Result<(), sqlx::Error>
where
	A: Acquire<'a>,
	A::Connection: 'a,
	A::Connection: sqlx::Executor<'a, Database = Postgres>,
{
	let conn = conn.acquire().await?;

	sqlx::query!("SELECT 1 as v",).fetch_one(conn).await?;

	Ok(())
}

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 this

pub async fn save<'a, A>(conn: A) -> Result<(), sqlx::Error>
where
	A: Acquire<'a>,
	A::Connection: 'a,
	&'a mut A::Connection: sqlx::Executor<'a, Database = Postgres>,
{
	let mut conn = conn.acquire().await?;

	sqlx::query!("SELECT 1 as v",).fetch_one(&mut conn).await?;

	Ok(())
}

But that fails with

error[E0597]: `conn` does not live long enough
    |
122 |     pub async fn save<'a, A>(conn: A) -> Result<(), sqlx::Error>
    |                       -- lifetime `'a` defined here
...
130 |         sqlx::query!("SELECT 1 as v",).fetch_one(&mut conn).await?;
    |         -----------------------------------------^^^^^^^^^-
    |         |                                        |
    |         |                                        borrowed value does not live long enough
    |         argument requires that `conn` is borrowed for `'a`
...
133 |     }
    |     - `conn` dropped here while still borrowed

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions