djc/bb8

Example of on_acquire?

mu-arch opened this issue · 6 comments

I've been trying to use this method but I can't figure out the syntax to use it correctly. Could you show me an example?

Here is what I have, I'm not sure if it wants that bb8 type or the actual Postgres Connection:

#[derive(Debug)]
struct ConnectionCustomizer {}

#[async_trait]
impl<'a>
    bb8_postgres::bb8::CustomizeConnection<
        PooledConnection<'a, PostgresConnectionManager<MakeTlsConnector>>,
        anyhow::Error,
    > for ConnectionCustomizer
{
    async fn on_acquire(
        &self,
        connection: &mut PooledConnection<'a, PostgresConnectionManager<MakeTlsConnector>>,
    ) -> Result<(), anyhow::Error> {
        println!("test");
        Ok(())
    }
}

My use case is setting up prepared statements for each new connection that is established. Is there a better way to do that?

djc commented

Please ask a more concrete question and/or show an error message that you're having trouble with.

I'll just ask a much more basic version then. Since prepared statements only work with the connection that created them, I want to prepare all my queries for every connection immediately after that connection opens, but before it is released for use by the pool.

Is it possible you could write an example of building a new pool with with .customize_connection and it's associated trait?

Appreciate your response and work on this project.

djc commented

Something like the code you posted should work. What is the problem with it?

I made a little bit of progress, but I'm still struggling with the compiler error: lifetime parameters or bounds on method on_acquire do not match the trait declaration

Here is my new code that I believe uses the right argument Client now.

#[derive(Debug)]
struct ConnectionCustomizer {}

#[async_trait]
impl<'a> bb8_postgres::bb8::CustomizeConnection<Client, bb8_postgres::tokio_postgres::Error> for ConnectionCustomizer {
    async fn on_acquire(
        &self,
        connection: &'a mut bb8_postgres::tokio_postgres::Client,
    ) -> Result<(), bb8_postgres::tokio_postgres::Error> {
        println!("test");
        Ok(())
    }
}

Update: all I needed to do was elide the lifetime 'a and it worked! Appreciate your time and work on this library regardless. Closing this issue.

djc commented

Great, happy you got it too work!