Add function and prefer .iter()

This commit is contained in:
Tobias Reisinger 2022-07-17 20:19:36 +02:00
parent 53c6fcd917
commit e3adc35221
12 changed files with 117 additions and 67 deletions

View file

@ -1,5 +1,5 @@
use actix_web::HttpResponse;
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
@ -18,7 +18,7 @@ impl DatabaseError {
match self {
DatabaseError::NotFound => StatusCode::NOT_FOUND,
DatabaseError::Protected => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}

View file

@ -1,3 +1,4 @@
use crate::db::models::Periods;
use chrono::{NaiveTime, Timelike};
use diesel::backend::Backend;
use diesel::deserialize::FromSql;
@ -7,7 +8,6 @@ use diesel::sqlite::Sqlite;
use diesel::{deserialize, serialize};
use serde::{Deserialize, Serialize};
use std::io::Write;
use crate::db::models::Periods;
#[derive(Debug, Serialize, Deserialize, AsExpression, FromSqlRow, PartialEq, Clone)]
#[sql_type = "Binary"]
@ -57,7 +57,7 @@ impl ToSql<Binary, Sqlite> for Periods {
impl FromSql<Binary, Sqlite> for Periods {
fn from_sql(bytes: Option<&<Sqlite as Backend>::RawValue>) -> deserialize::Result<Self> {
let blob = bytes.unwrap().read_blob();
let blob = bytes.unwrap().read_blob();
let mut vec = Vec::new();
for i in (3..blob.len()).step_by(4) {

View file

@ -1,6 +1,6 @@
use crate::db::model_utils::Period;
use diesel::sql_types::Binary;
use serde::{Deserialize, Serialize};
use crate::db::model_utils::Period;
use super::schema::*;
use crate::types::EmgauwaUid;
@ -12,7 +12,7 @@ pub struct Relay {
// TODO
}
#[derive(Debug, Serialize, Identifiable, Queryable)]
#[derive(Debug, Serialize, Identifiable, Queryable, Clone)]
pub struct Schedule {
#[serde(skip)]
pub id: i32,

View file

@ -1,16 +1,16 @@
use std::borrow::Borrow;
use diesel::dsl::sql;
use diesel::prelude::*;
use std::borrow::Borrow;
use crate::types::EmgauwaUid;
use crate::db::errors::DatabaseError;
use crate::db::{get_connection, schema};
use crate::db::models::*;
use crate::db::schema::tags::dsl::tags;
use crate::db::schema::junction_tag::dsl::junction_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> {
let connection = get_connection();
@ -51,11 +51,13 @@ pub fn delete_schedule_by_uid(filter_uid: EmgauwaUid) -> Result<(), DatabaseErro
let filter_uid = match filter_uid {
EmgauwaUid::Off => Err(DatabaseError::Protected),
EmgauwaUid::On => Err(DatabaseError::Protected),
EmgauwaUid::Any(_) => Ok(filter_uid)
EmgauwaUid::Any(_) => Ok(filter_uid),
}?;
let connection = get_connection();
match diesel::delete(schedules.filter(schema::schedules::uid.eq(filter_uid))).execute(&connection) {
match diesel::delete(schedules.filter(schema::schedules::uid.eq(filter_uid)))
.execute(&connection)
{
Ok(rows) => {
if rows != 0 {
Ok(())
@ -89,7 +91,11 @@ pub fn create_schedule(new_name: &str, new_periods: &Periods) -> Result<Schedule
Ok(result)
}
pub fn update_schedule(schedule: &Schedule, new_name: &str, new_periods: &Periods) -> Result<Schedule, DatabaseError> {
pub fn update_schedule(
schedule: &Schedule,
new_name: &str,
new_periods: &Periods,
) -> Result<Schedule, DatabaseError> {
let connection = get_connection();
let new_periods = match schedule.uid {
@ -114,18 +120,20 @@ pub fn set_schedule_tags(schedule: &Schedule, new_tags: &[String]) -> Result<(),
.execute(&connection)
.or(Err(DatabaseError::DeleteError))?;
let mut database_tags: Vec<Tag> = tags.filter(schema::tags::tag.eq_any(new_tags))
let mut database_tags: Vec<Tag> = tags
.filter(schema::tags::tag.eq_any(new_tags))
.load::<Tag>(&connection)
.expect("Error loading tags");
let mut database_tags_iter = database_tags.clone().into_iter().map(|tag_db| tag_db.tag);
let database_tags_str: Vec<String> = database_tags
.iter()
.map(|tag_db| tag_db.tag.clone())
.collect();
// create missing tags
for new_tag in new_tags {
if !database_tags_iter.any(|t| t.eq(new_tag)) {
database_tags.push(
create_tag(new_tag).expect("Error inserting tag")
);
if !database_tags_str.contains(new_tag) {
database_tags.push(create_tag(new_tag).expect("Error inserting tag"));
}
}

View file

@ -1,20 +1,16 @@
use diesel::dsl::sql;
use diesel::prelude::*;
use crate::db::errors::DatabaseError;
use crate::db::{get_connection, schema};
use crate::db::models::*;
use crate::db::schema::tags::dsl::tags;
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> {
let connection = get_connection();
let new_tag = NewTag {
tag: new_tag,
};
let new_tag = NewTag { tag: new_tag };
diesel::insert_into(tags)
.values(&new_tag)
@ -40,13 +36,17 @@ pub fn get_tag(target_tag: &str) -> Result<Tag, DatabaseError> {
Ok(result)
}
pub fn create_junction_tag(target_tag: Tag, target_relay: Option<&Relay>, target_schedule: Option<&Schedule>) -> Result<JunctionTag, DatabaseError> {
pub fn create_junction_tag(
target_tag: Tag,
target_relay: Option<&Relay>,
target_schedule: Option<&Schedule>,
) -> Result<JunctionTag, DatabaseError> {
let connection = get_connection();
let new_junction_tag = NewJunctionTag {
relay_id: target_relay.map(|r| r.id),
schedule_id: target_schedule.map(|s| s.id),
tag_id: target_tag.id
tag_id: target_tag.id,
};
diesel::insert_into(junction_tag)
@ -60,4 +60,4 @@ pub fn create_junction_tag(target_tag: Tag, target_relay: Option<&Relay>, target
.or(Err(DatabaseError::InsertGetError))?;
Ok(result)
}
}