use crate::db_object::{DBObject, OrderTypes};
use crate::df_world::{Coordinate, DBDFWorld, Path};
use crate::schema::rivers;
use crate::DbConnection;
use df_st_core::fillable::{Fillable, Filler};
use df_st_core::item_count::ItemCount;
use df_st_derive::{Fillable, HashAndPartialEqById};
use diesel::expression_methods::ExpressionMethods;
use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::Queryable;
use failure::Error;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash, Hasher};
#[derive(
Clone,
Debug,
AsChangeset,
Identifiable,
HashAndPartialEqById,
Queryable,
Insertable,
Fillable,
Default,
)]
#[table_name = "rivers"]
pub struct River {
pub id: i32,
pub world_id: i32,
pub name: Option<String>,
pub end_pos_id: Option<i32>,
}
impl River {
pub fn new() -> Self {
Self::default()
}
}
impl DBObject<df_st_core::River, River> for River {
fn add_missing_data_advanced(core_world: &df_st_core::DFWorld, world: &mut DBDFWorld) {
for river in core_world.rivers.values() {
let mut hasher = world.rivers.hasher().build_hasher();
river.hash(&mut hasher);
let hash = hasher.finish();
if let Some(coord) = &river.end_pos {
let new_id: i32 = world.coordinates.len() as i32;
world.coordinates.push(Coordinate {
id: new_id,
x: coord.x,
y: coord.y,
..Default::default()
});
if let Some(db_river) = world.rivers.get_mut(&hash) {
db_river.end_pos_id = Some(new_id);
} else {
warn!("River not found, Can not update end_pos_coord_id. Please report this.");
}
}
for path in &river.path {
let new_id: i32 = world.paths.len() as i32;
world.paths.push(Path {
id: new_id,
x: path.x,
y: path.y,
flow: path.flow,
exit_tile: path.exit_tile,
elevation: path.elevation,
river_id: Some(river.id),
..Default::default()
});
}
}
}
#[cfg(feature = "postgres")]
fn insert_into_db(conn: &DbConnection, rivers: &[River]) {
use diesel::pg::upsert::excluded;
diesel::insert_into(rivers::table)
.values(rivers)
.on_conflict((rivers::id, rivers::world_id))
.do_update()
.set((
rivers::name.eq(excluded(rivers::name)),
rivers::end_pos_id.eq(excluded(rivers::end_pos_id)),
))
.execute(conn)
.expect("Error saving rivers");
}
#[cfg(not(feature = "postgres"))]
fn insert_into_db(conn: &DbConnection, rivers: &[River]) {
diesel::insert_into(rivers::table)
.values(rivers)
.execute(conn)
.expect("Error saving rivers");
}
fn find_db_item(
conn: &DbConnection,
id_filter: HashMap<String, i32>,
) -> Result<Option<River>, Error> {
use crate::schema::rivers::dsl::*;
let query = rivers;
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::<River>(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<River>, Error> {
use crate::schema::rivers::dsl::*;
let (order_by, asc) = Self::get_order(order, order_by);
let query = rivers.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,
"end_pos_id" => end_pos_id,
})},
}
}
fn match_field_by(field: String) -> String {
match field.as_ref() {
"name" => "name",
"end_pos_id" => "end_pos_id",
_ => "id",
}
.to_owned()
}
fn add_nested_items(
conn: &DbConnection,
db_list: &[River],
mut core_list: Vec<df_st_core::River>,
) -> Result<Vec<df_st_core::River>, Error> {
use crate::schema::coordinates;
let world_id = match db_list.first() {
Some(x) => x.world_id,
None => 0,
};
let river_ids: Vec<i32> = db_list.iter().map(|river| river.id).collect();
let coord_list = coordinates::table
.inner_join(rivers::table.on(coordinates::id.nullable().eq(rivers::end_pos_id)))
.filter(crate::schema::coordinates::world_id.eq(world_id))
.filter(rivers::id.eq_any(river_ids))
.load::<(Coordinate, River)>(conn)?;
core_list = core_list
.into_iter()
.map(|mut river| {
let mut end_pos_coord: Option<df_st_core::Coordinate> = None;
for (coord, db_river) in &coord_list {
if &river == db_river {
end_pos_coord.add_missing_data(&Some(coord.clone()));
break;
}
}
river.end_pos = end_pos_coord;
river
})
.collect();
let path_list = Path::belonging_to(db_list)
.filter(crate::schema::paths::world_id.eq(world_id))
.load::<Path>(conn)?
.grouped_by(db_list);
core_list = core_list
.into_iter()
.zip(path_list)
.map(|(mut river, path)| {
let mut core_paths: Vec<df_st_core::Path> = Vec::new();
core_paths.add_missing_data(&path);
river.path = core_paths;
river
})
.collect();
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::rivers::dsl::*;
let query = rivers.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>},
"end_pos_id" => {end_pos_id: Option<i32>},
};},
};
}
}
impl Filler<River, df_st_core::River> for River {
fn add_missing_data(&mut self, source: &df_st_core::River) {
self.id.add_missing_data(&source.id);
self.name.add_missing_data(&source.name);
}
}
impl Filler<df_st_core::River, River> for df_st_core::River {
fn add_missing_data(&mut self, source: &River) {
self.id.add_missing_data(&source.id);
self.name.add_missing_data(&source.name);
}
}
impl PartialEq<River> for df_st_core::River {
fn eq(&self, other: &River) -> bool {
self.id == other.id
}
}
impl PartialEq<df_st_core::River> for River {
fn eq(&self, other: &df_st_core::River) -> bool {
self.id == other.id
}
}