From d23bc2440c5b1cc32c04d59c696db81f0c2e0675 Mon Sep 17 00:00:00 2001 From: albugowy15 Date: Tue, 6 Jun 2023 14:16:29 +0700 Subject: [PATCH] refactor: cleaner --- src/db.rs | 78 +++++++++++++---------------- src/excel.rs | 137 +++++++++++++++++++++------------------------------ src/main.rs | 28 +++++------ 3 files changed, 102 insertions(+), 141 deletions(-) diff --git a/src/db.rs b/src/db.rs index 11a6097..dc4ce93 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use mysql_async::{ prelude::{Query, Queryable, WithParams}, - Conn, Error, Pool, + Conn, Error, }; use crate::excel::Class; @@ -49,7 +49,6 @@ impl SQLData { Ok(()) } - pub async fn get_all_lecture(&mut self, conn: &mut Conn) -> Result<(), Error> { let loaded_lecture = "SELECT id, code FROM Lecturer" .with(()) @@ -62,7 +61,6 @@ impl SQLData { Ok(()) } - pub async fn get_all_session(&mut self, conn: &mut Conn) -> Result<(), Error> { let loaded_session = "SELECT id, session_time FROM Session" .with(()) @@ -76,48 +74,38 @@ impl SQLData { Ok(()) } - - pub async fn drop_class_table(&mut self, conn: &mut Conn) -> Result<(), Error> { - conn.query_drop("DELETE FROM Class").await - } - - #[allow(deprecated)] - pub async fn insert_data(&mut self, conn: &mut Conn, data: Vec) -> Result<(), Error> { - let prepared_stmt = conn.prep("INSERT INTO Class (id, matkulId, lecturerId, day, code, isAksel, taken, sessionId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").await?; - for item in data.iter() { - let id_class = cuid::cuid().unwrap(); - println!( - "Inserting : {}, {}, {}, {}, {}, {}, {}, {}", - id_class, - item.matkul_id, - item.lecture_id, - item.day, - item.code, - false, - 0, - item.session_id - ); - let values = ( - id_class.to_string(), - &item.matkul_id, - &item.lecture_id, - &item.day, - &item.code, - false, - 0, - &item.session_id, - ); - conn.exec_drop(&prepared_stmt, values).await?; - } - Ok(()) - } } -pub async fn start_connection(database_url: String) -> Result { - let builder = - mysql_async::OptsBuilder::from_opts(mysql_async::Opts::from_url(&database_url).unwrap()); - - return Ok(mysql_async::Pool::new( - builder.ssl_opts(mysql_async::SslOpts::default()), - )); +pub async fn drop_class_table(conn: &mut Conn) -> Result<(), Error> { + conn.query_drop("DELETE FROM Class").await +} +#[allow(deprecated)] +pub async fn insert_data(conn: &mut Conn, data: Vec) -> Result<(), Error> { + let prepared_stmt = conn.prep("INSERT INTO Class (id, matkulId, lecturerId, day, code, isAksel, taken, sessionId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").await?; + for item in data.iter() { + let id_class = cuid::cuid().unwrap(); + println!( + "Inserting : {}, {}, {}, {}, {}, {}, {}, {}", + id_class, + item.matkul_id, + item.lecture_id, + item.day, + item.code, + false, + 0, + item.session_id + ); + let values = ( + id_class.to_string(), + &item.matkul_id, + &item.lecture_id, + &item.day, + &item.code, + false, + 0, + &item.session_id, + ); + conn.exec_drop(&prepared_stmt, values).await?; + } + Ok(()) } diff --git a/src/excel.rs b/src/excel.rs index a6ed781..f0f4c41 100644 --- a/src/excel.rs +++ b/src/excel.rs @@ -1,18 +1,6 @@ -use std::collections::HashMap; - -/* -Data : -Matkul -> Matkul id -Lecture -> Lecture id -day -code -is Akses -> set false -taken -> set 0 -session -> session Id - */ use calamine::{open_workbook, Error, Reader, Xlsx}; +use std::collections::HashMap; -#[allow(dead_code)] pub struct Class { pub matkul_id: String, pub lecture_id: String, @@ -34,78 +22,67 @@ pub fn parse_excel( ); let mut excel: Xlsx<_> = open_workbook(path).unwrap(); let range = excel.worksheet_range("Jadwal Kuliah").unwrap()?; - let mut list_class: Vec = Vec::new(); - for (row_idx, row) in range.rows().enumerate() { for (col_idx, c) in row.iter().enumerate() { - if let Some(val) = c.get_string() { - // get subject - let subject_name = val.split(" - ").collect::>(); - if list_subject.contains_key(subject_name[0]) { - let subject_id = list_subject.get(subject_name[0]).unwrap(); - let lecture_code = range - .get_value((row_idx as u32 + 1, col_idx as u32)) - .unwrap() - .get_string() - .unwrap() - .split("/") - .collect::>()[2]; - if lecture_code.len() != 2 { - continue; - } - let lecture_id = match list_lecture.get(lecture_code) { - Some(val) => val, - None => { - println!("No lecture id for {}", lecture_code); - continue; - } - }; - - let day = match row_idx { - 0..=14 => "Senin", - 15..=28 => "Selasa", - 29..=42 => "Rabu", - 43..=56 => "Kamis", - _ => "Jum'at", - }; - // get code - let class_code = subject_name[1]; - - // session id - let session_name = range - .get_value((row_idx as u32, 1)) - .unwrap() - .get_string() - .unwrap() - .split(" - ") - .collect::>()[0]; - let session_id = match list_session.get(session_name) { - Some(val) => val, - None => { - println!("No session id for : {}", session_name); - continue; - } - }; - - let class = Class { - matkul_id: subject_id.to_string(), - lecture_id: lecture_id.to_string(), - day: day.to_string(), - code: class_code.to_string(), - is_akses: false, - taken: 0, - session_id: *session_id, - }; - - list_class.push(class); - } - - // get lecture + if c.get_string().is_none() { + continue; + } + let val = c.get_string().unwrap(); + let subject_name = val.split(" - ").collect::>(); + if !list_subject.contains_key(subject_name[0]) { + continue; + }; + let subject_id = list_subject.get(subject_name[0]).unwrap(); + let class_code = subject_name[1]; + let lecture_code = range + .get_value((row_idx as u32 + 1, col_idx as u32)) + .unwrap() + .get_string() + .unwrap() + .split("/") + .collect::>()[2]; + if lecture_code.len() != 2 { + continue; } + let lecture_id = match list_lecture.get(lecture_code) { + Some(val) => val, + None => { + println!("No lecture id for {}", lecture_code); + continue; + } + }; + let day = match row_idx { + 0..=14 => "Senin", + 15..=28 => "Selasa", + 29..=42 => "Rabu", + 43..=56 => "Kamis", + _ => "Jum'at", + }; + let session_name = range + .get_value((row_idx as u32, 1)) + .unwrap() + .get_string() + .unwrap() + .split(" - ") + .collect::>()[0]; + let session_id = match list_session.get(session_name) { + Some(val) => val, + None => { + println!("No session id for : {}", session_name); + continue; + } + }; + list_class.push(Class { + matkul_id: subject_id.to_string(), + lecture_id: lecture_id.to_string(), + day: day.to_string(), + code: class_code.to_string(), + is_akses: false, + taken: 0, + session_id: *session_id, + }); } } - println!("len class = {}", list_class.len()); - Ok(list_class) } diff --git a/src/main.rs b/src/main.rs index 8f6f824..f570d23 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,27 +1,20 @@ use auto_frs_schedule::{ - db::{start_connection, SQLData}, + db::{drop_class_table, insert_data, SQLData}, excel::parse_excel, }; use dotenv::dotenv; - use std::env; #[tokio::main] async fn main() { - println!("Hello, world!"); dotenv().ok(); - + // start db connection let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); - print!("Connecting to {}...", db_url); - let pool = match start_connection(db_url).await { - Ok(conn) => { - println!("success"); - conn - } - Err(e) => { - panic!("error: {}", e); - } - }; + println!("Connecting to {}...", db_url); + let builder = + mysql_async::OptsBuilder::from_opts(mysql_async::Opts::from_url(&db_url).unwrap()); + + let pool = mysql_async::Pool::new(builder.ssl_opts(mysql_async::SslOpts::default())); let mut conn = pool.get_conn().await.unwrap(); // retrieve data from database @@ -45,14 +38,17 @@ async fn main() { } }; + // parse excel let list_class = parse_excel(&sql_data.subject, &sql_data.lecturer, &sql_data.session).unwrap(); - match sql_data.drop_class_table(&mut conn).await { + + // insert data to database + match drop_class_table(&mut conn).await { Ok(_) => println!("successfully drop table"), Err(e) => { panic!("error drop table : {}", e); } }; - match sql_data.insert_data(&mut conn, list_class).await { + match insert_data(&mut conn, list_class).await { Ok(_) => println!("successfully insert data"), Err(e) => { panic!("error insert data : {}", e);