Migrate to sqlx

This commit is contained in:
Tobias Reisinger 2023-11-21 00:44:45 +01:00
parent bd44dc3183
commit f3d08aab80
19 changed files with 409 additions and 461 deletions

2
.env
View file

@ -1 +1 @@
DATABASE_URL=emgauwa-core.sqlite DATABASE_URL=sqlite://emgauwa-core.sqlite

1
.gitignore vendored
View file

@ -6,6 +6,7 @@
emgauwa-core.conf.d emgauwa-core.conf.d
emgauwa-core.sqlite emgauwa-core.sqlite
emgauwa-core.sqlite-*
# Added by cargo # Added by cargo

BIN
Cargo.lock generated

Binary file not shown.

View file

@ -12,8 +12,7 @@ authors = ["Tobias Reisinger <tobias@msrg.cc>"]
[dependencies] [dependencies]
actix-web = "4.4" actix-web = "4.4"
diesel = { version = "2.1", features = ["uuid", "sqlite"] } sqlx = { version = "0.7", features = ["sqlite", "runtime-async-std", "macros", "chrono"] }
diesel_migrations = "2.1"
dotenv = "0.15" dotenv = "0.15"
config = "0.13" config = "0.13"
@ -30,3 +29,5 @@ serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
libsqlite3-sys = { version = "*", features = ["bundled"] } libsqlite3-sys = { version = "*", features = ["bundled"] }
futures = "0.3.29"

View file

@ -1,5 +0,0 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/db/schema.rs"

View file

@ -1,73 +1,80 @@
use std::env; use log::{info, trace};
use sqlx::migrate::Migrator;
use sqlx::{Pool, Sqlite};
use sqlx::sqlite::SqlitePoolOptions;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::model_utils::Period; use crate::db::model_utils::Period;
use crate::db::models::{NewSchedule, Periods}; use crate::db::models::{Schedule, Periods};
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
use diesel::prelude::*;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use dotenv::dotenv;
use log::{info, trace};
pub mod errors; pub mod errors;
pub mod models; pub mod models;
pub mod schedules; pub mod schedules;
pub mod schema;
pub mod tag; pub mod tag;
mod model_utils; mod model_utils;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations"); static MIGRATOR: Migrator = sqlx::migrate!(); // defaults to "./migrations"
fn get_connection() -> SqliteConnection { pub async fn run_migrations(pool: &Pool<Sqlite>) {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
SqliteConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}
pub fn run_migrations() {
info!("Running migrations"); info!("Running migrations");
let mut connection = get_connection(); MIGRATOR
connection .run(pool)
.run_pending_migrations(MIGRATIONS) .await
.expect("Failed to run migrations."); .expect("Failed to run migrations.");
} }
fn init_schedule(schedule: &NewSchedule) -> Result<(), DatabaseError> { async fn init_schedule(pool: &Pool<Sqlite>, uid: &EmgauwaUid, name: &str, periods: Periods) -> Result<(), DatabaseError> {
trace!("Initializing schedule {:?}", schedule.name); trace!("Initializing schedule {:?}", name);
match schedules::get_schedule_by_uid(schedule.uid.clone()) { match schedules::get_schedule_by_uid(pool, uid).await {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => match err { Err(err) => match err {
DatabaseError::NotFound => { DatabaseError::NotFound => {
trace!("Schedule {:?} not found, inserting", schedule.name); trace!("Schedule {:?} not found, inserting", name);
let mut connection = get_connection(); sqlx::query_as!(Schedule, "INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
diesel::insert_into(schema::schedules::table) uid,
.values(schedule) name,
.execute(&mut connection) periods,
)
.fetch_optional(pool)
.await?
.ok_or(DatabaseError::InsertGetError)
.map(|_| ()) .map(|_| ())
.map_err(DatabaseError::InsertError)
} }
_ => Err(err), _ => Err(err),
}, },
} }
} }
pub fn init(db: &str) {
run_migrations();
init_schedule(&NewSchedule { pub async fn init(db: &str) -> Pool<Sqlite> {
uid: &EmgauwaUid::Off, let pool: Pool<Sqlite> = SqlitePoolOptions::new()
name: "Off", .acquire_timeout(std::time::Duration::from_secs(1))
periods: &Periods(vec![]), .max_connections(5)
}) .connect(db)
.expect("Error initializing schedule Off"); .await
.expect("Error connecting to database.");
init_schedule(&NewSchedule { run_migrations(&pool).await;
uid: &EmgauwaUid::On,
name: "On", init_schedule(
periods: &Periods(vec![Period::new_on()]), &pool,
}) &EmgauwaUid::Off,
.expect("Error initializing schedule On"); "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
} }

View file

@ -2,15 +2,16 @@ use actix_web::http::StatusCode;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use sqlx::Error;
#[derive(Debug)] #[derive(Debug)]
pub enum DatabaseError { pub enum DatabaseError {
DeleteError, DeleteError,
InsertError(diesel::result::Error), InsertError,
InsertGetError, InsertGetError,
NotFound, NotFound,
Protected, Protected,
UpdateError(diesel::result::Error), UpdateError,
Unknown, Unknown,
} }
@ -40,14 +41,14 @@ impl Serialize for DatabaseError {
impl From<&DatabaseError> for String { impl From<&DatabaseError> for String {
fn from(err: &DatabaseError) -> Self { fn from(err: &DatabaseError) -> Self {
match err { match err {
DatabaseError::InsertError(_) => String::from("error on inserting into database"), DatabaseError::InsertError => String::from("error on inserting into database"),
DatabaseError::InsertGetError => { DatabaseError::InsertGetError => {
String::from("error on retrieving new entry from database (your entry was saved)") String::from("error on retrieving new entry from database (your entry was saved)")
} }
DatabaseError::NotFound => String::from("model was not found in database"), DatabaseError::NotFound => String::from("model was not found in database"),
DatabaseError::DeleteError => String::from("error on deleting from database"), DatabaseError::DeleteError => String::from("error on deleting from database"),
DatabaseError::Protected => String::from("model is protected"), DatabaseError::Protected => String::from("model is protected"),
DatabaseError::UpdateError(_) => String::from("error on updating the model"), DatabaseError::UpdateError => String::from("error on updating the model"),
DatabaseError::Unknown => String::from("unknown error"), DatabaseError::Unknown => String::from("unknown error"),
} }
} }
@ -58,3 +59,12 @@ impl From<DatabaseError> for HttpResponse {
HttpResponse::build(err.get_code()).json(err) 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,
}
}
}

View file

@ -1,14 +1,13 @@
use crate::db::models::Periods; use crate::db::models::Periods;
use chrono::{NaiveTime, Timelike}; use chrono::{NaiveTime, Timelike};
use diesel::deserialize::FromSql;
use diesel::serialize::{IsNull, Output, ToSql};
use diesel::sql_types::Binary;
use diesel::sqlite::Sqlite;
use diesel::{deserialize, serialize};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{Decode, Encode, Sqlite, Type};
use sqlx::database::HasArguments;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
#[derive(Debug, Serialize, Deserialize, AsExpression, FromSqlRow, PartialEq, Clone)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[diesel(sql_type = Binary)]
pub struct Period { pub struct Period {
#[serde(with = "period_format")] #[serde(with = "period_format")]
pub start: NaiveTime, pub start: NaiveTime,
@ -52,13 +51,81 @@ impl Period {
} }
} }
impl ToSql<Binary, Sqlite> for Periods //impl ToSql<Binary, Sqlite> for Periods
where //where
Vec<u8>: ToSql<Binary, Sqlite>, // Vec<u8>: ToSql<Binary, Sqlite>,
{ //{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result { // fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
let periods_u8: Vec<u8> = self // let periods_u8: Vec<u8> = self
.0 // .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();
//
// out.set_value(periods_u8);
//
// Ok(IsNull::No)
// }
//}
//
//impl<DB> FromSql<Binary, DB> for Periods
//where
// DB: diesel::backend::Backend,
// Vec<u8>: FromSql<Binary, DB>,
//{
// fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
// let blob: Vec<u8> = Vec::from_sql(bytes).unwrap();
//
// let mut vec = Vec::new();
// for i in (3..blob.len()).step_by(4) {
// let start_val_h: u32 = blob[i - 3] as u32;
// let start_val_m: u32 = blob[i - 2] as u32;
// let end_val_h: u32 = blob[i - 1] as u32;
// let end_val_m: u32 = blob[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(),
// });
// }
// Ok(Periods(vec))
// }
//}
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() .iter()
.flat_map(|period| { .flat_map(|period| {
let vec = vec![ let vec = vec![
@ -69,33 +136,23 @@ where
]; ];
vec vec
}) })
.collect(); .collect()
out.set_value(periods_u8);
Ok(IsNull::No)
} }
} }
impl<DB> FromSql<Binary, DB> for Periods impl From<Vec<u8>> for Periods {
where fn from(value: Vec<u8>) -> Self {
DB: diesel::backend::Backend,
Vec<u8>: FromSql<Binary, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let blob: Vec<u8> = Vec::from_sql(bytes).unwrap();
let mut vec = Vec::new(); let mut vec = Vec::new();
for i in (3..blob.len()).step_by(4) { for i in (3..value.len()).step_by(4) {
let start_val_h: u32 = blob[i - 3] as u32; let start_val_h: u32 = value[i - 3] as u32;
let start_val_m: u32 = blob[i - 2] as u32; let start_val_m: u32 = value[i - 2] as u32;
let end_val_h: u32 = blob[i - 1] as u32; let end_val_h: u32 = value[i - 1] as u32;
let end_val_m: u32 = blob[i] as u32; let end_val_m: u32 = value[i] as u32;
vec.push(Period { vec.push(Period {
start: NaiveTime::from_hms_opt(start_val_h, start_val_m, 0).unwrap(), 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(), end: NaiveTime::from_hms_opt(end_val_h, end_val_m, 0).unwrap(),
}); });
} }
Ok(Periods(vec)) Periods(vec)
} }
} }

View file

@ -1,68 +1,37 @@
use crate::db::model_utils::Period; use crate::db::model_utils::Period;
use diesel::sql_types::Binary;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::schema::*;
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
#[derive(Debug, Serialize, Identifiable, Queryable)] #[derive(Debug, Serialize)]
pub struct Relay { pub struct Relay {
#[serde(skip)] #[serde(skip)]
pub id: i32, pub id: i64,
// TODO // TODO
} }
#[derive(Debug, Serialize, Identifiable, Queryable, Clone)] #[derive(Debug, Serialize, Clone)]
pub struct Schedule { pub struct Schedule {
#[serde(skip)] #[serde(skip)]
pub id: i32, pub id: i64,
#[serde(rename(serialize = "id"))] #[serde(rename(serialize = "id"))]
pub uid: EmgauwaUid, pub uid: EmgauwaUid,
pub name: String, pub name: String,
pub periods: Periods, pub periods: Periods,
} }
#[derive(Insertable)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[diesel(table_name = crate::db::schema::schedules)]
pub struct NewSchedule<'a> {
pub uid: &'a EmgauwaUid,
pub name: &'a str,
pub periods: &'a Periods,
}
#[derive(Debug, Serialize, Deserialize, AsExpression, FromSqlRow, PartialEq, Clone)]
#[diesel(sql_type = Binary)]
pub struct Periods(pub Vec<Period>); pub struct Periods(pub Vec<Period>);
#[derive(Debug, Serialize, Identifiable, Queryable, Clone)] #[derive(Debug, Serialize, Clone)]
#[diesel(table_name = crate::db::schema::tags)]
pub struct Tag { pub struct Tag {
pub id: i32, pub id: i64,
pub tag: String, pub tag: String,
} }
#[derive(Insertable)]
#[diesel(table_name = crate::db::schema::tags)]
pub struct NewTag<'a> {
pub tag: &'a str,
}
#[derive(Queryable, Associations, Identifiable)]
#[diesel(belongs_to(Relay))]
#[diesel(belongs_to(Schedule))]
#[diesel(belongs_to(Tag))]
#[diesel(table_name = crate::db::schema::junction_tag)]
pub struct JunctionTag { pub struct JunctionTag {
pub id: i32, pub id: i64,
pub tag_id: i32, pub tag_id: i64,
pub relay_id: Option<i32>, pub relay_id: Option<i64>,
pub schedule_id: Option<i32>, pub schedule_id: Option<i64>,
}
#[derive(Insertable)]
#[diesel(table_name = crate::db::schema::junction_tag)]
pub struct NewJunctionTag {
pub tag_id: i32,
pub relay_id: Option<i32>,
pub schedule_id: Option<i32>,
} }

View file

@ -1,141 +1,106 @@
use diesel::dsl::sql;
use diesel::prelude::*;
use std::borrow::Borrow; use std::borrow::Borrow;
use sqlx::{Pool, Sqlite};
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::models::*; use crate::db::models::*;
use crate::db::schema::junction_tag::dsl::junction_tag; use crate::db::tag::{create_junction_tag_schedule, create_tag};
use crate::db::schema::schedules::dsl::schedules;
use crate::db::schema::tags::dsl::tags;
use crate::db::tag::{create_junction_tag, create_tag};
use crate::db::{get_connection, schema};
pub fn get_schedule_tags(schedule: &Schedule) -> Vec<String> { pub async fn get_schedule_tags(pool: &Pool<Sqlite>, schedule: &Schedule) -> Result<Vec<String>, DatabaseError> {
let mut connection = get_connection(); Ok(sqlx::query_scalar!("SELECT tag FROM tags INNER JOIN junction_tag ON junction_tag.tag_id = tags.id WHERE junction_tag.schedule_id = ?", schedule.id)
JunctionTag::belonging_to(schedule) .fetch_all(pool)
.inner_join(schema::tags::dsl::tags) .await?)
.select(schema::tags::tag)
.load::<String>(&mut connection)
.expect("Error loading tags")
} }
pub fn get_schedules() -> Vec<Schedule> { pub async fn get_schedules(pool: &Pool<Sqlite>) -> Result<Vec<Schedule>, DatabaseError> {
let mut connection = get_connection(); Ok(sqlx::query_as!(Schedule, "SELECT * FROM schedules")
schedules .fetch_all(pool)
.load::<Schedule>(&mut connection) .await?)
.expect("Error loading schedules")
} }
pub fn get_schedule_by_uid(filter_uid: EmgauwaUid) -> Result<Schedule, DatabaseError> { pub async fn get_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: &EmgauwaUid) -> Result<Schedule, DatabaseError> {
let mut connection = get_connection(); sqlx::query_as!(Schedule, "SELECT * FROM schedules WHERE uid = ?", filter_uid)
let result = schedules .fetch_optional(pool)
.filter(schema::schedules::uid.eq(filter_uid)) .await
.first::<Schedule>(&mut connection) .map(|s| s.ok_or(DatabaseError::NotFound))?
.or(Err(DatabaseError::NotFound))?;
Ok(result)
} }
pub fn get_schedules_by_tag(tag: &Tag) -> Vec<Schedule> { pub async fn get_schedules_by_tag(pool: &Pool<Sqlite>, tag: &Tag) -> Result<Vec<Schedule>, DatabaseError> {
let mut connection = get_connection(); 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)
JunctionTag::belonging_to(tag) .fetch_all(pool)
.inner_join(schedules) .await?)
.select(schema::schedules::all_columns)
.load::<Schedule>(&mut connection)
.expect("Error loading tags")
} }
pub fn delete_schedule_by_uid(filter_uid: EmgauwaUid) -> Result<(), DatabaseError> { pub async fn delete_schedule_by_uid(pool: &Pool<Sqlite>, filter_uid: EmgauwaUid) -> Result<(), DatabaseError> {
let filter_uid = match filter_uid { let filter_uid = match filter_uid {
EmgauwaUid::Off => Err(DatabaseError::Protected), EmgauwaUid::Off => Err(DatabaseError::Protected),
EmgauwaUid::On => Err(DatabaseError::Protected), EmgauwaUid::On => Err(DatabaseError::Protected),
EmgauwaUid::Any(_) => Ok(filter_uid), EmgauwaUid::Any(_) => Ok(filter_uid),
}?; }?;
let mut connection = get_connection(); sqlx::query!("DELETE FROM schedules WHERE uid = ?", filter_uid)
match diesel::delete(schedules.filter(schema::schedules::uid.eq(filter_uid))) .execute(pool)
.execute(&mut connection) .await
{ .map(|res| match res.rows_affected() {
Ok(rows) => { 0 => Err(DatabaseError::DeleteError),
if rows != 0 { _ => Ok(()),
Ok(()) })?
} else {
Err(DatabaseError::DeleteError)
}
}
Err(_) => Err(DatabaseError::DeleteError),
}
} }
pub fn create_schedule(new_name: &str, new_periods: &Periods) -> Result<Schedule, DatabaseError> { pub async fn create_schedule(pool: &Pool<Sqlite>, new_name: &str, new_periods: &Periods) -> Result<Schedule, DatabaseError> {
let mut connection = get_connection(); let uid = EmgauwaUid::default();
sqlx::query_as!(Schedule, "INSERT INTO schedules (uid, name, periods) VALUES (?, ?, ?) RETURNING *",
let new_schedule = NewSchedule { uid,
uid: &EmgauwaUid::default(), new_name,
name: new_name, new_periods,
periods: new_periods, )
}; .fetch_optional(pool)
.await?
diesel::insert_into(schedules) .ok_or(DatabaseError::InsertGetError)
.values(&new_schedule)
.execute(&mut connection)
.map_err(DatabaseError::InsertError)?;
let result = schedules
.find(sql("last_insert_rowid()"))
.get_result::<Schedule>(&mut connection)
.or(Err(DatabaseError::InsertGetError))?;
Ok(result)
} }
pub fn update_schedule( pub async fn update_schedule(
pool: &Pool<Sqlite>,
schedule: &Schedule, schedule: &Schedule,
new_name: &str, new_name: &str,
new_periods: &Periods, new_periods: &Periods,
) -> Result<Schedule, DatabaseError> { ) -> Result<Schedule, DatabaseError> {
let mut connection = get_connection(); // overwrite periods on protected schedules
let new_periods = match schedule.uid { let new_periods = match schedule.uid {
EmgauwaUid::Off | EmgauwaUid::On => schedule.periods.borrow(), EmgauwaUid::Off | EmgauwaUid::On => schedule.periods.borrow(),
EmgauwaUid::Any(_) => new_periods, EmgauwaUid::Any(_) => new_periods,
}; };
diesel::update(schedule) sqlx::query!("UPDATE schedules SET name = ?, periods = ? WHERE id = ?",
.set(( new_name,
schema::schedules::name.eq(new_name), new_periods,
schema::schedules::periods.eq(new_periods), schedule.id,
)) )
.execute(&mut connection) .execute(pool)
.map_err(DatabaseError::UpdateError)?; .await?;
get_schedule_by_uid(schedule.uid.clone()) get_schedule_by_uid(pool, &schedule.uid).await
} }
pub fn set_schedule_tags(schedule: &Schedule, new_tags: &[String]) -> Result<(), DatabaseError> { pub async fn set_schedule_tags(pool: &Pool<Sqlite>, schedule: &Schedule, new_tags: &[String]) -> Result<(), DatabaseError> {
let mut connection = get_connection(); sqlx::query!("DELETE FROM junction_tag WHERE schedule_id = ?", schedule.id)
diesel::delete(junction_tag.filter(schema::junction_tag::schedule_id.eq(schedule.id))) .execute(pool)
.execute(&mut connection) .await?;
.or(Err(DatabaseError::DeleteError))?;
let mut database_tags: Vec<Tag> = tags
.filter(schema::tags::tag.eq_any(new_tags))
.load::<Tag>(&mut connection)
.expect("Error loading tags");
// create missing tags
for new_tag in new_tags { for new_tag in new_tags {
if !database_tags.iter().any(|tab_db| tab_db.tag.eq(new_tag)) { let tag: Option<Tag> = sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", new_tag)
database_tags.push(create_tag(new_tag).expect("Error inserting tag")); .fetch_optional(pool)
} .await?;
}
for database_tag in database_tags { let tag = match tag {
create_junction_tag(database_tag, None, Some(schedule)) Some(id) => id,
.expect("Error saving junction between tag and schedule"); None => {
} create_tag(pool, new_tag).await?
}
};
create_junction_tag_schedule(pool, tag, schedule).await?;
}
Ok(()) Ok(())
} }

View file

@ -1,93 +0,0 @@
table! {
controllers (id) {
id -> Integer,
uid -> Text,
name -> Text,
ip -> Nullable<Text>,
port -> Nullable<Integer>,
relay_count -> Nullable<Integer>,
active -> Bool,
}
}
table! {
junction_relay_schedule (id) {
id -> Integer,
weekday -> SmallInt,
relay_id -> Nullable<Integer>,
schedule_id -> Nullable<Integer>,
}
}
table! {
junction_tag (id) {
id -> Integer,
tag_id -> Integer,
relay_id -> Nullable<Integer>,
schedule_id -> Nullable<Integer>,
}
}
table! {
macro_actions (id) {
id -> Integer,
macro_id -> Integer,
relay_id -> Integer,
schedule_id -> Integer,
weekday -> SmallInt,
}
}
table! {
macros (id) {
id -> Integer,
uid -> Text,
name -> Text,
}
}
table! {
relays (id) {
id -> Integer,
name -> Text,
number -> Integer,
controller_id -> Integer,
}
}
table! {
schedules (id) {
id -> Integer,
uid -> Binary,
name -> Text,
periods -> Binary,
}
}
table! {
tags (id) {
id -> Integer,
tag -> Text,
}
}
joinable!(junction_relay_schedule -> relays (relay_id));
joinable!(junction_relay_schedule -> schedules (schedule_id));
joinable!(junction_tag -> relays (relay_id));
joinable!(junction_tag -> schedules (schedule_id));
joinable!(junction_tag -> tags (tag_id));
joinable!(macro_actions -> macros (macro_id));
joinable!(macro_actions -> relays (relay_id));
joinable!(macro_actions -> schedules (schedule_id));
joinable!(relays -> controllers (controller_id));
allow_tables_to_appear_in_same_query!(
controllers,
junction_relay_schedule,
junction_tag,
macro_actions,
macros,
relays,
schedules,
tags,
);

View file

@ -1,63 +1,41 @@
use diesel::dsl::sql; use sqlx::{Pool, Sqlite};
use diesel::prelude::*;
use crate::db::errors::DatabaseError; use crate::db::errors::DatabaseError;
use crate::db::models::*; use crate::db::models::*;
use crate::db::schema::junction_tag::dsl::junction_tag;
use crate::db::schema::tags::dsl::tags;
use crate::db::{get_connection, schema};
pub fn create_tag(new_tag: &str) -> Result<Tag, DatabaseError> { pub async fn create_tag(pool: &Pool<Sqlite>, new_tag: &str) -> Result<Tag, DatabaseError> {
let mut connection = get_connection(); sqlx::query_as!(Tag, "INSERT INTO tags (tag) VALUES (?) RETURNING *", new_tag)
.fetch_optional(pool)
let new_tag = NewTag { tag: new_tag }; .await?
.ok_or(DatabaseError::InsertGetError)
diesel::insert_into(tags)
.values(&new_tag)
.execute(&mut connection)
.map_err(DatabaseError::InsertError)?;
let result = tags
.find(sql("last_insert_rowid()"))
.get_result::<Tag>(&mut connection)
.or(Err(DatabaseError::InsertGetError))?;
Ok(result)
} }
pub fn get_tag(target_tag: &str) -> Result<Tag, DatabaseError> { pub async fn get_tag(pool: &Pool<Sqlite>, target_tag: &str) -> Result<Tag, DatabaseError> {
let mut connection = get_connection(); sqlx::query_as!(Tag, "SELECT * FROM tags WHERE tag = ?", target_tag)
.fetch_optional(pool)
let result = tags .await
.filter(schema::tags::tag.eq(target_tag)) .map(|t| t.ok_or(DatabaseError::NotFound))?
.first::<Tag>(&mut connection)
.or(Err(DatabaseError::NotFound))?;
Ok(result)
} }
pub fn create_junction_tag( #[allow(dead_code)]
pub async fn create_junction_tag_relay(
pool: &Pool<Sqlite>,
target_tag: Tag, target_tag: Tag,
target_relay: Option<&Relay>, target_relay: &Relay,
target_schedule: Option<&Schedule>,
) -> Result<JunctionTag, DatabaseError> { ) -> Result<JunctionTag, DatabaseError> {
let mut connection = get_connection();
let new_junction_tag = NewJunctionTag { sqlx::query_as!(JunctionTag, "INSERT INTO junction_tag (tag_id, relay_id) VALUES (?, ?) RETURNING *", target_tag.id, target_relay.id)
relay_id: target_relay.map(|r| r.id), .fetch_optional(pool)
schedule_id: target_schedule.map(|s| s.id), .await?
tag_id: target_tag.id, .ok_or(DatabaseError::InsertGetError)
}; }
diesel::insert_into(junction_tag) pub async fn create_junction_tag_schedule(
.values(&new_junction_tag) pool: &Pool<Sqlite>,
.execute(&mut connection) target_tag: Tag,
.map_err(DatabaseError::InsertError)?; target_schedule: &Schedule,
) -> Result<JunctionTag, DatabaseError> {
let result = junction_tag sqlx::query_as!(JunctionTag, "INSERT INTO junction_tag (tag_id, schedule_id) VALUES (?, ?) RETURNING *", target_tag.id, target_schedule.id)
.find(sql("last_insert_rowid()")) .fetch_optional(pool)
.get_result::<JunctionTag>(&mut connection) .await?
.or(Err(DatabaseError::InsertGetError))?; .ok_or(DatabaseError::InsertGetError)
Ok(result)
} }

View file

@ -3,6 +3,8 @@ use actix_web::{delete, get, post, put, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::borrow::Borrow; use std::borrow::Borrow;
use std::convert::TryFrom; use std::convert::TryFrom;
use futures::future;
use sqlx::{Pool, Sqlite};
use crate::db::models::{Periods, Schedule}; use crate::db::models::{Periods, Schedule};
use crate::db::schedules::*; use crate::db::schedules::*;
@ -20,38 +22,59 @@ pub struct RequestSchedule {
} }
#[get("/api/v1/schedules")] #[get("/api/v1/schedules")]
pub async fn index() -> impl Responder { pub async fn index(pool: web::Data<Pool<Sqlite>>) -> impl Responder {
let schedules = get_schedules(); let schedules = get_schedules(&pool).await;
let return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect(); if let Err(err) = schedules {
return HttpResponse::from(err);
}
let schedules = schedules.unwrap();
let mut return_schedules: Vec<ReturnSchedule> = schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool);
}
HttpResponse::Ok().json(return_schedules) HttpResponse::Ok().json(return_schedules)
} }
#[get("/api/v1/schedules/tag/{tag}")] #[get("/api/v1/schedules/tag/{tag}")]
pub async fn tagged(path: web::Path<(String,)>) -> impl Responder { pub async fn tagged(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let (tag,) = path.into_inner(); let (tag,) = path.into_inner();
let tag_db = get_tag(&tag); let tag_db = get_tag(&pool, &tag).await;
if tag_db.is_err() { if let Err(err) = tag_db {
return HttpResponse::from(tag_db.unwrap_err()); return HttpResponse::from(err);
} }
let tag_db = tag_db.unwrap(); let tag_db = tag_db.unwrap();
let schedules = get_schedules_by_tag(&tag_db); let schedules = get_schedules_by_tag(&pool, &tag_db).await;
let return_schedules: Vec<ReturnSchedule> = if let Err(err) = schedules {
return HttpResponse::from(err);
}
let schedules = schedules.unwrap();
let mut return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect(); schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool);
}
HttpResponse::Ok().json(return_schedules) HttpResponse::Ok().json(return_schedules)
} }
#[get("/api/v1/schedules/{schedule_id}")] #[get("/api/v1/schedules/{schedule_id}")]
pub async fn show(path: web::Path<(String,)>) -> impl Responder { pub async fn show(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
match emgauwa_uid { match emgauwa_uid {
Ok(uid) => { Ok(uid) => {
let schedule = get_schedule_by_uid(uid); let schedule = get_schedule_by_uid(&pool, &uid).await;
match schedule { match schedule {
Ok(ok) => HttpResponse::Ok().json(ReturnSchedule::from(ok)), Ok(ok) => {
let mut return_schedule = ReturnSchedule::from(ok);
return_schedule.load_tags(&pool);
HttpResponse::Ok().json(return_schedule)
},
Err(err) => HttpResponse::from(err), Err(err) => HttpResponse::from(err),
} }
} }
@ -60,35 +83,40 @@ pub async fn show(path: web::Path<(String,)>) -> impl Responder {
} }
#[post("/api/v1/schedules")] #[post("/api/v1/schedules")]
pub async fn add(data: web::Json<RequestSchedule>) -> impl Responder { pub async fn add(pool: web::Data<Pool<Sqlite>>, data: web::Json<RequestSchedule>) -> impl Responder {
let new_schedule = create_schedule(&data.name, &data.periods); let new_schedule = create_schedule(&pool, &data.name, &data.periods).await;
if new_schedule.is_err() { if let Err(err) = new_schedule {
return HttpResponse::from(new_schedule.unwrap_err()); return HttpResponse::from(err);
} }
let new_schedule = new_schedule.unwrap(); let new_schedule = new_schedule.unwrap();
let result = set_schedule_tags(&new_schedule, data.tags.as_slice()); let result = set_schedule_tags(&pool, &new_schedule, data.tags.as_slice()).await;
if result.is_err() { if let Err(err) = result {
return HttpResponse::from(result.unwrap_err()); return HttpResponse::from(err);
} }
HttpResponse::Created().json(ReturnSchedule::from(new_schedule)) let mut return_schedule = ReturnSchedule::from(new_schedule);
return_schedule.load_tags(&pool);
HttpResponse::Created().json(return_schedule)
}
async fn add_list_single(pool: &Pool<Sqlite>, request_schedule: &RequestSchedule) -> Result<Schedule, DatabaseError> {
let new_schedule = create_schedule(pool, &request_schedule.name, &request_schedule.periods).await?;
set_schedule_tags(pool, &new_schedule, request_schedule.tags.as_slice()).await?;
Ok(new_schedule)
} }
#[post("/api/v1/schedules/list")] #[post("/api/v1/schedules/list")]
pub async fn add_list(data: web::Json<Vec<RequestSchedule>>) -> impl Responder { pub async fn add_list(pool: web::Data<Pool<Sqlite>>, data: web::Json<Vec<RequestSchedule>>) -> impl Responder {
let result: Vec<Result<Schedule, DatabaseError>> = data let result: Vec<Result<Schedule, DatabaseError>> = future::join_all(
data
.as_slice() .as_slice()
.iter() .iter()
.map(|request_schedule| { .map(|request_schedule| add_list_single(&pool, request_schedule))
let new_schedule = create_schedule(&request_schedule.name, &request_schedule.periods)?; ).await;
set_schedule_tags(&new_schedule, request_schedule.tags.as_slice())?;
Ok(new_schedule)
})
.collect();
match vec_has_error(&result) { match vec_has_error(&result) {
true => HttpResponse::from( true => HttpResponse::from(
@ -99,10 +127,14 @@ pub async fn add_list(data: web::Json<Vec<RequestSchedule>>) -> impl Responder {
.unwrap_err(), .unwrap_err(),
), ),
false => { false => {
let return_schedules: Vec<ReturnSchedule> = result let mut return_schedules: Vec<ReturnSchedule> = result
.iter() .iter()
.map(|s| ReturnSchedule::from(s.as_ref().unwrap())) .map(|s| ReturnSchedule::from(s.as_ref().unwrap()))
.collect(); .collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&pool);
}
HttpResponse::Created().json(return_schedules) HttpResponse::Created().json(return_schedules)
} }
} }
@ -110,38 +142,41 @@ pub async fn add_list(data: web::Json<Vec<RequestSchedule>>) -> impl Responder {
#[put("/api/v1/schedules/{schedule_id}")] #[put("/api/v1/schedules/{schedule_id}")]
pub async fn update( pub async fn update(
pool: web::Data<Pool<Sqlite>>,
path: web::Path<(String,)>, path: web::Path<(String,)>,
data: web::Json<RequestSchedule>, data: web::Json<RequestSchedule>,
) -> impl Responder { ) -> impl Responder {
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
if emgauwa_uid.is_err() { if let Err(err) = emgauwa_uid {
return HttpResponse::from(emgauwa_uid.unwrap_err()); return HttpResponse::from(err);
} }
let emgauwa_uid = emgauwa_uid.unwrap(); let emgauwa_uid = emgauwa_uid.unwrap();
let schedule = get_schedule_by_uid(emgauwa_uid); let schedule = get_schedule_by_uid(&pool, &emgauwa_uid, ).await;
if schedule.is_err() { if let Err(err) = schedule {
return HttpResponse::from(schedule.unwrap_err()); return HttpResponse::from(err);
} }
let schedule = schedule.unwrap(); let schedule = schedule.unwrap();
let schedule = update_schedule(&schedule, data.name.as_str(), data.periods.borrow()); let schedule = update_schedule(&pool, &schedule, data.name.as_str(), data.periods.borrow()).await;
if schedule.is_err() { if let Err(err) = schedule {
return HttpResponse::from(schedule.unwrap_err()); return HttpResponse::from(err);
} }
let schedule = schedule.unwrap(); let schedule = schedule.unwrap();
let result = set_schedule_tags(&schedule, data.tags.as_slice()); let result = set_schedule_tags(&pool, &schedule, data.tags.as_slice()).await;
if result.is_err() { if let Err(err) = result {
return HttpResponse::from(result.unwrap_err()); return HttpResponse::from(err);
} }
HttpResponse::Ok().json(ReturnSchedule::from(schedule)) let mut return_schedule = ReturnSchedule::from(schedule);
return_schedule.load_tags(&pool);
HttpResponse::Ok().json(return_schedule)
} }
#[delete("/api/v1/schedules/{schedule_id}")] #[delete("/api/v1/schedules/{schedule_id}")]
pub async fn delete(path: web::Path<(String,)>) -> impl Responder { pub async fn delete(pool: web::Data<Pool<Sqlite>>, path: web::Path<(String,)>) -> impl Responder {
let (schedule_uid,) = path.into_inner(); let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid)); let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(HandlerError::BadUid));
@ -149,7 +184,7 @@ pub async fn delete(path: web::Path<(String,)>) -> impl Responder {
Ok(uid) => match uid { Ok(uid) => match uid {
EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule), EmgauwaUid::Off => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule), EmgauwaUid::On => HttpResponse::from(HandlerError::ProtectedSchedule),
EmgauwaUid::Any(_) => match delete_schedule_by_uid(uid) { EmgauwaUid::Any(_) => match delete_schedule_by_uid(&pool, uid).await {
Ok(_) => HttpResponse::Ok().json("schedule got deleted"), Ok(_) => HttpResponse::Ok().json("schedule got deleted"),
Err(err) => HttpResponse::from(err), Err(err) => HttpResponse::from(err),
}, },

View file

@ -1,13 +1,9 @@
#[macro_use]
extern crate diesel;
extern crate diesel_migrations;
extern crate dotenv; extern crate dotenv;
use actix_web::middleware::TrailingSlash; use actix_web::middleware::TrailingSlash;
use actix_web::{middleware, web, App, HttpServer}; use actix_web::{middleware, web, App, HttpServer};
use log::{trace, LevelFilter}; use log::{trace, LevelFilter};
use simple_logger::SimpleLogger; use simple_logger::SimpleLogger;
use std::fmt::format;
use std::str::FromStr; use std::str::FromStr;
mod db; mod db;
@ -31,9 +27,9 @@ async fn main() -> std::io::Result<()> {
.init() .init()
.unwrap_or_else(|_| panic!("Error initializing logger.")); .unwrap_or_else(|_| panic!("Error initializing logger."));
db::init(&settings.database); let pool = db::init(&settings.database).await;
HttpServer::new(|| { HttpServer::new(move || {
App::new() App::new()
.wrap( .wrap(
middleware::DefaultHeaders::new() middleware::DefaultHeaders::new()
@ -44,6 +40,7 @@ async fn main() -> std::io::Result<()> {
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim)) .wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
.app_data(web::JsonConfig::default().error_handler(handlers::json_error_handler)) .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::index)
.service(handlers::v1::schedules::tagged) .service(handlers::v1::schedules::tagged)
.service(handlers::v1::schedules::show) .service(handlers::v1::schedules::show)

View file

@ -1,3 +1,4 @@
use futures::executor;
use serde::Serialize; use serde::Serialize;
use crate::db::models::Schedule; use crate::db::models::Schedule;
@ -10,10 +11,15 @@ pub struct ReturnSchedule {
pub tags: Vec<String>, pub tags: Vec<String>,
} }
impl ReturnSchedule {
pub fn load_tags(&mut self, pool: &sqlx::Pool<sqlx::Sqlite>) {
self.tags = executor::block_on(get_schedule_tags(pool, &self.schedule)).unwrap();
}
}
impl From<Schedule> for ReturnSchedule { impl From<Schedule> for ReturnSchedule {
fn from(schedule: Schedule) -> Self { fn from(schedule: Schedule) -> Self {
let tags: Vec<String> = get_schedule_tags(&schedule); ReturnSchedule { schedule, tags: vec![]}
ReturnSchedule { schedule, tags }
} }
} }

View file

@ -1,10 +1,8 @@
use diesel::sql_types::Binary;
use uuid::Uuid; use uuid::Uuid;
pub mod emgauwa_uid; pub mod emgauwa_uid;
#[derive(AsExpression, FromSqlRow, PartialEq, Clone)] #[derive(PartialEq, Clone)]
#[diesel(sql_type = Binary)]
pub enum EmgauwaUid { pub enum EmgauwaUid {
Off, Off,
On, On,

View file

@ -3,12 +3,12 @@ use std::fmt::{Debug, Formatter};
use std::str::FromStr; use std::str::FromStr;
use crate::types::EmgauwaUid; use crate::types::EmgauwaUid;
use diesel::backend::Backend;
use diesel::deserialize::FromSql;
use diesel::serialize::{IsNull, Output, ToSql};
use diesel::sql_types::Binary;
use diesel::{deserialize, serialize};
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use sqlx::{Decode, Encode, Sqlite, Type};
use sqlx::database::HasArguments;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use uuid::Uuid; use uuid::Uuid;
impl EmgauwaUid { impl EmgauwaUid {
@ -36,34 +36,26 @@ impl Debug for EmgauwaUid {
} }
} }
impl<DB> ToSql<Binary, DB> for EmgauwaUid impl Type<Sqlite> for EmgauwaUid {
where fn type_info() -> SqliteTypeInfo {
DB: Backend, <&[u8] as Type<Sqlite>>::type_info()
[u8]: ToSql<Binary, DB>, }
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result { fn compatible(ty: &SqliteTypeInfo) -> bool {
match self { <&[u8] as Type<Sqlite>>::compatible(ty)
EmgauwaUid::Off => [EmgauwaUid::OFF_U8].to_sql(out)?,
EmgauwaUid::On => [EmgauwaUid::ON_U8].to_sql(out)?,
EmgauwaUid::Any(value) => value.as_bytes().to_sql(out)?,
};
Ok(IsNull::No)
} }
} }
impl<DB> FromSql<Binary, DB> for EmgauwaUid impl<'q> Encode<'q, Sqlite> for EmgauwaUid {
where //noinspection DuplicatedCode
DB: Backend, fn encode_by_ref(&self, buf: &mut <Sqlite as HasArguments<'q>>::ArgumentBuffer) -> IsNull {
Vec<u8>: FromSql<Binary, DB>, <&Vec<u8> as Encode<Sqlite>>::encode(&Vec::from(self), buf)
{ }
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { }
let blob: Vec<u8> = FromSql::<Binary, DB>::from_sql(bytes)?;
match blob.as_slice() { impl<'r> Decode<'r, Sqlite> for EmgauwaUid {
[EmgauwaUid::OFF_U8] => Ok(EmgauwaUid::Off), fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
[EmgauwaUid::ON_U8] => Ok(EmgauwaUid::On), Ok(EmgauwaUid::from(<&[u8] as Decode<Sqlite>>::decode(value)?))
value_bytes => Ok(EmgauwaUid::Any(Uuid::from_slice(value_bytes).unwrap())),
}
} }
} }
@ -104,8 +96,8 @@ impl TryFrom<&str> for EmgauwaUid {
impl From<&EmgauwaUid> for Uuid { impl From<&EmgauwaUid> for Uuid {
fn from(emgauwa_uid: &EmgauwaUid) -> Uuid { fn from(emgauwa_uid: &EmgauwaUid) -> Uuid {
match emgauwa_uid { match emgauwa_uid {
EmgauwaUid::Off => uuid::Uuid::from_u128(EmgauwaUid::OFF_U128), EmgauwaUid::Off => Uuid::from_u128(EmgauwaUid::OFF_U128),
EmgauwaUid::On => uuid::Uuid::from_u128(EmgauwaUid::ON_U128), EmgauwaUid::On => Uuid::from_u128(EmgauwaUid::ON_U128),
EmgauwaUid::Any(value) => *value, EmgauwaUid::Any(value) => *value,
} }
} }
@ -120,3 +112,33 @@ impl From<&EmgauwaUid> for 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 {
match value.as_slice() {
[EmgauwaUid::OFF_U8] => EmgauwaUid::Off,
[EmgauwaUid::ON_U8] => EmgauwaUid::On,
value_bytes => EmgauwaUid::Any(Uuid::from_slice(value_bytes).unwrap()),
}
}
}