Skip to content

[feature] Add/Get New Pooled Connections #212

@tneely

Description

@tneely

I have a use case where I want to periodically re-evaluate my login credentials against the underlying database.

Using something like Pool::get() doesn't work, because it doesn't necessarily mean that the connection is new - it could be from the pool instead. Luckily, this is pretty trivial today with Pool::dedicated_connection():

let pool = Pool::builder().build(mgr).await.unwrap();
let mut interval = time::interval(time::Duration::from_secs(5));
loop {
  tokio::select! {
    _ = interval.tick() => match pool.dedicated_connection().await {
      Ok(_) => (),
      Err(err) => handle_connection_error(err),
  }
}

However, establishing a connection against my database is expensive, and I don't want to just throw away the connection after its established. Instead, it would be great if that new connection could be added to the pool.

I see two obvious ways of going about this:

  1. A method to add a connection to the pool:
/// Adds a connection to the pool.
pub fn add(&self, conn: M::Connection) -> ()
match pool.dedicated_connection().await {
  Ok(conn) => pool.add(conn),
  Err(err) => handle_connection_error(err),
}
  1. A method to get a new connection from the pool:
/// Retrieves a new connection from the pool.
pub async fn get_new(&self) -> Result<PooledConnection<'_, M>, RunError<M::Error>>
match pool.get_new().await {
  Ok(_pooled_connection) => (), // returned to pool on drop
  Err(err) => handle_connection_error(err),
}

I'm leaning towards the first option, since it's both easier to implement and more flexible. For example, you can create connections independent from the pool and add them to be managed later.

I would be happy to write the code for this feature if it's something you're ok with adding to the project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions