Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initializate Pool without connect #312

Open
realtica opened this issue Mar 24, 2022 · 2 comments
Open

Initializate Pool without connect #312

realtica opened this issue Mar 24, 2022 · 2 comments

Comments

@realtica
Copy link

realtica commented Mar 24, 2022

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
Copy link
Owner

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
Copy link

daniel-pfeiffer commented Jun 8, 2023

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()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants