Refactor project into workspaces
This commit is contained in:
parent
131bdeec78
commit
bacea1e3e9
31 changed files with 119 additions and 99 deletions
2
.env
2
.env
|
|
@ -1,2 +0,0 @@
|
|||
# This is usually used in development by sqlx. It is not used in production
|
||||
DATABASE_URL=sqlite://emgauwa-core.sqlite
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -4,9 +4,8 @@
|
|||
/tests/testing_bak/
|
||||
/tests/testing_latest/
|
||||
|
||||
emgauwa-core.conf.d
|
||||
emgauwa-core.sqlite
|
||||
emgauwa-core.sqlite-*
|
||||
emgauwa-*.sqlite
|
||||
emgauwa-*.sqlite-*
|
||||
|
||||
|
||||
# Added by cargo
|
||||
|
|
|
|||
31
Cargo.lock
generated
31
Cargo.lock
generated
|
|
@ -819,12 +819,6 @@ version = "0.3.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257"
|
||||
|
||||
[[package]]
|
||||
name = "dotenv"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
|
||||
|
||||
[[package]]
|
||||
name = "dotenvy"
|
||||
version = "0.15.7"
|
||||
|
|
@ -849,15 +843,30 @@ dependencies = [
|
|||
"actix-web-actors",
|
||||
"chrono",
|
||||
"config",
|
||||
"dotenv",
|
||||
"emgauwa-lib",
|
||||
"futures",
|
||||
"lazy_static",
|
||||
"libsqlite3-sys",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"simple_logger",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "emgauwa-lib"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"actix",
|
||||
"actix-web",
|
||||
"actix-web-actors",
|
||||
"chrono",
|
||||
"futures",
|
||||
"libsqlite3-sys",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
"uuid",
|
||||
]
|
||||
|
|
@ -2618,9 +2627,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.5.0"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88ad59a7560b41a70d191093a945f0b87bc1deeda46fb237479708a1d6b6cdfc"
|
||||
checksum = "5e395fcf16a7a3d8127ec99782007af141946b4795001f876d54fb0d55978560"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"serde",
|
||||
|
|
|
|||
36
Cargo.toml
36
Cargo.toml
|
|
@ -1,30 +1,6 @@
|
|||
[package]
|
||||
name = "emgauwa-core"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-async-std", "macros", "chrono"] }
|
||||
|
||||
dotenv = "0.15"
|
||||
config = "0.13"
|
||||
lazy_static = { version = "1.4.0", features = [] }
|
||||
|
||||
simple_logger = "4.2"
|
||||
log = "0.4"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.5", features = ["serde", "v4"] }
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
libsqlite3-sys = { version = "*", features = ["bundled"] }
|
||||
|
||||
futures = "0.3.29"
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"emgauwa-core",
|
||||
"emgauwa-lib",
|
||||
]
|
||||
|
|
|
|||
3
build.rs
3
build.rs
|
|
@ -1,3 +0,0 @@
|
|||
fn main() {
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
}
|
||||
26
emgauwa-core/Cargo.toml
Normal file
26
emgauwa-core/Cargo.toml
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
[package]
|
||||
name = "emgauwa-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
[dependencies]
|
||||
emgauwa-lib = { path = "../emgauwa-lib" }
|
||||
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
|
||||
config = "0.13"
|
||||
|
||||
simple_logger = "4.2"
|
||||
log = "0.4"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.5", features = ["serde", "v4"] }
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
futures = "0.3.29"
|
||||
3
emgauwa-core/build.rs
Normal file
3
emgauwa-core/build.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://emgauwa-core.sqlite")
|
||||
}
|
||||
50
emgauwa-core/src/main.rs
Normal file
50
emgauwa-core/src/main.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use std::str::FromStr;
|
||||
|
||||
use actix_web::middleware::TrailingSlash;
|
||||
use actix_web::{middleware, web, App, HttpServer};
|
||||
use emgauwa_lib::handlers;
|
||||
use log::{trace, LevelFilter};
|
||||
use simple_logger::SimpleLogger;
|
||||
|
||||
mod settings;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let settings = settings::init();
|
||||
|
||||
let log_level: LevelFilter = log::LevelFilter::from_str(&settings.logging.level)
|
||||
.unwrap_or_else(|_| panic!("Error parsing log level."));
|
||||
trace!("Log level set to {:?}", log_level);
|
||||
|
||||
SimpleLogger::new()
|
||||
.with_level(log_level)
|
||||
.init()
|
||||
.unwrap_or_else(|_| panic!("Error initializing logger."));
|
||||
|
||||
let pool = emgauwa_lib::db::init(&settings.database).await;
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new()
|
||||
.add(("Access-Control-Allow-Origin", "*"))
|
||||
.add(("Access-Control-Allow-Headers", "*"))
|
||||
.add(("Access-Control-Allow-Methods", "*")),
|
||||
)
|
||||
.wrap(middleware::Logger::default())
|
||||
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
|
||||
.app_data(web::JsonConfig::default().error_handler(handlers::json_error_handler))
|
||||
.app_data(web::Data::new(pool.clone()))
|
||||
.service(handlers::v1::schedules::index)
|
||||
.service(handlers::v1::schedules::tagged)
|
||||
.service(handlers::v1::schedules::show)
|
||||
.service(handlers::v1::schedules::add)
|
||||
.service(handlers::v1::schedules::add_list)
|
||||
.service(handlers::v1::schedules::update)
|
||||
.service(handlers::v1::schedules::delete)
|
||||
.service(handlers::v1::ws::controllers::index)
|
||||
})
|
||||
.bind(format!("{}:{}", settings.host, settings.port))?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
54
emgauwa-core/src/settings.rs
Normal file
54
emgauwa-core/src/settings.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use config::Config;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[allow(unused)]
|
||||
pub struct Logging {
|
||||
pub level: String,
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[allow(unused)]
|
||||
pub struct Settings {
|
||||
pub database: String,
|
||||
pub port: u16,
|
||||
pub host: String,
|
||||
pub logging: Logging,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Settings {
|
||||
database: String::from("sqlite://emgauwa-core.sqlite"),
|
||||
port: 5000,
|
||||
host: String::from("127.0.0.1"),
|
||||
logging: Logging::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Logging {
|
||||
fn default() -> Self {
|
||||
Logging {
|
||||
level: String::from("info"),
|
||||
file: String::from("stdout"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init() -> Settings {
|
||||
Config::builder()
|
||||
.add_source(config::File::with_name("emgauwa-core"))
|
||||
.add_source(
|
||||
config::Environment::with_prefix("EMGAUWA")
|
||||
.prefix_separator("_")
|
||||
.separator("__"),
|
||||
)
|
||||
.build()
|
||||
.unwrap()
|
||||
.try_deserialize::<Settings>()
|
||||
.unwrap_or_else(|_| panic!("Error reading settings."))
|
||||
}
|
||||
23
emgauwa-lib/Cargo.toml
Normal file
23
emgauwa-lib/Cargo.toml
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
[package]
|
||||
name = "emgauwa-lib"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-async-std", "macros", "chrono"] }
|
||||
libsqlite3-sys = { version = "*", features = ["bundled"] }
|
||||
|
||||
log = "0.4"
|
||||
uuid = "1.6"
|
||||
futures = "0.3"
|
||||
4
emgauwa-lib/build.rs
Normal file
4
emgauwa-lib/build.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
fn main() {
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
println!("cargo:rustc-env=DATABASE_URL=sqlite://emgauwa-dev.sqlite")
|
||||
}
|
||||
8
emgauwa-lib/migrations/20231120000000_init.down.sql
Normal file
8
emgauwa-lib/migrations/20231120000000_init.down.sql
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
DROP TABLE macro_actions;
|
||||
DROP TABLE macros;
|
||||
DROP TABLE junction_relay_schedule;
|
||||
DROP TABLE junction_tag;
|
||||
DROP TABLE tags;
|
||||
DROP TABLE schedules;
|
||||
DROP TABLE relays;
|
||||
DROP TABLE controllers;
|
||||
162
emgauwa-lib/migrations/20231120000000_init.up.sql
Normal file
162
emgauwa-lib/migrations/20231120000000_init.up.sql
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
CREATE TABLE controllers
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
uid
|
||||
VARCHAR(36)
|
||||
NOT NULL
|
||||
UNIQUE,
|
||||
name
|
||||
VARCHAR(128)
|
||||
NOT NULL,
|
||||
ip
|
||||
VARCHAR(16),
|
||||
port
|
||||
INTEGER,
|
||||
relay_count
|
||||
INTEGER,
|
||||
active
|
||||
BOOLEAN
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE relays
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
name
|
||||
VARCHAR(128)
|
||||
NOT NULL,
|
||||
number
|
||||
INTEGER
|
||||
NOT NULL,
|
||||
controller_id
|
||||
INTEGER
|
||||
NOT NULL
|
||||
REFERENCES controllers (id)
|
||||
ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE schedules
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
uid
|
||||
BLOB
|
||||
NOT NULL
|
||||
UNIQUE,
|
||||
name
|
||||
VARCHAR(128)
|
||||
NOT NULL,
|
||||
periods
|
||||
BLOB
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE tags
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
tag
|
||||
VARCHAR(128)
|
||||
NOT NULL
|
||||
UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE junction_tag
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
tag_id
|
||||
INTEGER
|
||||
NOT NULL
|
||||
REFERENCES tags (id)
|
||||
ON DELETE CASCADE,
|
||||
relay_id
|
||||
INTEGER
|
||||
REFERENCES relays (id)
|
||||
ON DELETE CASCADE,
|
||||
schedule_id
|
||||
INTEGER
|
||||
REFERENCES schedules (id)
|
||||
ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE junction_relay_schedule
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
weekday
|
||||
SMALLINT
|
||||
NOT NULL,
|
||||
relay_id
|
||||
INTEGER
|
||||
REFERENCES relays (id)
|
||||
ON DELETE CASCADE,
|
||||
schedule_id
|
||||
INTEGER
|
||||
DEFAULT 1
|
||||
REFERENCES schedules (id)
|
||||
ON DELETE SET DEFAULT
|
||||
);
|
||||
|
||||
CREATE TABLE macros
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
uid
|
||||
VARCHAR(36)
|
||||
NOT NULL
|
||||
UNIQUE,
|
||||
name
|
||||
VARCHAR(128)
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE macro_actions
|
||||
(
|
||||
id
|
||||
INTEGER
|
||||
PRIMARY KEY
|
||||
AUTOINCREMENT
|
||||
NOT NULL,
|
||||
macro_id
|
||||
INTEGER
|
||||
NOT NULL
|
||||
REFERENCES macros (id)
|
||||
ON DELETE CASCADE,
|
||||
relay_id
|
||||
INTEGER
|
||||
NOT NULL
|
||||
REFERENCES relays (id)
|
||||
ON DELETE CASCADE,
|
||||
schedule_id
|
||||
INTEGER
|
||||
NOT NULL
|
||||
REFERENCES schedules (id)
|
||||
ON DELETE CASCADE,
|
||||
weekday
|
||||
SMALLINT
|
||||
NOT NULL
|
||||
);
|
||||
70
emgauwa-lib/src/db/errors.rs
Normal file
70
emgauwa-lib/src/db/errors.rs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
111
emgauwa-lib/src/db/model_utils.rs
Normal file
111
emgauwa-lib/src/db/model_utils.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
8
emgauwa-lib/src/db/models.rs
Normal file
8
emgauwa-lib/src/db/models.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Relay {
|
||||
#[serde(skip)]
|
||||
pub id: i64,
|
||||
// TODO
|
||||
}
|
||||
152
emgauwa-lib/src/db/schedules.rs
Normal file
152
emgauwa-lib/src/db/schedules.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
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::db::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(())
|
||||
}
|
||||
}
|
||||
81
emgauwa-lib/src/db/tag.rs
Normal file
81
emgauwa-lib/src/db/tag.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
146
emgauwa-lib/src/db/types/emgauwa_uid.rs
Normal file
146
emgauwa-lib/src/db/types/emgauwa_uid.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
use std::convert::TryFrom;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use sqlx::database::HasArguments;
|
||||
use sqlx::encode::IsNull;
|
||||
use sqlx::error::BoxDynError;
|
||||
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
|
||||
use sqlx::{Decode, Encode, Sqlite, Type};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum EmgauwaUid {
|
||||
Off,
|
||||
On,
|
||||
Any(Uuid),
|
||||
}
|
||||
|
||||
impl EmgauwaUid {
|
||||
const OFF_STR: &'static str = "off";
|
||||
const ON_STR: &'static str = "on";
|
||||
const OFF_U8: u8 = 0;
|
||||
const ON_U8: u8 = 1;
|
||||
const OFF_U128: u128 = 0;
|
||||
const ON_U128: u128 = 1;
|
||||
}
|
||||
|
||||
impl Default for EmgauwaUid {
|
||||
fn default() -> Self {
|
||||
EmgauwaUid::Any(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for EmgauwaUid {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
EmgauwaUid::Off => EmgauwaUid::OFF_STR.fmt(f),
|
||||
EmgauwaUid::On => EmgauwaUid::ON_STR.fmt(f),
|
||||
EmgauwaUid::Any(value) => value.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Sqlite> for EmgauwaUid {
|
||||
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 EmgauwaUid {
|
||||
//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 EmgauwaUid {
|
||||
fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
Ok(EmgauwaUid::from(<&[u8] as Decode<Sqlite>>::decode(value)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for EmgauwaUid {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
String::from(self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Uuid> for EmgauwaUid {
|
||||
fn from(uid: Uuid) -> EmgauwaUid {
|
||||
match uid.as_u128() {
|
||||
EmgauwaUid::OFF_U128 => EmgauwaUid::Off,
|
||||
EmgauwaUid::ON_U128 => EmgauwaUid::On,
|
||||
_ => EmgauwaUid::Any(uid),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for EmgauwaUid {
|
||||
type Error = uuid::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
EmgauwaUid::OFF_STR => Ok(EmgauwaUid::Off),
|
||||
EmgauwaUid::ON_STR => Ok(EmgauwaUid::On),
|
||||
any => match Uuid::from_str(any) {
|
||||
Ok(uuid) => Ok(EmgauwaUid::Any(uuid)),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&EmgauwaUid> for Uuid {
|
||||
fn from(emgauwa_uid: &EmgauwaUid) -> Uuid {
|
||||
match emgauwa_uid {
|
||||
EmgauwaUid::Off => Uuid::from_u128(EmgauwaUid::OFF_U128),
|
||||
EmgauwaUid::On => Uuid::from_u128(EmgauwaUid::ON_U128),
|
||||
EmgauwaUid::Any(value) => *value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&EmgauwaUid> for String {
|
||||
fn from(emgauwa_uid: &EmgauwaUid) -> String {
|
||||
match emgauwa_uid {
|
||||
EmgauwaUid::Off => String::from(EmgauwaUid::OFF_STR),
|
||||
EmgauwaUid::On => String::from(EmgauwaUid::ON_STR),
|
||||
EmgauwaUid::Any(value) => value.as_hyphenated().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&EmgauwaUid> for Vec<u8> {
|
||||
fn from(emgauwa_uid: &EmgauwaUid) -> Vec<u8> {
|
||||
match emgauwa_uid {
|
||||
EmgauwaUid::Off => vec![EmgauwaUid::OFF_U8],
|
||||
EmgauwaUid::On => vec![EmgauwaUid::ON_U8],
|
||||
EmgauwaUid::Any(value) => value.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&[u8]> for EmgauwaUid {
|
||||
fn from(value: &[u8]) -> Self {
|
||||
match value {
|
||||
[EmgauwaUid::OFF_U8] => EmgauwaUid::Off,
|
||||
[EmgauwaUid::ON_U8] => EmgauwaUid::On,
|
||||
value_bytes => EmgauwaUid::Any(Uuid::from_slice(value_bytes).unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for EmgauwaUid {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
EmgauwaUid::from(value.as_slice())
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue