Refactor project into workspaces
This commit is contained in:
parent
131bdeec78
commit
bacea1e3e9
31 changed files with 119 additions and 99 deletions
emgauwa-lib/src/db
83
emgauwa-lib/src/db/mod.rs
Normal file
83
emgauwa-lib/src/db/mod.rs
Normal file
|
@ -0,0 +1,83 @@
|
|||
use log::{info, trace};
|
||||
use sqlx::migrate::Migrator;
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::model_utils::Period;
|
||||
use crate::db::schedules::{Periods, Schedule};
|
||||
use crate::db::types::EmgauwaUid;
|
||||
|
||||
pub(crate) mod errors;
|
||||
mod model_utils;
|
||||
mod models;
|
||||
pub(crate) mod schedules;
|
||||
pub(crate) mod tag;
|
||||
pub mod types;
|
||||
|
||||
static MIGRATOR: Migrator = sqlx::migrate!(); // defaults to "./migrations"
|
||||
|
||||
pub async fn run_migrations(pool: &Pool<Sqlite>) {
|
||||
info!("Running migrations");
|
||||
MIGRATOR.run(pool).await.expect("Failed to run migrations.");
|
||||
}
|
||||
|
||||
async fn init_schedule(
|
||||
pool: &Pool<Sqlite>,
|
||||
uid: &EmgauwaUid,
|
||||
name: &str,
|
||||
periods: Periods,
|
||||
) -> Result<(), DatabaseError> {
|
||||
trace!("Initializing schedule {:?}", name);
|
||||
match Schedule::get_by_uid(&mut pool.acquire().await.unwrap(), uid).await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => match err {
|
||||
DatabaseError::NotFound => {
|
||||
trace!("Schedule {:?} not found, inserting", name);
|
||||
sqlx::query_as!(
|
||||
Schedule,
|
||||
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
|
||||
uid,
|
||||
name,
|
||||
periods,
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.ok_or(DatabaseError::InsertGetError)
|
||||
.map(|_| ())
|
||||
}
|
||||
_ => Err(err),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn init(db: &str) -> Pool<Sqlite> {
|
||||
let options = SqliteConnectOptions::from_str(db)
|
||||
.expect("Error parsing database path")
|
||||
.create_if_missing(true);
|
||||
|
||||
let pool: Pool<Sqlite> = SqlitePoolOptions::new()
|
||||
.acquire_timeout(std::time::Duration::from_secs(1))
|
||||
.max_connections(5)
|
||||
.connect_with(options)
|
||||
.await
|
||||
.expect("Error connecting to database");
|
||||
|
||||
run_migrations(&pool).await;
|
||||
|
||||
init_schedule(&pool, &EmgauwaUid::Off, "Off", Periods(vec![]))
|
||||
.await
|
||||
.expect("Error initializing schedule Off");
|
||||
|
||||
init_schedule(
|
||||
&pool,
|
||||
&EmgauwaUid::On,
|
||||
"On",
|
||||
Periods(vec![Period::new_on()]),
|
||||
)
|
||||
.await
|
||||
.expect("Error initializing schedule On");
|
||||
|
||||
pool
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue