Using lazy_static for postgres Connection


Please consider the following example:

use postgres::{Connection, TlsMode};
use postgres::params::{ConnectParams, Host};
use std::sync::{Arc, Mutex};

lazy_static! {
    static ref CONN: Arc<Mutex<Connection>> = Arc::new(Mutex::new(open_connection()));

fn open_connection() -> Connection {
    let params = ConnectParams::builder()
        .user("username", Some("password"))
    Connection::connect(params, TlsMode::None).unwrap()

fn execute<F: Fn(&Connection)>(f: F) {
    let ref mut conn = *CONN.lock().unwrap();
    if !conn.is_active() {
        *conn = open_connection();

Since the connection might be closed, its active state is checked and if it is not active the conn is reopened in execute function. Is this approach the correct way to do that? Is the new opened connection binded to CONN?


From what I understand in the docs, the is_active can only be false when there’s still an active transaction somewhere. Since the connection is behind a Mutex, it seems impossible.

Anyway, you can “cancel out” the * and ref mut to simplify a little bit:

let conn = CONN.lock().unwrap();

And yes, the line *conn = open_connection(); will put the new connection in the Mutex.