Add much stuff for rewrite
This commit is contained in:
parent
4261141c3a
commit
bd44dc3183
37 changed files with 1356 additions and 2551 deletions
src
53
src/db.rs
53
src/db.rs
|
@ -1,8 +1,13 @@
|
|||
use std::env;
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::model_utils::Period;
|
||||
use crate::db::models::{NewSchedule, Periods};
|
||||
use crate::types::EmgauwaUid;
|
||||
use diesel::prelude::*;
|
||||
use diesel_migrations::embed_migrations;
|
||||
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||||
use dotenv::dotenv;
|
||||
use log::{info, trace};
|
||||
|
||||
pub mod errors;
|
||||
pub mod models;
|
||||
|
@ -12,7 +17,7 @@ pub mod tag;
|
|||
|
||||
mod model_utils;
|
||||
|
||||
embed_migrations!("migrations");
|
||||
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
|
||||
|
||||
fn get_connection() -> SqliteConnection {
|
||||
dotenv().ok();
|
||||
|
@ -23,6 +28,46 @@ fn get_connection() -> SqliteConnection {
|
|||
}
|
||||
|
||||
pub fn run_migrations() {
|
||||
let connection = get_connection();
|
||||
embedded_migrations::run(&connection).expect("Failed to run migrations.");
|
||||
info!("Running migrations");
|
||||
let mut connection = get_connection();
|
||||
connection
|
||||
.run_pending_migrations(MIGRATIONS)
|
||||
.expect("Failed to run migrations.");
|
||||
}
|
||||
|
||||
fn init_schedule(schedule: &NewSchedule) -> Result<(), DatabaseError> {
|
||||
trace!("Initializing schedule {:?}", schedule.name);
|
||||
match schedules::get_schedule_by_uid(schedule.uid.clone()) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => match err {
|
||||
DatabaseError::NotFound => {
|
||||
trace!("Schedule {:?} not found, inserting", schedule.name);
|
||||
let mut connection = get_connection();
|
||||
diesel::insert_into(schema::schedules::table)
|
||||
.values(schedule)
|
||||
.execute(&mut connection)
|
||||
.map(|_| ())
|
||||
.map_err(DatabaseError::InsertError)
|
||||
}
|
||||
_ => Err(err),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(db: &str) {
|
||||
run_migrations();
|
||||
|
||||
init_schedule(&NewSchedule {
|
||||
uid: &EmgauwaUid::Off,
|
||||
name: "Off",
|
||||
periods: &Periods(vec![]),
|
||||
})
|
||||
.expect("Error initializing schedule Off");
|
||||
|
||||
init_schedule(&NewSchedule {
|
||||
uid: &EmgauwaUid::On,
|
||||
name: "On",
|
||||
periods: &Periods(vec![Period::new_on()]),
|
||||
})
|
||||
.expect("Error initializing schedule On");
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue