[BE] Fixes #21: Attempt to connect to DB on each query, if no connection is present
This commit is contained in:
parent
26c5472fcf
commit
4db7c19409
@ -10,7 +10,7 @@ use crate::{db, model::person::Person};
|
|||||||
|
|
||||||
#[get("/person/<dni>")]
|
#[get("/person/<dni>")]
|
||||||
pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
|
pub async fn get_by_dni(dni: i32) -> (Status, Json<JsonResult<Person>>) {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
info!("get person with dni {}", dni);
|
info!("get person with dni {}", dni);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use cors::Cors;
|
use cors::Cors;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
|
use rocket::tokio;
|
||||||
use sqlx::mysql::MySqlPoolOptions;
|
use sqlx::mysql::MySqlPoolOptions;
|
||||||
use sqlx::{MySql, Pool};
|
use sqlx::{MySql, Pool};
|
||||||
use std::env;
|
use std::env;
|
||||||
@ -17,17 +18,29 @@ pub mod json_result;
|
|||||||
static DB: OnceCell<Pool<MySql>> = OnceCell::new();
|
static DB: OnceCell<Pool<MySql>> = OnceCell::new();
|
||||||
|
|
||||||
/// Returns a global reference to the database pool
|
/// Returns a global reference to the database pool
|
||||||
/// This MUST be called after the DB pool has been initialized,
|
///
|
||||||
/// otherwise it will panic
|
/// If the database pool has not been initialized, this function will attempt to initialize it
|
||||||
pub fn db() -> &'static Pool<MySql> {
|
/// up to 3 times
|
||||||
DB.get().expect("DB not initialized")
|
///
|
||||||
|
/// If the database pool fails to initialize, this function will panic.
|
||||||
|
pub async fn db() -> &'static Pool<MySql> {
|
||||||
|
let attempts = 3;
|
||||||
|
|
||||||
|
for _ in 0..attempts {
|
||||||
|
match DB.get() {
|
||||||
|
Some(db) => return db,
|
||||||
|
None => {
|
||||||
|
log::info!("DB not initialized, initializing from db()");
|
||||||
|
init_db().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
log::error!("Failed to initialize DB after {} attempts", attempts);
|
||||||
|
panic!("DB not initialized");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[launch]
|
pub async fn init_db() {
|
||||||
async fn rocket() -> _ {
|
|
||||||
dotenvy::dotenv().expect("Failed to load .env file");
|
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Init DB and set it as a global variable
|
Init DB and set it as a global variable
|
||||||
*/
|
*/
|
||||||
@ -41,6 +54,14 @@ async fn rocket() -> _ {
|
|||||||
Ok(pool) => DB.set(pool).expect("Failed to set DB pool"),
|
Ok(pool) => DB.set(pool).expect("Failed to set DB pool"),
|
||||||
Err(e) => log::error!("Error connecting to DB: {}", e),
|
Err(e) => log::error!("Error connecting to DB: {}", e),
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[launch]
|
||||||
|
async fn rocket() -> _ {
|
||||||
|
dotenvy::dotenv().expect("Failed to load .env file");
|
||||||
|
env_logger::init();
|
||||||
|
|
||||||
|
init_db().await;
|
||||||
|
|
||||||
/* Init Rocket */
|
/* Init Rocket */
|
||||||
rocket::build().attach(Cors {}).mount(
|
rocket::build().attach(Cors {}).mount(
|
||||||
|
@ -28,7 +28,7 @@ pub struct Course {
|
|||||||
|
|
||||||
impl Course {
|
impl Course {
|
||||||
pub async fn get_all() -> Result<Vec<Course>, sqlx::Error> {
|
pub async fn get_all() -> Result<Vec<Course>, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let results = sqlx::query!("SELECT * FROM course")
|
let results = sqlx::query!("SELECT * FROM course")
|
||||||
.fetch_all(db)
|
.fetch_all(db)
|
||||||
@ -47,7 +47,7 @@ impl Course {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_course_name(course_id: i32) -> Option<String> {
|
pub async fn get_course_name(course_id: i32) -> Option<String> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let res = sqlx::query!(
|
let res = sqlx::query!(
|
||||||
"SELECT course_name FROM course WHERE course_id = ?",
|
"SELECT course_name FROM course WHERE course_id = ?",
|
||||||
|
@ -9,7 +9,7 @@ pub struct CustomLabel {
|
|||||||
|
|
||||||
impl CustomLabel {
|
impl CustomLabel {
|
||||||
pub async fn get_all() -> Result<Vec<CustomLabel>, sqlx::Error> {
|
pub async fn get_all() -> Result<Vec<CustomLabel>, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let result = sqlx::query_as::<_, CustomLabel>(
|
let result = sqlx::query_as::<_, CustomLabel>(
|
||||||
r#"
|
r#"
|
||||||
@ -24,7 +24,7 @@ impl CustomLabel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_id_by_value(value: &String) -> Result<i32, sqlx::Error> {
|
pub async fn get_id_by_value(value: &String) -> Result<i32, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let result = sqlx::query!(
|
let result = sqlx::query!(
|
||||||
"SELECT custom_label_id FROM custom_label WHERE custom_label_value = ?",
|
"SELECT custom_label_id FROM custom_label WHERE custom_label_value = ?",
|
||||||
@ -43,7 +43,7 @@ impl CustomLabel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create(value: &String) -> Result<i32, sqlx::Error> {
|
pub async fn create(value: &String) -> Result<i32, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
"INSERT INTO custom_label (custom_label_value) VALUES (?)",
|
"INSERT INTO custom_label (custom_label_value) VALUES (?)",
|
||||||
|
@ -32,7 +32,7 @@ pub struct Person {
|
|||||||
|
|
||||||
impl Person {
|
impl Person {
|
||||||
pub async fn get_by_dni(dni: i32) -> Result<Person, sqlx::Error> {
|
pub async fn get_by_dni(dni: i32) -> Result<Person, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let result = sqlx::query_as!(Person, "SELECT * FROM person WHERE person_dni = ?", dni)
|
let result = sqlx::query_as!(Person, "SELECT * FROM person WHERE person_dni = ?", dni)
|
||||||
.fetch_one(db)
|
.fetch_one(db)
|
||||||
@ -58,7 +58,7 @@ pub struct PersonCreate {
|
|||||||
|
|
||||||
impl PersonCreate {
|
impl PersonCreate {
|
||||||
pub async fn create(&self) -> Result<(), sqlx::Error> {
|
pub async fn create(&self) -> Result<(), sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
"INSERT INTO person (person_dni, person_names, person_paternal_surname, person_maternal_surname) VALUES (?, ?, ?, ?)",
|
"INSERT INTO person (person_dni, person_names, person_paternal_surname, person_maternal_surname) VALUES (?, ?, ?, ?)",
|
||||||
@ -84,7 +84,7 @@ pub struct PersonLink {
|
|||||||
impl PersonLink {
|
impl PersonLink {
|
||||||
/// Links a person to a user in the online classroom
|
/// Links a person to a user in the online classroom
|
||||||
pub async fn insert(&self) -> Result<(), String> {
|
pub async fn insert(&self) -> Result<(), String> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let res = sqlx::query!(
|
let res = sqlx::query!(
|
||||||
"UPDATE person SET person_classroom_id = ?, person_classroom_username = ? WHERE person_id = ?",
|
"UPDATE person SET person_classroom_id = ?, person_classroom_username = ? WHERE person_id = ?",
|
||||||
|
@ -32,7 +32,7 @@ pub struct RegisterCreate {
|
|||||||
impl RegisterCreate {
|
impl RegisterCreate {
|
||||||
/// Registers a new certificate
|
/// Registers a new certificate
|
||||||
pub async fn create(&self) -> Result<(), sqlx::Error> {
|
pub async fn create(&self) -> Result<(), sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
// Get custom_label_id from db based of self.custom_label
|
// Get custom_label_id from db based of self.custom_label
|
||||||
let custom_label_id = {
|
let custom_label_id = {
|
||||||
@ -82,7 +82,7 @@ impl RegisterCreate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn get_next_register_code(course_id: i32) -> Result<i32, sqlx::Error> {
|
async fn get_next_register_code(course_id: i32) -> Result<i32, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let course_name = Course::get_course_name(course_id).await;
|
let course_name = Course::get_course_name(course_id).await;
|
||||||
|
|
||||||
@ -140,7 +140,7 @@ pub struct Register {
|
|||||||
|
|
||||||
impl Register {
|
impl Register {
|
||||||
pub async fn get_by_dni(dni: String) -> Result<Vec<Register>, sqlx::Error> {
|
pub async fn get_by_dni(dni: String) -> Result<Vec<Register>, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let res = sqlx::query!(
|
let res = sqlx::query!(
|
||||||
"SELECT * FROM register
|
"SELECT * FROM register
|
||||||
@ -166,7 +166,7 @@ impl Register {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete(register_id: i32) -> Result<(), sqlx::Error> {
|
pub async fn delete(register_id: i32) -> Result<(), sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let _ = sqlx::query!("DELETE FROM register WHERE register_id = ?", register_id)
|
let _ = sqlx::query!("DELETE FROM register WHERE register_id = ?", register_id)
|
||||||
.execute(db)
|
.execute(db)
|
||||||
@ -179,7 +179,7 @@ impl Register {
|
|||||||
register_id_list: String,
|
register_id_list: String,
|
||||||
person_dni_list: String,
|
person_dni_list: String,
|
||||||
) -> Result<Vec<ScanData>, sqlx::Error> {
|
) -> Result<Vec<ScanData>, sqlx::Error> {
|
||||||
let db = db();
|
let db = db().await;
|
||||||
|
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"
|
"
|
||||||
|
Loading…
Reference in New Issue
Block a user