Handle database restarts
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
//! # Database connection management
|
||||
|
||||
use crate::app_config::AppConfig;
|
||||
use diesel::result::{DatabaseErrorKind, Error};
|
||||
use diesel::{Connection, PgConnection};
|
||||
use std::cell::RefCell;
|
||||
thread_local! {
|
||||
@ -10,7 +11,7 @@ thread_local! {
|
||||
/// Execute a request on the database
|
||||
pub fn execute<E, I>(cb: E) -> anyhow::Result<I>
|
||||
where
|
||||
E: FnOnce(&mut PgConnection) -> anyhow::Result<I>,
|
||||
E: FnOnce(&mut PgConnection) -> diesel::QueryResult<I>,
|
||||
{
|
||||
// Establish connection if required
|
||||
if POSTGRES_CONNECTION.with(|i| i.borrow().is_none()) {
|
||||
@ -21,5 +22,20 @@ where
|
||||
POSTGRES_CONNECTION.with(|i| *i.borrow_mut() = Some(conn))
|
||||
}
|
||||
|
||||
POSTGRES_CONNECTION.with(|i| cb(i.borrow_mut().as_mut().unwrap()))
|
||||
match POSTGRES_CONNECTION.with(|i| cb(i.borrow_mut().as_mut().unwrap())) {
|
||||
Ok(res) => Ok(res),
|
||||
Err(e) => {
|
||||
if matches!(
|
||||
e,
|
||||
Error::DatabaseError(DatabaseErrorKind::ClosedConnection, _)
|
||||
| Error::BrokenTransactionManager
|
||||
) {
|
||||
log::warn!("Connection to database closed, dropping handle!");
|
||||
POSTGRES_CONNECTION.with(|i| *i.borrow_mut() = None)
|
||||
}
|
||||
|
||||
log::error!("Database query error! {:?}", e);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user