ldap_backend/src/bin/update_wolves.rs

86 lines
2.3 KiB
Rust

use skynet_ldap_backend::{db_init, get_config, AccountWolves, Config};
use sqlx::{Pool, Sqlite};
#[async_std::main]
async fn main() -> tide::Result<()> {
let config = get_config();
let db = db_init(&config).await.unwrap();
let mut records = vec![];
if let Ok(accounts) = get_csv(&config) {
for account in accounts {
records.push(AccountWolves::from(account));
}
}
for account in records {
update_account(&db, &account).await;
}
Ok(())
}
#[derive(Debug, serde::Deserialize)]
struct RecordCSV {
#[serde(rename = "MemID")]
mem_id: String,
#[serde(rename = "Student Num")]
id_student: String,
#[serde(rename = "Contact Email")]
email: String,
#[serde(rename = "Expiry")]
expiry: String,
#[serde(rename = "First Name")]
name_first: String,
#[serde(rename = "Last Name")]
name_second: String,
}
impl From<RecordCSV> for AccountWolves {
fn from(input: RecordCSV) -> Self {
AccountWolves {
id_wolves: input.mem_id,
id_student: input.id_student,
email: input.email,
expiry: input.expiry,
name_first: input.name_first,
name_second: input.name_second,
}
}
}
fn get_csv(config: &Config) -> Result<Vec<RecordCSV>, Box<dyn std::error::Error>> {
let mut records: Vec<RecordCSV> = vec![];
if let Ok(mut rdr) = csv::Reader::from_path(format!("{}/{}", &config.home, &config.csv)) {
for result in rdr.deserialize() {
// Notice that we need to provide a type hint for automatic
// deserialization.
let record: RecordCSV = result?;
if record.mem_id.is_empty() {
continue;
}
records.push(record);
}
}
Ok(records)
}
async fn update_account(db: &Pool<Sqlite>, account: &AccountWolves) {
sqlx::query_as::<_, AccountWolves>(
"
INSERT OR REPLACE INTO accounts_wolves (id_wolves, id_student, email, expiry, name_first, name_second)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
",
)
.bind(&account.id_wolves)
.bind(&account.id_student)
.bind(&account.email)
.bind(&account.expiry)
.bind(&account.name_first)
.bind(&account.name_second)
.fetch_optional(db)
.await
.ok();
}