blackbeam / rust-mysql-simple

Mysql client library implemented in rust.
Apache License 2.0
658 stars 144 forks source link

Initializate Pool without connect #312

Open realtica opened 2 years ago

realtica commented 2 years ago

let pool = Pool::new(opts)?; This, tries to connect to database.., is it possible initialize an empty Pool?? Like let pool = Pool::default();

Then later, for example with a connection button event the Pool finally stay connected.

blackbeam commented 2 years ago

Hi. Pool will maintain the minimum number of connections as defined in its configuration. If you want to delay this behaviour, than you should delay the pool creation itself (wrap it into a lambda or Lazy or something)

daniel-pfeiffer commented 1 year ago

I have the same need. For functions called out of my control (REST APIs, callbacks with a signature imposed on me…) I need access to a global Pool. With (the former external crate once_cell) OnceLock part of the standard since Rust 1.70, I came up with this.

static DBPOOL: OnceLock<Pool> = OnceLock::new();
/// Set up the connection pool once at server start.
pub fn init(url: &str) {
    DBPOOL
        .set(mysql::Pool::new(url).unwrap())
        //.set(mysql::Pool::new(mysql::Opts::from_url(url).unwrap()).unwrap())
        .unwrap();
    info!("inited conn pool");
}

/// Get a new connection from the pool.
fn get_conn() -> Result<PooledConn> {
    // unwrap is ok, because inited in main at server start
    DBPOOL.get().unwrap().get_conn()
}

If that looks like a good solution, it would be nice if you could add something like this to the documentation.

But since Pool is already a smart wrapper, this looks redundant. As per @realtica's proposal, this could be simplified (but, just for kicks, generalizing opts) to:

static DBPOOL: Pool = Pool::default();
/// Set up the connection pool once at server start.
pub fn init<T, E>(opts: T)
where // and also enriched to allow all kinds of opts
    Opts: TryFrom<T, Error = E>,
    Error: From<E>,
{
    DBPOOL
        .init(opts)
        .unwrap();
    info!("inited conn pool");
}

/// Get a new connection from the pool.
fn get_conn() -> Result<PooledConn> {
    DBPOOL.get_conn()
}