use crate::db_object::{DBObject, OrderTypes};
use crate::df_world::{Coordinate, DBDFWorld, Rectangle};
use crate::schema::sites;
use crate::DbConnection;
use df_st_core::fillable::{Fillable, Filler};
use df_st_core::item_count::ItemCount;
use df_st_derive::{Fillable, Filler, HashAndPartialEqById};
use diesel::expression_methods::ExpressionMethods;
use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::Queryable;
use failure::Error;
use std::collections::HashMap;
use std::convert::TryInto;
mod structure;
pub use structure::*;
mod site_property;
pub use site_property::*;
#[derive(
Clone,
Debug,
AsChangeset,
Identifiable,
HashAndPartialEqById,
Associations,
Queryable,
Insertable,
Fillable,
Filler,
Default,
)]
#[table_name = "sites"]
#[belongs_to(Coordinate)]
#[belongs_to(Rectangle)]
#[belongs_to(Site, foreign_key = "id")]
pub struct Site {
pub id: i32,
pub world_id: i32,
pub type_: Option<String>,
pub name: Option<String>,
pub coordinate_id: Option<i32>,
pub rectangle_id: Option<i32>,
pub civ_id: Option<i32>,
pub cur_owner_id: Option<i32>,
}
impl Site {
pub fn new() -> Self {
Self::default()
}
}
impl DBObject<df_st_core::Site, Site> for Site {
fn add_missing_data_advanced(core_world: &df_st_core::DFWorld, world: &mut DBDFWorld) {
for site in core_world.sites.values() {
if let Some(coord) = &site.coord {
let new_id: i32 = world.coordinates.len().try_into().unwrap();
world.coordinates.push(Coordinate {
id: new_id,
x: coord.x,
y: coord.y,
..Default::default()
});
for db_item in world.sites.values_mut() {
if db_item == site {
db_item.coordinate_id = Some(new_id);
}
}
}
if let Some(rectangle) = &site.rectangle {
let new_id: i32 = world.rectangles.len().try_into().unwrap();
world.rectangles.push(Rectangle {
id: new_id,
x1: rectangle.x1,
y1: rectangle.y1,
x2: rectangle.x2,
y2: rectangle.y2,
..Default::default()
});
for db_item in world.sites.values_mut() {
if db_item == site {
db_item.rectangle_id = Some(new_id);
}
}
}
}
}
#[cfg(feature = "postgres")]
fn insert_into_db(conn: &DbConnection, site: &[Site]) {
use diesel::pg::upsert::excluded;
diesel::insert_into(sites::table)
.values(site)
.on_conflict((sites::id, sites::world_id))
.do_update()
.set((
sites::type_.eq(excluded(sites::type_)),
sites::name.eq(excluded(sites::name)),
sites::coordinate_id.eq(excluded(sites::coordinate_id)),
sites::rectangle_id.eq(excluded(sites::rectangle_id)),
sites::civ_id.eq(excluded(sites::civ_id)),
sites::cur_owner_id.eq(excluded(sites::cur_owner_id)),
))
.execute(conn)
.expect("Error saving site");
}
#[cfg(not(feature = "postgres"))]
fn insert_into_db(conn: &DbConnection, site: &[Site]) {
diesel::insert_into(sites::table)
.values(site)
.execute(conn)
.expect("Error saving site");
}
fn find_db_item(
conn: &DbConnection,
id_filter: HashMap<String, i32>,
) -> Result<Option<Site>, Error> {
use crate::schema::sites::dsl::*;
let query = sites;
let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
let query = query.filter(id.eq(id_filter.get("id").unwrap_or(&0)));
Ok(query.first::<Site>(conn).optional()?)
}
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<Site>, Error> {
use crate::schema::sites::dsl::*;
let (order_by, asc) = Self::get_order(order, order_by);
let query = sites.limit(limit).offset(offset);
let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
optional_filter! {
query, id_filter,
id_list => id,
[
"id" => id,
],
{Ok(order_by! {
order_by, asc, query, conn,
"id" => id,
"name" => name,
"type" => type_,
"coordinate_id" => coordinate_id,
"rectangle_id" => rectangle_id,
"civ_id" => civ_id,
"cur_owner_id" => cur_owner_id,
})},
}
}
fn match_field_by(field: String) -> String {
match field.as_ref() {
"name" => "name",
"type" => "type",
"coordinate_id" => "coordinate_id",
"rectangle_id" => "rectangle_id",
"civ_id" => "civ_id",
"cur_owner_id" => "cur_owner_id",
_ => "id",
}
.to_owned()
}
fn add_nested_items(
conn: &DbConnection,
db_list: &[Site],
mut core_list: Vec<df_st_core::Site>,
) -> Result<Vec<df_st_core::Site>, Error> {
use crate::schema::coordinates;
use crate::schema::rectangles;
let world_id = match db_list.first() {
Some(x) => x.world_id,
None => 0,
};
let site_ids: Vec<i32> = db_list.iter().map(|site| site.id).collect();
let coord_list = sites::table
.filter(sites::id.eq_any(site_ids))
.filter(sites::world_id.eq(world_id))
.left_join(coordinates::table.on(coordinates::id.nullable().eq(sites::coordinate_id)))
.left_join(rectangles::table.on(rectangles::id.nullable().eq(sites::rectangle_id)))
.load::<(Site, Option<Coordinate>, Option<Rectangle>)>(conn)?
.grouped_by(db_list);
let data: Vec<df_st_core::Site> = db_list
.iter()
.zip(coord_list)
.map(|(site, site_and_coord)| {
let (_site_new, coord_opt, rect_opt) = site_and_coord.get(0).unwrap();
let mut core_site = df_st_core::Site::new();
core_site.add_missing_data(site);
let mut core_coord: Option<df_st_core::Coordinate> = None;
core_coord.add_missing_data(&coord_opt);
core_site.coord = core_coord;
let mut core_rect: Option<df_st_core::Rectangle> = None;
core_rect.add_missing_data(&rect_opt);
core_site.rectangle = core_rect;
core_site
})
.collect();
core_list.add_missing_data(&data);
let structure_list = Structure::belonging_to(db_list)
.filter(crate::schema::sites_structures::world_id.eq(world_id))
.load::<Structure>(conn)?
.grouped_by(db_list);
let core_list2: Vec<df_st_core::Site> = db_list
.iter()
.zip(structure_list)
.map(|(site, structure)| {
let mut core_site = df_st_core::Site::new();
core_site.add_missing_data(site);
let mut core_structures: Vec<df_st_core::Structure> = Vec::new();
core_structures.add_missing_data(&structure);
core_site.add_missing_data(&df_st_core::Site {
id: core_site.id,
structures: core_structures,
..Default::default()
});
core_site
})
.collect();
core_list.add_missing_data(&core_list2);
let site_properties_list = SiteProperty::belonging_to(db_list)
.filter(crate::schema::sites_properties::world_id.eq(world_id))
.load::<SiteProperty>(conn)?
.grouped_by(db_list);
let core_list2: Vec<df_st_core::Site> = db_list
.iter()
.zip(site_properties_list)
.map(|(site, site_properties)| {
let mut core_site = df_st_core::Site::new();
core_site.add_missing_data(site);
let mut core_site_properties: Vec<df_st_core::SiteProperty> = Vec::new();
core_site_properties.add_missing_data(&site_properties);
core_site.add_missing_data(&df_st_core::Site {
id: core_site.id,
site_properties: core_site_properties,
..Default::default()
});
core_site
})
.collect();
core_list.add_missing_data(&core_list2);
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::dsl::*;
let query = sites.limit(limit as i64).offset(offset as i64);
let query = query.filter(world_id.eq(id_filter.get("world_id").unwrap_or(&0)));
optional_filter! {
query, id_filter,
id_list => id,
[
"id" => id,
],
{group_by!{
group_by_opt, query, conn,
"id" => {id: i32},
"name" => {name: Option<String>},
"type" => {type_: Option<String>},
"coordinate_id" => {coordinate_id: Option<i32>},
"rectangle_id" => {rectangle_id: Option<i32>},
"civ_id" => {civ_id: Option<i32>},
"cur_owner_id" => {cur_owner_id: Option<i32>},
};},
};
}
}
impl Filler<Site, df_st_core::Site> for Site {
fn add_missing_data(&mut self, source: &df_st_core::Site) {
self.id.add_missing_data(&source.id);
self.type_.add_missing_data(&source.type_);
self.name.add_missing_data(&source.name);
self.civ_id.add_missing_data(&source.civ_id);
self.cur_owner_id.add_missing_data(&source.cur_owner_id);
}
}
impl Filler<df_st_core::Site, Site> for df_st_core::Site {
fn add_missing_data(&mut self, source: &Site) {
self.id.add_missing_data(&source.id);
self.type_.add_missing_data(&source.type_);
self.name.add_missing_data(&source.name);
self.civ_id.add_missing_data(&source.civ_id);
self.cur_owner_id.add_missing_data(&source.cur_owner_id);
}
}
impl PartialEq<Site> for df_st_core::Site {
fn eq(&self, other: &Site) -> bool {
self.id == other.id
}
}
impl PartialEq<df_st_core::Site> for Site {
fn eq(&self, other: &df_st_core::Site) -> bool {
self.id == other.id
}
}