Skip to content

Add PoolOptions::before_connect to execute a function before creating a new connection in the poolΒ #3117

Open
@MattDelac

Description

@MattDelac

Is your feature request related to a problem? Please describe.
When connecting to RDS using IAM I would need Sqlx to call a function that provide a new connection string (or PoolOptions) before creating a connection

Looking at some workaround, none of them work in my case. For example using set_connection_options() does not solve my problem since the password of PgPoolOptions is going to be invalidated 15min after my app started

#[tokio::main]
async fn main() {
    let pool = get_pg_pool()
        .await
        .set_connect_options(get_pg_options())
        .await;

    let state = SharedState {
        pool,
        ...
    };

    let app = Router::new()...;
    ...
    axum::serve(listener, app).await.unwrap();
}

Describe the solution you'd like
Be able to execute a function that creates a new URL string (or PoolOptions object) right before creating a new connection in the pool
Example of how I could use it

#[tokio::main]
async fn main() {
    let pool = get_pg_pool()
        .await
        .before_connect(function_to_execute_right_before_creating_a_new_connection);
    ....

Describe alternatives you've considered
If I create all the connections at the beginning if any of them dies, it won't be possible to create a new one since the IAM auth password is valid only for 15min.

So basically the following does not solve my problem either

PgPoolOptions::new()
    .min_connections(max_connections)
    .max_connections(max_connections)
    ...

If any connection is reaped by max_lifetime or idle_timeout or explicitly closed, and it brings the connection count below this amount, a new connection will be opened to replace it.
https://docs.rs/sqlx/latest/sqlx/pool/struct.PoolOptions.html#method.min_connections

Another alternative coming from a conversation from Discord would be to create my own custom Database to override the connect method. This sounds like some work and pretty risky without much context about how Sqlx is built

Hmm, actually, I guess you could do it by having a custom Database implementation which wraps the underlying postgres one. Then that Database implementation would have a ConnectOptions::connect implementation which fetches a fresh password.

Additional context
This is because we use AWS RDS IAM for which the password is valid only for 15min. So if any connection dies after 15min then creating a new connection with the initial PgPoolOptions or connection string will simply fail

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions