Skip to content

Commit

Permalink
refactor: cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
albugowy15 committed Jun 6, 2023
1 parent 7cddcd6 commit d23bc24
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 141 deletions.
78 changes: 33 additions & 45 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;

use mysql_async::{
prelude::{Query, Queryable, WithParams},
Conn, Error, Pool,
Conn, Error,
};

use crate::excel::Class;
Expand Down Expand Up @@ -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(())
Expand All @@ -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(())
Expand All @@ -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<Class>) -> 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<Pool, Error> {
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<Class>) -> 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(())
}
137 changes: 57 additions & 80 deletions src/excel.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<Class> = 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::<Vec<&str>>();
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::<Vec<&str>>()[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::<Vec<&str>>()[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::<Vec<&str>>();
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::<Vec<&str>>()[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::<Vec<&str>>()[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)
}
28 changes: 12 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
Expand Down

0 comments on commit d23bc24

Please sign in to comment.