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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
//! The SQL builder can build different select statements.
pub mod build_result;
pub mod select_stream;
pub mod sql_builder_error;

pub(crate) mod build_context;
pub(crate) mod path_tree;

use crate::{
    error::ToqlError,
    parameter_map::ParameterMap,
    query::{
        concatenation::Concatenation, field_order::FieldOrder, field_path::FieldPath,
        query_token::QueryToken, Query,
    },
    result::Result,
    role_validator::RoleValidator,
    sql_arg::SqlArg,
    sql_builder::{
        build_context::BuildContext, build_result::BuildResult, sql_builder_error::SqlBuilderError,
    },
    sql_expr::{resolver::Resolver, SqlExpr},
    table_mapper::{join_type::JoinType, DeserializeType, TableMapper},
    table_mapper_registry::TableMapperRegistry,
};

use path_tree::PathTree;
use select_stream::Select;
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
};

enum MapperOrMerge<'a> {
    Mapper(&'a TableMapper),
    Merge(String),
}

/// The Sql builder to build normal queries and count queries.
pub struct SqlBuilder<'a> {
    root_mapper: String, // root type
    home_mapper: String, // home mapper, depends on query root
    table_mapper_registry: &'a TableMapperRegistry,
    roles: HashSet<String>,
    aux_params: HashMap<String, SqlArg>, // Aux params used for all queries with this builder instance, contains typically config or auth data
    extra_joins: HashSet<String>,        // Use this joins
}

impl<'a> SqlBuilder<'a> {
    /// Create a new SQL Builder from a root mapper and the table mapper registry
    pub fn new(root_mapper: &'a str, table_mapper_registry: &'a TableMapperRegistry) -> Self {
        SqlBuilder {
            root_mapper: root_mapper.to_string(),
            home_mapper: root_mapper.to_string(),
            table_mapper_registry,
            roles: HashSet::new(),
            aux_params: HashMap::new(),
            extra_joins: HashSet::new(),
        }
    }
    /// Use these roles with the builder.
    pub fn with_roles(mut self, roles: HashSet<String>) -> Self {
        self.roles = roles;
        self
    }
    /// Use these auxiliary parameters with the builder.
    pub fn with_aux_params(mut self, aux_params: HashMap<String, SqlArg>) -> Self {
        self.aux_params = aux_params;
        self
    }
    /// Add this raw SQL join statement to the result.
    /// (For internal merge joins)
    pub fn with_extra_join<T: Into<String>>(mut self, join: T) -> Self {
        self.extra_joins.insert(join.into());
        self
    }

    pub fn columns_expr(&self, query_field_path: &str, alias: &str) -> Result<(SqlExpr, SqlExpr)> {
        let mut columns_expr = SqlExpr::new();
        let mut join_expr = SqlExpr::new();

        self.resolve_columns_expr(
            query_field_path,
            alias,
            &mut columns_expr,
            &mut join_expr,
            //    &mut on_expr,
        )?;

        Ok((columns_expr, join_expr))
    }
    fn resolve_columns_expr(
        &self,
        query_path: &str,
        alias: &str,
        columns_expr: &mut SqlExpr,
        join_expr: &mut SqlExpr,
        //   on_expr: &mut SqlExpr,
    ) -> Result<()> {
        let mapper = self.mapper_for_query_path(&FieldPath::from(query_path))?;

        for order in &mapper.deserialize_order {
            match order {
                DeserializeType::Field(name) => {
                    let field = mapper
                        .field(&name)
                        .ok_or_else(|| SqlBuilderError::FieldMissing(name.to_string()))?;
                    if !field.options.key {
                        return Ok(());
                    }
                    let resolver = Resolver::new().with_self_alias(alias);
                    if !columns_expr.is_empty() {
                        columns_expr.push_literal(", ");
                    }
                    columns_expr.extend(resolver.resolve(&field.expression)?);
                }
                DeserializeType::Join(name) => {
                    let join = mapper.join(&name).ok_or_else(|| {
                        SqlBuilderError::JoinMissing(
                            name.to_string(),
                            mapper.table_name.to_string(),
                        )
                    })?;
                    if !join.options.key {
                        return Ok(());
                    }
                    let other_alias = FieldPath::from(alias).append(&mapper.canonical_table_alias);
                    let resolver = Resolver::new()
                        .with_self_alias(alias)
                        .with_other_alias(&other_alias);

                    join_expr.push_literal("JOIN ");
                    join_expr.extend(resolver.resolve(&join.table_expression)?);
                    join_expr.push_literal(" ON (");
                    join_expr.extend(resolver.resolve(&join.on_expression)?);
                    join_expr.push_literal(") ");

                    let joined_query_path = FieldPath::from(query_path).append(&name);

                    self.resolve_columns_expr(
                        &joined_query_path,
                        &other_alias,
                        columns_expr,
                        join_expr,
                        //     on_expr,
                    )?;
                }

                DeserializeType::Merge(_) => {}
            }
        }
        Ok(())
    }

    pub fn merge_expr(&self, query_field_path: &str) -> Result<(SqlExpr, SqlExpr)> {
        let (query_path, basename) = FieldPath::split_basename(query_field_path);
        let mapper = self.mapper_for_query_path(&query_path)?;

        // Get merge join statement and on predicate
        let merge = mapper.merge(basename).ok_or(ToqlError::NotFound)?;

        Ok((
            merge.merge_join.to_owned(),
            merge.merge_predicate.to_owned(),
        ))
    }

    /// Build a delete statement from the [Query].
    /// This build a delete filter predicate from the field filters and predicates in the query.
    /// Any field selections are ignored.
    ///
    /// Returns a [BuildResult] that can be turned into SQL.
    pub fn build_delete<M>(&mut self, query: &Query<M>) -> Result<BuildResult> {
        let mut context = BuildContext::new();
        let root_mapper = self
            .table_mapper_registry
            .mappers
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_owned()))?;

        if let Some(role_expr) = &root_mapper.delete_role_expr {
            if !RoleValidator::is_valid(&self.roles, role_expr) {
                return Err(SqlBuilderError::RoleRequired(
                    role_expr.to_string(),
                    format!("mapper `{}`", self.home_mapper.to_string(),),
                )
                .into());
            }
        }

        let mut result = BuildResult::new(SqlExpr::literal("DELETE"));

        result.set_from(
            root_mapper.table_name.to_owned(),
            root_mapper.canonical_table_alias.to_owned(),
        );
        self.preparse_filter_joins(&query, &mut context, false)?;
        self.build_where_clause(&query, &mut context, false, &mut result)?;
        self.build_join_clause(&query.aux_params, &mut context, &mut result, true, false)?;

        Ok(result)
    }

    //TODO move function itno separate unit
    pub fn build_merge_delete(
        &mut self,
        merge_path: &FieldPath,
        key_predicate: SqlExpr,
    ) -> Result<SqlExpr> {
        let root_mapper = self
            .table_mapper_registry
            .mappers
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_owned()))?;

        let (query_path, merge_field) = FieldPath::split_basename(&merge_path);

        let base_mapper = self.mapper_for_query_path(&query_path)?;
        let root_path = FieldPath::from(&root_mapper.canonical_table_alias);
        let canonical_path = root_path.append(&query_path);

        let merge = base_mapper
            .merge(merge_field)
            .ok_or_else(|| SqlBuilderError::FieldMissing(merge_field.to_string()))?;

        let merge_mapper = self
            .table_mapper_registry
            .mappers
            .get(&merge.merged_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(merge.merged_mapper.to_string()))?;

        let mut delete_expr = SqlExpr::new();

        // TODO move into backend
        // Mysql specific
        delete_expr.push_literal("DELETE ");
        delete_expr.push_other_alias();
        delete_expr.push_literal(" FROM ");
        delete_expr.push_literal(&merge_mapper.table_name);
        delete_expr.push_literal(" ");
        delete_expr.push_other_alias();
        delete_expr.push_literal(" ");
        delete_expr.extend(merge.merge_join.clone()); // Maybe conctruct custom join for postgres
        delete_expr.push_literal(" ON ");
        delete_expr.extend(merge.merge_predicate.clone());
        delete_expr.push_literal(" WHERE ");
        delete_expr.extend(key_predicate);

        let canonical_merge_alias = canonical_path.append(merge_field);
        let resolver = Resolver::new()
            .with_self_alias(&canonical_path)
            .with_other_alias(&canonical_merge_alias);

        resolver.resolve(&delete_expr).map_err(ToqlError::from)
    }

    /// Build a normal select statement from the [Query].
    ///
    /// Returns a [BuildResult] that can be turned into SQL.
    pub fn build_select<M>(
        &mut self,
        query_home_path: &str,
        query: &Query<M>,
    ) -> Result<BuildResult> {
        let mut context = BuildContext::new();
        context.query_home_path = query_home_path.to_string();

        self.set_home_joined_mapper_for_path(&FieldPath::from(query_home_path))?;

        let mapper = self
            .table_mapper_registry
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_string()))?;

        if let Some(role) = mapper.load_role_expr.as_ref() {
            if !RoleValidator::is_valid(&self.roles, role) {
                return Err(SqlBuilderError::RoleRequired(
                    role.to_string(),
                    if query_home_path.is_empty() {
                        format!("mapper `{}`", &self.home_mapper)
                    } else {
                        format!("path `{}`", query_home_path)
                    },
                )
                .into());
            }
        }

        let mut result = BuildResult::new(SqlExpr::literal("SELECT"));
        result.set_from(
            mapper.table_name.to_owned(),
            mapper.canonical_table_alias.to_owned(),
        );

        self.preparse_query(&query, &mut context, &mut result)?;
        self.build_where_clause(&query, &mut context, false, &mut result)?;
        self.build_select_clause(&query, &mut context, &mut result)?;
        self.build_join_clause(&query.aux_params, &mut context, &mut result, false, true)?;
        self.build_order_clause(&query.aux_params, &mut context, &mut result)?;

        Ok(result)
    }

    /// Build a count statement from the [Query].
    /// This build a count filter predicate from the field filters and predicates.
    /// If `count_selection_ony` is true then only filters are used that are part
    /// of the count selection ($cnt) or predicates that are marked as count_filters.
    ///
    /// Returns a [BuildResult] that can be turned into SQL.
    pub fn build_count<M>(
        &mut self,
        query_root_path: &str,
        query: &Query<M>,
        count_selection_only: bool,
    ) -> Result<BuildResult> {
        let mut build_context = BuildContext::new();
        build_context.query_home_path = query_root_path.to_string();
        let root_mapper = self.root_mapper()?; // self.joined_mapper_for_path(&Self::root_field_path(root_path))?;

        let mut result = BuildResult::new(SqlExpr::literal("SELECT"));
        result.select_expr.push_literal("COUNT(*)");

        result.set_from(
            root_mapper.table_name.to_owned(),
            root_mapper.canonical_table_alias.to_owned(),
        );

        self.build_where_clause(
            &query,
            &mut build_context,
            count_selection_only,
            &mut result,
        )?;

        self.preparse_filter_joins(&query, &mut build_context, count_selection_only)?;

        self.build_join_clause(
            &query.aux_params,
            &mut build_context,
            &mut result,
            true,
            true,
        )?;

        Ok(result)
    }

    pub fn joined_mapper_for_local_path(&self, local_path: &FieldPath) -> Result<&TableMapper> {
        self.joined_mapper_for_path(&self.home_mapper, local_path)
    }
    pub fn joined_mapper_for_query_path(&self, query_path: &FieldPath) -> Result<&TableMapper> {
        self.joined_mapper_for_path(&self.root_mapper, query_path)
    }
    fn joined_mapper_for_path(&self, mapper_name: &str, path: &FieldPath) -> Result<&TableMapper> {
        let mut current_mapper = self
            .table_mapper_registry
            .get(mapper_name)
            .ok_or_else(|| ToqlError::MapperMissing(mapper_name.to_string()))?;

        if !path.is_empty() {
            for p in path.children() {
                if let Some(join) = current_mapper.joins.get(p.as_str()) {
                    current_mapper = self
                        .table_mapper_registry
                        .get(&join.joined_mapper)
                        .ok_or_else(|| ToqlError::MapperMissing(join.joined_mapper.to_string()))?;
                } else {
                    return Err(SqlBuilderError::JoinMissing(
                        p.to_string(),
                        current_mapper.table_name.to_string(),
                    )
                    .into());
                }
            }
        }

        Ok(current_mapper)
    }

    pub fn mapper_for_query_path(&self, query_path: &FieldPath) -> Result<&TableMapper> {
        let mut current_mapper = self
            .table_mapper_registry
            .get(&self.root_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.root_mapper.to_string()))?;

        if !query_path.is_empty() {
            for p in query_path.children() {
                if let Some(join) = current_mapper.joins.get(p.as_str()) {
                    current_mapper = self
                        .table_mapper_registry
                        .get(&join.joined_mapper)
                        .ok_or_else(|| ToqlError::MapperMissing(join.joined_mapper.to_string()))?;
                } else if let Some(merge) = current_mapper.merges.get(p.as_str()) {
                    current_mapper = self
                        .table_mapper_registry
                        .get(&merge.merged_mapper)
                        .ok_or_else(|| ToqlError::MapperMissing(merge.merged_mapper.to_string()))?;
                } else {
                    return Err(ToqlError::MapperMissing(p.to_string()));
                }
            }
        }

        Ok(current_mapper)
    }

    fn mapper_or_merge_for_path(&'a self, local_path: &'a FieldPath) -> Result<MapperOrMerge<'a>> {
        let mut current_mapper = self
            .table_mapper_registry
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_string()))?;

        if !local_path.is_empty() {
            for (p, a) in local_path.children().zip(local_path.step_down()) {
                //  dbg!(&a);
                if current_mapper.merges.contains_key(p.as_str()) {
                    return Ok(MapperOrMerge::Merge(a.to_string()));
                }
                let join = current_mapper
                    .joins
                    .get(p.as_str())
                    .ok_or_else(|| ToqlError::MapperMissing(p.to_string()))?;
                current_mapper = self
                    .table_mapper_registry
                    .get(&join.joined_mapper)
                    .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_string()))?;
            }
        }

        Ok(MapperOrMerge::Mapper(current_mapper))
    }
    fn set_home_joined_mapper_for_path(&mut self, path: &FieldPath) -> Result<()> {
        if !path.is_empty() {
            let mut current_type: &str = &self.root_mapper;
            let mut current_mapper = self
                .table_mapper_registry
                .get(current_type)
                .ok_or_else(|| ToqlError::MapperMissing(current_type.to_string()))?;

            for p in path.children() {
                if let Some(merge) = current_mapper.merges.get(p.as_str()) {
                    current_mapper = self
                        .table_mapper_registry
                        .get(&merge.merged_mapper)
                        .ok_or_else(|| ToqlError::MapperMissing(merge.merged_mapper.to_string()))?;
                    current_type = &merge.merged_mapper;
                } else if let Some(join) = current_mapper.joins.get(p.as_str()) {
                    current_mapper = self
                        .table_mapper_registry
                        .get(&join.joined_mapper)
                        .ok_or_else(|| ToqlError::MapperMissing(join.joined_mapper.to_string()))?;
                    current_type = &join.joined_mapper;
                } else {
                    return Err(ToqlError::MapperMissing(p.to_string()));
                }
            }

            self.home_mapper = current_type.to_string();
        }

        Ok(())
    }

    fn build_join_clause(
        &self,
        query_aux_params: &HashMap<String, SqlArg>,
        mut build_context: &mut BuildContext,
        result: &mut BuildResult,
        enforce_inner_joins: bool,
        restrict_load: bool,
    ) -> Result<()> {
        // Build join tree for all selected paths
        // This allows to nest joins properly
        // Eg [user] = [user_address, user_folder]
        // [user_folder] = [ user_folder_owner]
        // [user_folder_owner] =[]
        // [user address] =[]

        let mut join_tree = PathTree::new();

        for local_path in &build_context.local_joined_paths {
            join_tree.insert(&FieldPath::from(&local_path));
        }

        // Build join
        let expr: SqlExpr = self.resolve_join(
            &join_tree,
            &join_tree.roots(),
            &mut build_context,
            enforce_inner_joins,
            restrict_load,
            query_aux_params,
        )?;
        result.join_expr.extend(expr);
        result.join_expr.pop_literals(1); // Remove trailing whitespace

        Ok(())
    }
    fn resolve_join(
        &self,
        join_tree: &PathTree,
        nodes: &HashSet<String>,
        build_context: &mut BuildContext,
        enforce_inner_joins: bool,
        restrict_load: bool,
        query_aux_params: &HashMap<String, SqlArg>,
    ) -> Result<SqlExpr> {
        let mut join_expr = SqlExpr::new();

        for local_path_with_join in nodes {
            let (local_path, join_name) = FieldPath::split_basename(local_path_with_join);

            let local_mapper = self.joined_mapper_for_local_path(&local_path)?;

            let join = local_mapper.join(join_name).ok_or_else(|| {
                SqlBuilderError::JoinMissing(
                    join_name.to_string(),
                    local_mapper.table_name.to_string(),
                )
            })?;
            if restrict_load {
                let joined_mapper = self
                    .table_mapper_registry
                    .get(&join.joined_mapper)
                    .ok_or_else(|| ToqlError::MapperMissing(join.joined_mapper.to_string()))?;

                if let Some(role) = joined_mapper.load_role_expr.as_ref() {
                    if !RoleValidator::is_valid(&self.roles, role) {
                        return Err(SqlBuilderError::RoleRequired(
                            role.to_string(),
                            format!(
                                "path `{}`",
                                FieldPath::from(&build_context.query_home_path)
                                    .append(&local_path)
                                    .to_string(),
                            ),
                        )
                        .into());
                    }
                }
            }

            let canonical_self_alias = self.canonical_alias(&local_path)?.to_string();
            let canonical_other_alias = self
                .canonical_alias(&FieldPath::from(local_path_with_join))?
                .to_string();
            let resolver = Resolver::new()
                .with_self_alias(&canonical_self_alias)
                .with_other_alias(&canonical_other_alias);

            join_expr.push_literal(if enforce_inner_joins {
                "JOIN ("
            } else {
                match &join.join_type {
                    JoinType::Inner => "JOIN (",
                    JoinType::Left => "LEFT JOIN (",
                }
            });
            let join_e = resolver.resolve(&join.table_expression)?;
            join_expr.extend(join_e);
            join_expr.push_literal(" ");

            if let Some(subnodes) = join_tree.nodes(local_path_with_join) {
                if !subnodes.is_empty() {
                    let subjoin_expr = self.resolve_join(
                        join_tree,
                        &subnodes,
                        build_context,
                        enforce_inner_joins,
                        restrict_load,
                        query_aux_params,
                    )?;
                    if !subjoin_expr.is_empty() {
                        join_expr.extend(subjoin_expr);
                    }
                }
            }
            join_expr.pop_literals(1); // Remove trailing whitespace
            join_expr.push_literal(") ON (".to_string());

            let on_expr = resolver.resolve(&join.on_expression)?;

            let on_expr = {
                let p = [
                    &self.aux_params,
                    &join.options.aux_params,
                    &build_context.on_aux_params,
                    &query_aux_params,
                ];
                let aux_params = ParameterMap::new(&p);
                match &join.options.join_handler {
                    Some(handler) => handler.build_on_predicate(on_expr, &aux_params)?,
                    None => Resolver::resolve_aux_params(on_expr, &aux_params),
                }
            };

            // Skip left joins with unresolved aux params
            let on_expr = match on_expr.first_aux_param() {
                Some(p) if join.join_type == JoinType::Left => {
                    let query_path_with_join = FieldPath::from(&build_context.query_home_path)
                        .append(local_path_with_join);
                    tracing::info!("Setting condition of left join `{}` to `false`, because aux param `{}` is missing", query_path_with_join.as_str(), &p );
                    SqlExpr::literal("false")
                }
                _ => on_expr,
            };

            join_expr.extend(on_expr);
            join_expr.push_literal(") ");
        }

        Ok(join_expr)
    }

    fn build_where_clause<M>(
        &mut self,
        query: &Query<M>,
        build_context: &mut BuildContext,
        count_selection_only: bool,
        result: &mut BuildResult,
    ) -> Result<()> {
        let p = [&self.aux_params, &query.aux_params];
        let aux_params = ParameterMap::new(&p);

        for token in &query.tokens {
            match token {
                QueryToken::Field(field) => {
                    // Continue if field is not filtered
                    if field.filter.is_none() {
                        continue;
                    }
                    let (query_path, field_name) = FieldPath::split_basename(&field.name);

                    // skip if field path is not relative to root path
                    if !Self::home_contains(&build_context.query_home_path, &query_path) {
                        continue;
                    }

                    if count_selection_only {
                        let root_mapper = self.root_mapper()?;
                        match root_mapper.selections.get("cnt") {
                            Some(selection) => {
                                let wildcard_path = format!("{}_*", field.name.as_str());
                                if !selection.contains(&field.name)
                                    && !selection.contains(&wildcard_path)
                                {
                                    continue;
                                }
                            }
                            None => continue,
                        }
                    }

                    // Get relative path
                    let local_path = match query_path.localize_path(&build_context.query_home_path)
                    {
                        Some(l) => l,
                        None => return Ok(()),
                    };

                    let mapper_or_merge = self.mapper_or_merge_for_path(&local_path)?;

                    match mapper_or_merge {
                        MapperOrMerge::Mapper(mapper) => {
                            let mapped_field = mapper.fields.get(field_name).ok_or_else(|| {
                                SqlBuilderError::FieldMissing(field.name.to_string())
                            })?;

                            if let Some(role_expr) = &mapped_field.options.load_role_expr {
                                if !crate::role_validator::RoleValidator::is_valid(
                                    &self.roles,
                                    role_expr,
                                ) {
                                    return Err(SqlBuilderError::RoleRequired(
                                        role_expr.to_string(),
                                        format!(
                                            "field `{}`",
                                            FieldPath::from(&build_context.query_home_path)
                                                .append(&local_path)
                                                .append(field_name)
                                                .to_string(),
                                        ),
                                    )
                                    .into());
                                }
                            }
                            let canonical_alias = self.canonical_alias(&query_path)?;

                            let p = [
                                &self.aux_params,
                                &query.aux_params,
                                &mapped_field.options.aux_params,
                            ];
                            let aux_params = ParameterMap::new(&p);

                            let handler = mapped_field
                                .options
                                .field_handler
                                .as_ref()
                                .unwrap_or(&mapper.field_handler);
                            let select_expr = handler
                                .build_select(mapped_field.expression.clone(), &aux_params)?
                                .unwrap_or_default();

                            // Does filter apply
                            if let Some(expr) = handler.build_filter(
                                select_expr,
                                field.filter.as_ref().unwrap(),
                                &aux_params,
                            )? {
                                let resolver = Resolver::new().with_self_alias(&canonical_alias);
                                let expr = resolver.resolve(&expr)?;
                                if !result.where_expr.is_empty()
                                    && !result.where_expr.ends_with_literal("(")
                                {
                                    result.where_expr.push_literal(
                                        if field.concatenation == Concatenation::And {
                                            " AND "
                                        } else {
                                            " OR "
                                        },
                                    );
                                }
                                result.where_expr.extend(expr);
                            }
                        }
                        MapperOrMerge::Merge(_merge_path) => {
                            // result.unmerged_paths.insert(merge_path);
                        }
                    }
                }

                QueryToken::Predicate(predicate) => {
                    let (query_path, basename) = FieldPath::split_basename(&predicate.name);

                    // skip if field path is not relative to root path
                    if !Self::home_contains(&build_context.query_home_path, &query_path) {
                        continue;
                    }

                    let local_path = match query_path.localize_path(&build_context.query_home_path)
                    {
                        Some(l) => l,
                        None => return Ok(()),
                    };

                    let mapper_or_merge = self.mapper_or_merge_for_path(&local_path)?;

                    match mapper_or_merge {
                        MapperOrMerge::Mapper(mapper) => {
                            let mapped_predicate =
                                mapper.predicates.get(basename).ok_or_else(|| {
                                    SqlBuilderError::PredicateMissing(basename.to_string())
                                })?;

                            if count_selection_only && !mapped_predicate.options.count_filter {
                                continue;
                            }

                            if let Some(role) = &mapped_predicate.options.load_role_expr {
                                if !RoleValidator::is_valid(&self.roles, role) {
                                    return Err(SqlBuilderError::RoleRequired(
                                        role.to_string(),
                                        format!(
                                            "predicate `@{}`",
                                            query_path
                                                .append(&local_path)
                                                .append(basename)
                                                .to_string()
                                        ),
                                    )
                                    .into());
                                }
                            }

                            let canonical_alias = self.canonical_alias(&local_path)?;

                            let resolver = Resolver::new()
                                .with_self_alias(&canonical_alias)
                                .with_arguments(&predicate.args)
                                .with_aux_params(&aux_params);

                            let handler = mapped_predicate
                                .options
                                .predicate_handler
                                .as_ref()
                                .unwrap_or(&mapper.predicate_handler);

                            if let Some(expr) = handler.build_predicate(
                                mapped_predicate.expression.clone(),
                                &predicate.args,
                                &aux_params,
                            )? {
                                if !result.where_expr.is_empty()
                                    && !result.where_expr.ends_with_literal("(")
                                {
                                    result.where_expr.push_literal(
                                        if predicate.concatenation == Concatenation::And {
                                            " AND "
                                        } else {
                                            " OR "
                                        },
                                    );
                                }
                                result.where_expr.extend(resolver.resolve(&expr)?);
                                if !mapped_predicate.options.on_aux_params.is_empty() {
                                    for (i, a) in &mapped_predicate.options.on_aux_params {
                                        if let Some(v) = predicate.args.get(*i as usize) {
                                            // tracing::info!("Setting on param `{}` = `{}`.", &a, v.to_string());
                                            build_context
                                                .on_aux_params
                                                .insert(a.clone(), v.clone());
                                        } else {
                                            tracing::warn!("Not enough predicate arguments to set on param `{}`.", &a);
                                        }
                                    }
                                }
                            }
                        }
                        MapperOrMerge::Merge(_merge_path) => {}
                    }
                }
                QueryToken::LeftBracket(concatenation) => {
                    // Omit concatenation if where expression is empty or left bracket follows an outer left bracket
                    if !result.where_expr.is_empty() && !result.where_expr.ends_with_literal("(") {
                        result
                            .where_expr
                            .push_literal(if concatenation == &Concatenation::And {
                                " AND "
                            } else {
                                " OR "
                            });
                    }
                    result.where_expr.push_literal("(");
                }
                QueryToken::RightBracket => {
                    // If parentheses are empty, remove right bracket and concatenation
                    if result.where_expr.ends_with_literal("(") {
                        result.where_expr.pop(); // Remove '(' token

                        // Remove ' AND ' or 'OR ' token if bracket is not inner bracket
                        // 'AND (' -> removed
                        // 'AND ((' -> reduced to 'AND ('
                        if result.where_expr.ends_with_literal(" AND ")
                            || result.where_expr.ends_with_literal(" OR ")
                        {
                            result.where_expr.pop();
                        }
                    } else {
                        result.where_expr.push_literal(")");
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn canonical_alias<'c>(&'c self, query_path: &'c FieldPath) -> Result<Cow<String>> {
        let root_alias = &self.root_mapper()?.canonical_table_alias;

        Ok(match query_path.is_empty() {
            false => Cow::Owned(query_path.prepend(&root_alias).to_string()),
            true => Cow::Borrowed(&root_alias),
        })
    }

    fn preparse_query<M>(
        &mut self,
        query: &Query<M>,
        build_context: &mut BuildContext,
        result: &mut BuildResult,
    ) -> Result<()> {
        result.unmerged_home_paths = self.selection_from_query(query, build_context)?;
        build_context.update_joins_from_selections();

        Ok(())
    }

    fn build_order_clause(
        &mut self,
        query_aux_params: &HashMap<String, SqlArg>,
        build_context: &mut BuildContext,
        result: &mut BuildResult,
    ) -> Result<()> {
        let mut ordinals = Vec::with_capacity(build_context.ordering.len());
        for o in build_context.ordering.keys() {
            ordinals.push(o);
        }
        ordinals.sort();

        for n in ordinals {
            if let Some(orderings) = build_context.ordering.get(n) {
                for (ord, local_path_with_basename) in orderings {
                    let (local_path, field_name) =
                        FieldPath::split_basename(local_path_with_basename);
                    // Skip merge fields
                    if let Ok(mapper) = self.joined_mapper_for_local_path(&local_path) {
                        if let Some(role) = &mapper.load_role_expr {
                            if !RoleValidator::is_valid(&self.roles, role) {
                                return Err(SqlBuilderError::RoleRequired(
                                    role.to_string(),
                                    format!(
                                        "field `{}`",
                                        FieldPath::from(&build_context.query_home_path)
                                            .append(&local_path)
                                            .to_string(),
                                    ),
                                )
                                .into());
                            }
                        }

                        let field_info = mapper
                            .field(field_name)
                            .ok_or_else(|| SqlBuilderError::FieldMissing(field_name.to_string()))?;

                        if let Some(load_role_expr) = &field_info.options.load_role_expr {
                            if !RoleValidator::is_valid(&self.roles, load_role_expr) {
                                return Err(SqlBuilderError::RoleRequired(
                                    load_role_expr.to_string(),
                                    format!(
                                        "field `{}`",
                                        FieldPath::from(&build_context.query_home_path)
                                            .append(local_path_with_basename)
                                            .to_string(),
                                    ),
                                )
                                .into());
                            }
                        }

                        let p = [
                            &self.aux_params,
                            &field_info.options.aux_params,
                            query_aux_params,
                        ];
                        let aux_params = ParameterMap::new(&p);

                        let handler = field_info
                            .options
                            .field_handler
                            .as_ref()
                            .unwrap_or(&mapper.field_handler);
                        let select_expr =
                            handler.build_select(field_info.expression.clone(), &aux_params)?;
                        let canonical_alias = self.canonical_alias(&local_path)?;
                        if let Some(expr) = select_expr {
                            let resolver = Resolver::new().with_self_alias(&canonical_alias);
                            let expr = resolver.resolve(&expr)?;
                            result.order_expr.extend(expr);
                            result.order_expr.push_literal(match ord {
                                FieldOrder::Asc(_) => " ASC, ",
                                FieldOrder::Desc(_) => " DESC, ",
                            });
                        }
                    }
                }
            }
        }
        if !result.order_expr.is_empty() {
            result.order_expr.pop_literals(2); // Remove trailing ,
        }

        Ok(())
    }

    fn build_select_clause<M>(
        &mut self,
        query: &Query<M>,
        build_context: &mut BuildContext,
        result: &mut BuildResult,
    ) -> Result<()> {
        self.resolve_select(&FieldPath::default(), query, build_context, result)?;
        if result.select_expr.is_empty() {
            result.select_expr.push_literal("1");
        } else {
            result.select_expr.pop_literals(2); // Remove trailing ,
        }
        if result.select_expr.is_empty() {
            result.select_expr.push_literal("1");
        } else {
            result.select_expr.pop_literals(2); // Remove trailing ,
        }

        Ok(())
    }

    fn resolve_select<M>(
        &self,
        local_path: &FieldPath,
        query: &Query<M>,
        build_context: &mut BuildContext,
        result: &mut BuildResult,
    ) -> Result<()> {
        let mapper = self.joined_mapper_for_local_path(&local_path)?;

        let canonical_alias = self.canonical_alias(local_path)?;

        let path_selection = build_context
            .local_selected_paths
            .contains(local_path.as_str());

        for deserialization_type in &mapper.deserialize_order {
            match deserialization_type {
                DeserializeType::Field(field_name) => {
                    let local_field = if !local_path.is_empty() {
                        Cow::Owned(format!("{}_{}", local_path.as_str(), field_name))
                    } else {
                        Cow::Borrowed(field_name)
                    };

                    let mapped_field = mapper
                        .field(field_name)
                        .ok_or_else(|| SqlBuilderError::FieldMissing(field_name.to_string()))?;

                    let p = [
                        &self.aux_params,
                        &query.aux_params,
                        &mapped_field.options.aux_params,
                    ];
                    let aux_params = ParameterMap::new(&p);

                    let role_valid = mapped_field
                        .options
                        .load_role_expr
                        .as_ref()
                        .map_or(true, |e| RoleValidator::is_valid(&self.roles, e));

                    // If field is preselected
                    if mapped_field.options.preselect {
                        if !role_valid {
                            let role_string = mapped_field
                                .options
                                .load_role_expr
                                .as_ref()
                                .map_or_else(|| String::new(), |e| e.to_string());
                            return Err(SqlBuilderError::RoleRequired(
                                role_string,
                                format!(
                                    "field `{}`",
                                    FieldPath::from(&build_context.query_home_path)
                                        .append(&local_field)
                                        .to_string(),
                                ),
                            )
                            .into());
                        }
                        let handler = mapped_field
                            .options
                            .field_handler
                            .as_ref()
                            .unwrap_or(&mapper.field_handler);
                        let select_expr =
                            handler.build_select(mapped_field.expression.clone(), &aux_params)?;

                        if let Some(expr) = select_expr {
                            let resolver = Resolver::new().with_self_alias(&canonical_alias);
                            let mut expr = resolver.resolve(&expr)?;

                            expr.push_literal(", ");

                            if local_path.is_empty()
                                || build_context
                                    .local_joined_paths
                                    .contains(local_path.as_str())
                            {
                                result.select_expr.extend(expr);
                                result.select_stream.push(Select::Preselect);
                            } else {
                                result.select_stream.push(Select::None);
                            }
                        } else {
                            // Column / expression is not selected
                            result.select_stream.push(Select::None);
                        }
                    }
                    // Field is selected through wildcard or explictit through field name
                    else if (path_selection && !mapped_field.options.skip_wildcard)
                        || build_context
                            .local_selected_fields
                            .contains(local_field.as_ref())
                    {
                        // If role is invalid raise error for explicit field and skip for wildcard selection
                        if !role_valid
                            && build_context
                                .local_selected_fields
                                .contains(local_field.as_ref())
                        {
                            let role_string = mapped_field
                                .options
                                .load_role_expr
                                .as_ref()
                                .map_or_else(|| String::new(), |e| e.to_string());
                            return Err(SqlBuilderError::RoleRequired(
                                role_string,
                                format!(
                                    "field `{}`",
                                    FieldPath::from(&build_context.query_home_path)
                                        .append(&local_field)
                                        .to_string()
                                ),
                            )
                            .into());
                        }

                        if role_valid {
                            let handler = mapped_field
                                .options
                                .field_handler
                                .as_ref()
                                .unwrap_or(&mapper.field_handler);
                            let select_expr = handler
                                .build_select(mapped_field.expression.clone(), &aux_params)?;
                            if let Some(expr) = select_expr {
                                // Fields with unresolved aux params that are selected through a wildcard are unselected
                                match expr.first_aux_param() {
                                    Some(p) if path_selection => {
                                        let query_field =
                                            FieldPath::from(build_context.query_home_path.as_str())
                                                .append(local_field.as_str());
                                        tracing::info!("Unselecting field `{}` in struct for table `{}` because aux param `{}` is missing", query_field.as_str(), &mapper.table_name, &p );
                                        result.select_stream.push(Select::None);
                                    }
                                    _ => {
                                        let resolver =
                                            Resolver::new().with_self_alias(&canonical_alias);
                                        let expr = resolver.resolve(&expr)?;
                                        result.select_expr.extend(expr);
                                        result.select_expr.push_literal(", ");
                                        result.select_stream.push(Select::Query);
                                        result.column_counter += 1;
                                    }
                                };
                            } else {
                                result.select_stream.push(Select::None);
                            }
                        } else {
                            result.select_stream.push(Select::None);
                        }
                    } else {
                        result.select_stream.push(Select::None);
                    }
                }
                DeserializeType::Join(join_name) => {
                    let mapped_join = mapper.join(join_name).ok_or_else(|| {
                        SqlBuilderError::JoinMissing(
                            join_name.to_string(),
                            mapper.table_name.to_string(),
                        )
                    })?;

                    let local_join_path = local_path.append(join_name);

                    let role_valid = mapped_join
                        .options
                        .load_role_expr
                        .as_ref()
                        .map_or(true, |e| RoleValidator::is_valid(&self.roles, e));

                    let role_string = if let Some(e) = &mapped_join.options.load_role_expr {
                        e.to_string()
                    } else {
                        String::from("")
                    };
                    // If role is invalid raise error for explicit join
                    if build_context
                        .local_joined_paths
                        .contains(&local_join_path.to_string())
                    {
                        if !role_valid {
                            return Err(SqlBuilderError::RoleRequired(
                                role_string,
                                format!(
                                    "path `{}`",
                                    FieldPath::from(&build_context.query_home_path)
                                        .append(&local_join_path)
                                        .to_string(),
                                ),
                            )
                            .into());
                        }
                        // Query selected join
                        result.select_stream.push(Select::Query);

                        // Select fields for this path
                        self.resolve_select(&local_join_path, query, build_context, result)?;
                    } else if mapped_join.options.preselect {
                        if !role_valid {
                            return Err(SqlBuilderError::RoleRequired(
                                role_string,
                                format!(
                                    "path `{}`",
                                    FieldPath::from(&build_context.query_home_path)
                                        .append(&local_join_path)
                                        .to_string(),
                                ),
                            )
                            .into());
                        }

                        // Add preselected join to joined paths
                        build_context
                            .local_joined_paths
                            .insert(local_join_path.to_string());

                        result.select_stream.push(Select::Preselect); // Preselected join

                        self.resolve_select(&local_join_path, query, build_context, result)?;
                    } else {
                        result.select_stream.push(Select::None); // No Join
                    }
                }
                DeserializeType::Merge(merge_name) => {
                    let mapped_merge = mapper
                        .merge(merge_name)
                        .ok_or_else(|| SqlBuilderError::MergeMissing(merge_name.to_string()))?;

                    let query_field = FieldPath::from(build_context.query_home_path.as_str())
                        .append(local_path.as_str())
                        .append(merge_name.as_str());

                    if mapped_merge.options.preselect
                        || query.contains_path_starts_with(&query_field)
                    {
                        if let Some(role_expr) = &mapped_merge.options.load_role_expr {
                            if !RoleValidator::is_valid(&self.roles, role_expr) {
                                return Err(SqlBuilderError::RoleRequired(
                                    role_expr.to_string(),
                                    format!("path `{}`", query_field.to_string(),),
                                )
                                .into());
                            }
                        }

                        result.unmerged_home_paths.insert(query_field.to_string());
                    }
                }
            }
        }

        Ok(())
    }

    fn add_query_field(
        &self,
        query_field: &str,
        build_context: &mut BuildContext,
        unmerged_home_paths: &mut HashSet<String>,
        field_hidden: bool,
    ) -> Result<()> {
        let query_path = FieldPath::trim_basename(query_field);
        if !Self::home_contains(&build_context.query_home_path, &query_path) {
            return Ok(());
        }
        let local_path = match query_path.localize_path(&build_context.query_home_path) {
            Some(l) => l,
            None => return Ok(()),
        };

        if let Some(local_merge_path) = self.next_merge_path(&local_path)? {
            unmerged_home_paths.insert(
                FieldPath::from(&build_context.query_home_path)
                    .append(&local_merge_path)
                    .to_string(),
            );

            for path in FieldPath::from(&local_merge_path).step_up().skip(1) {
                build_context.local_joined_paths.insert(path.to_string());
            }
        } else {
            let query_field = FieldPath::from(&query_field);
            let local_field = match query_field.localize_path(&build_context.query_home_path) {
                Some(f) => f,
                None => return Ok(()),
            };
            if !field_hidden {
                build_context
                    .local_selected_fields
                    .insert(local_field.to_string());
            } else {
                // Insert path only for join (needed for hidden order, hidden filter)
                for path in FieldPath::from(&local_field).step_up().skip(1) {
                    build_context.local_joined_paths.insert(path.to_string());
                }
            }
        }

        Ok(())
    }

    fn resolve_custom_selection(
        &self,
        query_selection: &str,
        mut build_context: &mut BuildContext,
        mut unmerged_home_paths: &mut HashSet<String>,
    ) -> Result<()> {
        let (query_path, selection_name) = FieldPath::split_basename(query_selection);
        let mapper = self.mapper_for_query_path(&query_path)?;
        let selection = mapper
            .selections
            .get(selection_name)
            .ok_or_else(|| SqlBuilderError::SelectionMissing(selection_name.to_string()))?;
        for local_field_or_path in selection {
            // Path either ends with `*` or `_`
            if local_field_or_path.ends_with('*') || local_field_or_path.ends_with('_') {
                let query_path = FieldPath::from(query_path.as_str()).append(
                    local_field_or_path
                        .trim_end_matches('*')
                        .trim_end_matches('_'),
                );
                if let Some(local_path) = query_path.localize_path(&build_context.query_home_path) {
                    if let Some(merge_path) = self.next_merge_path(&local_path)? {
                        unmerged_home_paths.insert(
                            FieldPath::from(&build_context.query_home_path)
                                .append(&merge_path)
                                .to_string(),
                        );
                    } else {
                        build_context
                            .local_selected_paths
                            .insert(local_path.to_string());
                    }
                }
            } else {
                let query_field = FieldPath::from(query_path.as_str())
                    .append(local_field_or_path)
                    .to_string();
                let query_path = FieldPath::trim_basename(query_field.as_str());
                if let Some(local_path) = query_path.localize_path(&build_context.query_home_path) {
                    if let Some(merge_path) = self.next_merge_path(&local_path)? {
                        unmerged_home_paths.insert(
                            FieldPath::from(&build_context.query_home_path)
                                .append(&merge_path)
                                .to_string(),
                        );
                    } else {
                        self.add_query_field(
                            query_field.as_str(),
                            &mut build_context,
                            &mut unmerged_home_paths,
                            false,
                        )?;
                    }
                }
            }
        }
        Ok(())
    }

    fn preparse_filter_joins<M>(
        &mut self,
        query: &Query<M>,
        build_context: &mut BuildContext,
        count_selection_only: bool,
    ) -> Result<()> {
        for token in &query.tokens {
            if let QueryToken::Field(field) = token {
                if field.filter.is_some() {
                    let query_path = FieldPath::from(&field.name);
                    if count_selection_only {
                        let root_mapper = self.root_mapper()?;
                        match root_mapper.selections.get("cnt") {
                            Some(selection) => {
                                let wildcard_path = format!("{}_*", field.name.as_str());
                                if !selection.contains(&field.name)
                                    && !selection.contains(&wildcard_path)
                                {
                                    continue;
                                }
                            }
                            None => continue,
                        }
                    }
                    if let Some(local_path_with_name) =
                        query_path.localize_path(&build_context.query_home_path)
                    {
                        let field_path = FieldPath::trim_basename(local_path_with_name.as_str());
                        if self.next_merge_path(&field_path)?.is_none() {
                            for path in field_path.step_up() {
                                build_context.local_joined_paths.insert(path.to_string());
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }
    fn selection_from_query<M>(
        &mut self,
        query: &Query<M>,
        mut build_context: &mut BuildContext,
    ) -> Result<HashSet<String>> {
        let mut unmerged_home_paths = HashSet::new();

        for token in &query.tokens {
            match token {
                QueryToken::Field(field) => {
                    self.add_query_field(
                        &field.name,
                        &mut build_context,
                        &mut unmerged_home_paths,
                        field.hidden,
                    )?;
                    if let Some(o) = &field.order {
                        let order = match o {
                            FieldOrder::Asc(o) => o,
                            FieldOrder::Desc(o) => o,
                        };
                        let query_path = FieldPath::from(&field.name);
                        if let Some(local_path_with_name) =
                            query_path.localize_path(&build_context.query_home_path)
                        {
                            build_context
                                .ordering
                                .entry(*order)
                                .or_insert_with(Vec::new)
                                .push((o.to_owned(), local_path_with_name.to_string()));
                        }
                    }
                }
                QueryToken::Wildcard(wildcard) => {
                    // TODO: Wildcard path may have ending _, check why and to remove
                    let query_path = FieldPath::from(&wildcard.path.trim_end_matches('_'));

                    if let Some(local_path) =
                        query_path.localize_path(&build_context.query_home_path)
                    {
                        // if !local_path.is_empty() {
                        // local_selected_paths.insert(local_path.to_string());
                        if let Some(local_merge_path) = self.next_merge_path(&local_path)? {
                            // insert full query path
                            unmerged_home_paths.insert(
                                FieldPath::from(&build_context.query_home_path)
                                    .append(&local_merge_path)
                                    .to_string(),
                            );
                            for path in FieldPath::from(&local_merge_path).step_up().skip(1) {
                                build_context.local_joined_paths.insert(path.to_string());
                            }
                        } else {
                            build_context
                                .local_selected_paths
                                .insert(local_path.to_string());
                        }
                        // }
                    }

                    //  relative_paths.insert(wildcard.path.to_string());
                }
                QueryToken::Selection(selection) => {
                    let (query_path, selection_name) = FieldPath::split_basename(&selection.name);

                    // Process only if selection path is a valid local path
                    if let Some(local_path) =
                        query_path.localize_path(&build_context.query_home_path)
                    {
                        if let Some(local_merge_path) = self.next_merge_path(&local_path)? {
                            // insert full query path
                            unmerged_home_paths.insert(
                                FieldPath::from(&build_context.query_home_path)
                                    .append(&local_merge_path)
                                    .to_string(),
                            );
                            for path in FieldPath::from(&local_merge_path).step_up().skip(1) {
                                build_context.local_joined_paths.insert(path.to_string());
                            }
                        } else {
                            let mapper = self.joined_mapper_for_local_path(&local_path)?;
                            match selection_name {
                                "all" => {
                                    // Add all fields explicitly. This will include fields that are skip_wildcard
                                    for deserialization_type in &mapper.deserialize_order {
                                        if let DeserializeType::Field(field_name) =
                                            deserialization_type
                                        {
                                            // Skip invliad load role restriction
                                            let f =
                                                mapper.fields.get(field_name).ok_or_else(|| {
                                                    SqlBuilderError::FieldMissing(
                                                        field_name.to_string(),
                                                    )
                                                })?;
                                            if let Some(role_expr) = &f.options.load_role_expr {
                                                if !RoleValidator::is_valid(&self.roles, role_expr)
                                                {
                                                    continue;
                                                }
                                            }

                                            let query_field = FieldPath::from(
                                                build_context.query_home_path.as_str(),
                                            )
                                            .append(local_path.as_str())
                                            .append(field_name)
                                            .to_string();
                                            self.add_query_field(
                                                query_field.as_str(),
                                                &mut build_context,
                                                &mut unmerged_home_paths,
                                                false,
                                            )?;
                                        }
                                    }
                                }
                                "mut" => {
                                    // Add all mutable fields on that path
                                    // (additionally keys and preselects will be added when building actual select expression)
                                    for deserialization_type in &mapper.deserialize_order {
                                        if let DeserializeType::Field(field_name) =
                                            deserialization_type
                                        {
                                            let f =
                                                mapper.fields.get(field_name).ok_or_else(|| {
                                                    SqlBuilderError::FieldMissing(
                                                        field_name.to_string(),
                                                    )
                                                })?;
                                            // Skip invalid load role restriction
                                            if let Some(role_expr) = &f.options.load_role_expr {
                                                if !RoleValidator::is_valid(&self.roles, role_expr)
                                                {
                                                    continue;
                                                }
                                            }
                                            // Skip invalid mut role restriction
                                            if let Some(role_expr) = &f.options.update_role_expr {
                                                if !RoleValidator::is_valid(&self.roles, role_expr)
                                                {
                                                    continue;
                                                }
                                            }
                                            if !f.options.skip_mut && !f.options.key {
                                                let query_field = FieldPath::from(
                                                    build_context.query_home_path.as_str(),
                                                )
                                                .append(local_path.as_str())
                                                .append(field_name)
                                                .to_string();
                                                self.add_query_field(
                                                    query_field.as_str(),
                                                    &mut build_context,
                                                    &mut unmerged_home_paths,
                                                    false,
                                                )?;
                                            }
                                        }
                                    }
                                }
                                "cnt" => {
                                    let selection = mapper.selections.get("cnt");
                                    if let Some(selection) = selection {
                                        // Select fields that are used for counting
                                        // Additionally to keys and preselects
                                        for deserialization_type in &mapper.deserialize_order {
                                            if let DeserializeType::Field(query_field_name) =
                                                deserialization_type
                                            {
                                                let wildcard_path =
                                                    format!("{}_*", query_field_name);
                                                if !selection.contains(&query_field_name)
                                                    && !selection.contains(&wildcard_path)
                                                {
                                                    continue;
                                                }

                                                self.add_query_field(
                                                    &query_field_name,
                                                    &mut build_context,
                                                    &mut unmerged_home_paths,
                                                    false,
                                                )?;
                                            }
                                        }
                                    } else {
                                        // If cnt selection is undefined, select keys and preselects
                                        for deserialization_type in &mapper.deserialize_order {
                                            if let DeserializeType::Field(field_name) =
                                                deserialization_type
                                            {
                                                let f = mapper.fields.get(field_name).ok_or_else(
                                                    || {
                                                        SqlBuilderError::FieldMissing(
                                                            field_name.to_string(),
                                                        )
                                                    },
                                                )?;
                                                if f.options.key || f.options.preselect {
                                                    let query_field = FieldPath::from(
                                                        build_context.query_home_path.as_str(),
                                                    )
                                                    .append(local_path.as_str())
                                                    .append(field_name)
                                                    .to_string();
                                                    self.add_query_field(
                                                        query_field.as_str(),
                                                        &mut build_context,
                                                        &mut unmerged_home_paths,
                                                        false,
                                                    )?;
                                                }
                                            }
                                        }
                                    }
                                }
                                _ => {
                                    self.resolve_custom_selection(
                                        &selection.name,
                                        &mut build_context,
                                        &mut unmerged_home_paths,
                                    )?;
                                }
                            }
                        }
                    } else {
                        // Evaluate selections that are not local to the selection path.
                        // Custom and standart selections may start above the current home path
                        // Eg. Selection `*, users_name` on top path must also be evaluated in home path `users`,
                        // because `users_name` affects selection.
                        if build_context
                            .query_home_path
                            .starts_with(query_path.as_str())
                        {
                            if selection_name != "cnt"
                                && selection_name != "mut"
                                && selection_name != "all"
                            {
                                self.resolve_custom_selection(
                                    &selection.name,
                                    &mut build_context,
                                    &mut unmerged_home_paths,
                                )?;
                            }
                        }
                    }
                }
                QueryToken::Predicate(predicate) => {
                    let query_path = FieldPath::trim_basename(&predicate.name);
                    if let Some(local_path) =
                        query_path.localize_path(&build_context.query_home_path)
                    {
                        // Skip local path if it contains a merged field
                        if self.joined_mapper_for_query_path(&local_path).is_ok() {
                            for partial_local_path in FieldPath::from(&local_path).step_up() {
                                // Skip predicate name
                                build_context
                                    .local_joined_paths
                                    .insert(partial_local_path.to_string());
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(unmerged_home_paths)
    }

    fn root_mapper(&self) -> Result<&TableMapper> {
        self.table_mapper_registry
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_string()))
    }
    fn next_merge_path(&self, local_path: &FieldPath) -> Result<Option<String>> {
        let mut current_mapper = self
            .table_mapper_registry
            .get(&self.home_mapper)
            .ok_or_else(|| ToqlError::MapperMissing(self.home_mapper.to_string()))?;

        for (mapper_name, merge_path) in local_path.children().zip(local_path.step_down()) {
            if current_mapper.merged_mapper(mapper_name.as_str()).is_some() {
                return Ok(Some(merge_path.to_string()));
            } else if let Some(joined_mapper_name) =
                current_mapper.joined_mapper(mapper_name.as_str())
            {
                let m = self
                    .table_mapper_registry
                    .get(&joined_mapper_name)
                    .ok_or_else(|| ToqlError::MapperMissing(mapper_name.to_string()))?;
                current_mapper = m;
            } else {
                break;
            }
        }
        Ok(None)
    }

    fn home_contains(home_path: &str, query_path: &FieldPath) -> bool {
        let r = match (home_path.is_empty(), query_path.is_empty()) {
            (true, true) => true,
            (false, true) => false,
            (true, false) => true,
            (false, false) => query_path.as_str().starts_with(home_path),
        };

        r
    }
}