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"))
.database("db_name")
.port(5432_u16)
.build(Host::Tcp("localhost"));
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();
}
f(conn);
}
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
?