1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use crate::df_world::DBDFWorld;
use crate::DbConnection;
use df_st_core::fillable::{Fillable, Filler};
use df_st_core::item_count::ItemCount;
use failure::Error;
use indexmap::IndexMap;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::collections::HashMap;
use std::fmt::Debug;

/// Create a HashMap used for id_filter
#[macro_export]
macro_rules! id_filter(
    { $($key:expr => $value:expr),* $(,)* } => {
        {
            let mut m: ::std::collections::HashMap<String,i32> =
            ::std::collections::HashMap::new();
            $(
                m.insert($key.to_owned(), $value);
            )*
            m
        }
     };
);

/// Create a HashMap used for string_filter
#[macro_export]
macro_rules! string_filter(
    { $($key:expr => $value:expr),* $(,)* } => {
        {
            let mut m: ::std::collections::HashMap<String,String> =
            ::std::collections::HashMap::new();
            $(
                m.insert($key.to_owned(), $value);
            )*
            m
        }
     };
);

/// Creates a match condition on `order_by` used for
/// sorting the database query.
/// Parameters:
/// * `order_by`: `String`, variable used as a key.
/// * `asc`: `bool`, true is sorting by asc, false if desc.
/// * `query`: First part of the Diesel query. (stored in variable)
/// * `conn`: `&DbConnection`, connection to database.
/// * `key => value`: (first pair will be used as default)
///   * `key`: `&str`, name of the field that matches the `order_by`.
///   * `value`: Diesel column, the column that matches the key.
/// Return: The result of the database query,
/// returned type has to be set outside.
/// Example use:
/// ```ignore
/// let result: Vec<Region> = order_by!{
///     order_by, asc, query, conn,
///     "id" => id,
///     "name" => name,
///     "type" => type_,
///     "evilness" => evilness,
/// };
/// ```
/// Example generated code output:
/// ```ignore
/// let result: Vec<Region> = match order_by.as_ref() {
///     "name" => if asc {query.order(name.asc()).load(conn)}
///         else {query.order(name.desc()).load(conn)},
///     "type" => if asc {query.order(type_.asc()).load(conn)}
///         else {query.order(type_.desc()).load(conn)},
///     "evilness" => if asc {query.order(evilness.asc()).load(conn)}
///         else {query.order(evilness.desc()).load(conn)},
///     _ => if asc {query.order(id.asc()).load(conn)}
///         else {query.order(id.desc()).load(conn)},
/// }?;
/// ```
#[macro_export]
macro_rules! order_by(
    { $order_by:ident, $asc:ident, $query:ident, $conn:ident,
      $default_key:expr => $default_variable:ident,
      $($key:expr => $variable:ident),* $(,)* } => {
        {
            match $order_by.as_ref() {
                $(
                    $key => if $asc {$query.order($variable.asc())}
                        else {$query.order($variable.desc())},
                )*
                _ => if $asc {$query.order($default_variable.asc())}
                    else {$query.order($default_variable.desc())},
            }.load($conn)?
        }
     };
);

/// Creates a match condition on `group_by` used for
/// counting the items with a particular value in the field that is grouped.
/// Parameters:
/// * `group_by_opt`: `Option<String>`, variable used group items, if `None` it will calculate total.
/// * `query`: First part of the Diesel query. (stored in variable)
/// * `conn`: `&DbConnection`, connection to database.
/// * `key => {value: type}`: (first pair will be used as default)
///   * `key`: `&str`, name of the field that matches the `group_by_opt`.
///   * `value`: Diesel column, the column that matches the key.
///   * `type`: They type of the value that is stored in the column.
/// Return: The list of result of the database query stored in `ItemCount` objects.
/// Example use:
/// ```ignore
/// group_by!{
///     group_by_opt, query, conn,
//     "type" => {type_: Option<String>},
//     "civ_id" => {civ_id: Option<i32>},
// };
/// ```
/// Example generated code output:
/// ```ignore
/// let count_star = diesel::dsl::sql::<diesel::sql_types::BigInt>("count(*)");
/// if let Some(group_by) = group_by_opt {
///     match group_by.as_ref() {
///         "civ_id" => {
///             let query = sites.select((count_star, civ_id));
///             let query = query.group_by(civ_id);
///             let result = query.load::<(i64, Option<i32>)>(conn)?;
///             let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
///                 ItemCount{
///                     count: count as u32,
///                     value: serde_json::json!(value),
///                 }
///             }).collect();
///             return Ok(result);
///         }
///         _ => {
///             let query = sites.select((count_star, type_));
///             let query = query.group_by(type_);
///             let result = query.load::<(i64, Option<String>)>(conn)?;
///             let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
///                 ItemCount{
///                     count: count as u32,
///                     value: serde_json::json!(value),
///                 }
///             }).collect();
///             return Ok(result);
///         }
///     }
/// }
/// let query = sites.select(count_star);
/// let result = query.load::<i64>(conn)?;
/// let result: Vec<ItemCount> = result.into_iter().map(|count|{
///     ItemCount{
///         count: count as u32,
///         value: serde_json::json!("total"),
///     }
/// }).collect();
/// ```
#[macro_export]
macro_rules! group_by(
    { $group_by_opt:ident, $query:ident, $conn:ident,
      $default_key:expr => {$default_variable:ident: $default_type:ty},
      $($key:expr => {$variable:ident: $variable_type:ty}),* $(,)* } => {
        {
            let count_star = diesel::dsl::sql::<diesel::sql_types::BigInt>("count(*) as count");
            let count_star_name = diesel::dsl::sql::<diesel::sql_types::Text>("count");
            if let Some(group_by) = $group_by_opt {
                match group_by.as_ref() {
                    $(
                        $key => {
                            let query = $query.select((count_star, $variable));
                            let query = query.group_by($variable);
                            let query = query.order(count_star_name.desc());
                            let result = query.load::<(i64, $variable_type)>($conn)?;
                            let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
                                ItemCount{
                                    count: count as u32,
                                    value: serde_json::json!(value),
                                }
                            }).collect();
                            return Ok(result);
                        },
                    )*
                    _ => {
                        let query = $query.select((count_star, $default_variable));
                        let query = query.group_by($default_variable);
                        let query = query.order(count_star_name.desc());
                        let result = query.load::<(i64, $default_type)>($conn)?;
                        let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
                            ItemCount{
                                count: count as u32,
                                value: serde_json::json!(value),
                            }
                        }).collect();
                        return Ok(result);
                    },
                }
            } else {
                let query = $query.select(count_star);
                let result = query.load::<i64>($conn)?;
                let result: Vec<ItemCount> = result.into_iter().map(|count|{
                    ItemCount{
                        count: count as u32,
                        value: serde_json::json!("total"),
                    }
                }).collect();
                return Ok(result);
            }
        }
     };
);

/// Add if statements for all the possible filters.
/// The function must return in this statement for the filters to work.
/// Parameters:
/// * `query`: First part of the Diesel query. (stored in variable)
/// * `id_filter`: `HashMap<String,i32>`, a list where the keys are the field to filter.
/// * [`key => value`,...]: A list of allowed filters
///   * `key`: `&str`, name of the field that matches the `order_by`.
///   * `value`: Diesel column, the column that matches the key.
/// * {...}: A block of code with anything in it. But it must return in all cases.
///   The `query` variable can be used the further extend the result after the addition of the filter.
/// Return: The value output from the last code block.
/// Example use:
/// ```ignore
/// optional_filter!{
///     query, id_filter,
///     id_list => id,
///     [
///         "id" => id,
///         "region_id" => region_id,
///     ],
///     {return Ok(order_by!{
///         order_by, asc, query, conn,
///         "id" => id,
///         "region_id" => region_id,
///         "x" => x,
///         "y" => y,
///     });},
/// };
/// ```
/// Example generated code output:
/// ```ignore
/// let mut query = query.into_boxed::<diesel::sqlite::Sqlite>(); // Or Postgres
/// if let Some(id_list) = id_list {
///     query = query.filter(id.eq_any(id_list));
/// }
/// if let Some(id_x) = id_filter.get("id"){
///     query = query.filter(id.eq(id_x));
/// }
/// if let Some(id_x) = id_filter.get("region_id"){
///     query = query.filter(region_id.eq(id_x));
/// }
/// return Ok(order_by!{
///     order_by, asc, query, conn,
///     "id" => id,
///     "region_id" => region_id,
///     "x" => x,
///     "y" => y,
/// });
/// ```
#[macro_export]
macro_rules! optional_filter(
    { $query:ident, $id_filter:ident,
      $id_list:ident => $id_variable:ident,
      [$($key:expr => $variable:ident),*,],
      $order_by_block:block,
      } => {
        {
            // For non `into_boxed` version look into issue #56
            #[cfg(feature = "postgres")]
            let mut $query = $query.into_boxed::<diesel::pg::Pg>();
            #[cfg(not(feature = "postgres"))]
            let mut $query = $query.into_boxed::<diesel::sqlite::Sqlite>();
            if let Some(id_list) = $id_list {
                // TODO
                // #[cfg(feature = "postgres")]
                // $query = $query.filter($id_variable.eq(any(id_list)));
                // #[cfg(not(feature = "postgres"))]
                $query = $query.filter($id_variable.eq_any(id_list));
            }
            $(
                if let Some(id_x) = $id_filter.get($key){
                    $query = $query.filter($variable.eq(id_x));
                }
            )*
            $order_by_block
        }
    };
    { $query:ident, $id_filter:ident,
      [$($key:expr => $variable:ident),*,],
      $order_by_block:block,
      } => {
        {
            // For non `into_boxed` version look into issue #56
            #[cfg(feature = "postgres")]
            let mut $query = $query.into_boxed::<diesel::pg::Pg>();
            #[cfg(not(feature = "postgres"))]
            let mut $query = $query.into_boxed::<diesel::sqlite::Sqlite>();
            $(
                if let Some(id_x) = $id_filter.get($key){
                    $query = $query.filter($variable.eq(id_x));
                }
            )*
            $order_by_block
        }
    };
    { $query:ident, $id_filter:ident,
      $id_list:ident => $id_variable:ident,
      [$($key_id:expr => $variable_id:ident),*,],
      $string_filter:ident,
      [$($key_s:expr => $variable_s:ident),*,],
      $order_by_block:block,
      } => {
        {
            // For non `into_boxed` version look into issue #56
            #[cfg(feature = "postgres")]
            let mut $query = $query.into_boxed::<diesel::pg::Pg>();
            #[cfg(not(feature = "postgres"))]
            let mut $query = $query.into_boxed::<diesel::sqlite::Sqlite>();
            if let Some(id_list) = $id_list {
                // TODO
                // #[cfg(feature = "postgres")]
                // $query = $query.filter($id_variable.eq(any(id_list)));
                // #[cfg(not(feature = "postgres"))]
                $query = $query.filter($id_variable.eq_any(id_list));
            }
            $(
                if let Some(id_x) = $id_filter.get($key_id){
                    $query = $query.filter($variable_id.eq(id_x));
                }
            )*
            $(
                if let Some(string_x) = $string_filter.get($key_s){
                    $query = $query.filter($variable_s.eq(string_x));
                }
            )*
            $order_by_block
        }
    };
);

#[derive(Clone, Debug)]
pub enum OrderTypes {
    Asc,
    Desc,
}

pub trait DBObject<C, D>
where
    C: Fillable + Filler<C, D> + Default + Debug + Clone,
    D: PartialEq<C> + Debug + Clone,
{
    fn get_order(order: Option<OrderTypes>, order_by: Option<String>) -> (String, bool) {
        let mut order_by = order_by.unwrap_or_else(|| "".to_owned());
        order_by = Self::match_field_by(order_by);
        let asc = match order {
            Some(x) => match x {
                OrderTypes::Asc => true,
                OrderTypes::Desc => false,
            },
            None => true,
        };
        (order_by, asc)
    }

    fn match_field_by(field: String) -> String;

    fn match_field_by_opt(field: Option<String>) -> Option<String> {
        match field {
            Some(x) => Some(Self::match_field_by(x)),
            None => None,
        }
    }

    /// Add other items to the world that are part of DB Object,
    /// but are still part of the Core object.
    fn add_missing_data_advanced(core_world: &df_st_core::DFWorld, world: &mut DBDFWorld);

    /// Insert the DB object into the database
    fn insert_into_db(conn: &DbConnection, db_list: &[D]);

    /// Inserts the DB objects into the database.
    /// If the list is to long to insert in 1 database call it will split it up in
    /// chunks and insert them in multiple calls. See #46
    fn insert_into_db_chunked(conn: &DbConnection, db_list: &[D]) {
        // 65535 is the default parameter limit on `libpq`
        // See: https://github.com/diesel-rs/diesel/issues/2414
        // Testing shows that a chunk_size of 10000 works sometimes, 5000 is more reliable,
        // a chunk_size of 20000 is to much and will return errors.
        // Update: 5000 is to much in some cases, reduced to 4000.
        for chunk in db_list.chunks(4000) {
            Self::insert_into_db(conn, chunk);
        }
    }

    /// Inserts the DB objects into the database.
    /// If the list is to long to insert in 1 database call it will split it up in
    /// chunks and insert them in multiple calls. See #46
    fn insert_into_db_chunked_indexmap(conn: &DbConnection, db_list: &IndexMap<u64, D>) {
        // 65535 is the default parameter limit on `libpq`
        // See: https://github.com/diesel-rs/diesel/issues/2414
        // Testing shows that a chunk_size of 10000 works sometimes, 5000 is more reliable,
        // a chunk_size of 20000 is to much and will return errors.
        // Update: 5000 is to much in some cases, reduced to 4000.
        let mut count: usize = 0;
        while count <= db_list.len() {
            let chunk = Self::indexmap_chunks(db_list, 4000, count);
            Self::insert_into_db(conn, &chunk);
            count += 4000;
        }
    }

    fn indexmap_chunks(indexmap: &IndexMap<u64, D>, chunk_size: usize, offset: usize) -> Vec<D> {
        let mut list: Vec<D> = Vec::new();
        let mut count: usize = 0;
        while count <= chunk_size {
            let (_key, value) = match indexmap.get_index(offset + count) {
                Some(pair) => pair,
                None => break,
            };
            list.push(value.clone());
            count += 1;
            if count >= chunk_size {
                break;
            }
        }
        list
    }

    /// Get a list of all the Core items from that database given some parameters
    /// Limit: the maximum amount of items in the list that are returned.
    #[allow(clippy::too_many_arguments)]
    fn get_list_from_db(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
        string_filter: HashMap<String, String>,
        offset: u32,
        limit: u32,
        order: Option<OrderTypes>,
        order_by: Option<String>,
        id_list: Option<Vec<i32>>,
        add_nested_items: bool,
    ) -> Result<Vec<C>, Error> {
        let mut core_list: Vec<C> = Vec::new();

        let db_list = Self::find_db_list(
            &conn,
            id_filter,
            string_filter,
            offset as i64,
            limit as i64,
            order,
            order_by,
            id_list,
        )?;

        core_list.add_missing_data(&db_list);
        if add_nested_items {
            core_list = Self::add_nested_items(&conn, &db_list, core_list)?;
        }

        Ok(core_list)
    }

    /// Get a Core item from the database, search by id
    /// If item is not found it will return None
    fn get_from_db(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
        add_nested_items: bool,
    ) -> Result<Option<C>, Error> {
        let mut core_item_opt: Option<C> = None;

        let db_item_option = Self::find_db_item(&conn, id_filter)?;

        core_item_opt.add_missing_data(&db_item_option);
        if add_nested_items {
            if let Some(db_item) = db_item_option {
                if let Some(core_item) = core_item_opt {
                    // Create a list of 1 item.
                    let db_list = vec![db_item];
                    let core_list = vec![core_item];
                    let mut core_list = Self::add_nested_items(&conn, &db_list, core_list)?;
                    // Separate list.
                    core_item_opt = core_list.pop();
                }
            }
        }

        Ok(core_item_opt)
    }

    /// Get the amount of items that would be returned when using these filters.
    /// The fields can optionally be grouped using the `group_by_opt`.
    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>;

    /// The database call for an item by id
    /// If item not found returns None
    fn find_db_item(
        conn: &DbConnection,
        id_filter: HashMap<String, i32>,
    ) -> Result<Option<D>, Error>;

    /// The database call for the list of items given some limit
    /// Limit: the maximum amount of items in the list that are returned.
    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<D>, Error>;

    /// Add additional data to the list of objects
    /// This can call additional DB requests
    fn add_nested_items(
        conn: &DbConnection,
        db_list: &[D],
        core_list: Vec<C>,
    ) -> Result<Vec<C>, Error>;
}