df_st_db 0.3.0-development-2

Database store and query implementation for the DF Storyteller project.
Documentation
use crate::db_object::{DBObject, MatchBy, OrderTypes};
use crate::df_world::{DBDFWorld, Site};
use crate::schema::sites_properties;
use crate::DbConnection;
use anyhow::Error;
use df_st_core::fillable::{Fillable, Filler};
use df_st_core::item_count::ItemCount;
use df_st_derive::Fillable;
use diesel::expression_methods::ExpressionMethods;
use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::Queryable;
use std::collections::HashMap;

#[derive(
    Clone, Debug, AsChangeset, Identifiable, Associations, Queryable, Insertable, Fillable, Default,
)]
#[table_name = "sites_properties"]
#[primary_key(site_id, local_id)]
#[belongs_to(Site)]
pub struct SiteProperty {
    pub site_id: i32,
    pub local_id: i32,
    pub world_id: i32,
    pub type_: Option<String>,
    pub structure_id: Option<i32>,
    pub owner_hf_id: Option<i32>,
}

impl SiteProperty {
    pub fn new() -> Self {
        Self::default()
    }
}

impl DBObject<df_st_core::SiteProperty, SiteProperty> for SiteProperty {
    fn add_missing_data_advanced(core_world: &df_st_core::DFWorld, world: &mut DBDFWorld) {
        for site in core_world.sites.values() {
            for site_property in &site.site_properties {
                let mut db_site_property = SiteProperty::new();
                db_site_property.add_missing_data(&site_property);
                db_site_property.site_id = site.id;
                world.sites_properties.push(db_site_property);
            }
        }
    }

    #[cfg(feature = "postgres")]
    fn insert_into_db(conn: &DbConnection, sites_properties: &[SiteProperty]) {
        use diesel::pg::upsert::excluded;
        diesel::insert_into(sites_properties::table)
            .values(sites_properties)
            .on_conflict((
                sites_properties::site_id,
                sites_properties::local_id,
                sites_properties::world_id,
            ))
            .do_update()
            .set((
                sites_properties::type_.eq(excluded(sites_properties::type_)),
                sites_properties::structure_id.eq(excluded(sites_properties::structure_id)),
                sites_properties::owner_hf_id.eq(excluded(sites_properties::owner_hf_id)),
            ))
            .execute(conn)
            .expect("Error saving SiteProperty");
    }

    #[cfg(not(feature = "postgres"))]
    fn insert_into_db(conn: &DbConnection, sites_properties: &[SiteProperty]) {
        diesel::insert_into(sites_properties::table)
            .values(sites_properties)
            .execute(conn)
            .expect("Error saving SiteProperty");
    }

    fn find_db_list(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
        _string_filter: HashMap<String, String>,
        offset: i64,
        limit: i64,
        order: Option<OrderTypes>,
        order_by: Option<String>,
        _id_list: Option<Vec<i32>>,
    ) -> Result<Vec<SiteProperty>, Error> {
        use crate::schema::sites_properties::dsl::*;
        let (order_by, asc) = Self::get_order(order, order_by);
        let query = sites_properties.limit(limit).offset(offset);
        let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
        if id_filter.get("site_id").is_some() {
            let query = query.filter(site_id.eq(id_filter.get("site_id").unwrap_or(&0)));
            optional_filter! {
                query, id_filter,
                [
                    "local_id" => local_id,
                ],
                {Ok(order_by!{
                    order_by, asc, query, conn,
                    "site_id" => site_id,
                    "local_id" => local_id,
                    "type" => type_,
                    "structure_id" => structure_id,
                    "owner_hf_id" => owner_hf_id,
                })},
            }
        } else {
            optional_filter! {
                query, id_filter,
                [
                    "local_id" => local_id,
                ],
                {Ok(order_by!{
                    order_by, asc, query, conn,
                    "site_id" => site_id,
                    "local_id" => local_id,
                    "type" => type_,
                    "structure_id" => structure_id,
                    "owner_hf_id" => owner_hf_id,
                })},
            }
        }
    }

    fn find_db_item(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
    ) -> Result<Option<SiteProperty>, Error> {
        use crate::schema::sites_properties::dsl::*;
        let query = sites_properties;
        let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
        let query = query.filter(site_id.eq(id_filter.get("site_id").unwrap_or(&0)));
        let query = query.filter(local_id.eq(id_filter.get("local_id").unwrap_or(&0)));
        Ok(query.first::<SiteProperty>(conn).optional()?)
    }

    fn match_field_by(_match_by: MatchBy) -> Vec<&'static str> {
        vec!["site_id", "local_id", "type", "structure_id", "owner_hf_id"]
    }

    fn add_nested_items(
        _conn: &DbConnection,
        _db_list: &[SiteProperty],
        core_list: Vec<df_st_core::SiteProperty>,
    ) -> Result<Vec<df_st_core::SiteProperty>, Error> {
        Ok(core_list)
    }

    fn get_count_from_db(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
        _string_filter: HashMap<String, String>,
        offset: u32,
        limit: u32,
        group_by_opt: Option<String>,
        _id_list: Option<Vec<i32>>,
    ) -> Result<Vec<ItemCount>, Error> {
        use crate::schema::sites_properties::dsl::*;
        let query = sites_properties.limit(limit as i64).offset(offset as i64);
        let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
        if id_filter.get("site_id").is_some() {
            let query = query.filter(site_id.eq(id_filter.get("site_id").unwrap_or(&0)));
            optional_filter! {
                query, id_filter,
                [
                    "local_id" => local_id,
                ],
                {group_by!{
                    group_by_opt, query, conn,
                    "site_id" => {site_id: i32},
                    "local_id" => {local_id: i32},
                    "type" => {type_: Option<String>},
                    "structure_id" => {structure_id: Option<i32>},
                    "owner_hf_id" => {owner_hf_id: Option<i32>}
                };},
            };
        } else {
            optional_filter! {
                query, id_filter,
                [
                    "local_id" => local_id,
                ],
                {
                    group_by!{
                        group_by_opt, query, conn,
                        "site_id" => {site_id: i32},
                        "local_id" => {local_id: i32},
                        "type" => {type_: Option<String>},
                        "structure_id" => {structure_id: Option<i32>},
                        "owner_hf_id" => {owner_hf_id: Option<i32>},
                    };
                },
            };
        }
    }
}

/// From Core to DB
impl Filler<SiteProperty, df_st_core::SiteProperty> for SiteProperty {
    fn add_missing_data(&mut self, source: &df_st_core::SiteProperty) {
        self.site_id.add_missing_data(&source.site_id);
        self.local_id.add_missing_data(&source.local_id);
        self.type_.add_missing_data(&source.type_);
        self.structure_id.add_missing_data(&source.structure_id);
        self.owner_hf_id.add_missing_data(&source.owner_hf_id);
    }
}

/// From DB to Core
impl Filler<df_st_core::SiteProperty, SiteProperty> for df_st_core::SiteProperty {
    fn add_missing_data(&mut self, source: &SiteProperty) {
        self.site_id.add_missing_data(&source.site_id);
        self.local_id.add_missing_data(&source.local_id);
        self.type_.add_missing_data(&source.type_);
        self.structure_id.add_missing_data(&source.structure_id);
        self.owner_hf_id.add_missing_data(&source.owner_hf_id);
    }
}

impl PartialEq<df_st_core::SiteProperty> for SiteProperty {
    fn eq(&self, other: &df_st_core::SiteProperty) -> bool {
        self.site_id == other.site_id && self.local_id == other.local_id
    }
}

impl PartialEq<SiteProperty> for df_st_core::SiteProperty {
    fn eq(&self, other: &SiteProperty) -> bool {
        self.site_id == other.site_id && self.local_id == other.local_id
    }
}

impl PartialEq<SiteProperty> for SiteProperty {
    fn eq(&self, other: &Self) -> bool {
        self.site_id == other.site_id && self.local_id == other.local_id
    }
}