Refactor project into workspaces
This commit is contained in:
parent
131bdeec78
commit
bacea1e3e9
31 changed files with 119 additions and 99 deletions
|
@ -1,70 +0,0 @@
|
|||
use actix_web::http::StatusCode;
|
||||
use actix_web::HttpResponse;
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde::{Serialize, Serializer};
|
||||
use sqlx::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DatabaseError {
|
||||
DeleteError,
|
||||
InsertError,
|
||||
InsertGetError,
|
||||
NotFound,
|
||||
Protected,
|
||||
UpdateError,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl DatabaseError {
|
||||
pub fn get_code(&self) -> StatusCode {
|
||||
match self {
|
||||
DatabaseError::NotFound => StatusCode::NOT_FOUND,
|
||||
DatabaseError::Protected => StatusCode::FORBIDDEN,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for DatabaseError {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut s = serializer.serialize_struct("error", 3)?;
|
||||
s.serialize_field("type", "database-error")?;
|
||||
s.serialize_field("code", &self.get_code().as_u16())?;
|
||||
s.serialize_field("description", &String::from(self))?;
|
||||
s.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&DatabaseError> for String {
|
||||
fn from(err: &DatabaseError) -> Self {
|
||||
match err {
|
||||
DatabaseError::InsertError => String::from("error on inserting into database"),
|
||||
DatabaseError::InsertGetError => {
|
||||
String::from("error on retrieving new entry from database (your entry was saved)")
|
||||
}
|
||||
DatabaseError::NotFound => String::from("model was not found in database"),
|
||||
DatabaseError::DeleteError => String::from("error on deleting from database"),
|
||||
DatabaseError::Protected => String::from("model is protected"),
|
||||
DatabaseError::UpdateError => String::from("error on updating the model"),
|
||||
DatabaseError::Unknown => String::from("unknown error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DatabaseError> for HttpResponse {
|
||||
fn from(err: DatabaseError) -> Self {
|
||||
HttpResponse::build(err.get_code()).json(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for DatabaseError {
|
||||
fn from(value: Error) -> Self {
|
||||
match value {
|
||||
Error::RowNotFound => DatabaseError::NotFound,
|
||||
_ => DatabaseError::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,78 +0,0 @@
|
|||
use log::{info, trace};
|
||||
use sqlx::migrate::Migrator;
|
||||
use sqlx::sqlite::SqlitePoolOptions;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::model_utils::Period;
|
||||
use crate::db::schedules::{Periods, Schedule};
|
||||
use crate::types::EmgauwaUid;
|
||||
|
||||
pub mod errors;
|
||||
pub mod models;
|
||||
pub mod schedules;
|
||||
pub mod tag;
|
||||
|
||||
mod model_utils;
|
||||
|
||||
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 pool: Pool<Sqlite> = SqlitePoolOptions::new()
|
||||
.acquire_timeout(std::time::Duration::from_secs(1))
|
||||
.max_connections(5)
|
||||
.connect(db)
|
||||
.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
|
||||
}
|
|
@ -1,111 +0,0 @@
|
|||
use crate::db::schedules::Periods;
|
||||
use chrono::{NaiveTime, Timelike};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::database::HasArguments;
|
||||
use sqlx::encode::IsNull;
|
||||
use sqlx::error::BoxDynError;
|
||||
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
|
||||
use sqlx::{Decode, Encode, Sqlite, Type};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
pub struct Period {
|
||||
#[serde(with = "period_format")]
|
||||
pub start: NaiveTime,
|
||||
#[serde(with = "period_format")]
|
||||
pub end: NaiveTime,
|
||||
}
|
||||
|
||||
mod period_format {
|
||||
use chrono::NaiveTime;
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
|
||||
const FORMAT: &str = "%H:%M";
|
||||
|
||||
pub fn serialize<S>(time: &NaiveTime, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let s = format!("{}", time.format(FORMAT));
|
||||
serializer.serialize_str(&s)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveTime, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
NaiveTime::parse_from_str(&s, FORMAT).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Period {
|
||||
pub fn new(start: NaiveTime, end: NaiveTime) -> Self {
|
||||
Period { start, end }
|
||||
}
|
||||
|
||||
pub fn new_on() -> Self {
|
||||
Period {
|
||||
start: NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
|
||||
end: NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Sqlite> for Periods {
|
||||
fn type_info() -> SqliteTypeInfo {
|
||||
<&[u8] as Type<Sqlite>>::type_info()
|
||||
}
|
||||
|
||||
fn compatible(ty: &SqliteTypeInfo) -> bool {
|
||||
<&[u8] as Type<Sqlite>>::compatible(ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'q> Encode<'q, Sqlite> for Periods {
|
||||
//noinspection DuplicatedCode
|
||||
fn encode_by_ref(&self, buf: &mut <Sqlite as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
|
||||
<&Vec<u8> as Encode<Sqlite>>::encode(&Vec::from(self), buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Sqlite> for Periods {
|
||||
fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
let blob = <&[u8] as Decode<Sqlite>>::decode(value)?;
|
||||
Ok(Periods::from(Vec::from(blob)))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Periods> for Vec<u8> {
|
||||
fn from(periods: &Periods) -> Vec<u8> {
|
||||
periods
|
||||
.0
|
||||
.iter()
|
||||
.flat_map(|period| {
|
||||
let vec = vec![
|
||||
period.start.hour() as u8,
|
||||
period.start.minute() as u8,
|
||||
period.end.hour() as u8,
|
||||
period.end.minute() as u8,
|
||||
];
|
||||
vec
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for Periods {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
let mut vec = Vec::new();
|
||||
for i in (3..value.len()).step_by(4) {
|
||||
let start_val_h: u32 = value[i - 3] as u32;
|
||||
let start_val_m: u32 = value[i - 2] as u32;
|
||||
let end_val_h: u32 = value[i - 1] as u32;
|
||||
let end_val_m: u32 = value[i] as u32;
|
||||
vec.push(Period {
|
||||
start: NaiveTime::from_hms_opt(start_val_h, start_val_m, 0).unwrap(),
|
||||
end: NaiveTime::from_hms_opt(end_val_h, end_val_m, 0).unwrap(),
|
||||
});
|
||||
}
|
||||
Periods(vec)
|
||||
}
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Relay {
|
||||
#[serde(skip)]
|
||||
pub id: i64,
|
||||
// TODO
|
||||
}
|
|
@ -1,152 +0,0 @@
|
|||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::borrow::Borrow;
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::Sqlite;
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::model_utils::Period;
|
||||
use crate::db::tag::Tag;
|
||||
use crate::types::EmgauwaUid;
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub struct Schedule {
|
||||
#[serde(skip)]
|
||||
pub id: i64,
|
||||
#[serde(rename(serialize = "id"))]
|
||||
pub uid: EmgauwaUid,
|
||||
pub name: String,
|
||||
pub periods: Periods,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
pub struct Periods(pub Vec<Period>);
|
||||
|
||||
impl Schedule {
|
||||
pub async fn get_all(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
) -> Result<Vec<Schedule>, DatabaseError> {
|
||||
Ok(sqlx::query_as!(Schedule, "SELECT * FROM schedules")
|
||||
.fetch_all(conn.deref_mut())
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn get_by_uid(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
filter_uid: &EmgauwaUid,
|
||||
) -> Result<Schedule, DatabaseError> {
|
||||
sqlx::query_as!(
|
||||
Schedule,
|
||||
"SELECT * FROM schedules WHERE uid = ?",
|
||||
filter_uid
|
||||
)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await
|
||||
.map(|s| s.ok_or(DatabaseError::NotFound))?
|
||||
}
|
||||
|
||||
pub async fn get_by_tag(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
tag: &Tag,
|
||||
) -> Result<Vec<Schedule>, DatabaseError> {
|
||||
Ok(sqlx::query_as!(Schedule, "SELECT schedule.* FROM schedules AS schedule INNER JOIN junction_tag ON junction_tag.schedule_id = schedule.id WHERE junction_tag.tag_id = ?", tag.id)
|
||||
.fetch_all(conn.deref_mut())
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn delete_by_uid(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
filter_uid: EmgauwaUid,
|
||||
) -> Result<(), DatabaseError> {
|
||||
let filter_uid = match filter_uid {
|
||||
EmgauwaUid::Off => Err(DatabaseError::Protected),
|
||||
EmgauwaUid::On => Err(DatabaseError::Protected),
|
||||
EmgauwaUid::Any(_) => Ok(filter_uid),
|
||||
}?;
|
||||
|
||||
sqlx::query!("DELETE FROM schedules WHERE uid = ?", filter_uid)
|
||||
.execute(conn.deref_mut())
|
||||
.await
|
||||
.map(|res| match res.rows_affected() {
|
||||
0 => Err(DatabaseError::DeleteError),
|
||||
_ => Ok(()),
|
||||
})?
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
new_name: &str,
|
||||
new_periods: &Periods,
|
||||
) -> Result<Schedule, DatabaseError> {
|
||||
let uid = EmgauwaUid::default();
|
||||
sqlx::query_as!(
|
||||
Schedule,
|
||||
"INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
|
||||
uid,
|
||||
new_name,
|
||||
new_periods,
|
||||
)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await?
|
||||
.ok_or(DatabaseError::InsertGetError)
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
&self,
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
new_name: &str,
|
||||
new_periods: &Periods,
|
||||
) -> Result<Schedule, DatabaseError> {
|
||||
// overwrite periods on protected schedules
|
||||
let new_periods = match self.uid {
|
||||
EmgauwaUid::Off | EmgauwaUid::On => self.periods.borrow(),
|
||||
EmgauwaUid::Any(_) => new_periods,
|
||||
};
|
||||
|
||||
sqlx::query!(
|
||||
"UPDATE schedules SET name = ?, periods = ? WHERE id = ?",
|
||||
new_name,
|
||||
new_periods,
|
||||
self.id,
|
||||
)
|
||||
.execute(conn.deref_mut())
|
||||
.await?;
|
||||
|
||||
Schedule::get_by_uid(conn, &self.uid).await
|
||||
}
|
||||
|
||||
pub async fn get_tags(
|
||||
&self,
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
) -> Result<Vec<String>, DatabaseError> {
|
||||
Ok(sqlx::query_scalar!("SELECT tag FROM tags INNER JOIN junction_tag ON junction_tag.tag_id = tags.id WHERE junction_tag.schedule_id = ?", self.id)
|
||||
.fetch_all(conn.deref_mut())
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn set_tags(
|
||||
&self,
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
new_tags: &[String],
|
||||
) -> Result<(), DatabaseError> {
|
||||
sqlx::query!("DELETE FROM junction_tag WHERE schedule_id = ?", self.id)
|
||||
.execute(conn.deref_mut())
|
||||
.await?;
|
||||
|
||||
for new_tag in new_tags {
|
||||
let tag: Option<Tag> =
|
||||
sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", new_tag)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await?;
|
||||
|
||||
let tag = match tag {
|
||||
Some(id) => id,
|
||||
None => Tag::create(conn, new_tag).await?,
|
||||
};
|
||||
|
||||
tag.link_schedule(conn, self).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
use serde_derive::Serialize;
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::Sqlite;
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::models::*;
|
||||
use crate::db::schedules::Schedule;
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub struct Tag {
|
||||
pub id: i64,
|
||||
pub tag: String,
|
||||
}
|
||||
|
||||
pub struct JunctionTag {
|
||||
pub id: i64,
|
||||
pub tag_id: i64,
|
||||
pub relay_id: Option<i64>,
|
||||
pub schedule_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
pub async fn create(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
new_tag: &str,
|
||||
) -> Result<Tag, DatabaseError> {
|
||||
sqlx::query_as!(
|
||||
Tag,
|
||||
"INSERT INTO tags (tag) VALUES (?) RETURNING *",
|
||||
new_tag
|
||||
)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await?
|
||||
.ok_or(DatabaseError::InsertGetError)
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
target_tag: &str,
|
||||
) -> Result<Tag, DatabaseError> {
|
||||
sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", target_tag)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await
|
||||
.map(|t| t.ok_or(DatabaseError::NotFound))?
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn link_relay(
|
||||
&self,
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
target_relay: &Relay,
|
||||
) -> Result<JunctionTag, DatabaseError> {
|
||||
sqlx::query_as!(
|
||||
JunctionTag,
|
||||
"INSERT INTO junction_tag (tag_id, relay_id) VALUES (?, ?) RETURNING *",
|
||||
self.id,
|
||||
target_relay.id
|
||||
)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await?
|
||||
.ok_or(DatabaseError::InsertGetError)
|
||||
}
|
||||
|
||||
pub async fn link_schedule(
|
||||
&self,
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
target_schedule: &Schedule,
|
||||
) -> Result<JunctionTag, DatabaseError> {
|
||||
sqlx::query_as!(
|
||||
JunctionTag,
|
||||
"INSERT INTO junction_tag (tag_id, schedule_id) VALUES (?, ?) RETURNING *",
|
||||
self.id,
|
||||
target_schedule.id
|
||||
)
|
||||
.fetch_optional(conn.deref_mut())
|
||||
.await?
|
||||
.ok_or(DatabaseError::InsertGetError)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue