Skip to content

Commit

Permalink
fix: handle error by output the error into console
Browse files Browse the repository at this point in the history
  • Loading branch information
albugowy15 committed Feb 11, 2024
1 parent 5127976 commit 7619b2d
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 50 deletions.
14 changes: 10 additions & 4 deletions src/commands/clean.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
use tokio::try_join;

use crate::{
commands::create_db_connection,
db::repository::{many_to_many::ManyToManyRepository, Repository},
use crate::db::{
self,
repository::{many_to_many::ManyToManyRepository, Repository},
};

pub async fn clean_handler() {
let pool = create_db_connection().await.unwrap();
let pool = match db::Database::create_connection().await {
Ok(pool) => pool,
Err(e) => {
log::error!("{}", e);
return;
}
};
log::info!("Clean up invalid foreign key");
let many_to_many_repo = ManyToManyRepository::new(&pool);

Expand Down
43 changes: 30 additions & 13 deletions src/commands/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ use anyhow::{Error, Result};
use sqlx::MySqlPool;

use crate::{
commands::create_db_connection,
db::repository::{
class::{ClassFromSchedule, ClassRepository},
prepare_data, LecturerSubjectSessionMap, Repository,
db::{
self,
repository::{
class::{ClassFromSchedule, ClassRepository},
prepare_data, LecturerSubjectSessionMap, Repository,
},
},
utils::{
excel::{Excel, ScheduleParser},
Expand Down Expand Up @@ -80,17 +82,25 @@ fn compare_schedule(
}

pub async fn compare_handler(file: &PathBuf, sheet: &str, outdir: &PathBuf) {
let pool = Arc::new(create_db_connection().await.unwrap());
let pool = match db::Database::create_connection().await {
Ok(pool) => Arc::new(pool),
Err(e) => {
log::error!("{}", e);
return;
}
};
log::info!("Get existing schedule from DB");

let class_repo_schedule_task = spawn_get_schedule(&pool);
let prepare_data_task = spawn_prepare_data(&pool);
let (db_classes_res, repo_data_res) =
tokio::try_join!(class_repo_schedule_task, prepare_data_task)
.map_err(|e| {
log::error!("Thread error: {}", e);
})
.unwrap();
match tokio::try_join!(class_repo_schedule_task, prepare_data_task) {
Ok((db, repo)) => (db, repo),
Err(e) => {
log::error!("{}", e);
return;
}
};

let db_classes = match db_classes_res {
Ok(res) => res,
Expand Down Expand Up @@ -131,9 +141,16 @@ pub async fn compare_handler(file: &PathBuf, sheet: &str, outdir: &PathBuf) {
deleted.len()
);
log::info!("Write the result to {:?}", &outdir);
if let Err(e) = OutWriter::new(outdir)
.await
.unwrap()

let mut writer = match OutWriter::new(outdir).await {
Ok(writer) => writer,
Err(e) => {
log::error!("{}", e);
return;
}
};

if let Err(e) = writer
.write_compare_result(&added, &changed, &deleted)
.await
{
Expand Down
24 changes: 7 additions & 17 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::path::PathBuf;

use clap::Subcommand;
use sqlx::MySqlPool;

use crate::db::Database;

pub mod clean;
pub mod compare;
Expand All @@ -26,6 +23,7 @@ pub enum Commands {
#[arg(short, long, value_name = "Required for output path")]
outdir: PathBuf,
},

#[command(
long_about = "Parses all class data from an Excel file and subsequently updates the MySQL database. Alternatively, it provides an option to save the parsed data to an SQL file."
)]
Expand All @@ -50,9 +48,7 @@ pub enum Commands {
)]
outdir: Option<PathBuf>,
},
#[command(
long_about = "Removes any invalid foreign keys present in the _ClassToPlan and _ClassToLecturer tables."
)]

#[command(long_about = "Find class schedule from excel")]
Find {
#[arg(short, long, value_name = "Required for excel file path")]
Expand All @@ -64,20 +60,14 @@ pub enum Commands {
#[arg(short, long, value_name = "Required for class subject name to find")]
course: String,
},

#[command(
long_about = "Removes any invalid foreign keys present in the _ClassToPlan and _ClassToLecturer tables."
)]
Clean,

#[command(
long_about = "Synchronizes the taken field in the Class table and the totalSks field in the Plan table to reflect their current values."
)]
Sync,
}

async fn create_db_connection() -> anyhow::Result<MySqlPool> {
let pool = Database::create_connection()
.await
.map_err::<anyhow::Error, _>(|e| {
log::error!("Failed to create a db connection: {}", e);
e
})?;

Ok(pool)
}
14 changes: 10 additions & 4 deletions src/commands/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use std::sync::Arc;

use sqlx::MySqlPool;

use crate::{
commands::create_db_connection,
db::repository::{class::ClassRepository, plan::PlanRepository, Repository},
use crate::db::{
self,
repository::{class::ClassRepository, plan::PlanRepository, Repository},
};

fn sync_taken(pool: &Arc<MySqlPool>) -> tokio::task::JoinHandle<()> {
Expand All @@ -30,7 +30,13 @@ fn sync_total_sks(pool: &Arc<MySqlPool>) -> tokio::task::JoinHandle<()> {
}

pub async fn sync_handler() {
let pool = Arc::new(create_db_connection().await.unwrap());
let pool = match db::Database::create_connection().await {
Ok(pool) => Arc::new(pool),
Err(e) => {
log::error!("{}", e);
return;
}
};

if let Err(e) = tokio::try_join!(sync_taken(&pool), sync_total_sks(&pool)) {
log::error!("Error syncing: {}", e);
Expand Down
18 changes: 13 additions & 5 deletions src/commands/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ use std::{path::PathBuf, sync::Arc};
use sqlx::MySqlPool;

use crate::{
commands::create_db_connection,
db::repository::{
class::{Class, ClassRepository},
prepare_data, Repository,
db::{
self,
repository::{
class::{Class, ClassRepository},
prepare_data, Repository,
},
},
utils::{
excel::{Excel, ScheduleParser},
Expand Down Expand Up @@ -43,7 +45,13 @@ fn write_change_to_output_file(
}

pub async fn update_handler(push: &bool, file: &PathBuf, sheet: &String, outdir: &Option<PathBuf>) {
let pool = Arc::new(create_db_connection().await.unwrap());
let pool = match db::Database::create_connection().await {
Ok(pool) => Arc::new(pool),
Err(e) => {
log::error!("{}", e);
return;
}
};
let repo_data = match prepare_data(&pool).await {
Ok(repo_data) => repo_data,
Err(e) => {
Expand Down
3 changes: 2 additions & 1 deletion src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ impl Database {
let pool = MySqlPoolOptions::new()
.max_connections(5)
.connect(&db_url)
.await?;
.await
.with_context(|| "Error when create database connection")?;
Ok(pool)
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/db/repository/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,8 @@ impl ClassRepository<'_> {
})?;
bar.inc(1);
}
bar.finish_with_message(format!(
"Done inserting {} classes to Class table",
data.len()
));
bar.finish_and_clear();
log::info!("Done inserting {} classes to Class table", data.len());
log::info!("Inserting non-class subject");
Self::insert_non_classes(&mut tx).await?;
tx.commit().await?;
Expand Down
2 changes: 0 additions & 2 deletions src/utils/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::env;
use env_logger::{Builder, Env};

pub fn setup_env() {
env::set_var("RUST_BACKTRACE", "1");
let env = Env::default()
.filter("AUTO_FRS_SCHEDULE_LOG_LEVEL")
.write_style("AUTO_FRS_SCHEDULE_LOG_STYLE");
Expand All @@ -23,7 +22,6 @@ mod tests {
fn test_setup_env() {
setup_env();

assert_eq!(env::var("RUST_BACKTRACE").unwrap(), "1");
assert_eq!(env::var("AUTO_FRS_SCHEDULE_LOG_LEVEL").unwrap(), "INFO");
assert_eq!(env::var("AUTO_FRS_SCHEDULE_LOG_STYLE").unwrap(), "AUTO");
}
Expand Down

0 comments on commit 7619b2d

Please sign in to comment.