GeneIT/geneit_backend/src/connections/db_connection.rs

63 lines
1.9 KiB
Rust
Raw Normal View History

2023-05-24 14:19:46 +00:00
//! # Database connection management
use crate::app_config::AppConfig;
2023-06-13 13:24:13 +00:00
use diesel::result::{DatabaseErrorKind, Error};
2023-05-24 14:19:46 +00:00
use diesel::{Connection, PgConnection};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
2023-05-24 14:19:46 +00:00
use std::cell::RefCell;
const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
2023-05-24 14:19:46 +00:00
thread_local! {
Update dependency filesize to v10.1.1 (#116) This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [filesize](https://filesizejs.com) ([source](https://github.com/avoidwork/filesize.js)) | dependencies | patch | [`10.1.0` -> `10.1.1`](https://renovatebot.com/diffs/npm/filesize/10.1.0/10.1.1) | --- ### Release Notes <details> <summary>avoidwork/filesize.js (filesize)</summary> ### [`v10.1.1`](https://github.com/avoidwork/filesize.js/blob/HEAD/CHANGELOG.md#1011) [Compare Source](https://github.com/avoidwork/filesize.js/compare/10.1.0...10.1.1) - Rework types to allow Parameters\<typeof filesize> to function properly [`#180`](https://github.com/avoidwork/filesize.js/pull/180) - Bump [@&#8203;babel/traverse](https://github.com/babel/traverse) from 7.23.0 to 7.23.2 [`#178`](https://github.com/avoidwork/filesize.js/pull/178) - change: rework types to allow usages like Parameters\<typeof filesize> [`fbfc87f`](https://github.com/avoidwork/filesize.js/commit/fbfc87f4d24de80813330a74fc30392f8bfb1002) - Generating CHANGELOG.md [`d80c457`](https://github.com/avoidwork/filesize.js/commit/d80c4579e1259f3a133fed3ae8b6762712b72623) - fix: types for partial now return a higher order function [`af4a6ef`](https://github.com/avoidwork/filesize.js/commit/af4a6efe8e065ca97916afa19a22af5e42fa2196) </details> --- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Enabled. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4yNjUuMCIsInVwZGF0ZWRJblZlciI6IjM3LjI2NS4wIiwidGFyZ2V0QnJhbmNoIjoibWFzdGVyIn0=--> Reviewed-on: https://gitea.communiquons.org/pierre/GeneIT/pulls/116
2024-03-22 10:38:13 +00:00
static POSTGRES_CONNECTION: RefCell<Option<PgConnection>> = const { RefCell::new(None) };
2023-05-24 14:19:46 +00:00
}
/// Execute a request on the database
pub fn execute<E, I>(cb: E) -> anyhow::Result<I>
where
2023-06-13 13:24:13 +00:00
E: FnOnce(&mut PgConnection) -> diesel::QueryResult<I>,
2023-05-24 14:19:46 +00:00
{
// Establish connection if required
if POSTGRES_CONNECTION.with(|i| i.borrow().is_none()) {
let database_url = AppConfig::get().db_connection_chain();
let conn = PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url));
POSTGRES_CONNECTION.with(|i| *i.borrow_mut() = Some(conn))
}
2023-06-13 13:24:13 +00:00
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())
}
}
2023-05-24 14:19:46 +00:00
}
/// Initialize database connection
pub fn initialize_conn() -> anyhow::Result<()> {
// Run pending diesel migrations
execute(|db| {
let res = db
.run_pending_migrations(MIGRATIONS)
.expect("Failed to run database migration!");
for migration in res {
log::info!("Executed database migration {migration}")
}
Ok(())
})?;
Ok(())
}