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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//!
//! The SQL Builder turns a [Query](../query/struct.Query.html) with the help of a [SQL Mapper](../sql_mapper/struct.SqlMapper.html)
//! into a [Sql Builder Result](../sql_builder_result/SqlBuilderResult.html) 
//! The result hold the different parts of an SQL query and can be turned into an SQL query that can be sent to the database.
//! 
//! ## Example
//! 
//! ``` ignore
//! 
//! let  query = Query::wildcard().and(Field::from("foo").eq(5));
//! let mapper::new("Bar b").map_field("foo", "b.foo");
//! let builder_result = QueryBuilder::new().build_query(&mapper, &query);
//! assert_eq!("SELECT b.foo FROM Bar b WHERE b.foo = ?", builder_result.to_sql());
//! assert_eq!(["5"], builder_result.params());
//! ```
//! 
//! The SQL Builder can also add joins if needed. Joins must be registered on the SQL Mapper for this.
//! 
//! ### Count queries
//! Besides normal queries the SQL Builder can als build count queries.
//! 
//! Let's assume you have a grid view with books and the user enters a search term to filter your grid.
//! The normal query will get 50 books, but you will only display 10 books. Toql calls those 50 _the filtered count_.
//! To get the unfilted count, Toql must issue another query with different filter settings. Typically to get
//! the number of all books only that user has access to. Toql calls this _the total count_.
//! 
//! ### Paths
//! The SQL Builder can also ignore paths to skip paths in the query that are not mapped in the mapper.
//! This is needed for structs that contain collections, as these collections must be querried with a different mapper.
//! 
//! Let's assume a struct *user* had a collection of *phones*. 
//! The Toql query may look like:  `username, phones_number`.
//! The SQL Builder needs 2 passes to resolve that query:
//!  - The first pass will query all users with the user mapper and will ignore the path *phones_*.
//!  - The second pass will only build the query for the path *phones_* with the help of the phone mapper. 
//! 
use crate::query::Concatenation;
use crate::query::FieldOrder;
use crate::query::Query;
use crate::query::QueryToken;
use crate::sql_builder_result::SqlBuilderResult;
use crate::sql_mapper::Join;
use crate::sql_mapper::SqlMapper;
use crate::sql_mapper::SqlTarget;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::fmt;

struct SqlTargetData {
    selected: bool, // Target is selected
    used: bool,     // Target is either selected or filtered
}

impl Default for SqlTargetData {
    fn default() -> SqlTargetData {
        SqlTargetData {
            used: false,
            selected: false,
        }
    }
}

struct SqlJoinData {
    joined: bool, // Join has been added to join clause
}
impl Default for SqlJoinData {
    fn default() -> SqlJoinData {
        SqlJoinData { joined: false }
    }
}
/// The Sql builder to build normal queries and count queries.
pub struct SqlBuilder {
    count_query: bool,       // Build count query
    subpath: String,         // Build only subpath
    joins: BTreeSet<String>, // Use this joins
    ignored_paths: Vec<String>, // Ignore paths, no errors are raised for them
                             // alias: String,           // Alias all fields with this
}

#[derive(Debug)]
/// Represents all errors from the SQL Builder
pub enum SqlBuilderError {
    /// The field is not mapped to a column or SQL expression. Contains the field name.
    FieldMissing(String),
    /// The field requires a role that the query does not have. Contains the role.
    RoleRequired(String),
    /// The filter expects other arguments. Typically raised by custom functions (FN) if the number of arguments is wrong.
    FilterInvalid(String)
}

impl fmt::Display for SqlBuilderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SqlBuilderError::FieldMissing(ref s) =>
                write!(f, "field `{}` is missing", s),
            SqlBuilderError::RoleRequired(ref s) =>
                write!(f, "role `{}` is required", s),
            SqlBuilderError::FilterInvalid(ref s) =>
                write!(f, "filter `{}` is invalid ", s),
        }
    }
}


impl SqlBuilder {
    /// Create a new SQL Builder
    pub fn new() -> Self {
        SqlBuilder {
            count_query: false,
            subpath: "".to_string(),
            joins: BTreeSet::new(),
            ignored_paths: Vec::new(),
        }
    }
    /// Add path to list of ignore paths.
    pub fn ignore_path<T: Into<String>>(mut self, path: T) -> Self {
        self.ignored_paths.push(path.into());
        self
    }
    /* pub fn for_role<T: Into<String>>(mut self, role: T) -> Self {
        self.roles.insert(role.into());
        self
    } */
    /// TODO
    pub fn with_join<T: Into<String>>(mut self, join: T) -> Self {
        self.joins.insert(join.into());
        self
    }

    /// Build query for total count.
    pub fn build_count(
        &mut self,
        sql_mapper: &SqlMapper,
        query: &Query,
    ) -> Result<SqlBuilderResult, SqlBuilderError> {
        self.count_query = true;
        self.build(sql_mapper, query)
    }

    // Build normal query for this path
    pub fn build_path<T: Into<String>>(
        &mut self,
        path: T,
        sql_mapper: &SqlMapper,
        query: &Query,
    ) -> Result<SqlBuilderResult, SqlBuilderError> {
        self.subpath = {
            let p = path.into();
            if p.ends_with("_") {
                p
            } else {
                format!("{}_", p)
            }
        };
        self.build(sql_mapper, query)
    }

    fn validate_roles(proposed: &BTreeSet<String>, required: &BTreeSet<String>) -> bool {
        if required.is_empty() {
            return true;
        } // Is valid, if no roles are required
        if proposed.is_empty() {
            return false;
        } // Is invalid, if roles are required, but no roles proposed

        for r in required {
            if !proposed.contains(r) {
                return false;
            }
        }
        true
    }

    fn build_ordering(
        result: &mut SqlBuilderResult,
        sql_target_data: &HashMap<&str, SqlTargetData>,
        sql_targets: &HashMap<String, SqlTarget>,
        ordinals: &BTreeSet<u8>,
        ordering: &HashMap<u8, Vec<(FieldOrder, String)>>,
    ) {
        // Build ordering clause
        for n in ordinals {
            if let Some(fields) = ordering.get(n) {
                for (ord, toql_field) in fields {
                    let o = match ord {
                        FieldOrder::Asc(_) => " ASC",
                        FieldOrder::Desc(_) => " DESC",
                    };
                    if let Some(_sql_target_data) = sql_target_data.get(toql_field.as_str()) {
                        if let Some(sql_target) = sql_targets.get(toql_field) {
                            if let Some(s) = sql_target.handler.build_select(&sql_target.expression)
                            {
                                result.order_by_clause.push_str(&s);
                            }
                        }
                    }
                    result.order_by_clause.push_str(o);
                    result.order_by_clause.push_str(", ");
                }
            }
        }
        result.order_by_clause = result.order_by_clause.trim_end_matches(", ").to_string();
    }

    fn build_count_select_clause(
        result: &mut SqlBuilderResult,
        sql_targets: &HashMap<String, SqlTarget>,
        field_order: &Vec<String>,
    ) {
        let mut any_selected = false;
        for toql_field in field_order {
            if let Some(sql_target) = sql_targets.get(toql_field) {
                // For selected fields there exists target data
                if sql_target.options.count_select {
                    if let Some(sql_field) = sql_target.handler.build_select(&sql_target.expression)
                    {
                        result.select_clause.push_str(&sql_field);
                        result.select_clause.push_str(", ");
                        any_selected = true;
                    }
                }
            }
        }
        result.any_selected = any_selected;
        if any_selected {
            // Remove last ,
            result.select_clause = result.select_clause.trim_end_matches(", ").to_string();
        } else {
            result.select_clause = "1".to_string();
        }
    }

    fn build_select_clause(
        result: &mut SqlBuilderResult,
        sql_targets: &HashMap<String, SqlTarget>,
        sql_target_data: &HashMap<&str, SqlTargetData>,
        field_order: &Vec<String>,
    ) {
        // Build select clause
        let mut any_selected = false;
        for toql_field in field_order {
            if let Some(sql_target) = sql_targets.get(toql_field) {
                // For selected fields there exists target data
                let selected = sql_target.options.always_selected
                    || sql_target_data
                        .get(toql_field.as_str())
                        .map_or(false, |d| d.selected);

                if selected {
                    if let Some(sql_field) = sql_target.handler.build_select(&sql_target.expression)
                    {
                        result.select_clause.push_str(&sql_field);
                        any_selected = true;
                    } else {
                        result.select_clause.push_str("null");
                    }
                } else {
                    result.select_clause.push_str("null");
                }
                result.select_clause.push_str(", ");
            }
        }
        result.any_selected = any_selected;
        // Remove last ,
        result.select_clause = result.select_clause.trim_end_matches(", ").to_string();
    }
    fn build_join_clause(
        sql_join_data: &mut HashMap<&str, SqlJoinData>,
        sql_joins: &HashMap<String, Join>,
        result: &mut SqlBuilderResult,
    ) {
        // Process all fields with subpaths from the query
        for (k, v) in sql_join_data {
            // If not yet joined, check if subpath should be optionally joined
            if !v.joined {
                // For every subpath, check if there is JOIN data available
                if let Some(t) = sql_joins.get(*k) {
                    // If there is JOIN data available, use it to construct join
                    // Join data can be missing for directly typed join

                    result.join_clause.push_str(&t.join_clause);
                    result.join_clause.push(' ');
                }
                v.joined = true; // Mark join as processed
            }
        }
        if result
            .join_clause
            .chars()
            .rev()
            .next()
            .unwrap_or('A')
            .is_whitespace()
        {
            result.join_clause = result.join_clause.trim_end().to_string();
        }
    }
    /// Build normal query.
    pub fn build(
        &mut self,
        sql_mapper: &SqlMapper,
        query: &Query,
    ) -> Result<SqlBuilderResult, SqlBuilderError> {
        let mut ordinals: BTreeSet<u8> = BTreeSet::new();
        let mut ordering: HashMap<u8, Vec<(FieldOrder, String)>> = HashMap::new();

        let mut need_where_concatenation = false;
        let mut need_having_concatenation = false;
        let mut pending_where_parens_concatenation: Option<Concatenation> = None;
        let mut pending_having_parens_concatenation: Option<Concatenation> = None;
        let mut pending_where_parens: u8 = 0;
        let mut pending_having_parens: u8 = 0;

        let mut sql_target_data: HashMap<&str, SqlTargetData> = HashMap::new();
        let mut sql_join_data: HashMap<&str, SqlJoinData> = HashMap::new();

        let mut result = SqlBuilderResult {
            table: sql_mapper.table.clone(),
            any_selected: false,
            distinct: query.distinct,
            join_clause: String::from(""),
            select_clause: String::from(""),
            where_clause: String::from(""),
            order_by_clause: String::from(""),
            having_clause: String::from(""),
            where_params: vec![],
            having_params: vec![],
            combined_params: vec![],
        };

        for t in &query.tokens {
            {
                match t {
                    QueryToken::LeftBracket(ref concatenation) => {
                        pending_where_parens += 1;
                        pending_having_parens += 1;
                        pending_having_parens_concatenation = Some(concatenation.clone());
                        pending_where_parens_concatenation = Some(concatenation.clone());
                    }
                    QueryToken::RightBracket => {
                        if pending_where_parens > 0 {
                            pending_where_parens -= 1;
                        } else {
                            result.where_clause.push_str(")");
                            need_where_concatenation = true;
                        }
                        if pending_having_parens > 0 {
                            pending_having_parens -= 1;
                        } else {
                            result.having_clause.push_str(")");
                            need_having_concatenation = true;
                        }
                    }
                    QueryToken::DoubleWildcard(..) => {
                         // Skip wildcard for count queries
                        if self.count_query {
                            continue;
                        }
                        for (field_name, sql_target) in &sql_mapper.fields {
                            // Skip fields, that ignore wildcard
                            if sql_target.options.ignore_wildcard {
                                continue;
                            }
                            if self.ignored_paths.iter().any(|p| field_name.starts_with(p)) {
                                continue;
                            }
                          
                            // Skip fields with missing role
                            let role_valid =
                                Self::validate_roles(&query.roles, &sql_target.options.roles);
                            if role_valid == false {
                                continue;
                            }
                            let f = sql_target_data.entry(field_name.as_str()).or_default();
                            f.selected = true; // Select field
                            // Add JOIN information for subfields
                            if sql_target.subfields {
                                for subfield in field_name.split('_').rev().skip(1) {
                                    if !sql_join_data.contains_key(subfield) {
                                        sql_join_data.insert(subfield, SqlJoinData::default());
                                    }
                                }
                            }
                        }
                    }

                    QueryToken::Wildcard(wildcard) => {
                        // Skip wildcard for count queries
                        if self.count_query {
                            continue;
                        }
                        // Skip field from other path
                        if !self.subpath.is_empty() && ! wildcard.path.starts_with(&self.subpath)
                        {
                            continue;
                        }

                        for (field_name, sql_target) in &sql_mapper.fields {

                            if sql_target.options.ignore_wildcard {
                                continue;
                            }
                            if self.ignored_paths.iter().any(|p| field_name.starts_with(p)) {
                                continue;
                            }
                            // Skip fields with missing role
                            let role_valid =
                                Self::validate_roles(&query.roles, &sql_target.options.roles);
                            if role_valid == false {
                                continue;
                            }

                            // Select all top fields, that are top fields or are in the right path level
                            if  (wildcard.path.is_empty() && !sql_target.subfields)
                            || (field_name.starts_with(&wildcard.path) 
                                && field_name.rfind("_").unwrap_or(field_name.len()) < wildcard.path.len()) {
                                let f = sql_target_data.entry(field_name.as_str()).or_default();
                                f.selected = true; // Select field

                                //println!("PATH= {}", path);
                                //println!("FIELDNAME= {}", field_name);
                                //println!("MATCH = {}",field_name.starts_with(path) && field_name.rfind("_").unwrap_or(field_name.len()) < field_name.len() );
                                // Add JOIN information
                                if sql_target.subfields {
                                    for subfield in field_name.split('_').rev().skip(1) {
                                        if !sql_join_data.contains_key(subfield) {
                                            sql_join_data.insert(subfield, SqlJoinData::default());
                                        }
                                    }
                                }

                            }
                        }
                    }
                    QueryToken::Field(query_field) => {
                        // Ignore field if name does not start with path
                        // E.g "user_id" has path "user"
                        if !self.subpath.is_empty() && !query_field.name.starts_with(&self.subpath)
                        {
                            continue;
                        }
                        if self.ignored_paths.iter().any(|p| query_field.name.starts_with(p)) {
                            continue;
                        }

                        let fieldname = if self.subpath.is_empty() {
                            &query_field.name
                        } else {
                            query_field
                                .name
                                .trim_start_matches(&self.subpath)
                                .trim_start_matches('_')
                        };

                        match sql_mapper.fields.get(fieldname) {
                            Some(sql_target) => {
                                // Verify user role and skip field role mismatches
                                let role_valid =
                                    Self::validate_roles(&query.roles, &sql_target.options.roles);
                                if role_valid == false {
                                    return Err(SqlBuilderError::RoleRequired(format!(
                                        "Field requires a user role: '{}'. ",
                                        fieldname
                                    )));
                                }
                                // Skip filtering and ordering in count queries for unfiltered fields
                                if self.count_query == true && !sql_target.options.count_filter {
                                    continue;
                                }

                                // Select sql target if field is not hidden
                                let data = sql_target_data.entry(fieldname).or_default();

                                // Add Join data for all sub fields
                                if sql_target.subfields {
                                    for subfield in fieldname.split('_').rev().skip(1) {
                                        if !sql_join_data.contains_key(subfield) {
                                            sql_join_data.insert(subfield, SqlJoinData::default());
                                        }
                                    }
                                }

                                data.selected = if self.count_query {
                                    sql_target.options.count_select
                                } else {
                                    !query_field.hidden
                                };

                                data.used = !query_field.hidden;

                                if let Some(f) = &query_field.filter {
                                    
                                    if let Some(f) = sql_target.handler.build_filter(&sql_target.expression, &f)?
                                        
                                    {
                                        if query_field.aggregation == true {
                                            if need_having_concatenation == true {
                                                if pending_having_parens > 0 {
                                                    SqlBuilderResult::push_concatenation(
                                                        &mut result.having_clause,
                                                        &pending_having_parens_concatenation,
                                                    );
                                                } else {
                                                    SqlBuilderResult::push_concatenation(
                                                        &mut result.having_clause,
                                                        &Some(query_field.concatenation.clone()), // OPTIMISE
                                                    );
                                                }
                                            }

                                            SqlBuilderResult::push_pending_parens(
                                                &mut result.having_clause,
                                                &pending_having_parens,
                                            );

                                            SqlBuilderResult::push_filter(
                                                &mut result.having_clause,
                                                &f,
                                            );

                                            need_having_concatenation = true;
                                            pending_having_parens = 0;
                                        } else {
                                            if need_where_concatenation == true {
                                                if pending_where_parens > 0 {
                                                    SqlBuilderResult::push_concatenation(
                                                        &mut result.where_clause,
                                                        &pending_where_parens_concatenation,
                                                    );
                                                } else {
                                                    SqlBuilderResult::push_concatenation(
                                                        &mut result.where_clause,
                                                        &Some(query_field.concatenation.clone()), // IMPROVE
                                                    );
                                                }
                                            }
                                            SqlBuilderResult::push_pending_parens(
                                                &mut result.where_clause,
                                                &pending_where_parens,
                                            );
                                            SqlBuilderResult::push_filter(
                                                &mut result.where_clause,
                                                &f,
                                            );

                                            pending_where_parens = 0;
                                            need_where_concatenation = true;
                                        }
                                    }
                                    let mut p = sql_target.handler.build_param(&f);
                                    if query_field.aggregation == true {
                                        result.having_params.append(&mut p);
                                    } else {
                                        result.where_params.append(&mut p);
                                    }

                                    if let Some(j) = sql_target.handler.build_join() {
                                        result.join_clause.push_str(&j);
                                        result.join_clause.push_str(" ");
                                    }
                                }
                                if let Some(o) = &query_field.order {
                                    let num = match o {
                                        FieldOrder::Asc(num) => num,
                                        FieldOrder::Desc(num) => num,
                                    };
                                    ordinals.insert(*num);
                                    let l = ordering.entry(*num).or_insert(Vec::new());
                                    l.push((o.clone(), query_field.name.clone())); // OPTIMISE
                                }
                            }
                            None => {
                                // If field has path, validate to known paths
                                if !query_field.name.contains("_")
                                    || !self.path_ignored(&query_field.name)
                                {
                                    return Err(SqlBuilderError::FieldMissing(query_field.name.clone()));
                                }
                            }
                        }
                    }
                }
            }
        }

        // Select all fields for count queries that are marked with count_select
        if self.count_query {
            for (field_name, mapper_field) in &sql_mapper.fields {
                if mapper_field.options.count_select {
                    let f = sql_target_data.entry(field_name.as_str()).or_default();
                    f.selected = true;
                }
            }
        }

        // Build select
        // Ensure implicitly selected subfields are joined
        for toql_field in &sql_mapper.field_order {
            if let Some(sql_target) = sql_mapper.fields.get(toql_field.as_str()) {
                if sql_target.options.always_selected && sql_target.subfields {
                    for subfield in toql_field.split('_').rev().skip(1) {
                        if !sql_join_data.contains_key(subfield) {
                            sql_join_data.insert(subfield, SqlJoinData::default());
                        }
                    }
                }
            }
        }

        if self.count_query {
            Self::build_count_select_clause(
                &mut result,
                &sql_mapper.fields,
                &sql_mapper.field_order,
            );
        } else {
            Self::build_ordering(
                &mut result,
                &sql_target_data,
                &sql_mapper.fields,
                &ordinals,
                &ordering,
            );
            Self::build_select_clause(
                &mut result,
                &sql_mapper.fields,
                &sql_target_data,
                &sql_mapper.field_order,
            );
        }

        Self::build_join_clause(&mut sql_join_data, &sql_mapper.joins, &mut result);

        // Remove trailing whitespace on JOIN and ORDER clause
        if result
            .join_clause
            .chars()
            .rev()
            .next()
            .unwrap_or(' ')
            .is_whitespace()
        {
            result.join_clause = result.join_clause.trim_end().to_owned();
        }
        if result
            .order_by_clause
            .chars()
            .rev()
            .next()
            .unwrap_or('_')
            .is_whitespace()
        {
            result.order_by_clause = result.order_by_clause.trim_end().to_owned();
        }

        // Create combined params if needed
        if !result.having_params.is_empty() && !result.where_params.is_empty() {
            result
                .combined_params
                .extend_from_slice(&result.where_params);
            result
                .combined_params
                .extend_from_slice(&result.having_params);
        }

        Ok(result)
    }

    fn path_ignored(&self, fieldname: &str) -> bool {
        for path in &self.ignored_paths {
            if fieldname.starts_with(path) {
                return true;
            }
        }
        false
    }
}