File: tags_storage_sqlite3.cpp

package info (click to toggle)
codelite 14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 112,816 kB
  • sloc: cpp: 483,662; ansic: 150,144; php: 9,569; lex: 4,186; python: 3,417; yacc: 2,820; sh: 1,147; makefile: 52; xml: 13
file content (1713 lines) | stat: -rw-r--r-- 56,598 bytes parent folder | download
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
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : tags_database.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "file_logger.h"
#include "fileutils.h"
#include "precompiled_header.h"
#include "tags_storage_sqlite3.h"
#include <algorithm>
#include <wx/longlong.h>
#include <wx/tokenzr.h>

//-------------------------------------------------
// Tags database class implementation
//-------------------------------------------------
TagsStorageSQLite::TagsStorageSQLite()
    : ITagsStorage()
{
    m_db = new clSqliteDB();
    SetUseCache(true);
}

TagsStorageSQLite::~TagsStorageSQLite()
{
    if(m_db) {
        m_db->Close();
        delete m_db;
        m_db = NULL;
    }
}

void TagsStorageSQLite::OpenDatabase(const wxFileName& fileName)
{
    if(m_fileName.GetFullPath() == fileName.GetFullPath()) return;

    // Did we get a file name to use?
    if(!fileName.IsOk() && !m_fileName.IsOk()) return;

    // We did not get any file name to use BUT we
    // do have an open database, so we will use it
    if(!fileName.IsOk()) return;

    try {
        if(!m_fileName.IsOk()) {
            // First time we open the db
            m_db->Open(fileName.GetFullPath());
            m_db->SetBusyTimeout(10);
            CreateSchema();
            m_fileName = fileName;

        } else {
            // We have both fileName & m_fileName and they
            // are different, Close previous db
            m_db->Close();
            m_db->Open(fileName.GetFullPath());
            m_db->SetBusyTimeout(10);
            CreateSchema();
            m_fileName = fileName;
        }

    } catch(wxSQLite3Exception& e) {
        clWARNING() << "Failed to open file:" << m_fileName.GetFullPath() << "." << e.GetMessage();
    }
}

void TagsStorageSQLite::CreateSchema()
{
    wxString sql;

    // improve performace by using pragma command:
    // (this needs to be done before the creation of the
    // tables and indices)
    try {
        sql = wxT("PRAGMA journal_mode= OFF;");
        m_db->ExecuteUpdate(sql);

        sql = wxT("PRAGMA synchronous = OFF;");
        m_db->ExecuteUpdate(sql);

        sql = wxT("PRAGMA temp_store = MEMORY;");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create  table if not exists tags (ID INTEGER PRIMARY KEY AUTOINCREMENT, name string, file string, "
                  "line integer, kind string, access string, signature string, pattern string, parent string, inherits "
                  "string, path string, typeref string, scope string, return_value string);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create  table if not exists global_tags (ID INTEGER PRIMARY KEY AUTOINCREMENT, name string, tag_id "
                  "integer)");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create  table if not exists FILES (ID INTEGER PRIMARY KEY AUTOINCREMENT, file string, last_retagged "
                  "integer);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create  table if not exists MACROS (ID INTEGER PRIMARY KEY AUTOINCREMENT, file string, line "
                  "integer, name string, is_function_like int, replacement string, signature string);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create  table if not exists SIMPLE_MACROS (ID INTEGER PRIMARY KEY AUTOINCREMENT, file string, name "
                  "string);");
        m_db->ExecuteUpdate(sql);

        // create unuque index on Files' file column
        sql = wxT("CREATE UNIQUE INDEX IF NOT EXISTS FILES_NAME on FILES(file)");
        m_db->ExecuteUpdate(sql);

        // Create a trigger that makes sure that whenever a record is deleted
        // from the TAGS table, the corresponded entry is also deleted from the
        // global_tags
        wxString trigger1 = wxT("CREATE TRIGGER IF NOT EXISTS tags_delete AFTER DELETE ON tags ") wxT("FOR EACH ROW ")
            wxT("BEGIN ") wxT("    DELETE FROM global_tags WHERE global_tags.tag_id = OLD.id;") wxT("END;");

        m_db->ExecuteUpdate(trigger1);

        wxString trigger2 = wxT("CREATE TRIGGER IF NOT EXISTS tags_insert AFTER INSERT ON tags ")
            wxT("FOR EACH ROW WHEN NEW.scope = '<global>' ") wxT("BEGIN ")
                wxT("    INSERT INTO global_tags (id, name, tag_id) VALUES (NULL, NEW.name, NEW.id);") wxT("END;");
        m_db->ExecuteUpdate(trigger2);

        // Create unique index on tags table
        sql = wxT("CREATE UNIQUE INDEX IF NOT EXISTS TAGS_UNIQ on tags(kind, path, signature, typeref);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS KIND_IDX on tags(kind);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS FILE_IDX on tags(file);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE UNIQUE INDEX IF NOT EXISTS MACROS_UNIQ on MACROS(name);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS global_tags_idx_1 on global_tags(name);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS global_tags_idx_2 on global_tags(tag_id);");
        m_db->ExecuteUpdate(sql);

        // Create search indexes
        sql = wxT("CREATE INDEX IF NOT EXISTS TAGS_NAME on tags(name);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS TAGS_SCOPE on tags(scope);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS TAGS_PATH on tags(path);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS TAGS_PARENT on tags(parent);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS TAGS_TYPEREF on tags(typeref);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS MACROS_NAME on MACROS(name);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("CREATE INDEX IF NOT EXISTS SIMPLE_MACROS_FILE on SIMPLE_MACROS(file);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create table if not exists tags_version (version string primary key);");
        m_db->ExecuteUpdate(sql);

        sql = wxT("create unique index if not exists tags_version_uniq on tags_version(version);");
        m_db->ExecuteUpdate(sql);

        sql = wxString(wxT("replace into tags_version values ('")) << GetVersion() << wxT("');");
        m_db->ExecuteUpdate(sql);

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::RecreateDatabase()
{
    try {
        // commit any open transactions
        Commit();

        // Close the database
        m_db->Close();
        wxString filename = m_fileName.GetFullPath();
        if(clRemoveFile(m_fileName.GetFullPath()) == false) {

            // re-open the database
            m_fileName.Clear();
            OpenDatabase(filename);

            // and drop tables
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS TAGS"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS COMMENTS"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS TAGS_VERSION"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS VARIABLES"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS FILES"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS MACROS"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS SIMPLE_MACROS"));
            m_db->ExecuteUpdate(wxT("DROP TABLE IF EXISTS GLOBAL_TAGS"));

            // drop indexes
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS FILES_NAME"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS TAGS_UNIQ"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS KIND_IDX"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS FILE_IDX"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS TAGS_NAME"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS TAGS_SCOPE"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS TAGS_PATH"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS TAGS_PARENT"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS tags_version_uniq"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS MACROS_UNIQ"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS MACROS_NAME"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS SIMPLE_MACROS_FILE"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS GLOBAL_TAGS_IDX_1"));
            m_db->ExecuteUpdate(wxT("DROP INDEX IF EXISTS GLOBAL_TAGS_IDX_2"));

            // Recreate the schema
            CreateSchema();
        } else {
            // We managed to delete the file
            // re-open it

            m_fileName.Clear();
            OpenDatabase(filename);
        }
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

wxString TagsStorageSQLite::GetSchemaVersion() const
{
    // return the current schema version
    try {
        wxString sql;
        wxString version;
        sql = wxT("SELECT * FROM TAGS_VERSION");
        wxSQLite3ResultSet rs = m_db->ExecuteQuery(sql);

        if(rs.NextRow()) version = rs.GetString(0);
        return version;
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
    return wxEmptyString;
}

void TagsStorageSQLite::Store(TagTreePtr tree, const wxFileName& path, bool autoCommit)
{
    if(!path.IsOk() && !m_fileName.IsOk()) {
        // An attempt is made to save the tree into db but no database
        // is provided and none is currently opened to use
        return;
    }

    if(!tree) return;

    OpenDatabase(path);
    TreeWalker<wxString, TagEntry> walker(tree->GetRoot());

    try {
        // Create the statements before the execution
        std::vector<TagEntry> updateList;

        // AddChild entries to database
        if(autoCommit) m_db->Begin();

        for(; !walker.End(); walker++) {
            // Skip root node
            if(walker.GetNode() == tree->GetRoot()) continue;

            DoInsertTagEntry(walker.GetNode()->GetData());
        }

        if(autoCommit) m_db->Commit();

    } catch(wxSQLite3Exception& e) {
        try {
            if(autoCommit) m_db->Rollback();
        } catch(wxSQLite3Exception& WXUNUSED(e1)) {
            wxUnusedVar(e);
        }
    }
}

void TagsStorageSQLite::SelectTagsByFile(const wxString& file, std::vector<TagEntryPtr>& tags, const wxFileName& path)
{
    // Incase empty file path is provided, use the current file name
    wxFileName databaseFileName(path);
    path.IsOk() == false ? databaseFileName = m_fileName : databaseFileName = path;
    OpenDatabase(databaseFileName);

    wxString query;
    query << wxT("select * from tags where file='") << file << "' ";
    //#ifdef __WXMSW__
    //    // Under Windows, the file-crawler changes the file path
    //    // to lowercase. However, the database matches the file name
    //    // by case-sensitive
    //    query << "COLLATE NOCASE ";
    //#endif
    query << wxT("order by line asc");
    DoFetchTags(query, tags);
}

void TagsStorageSQLite::DeleteByFileName(const wxFileName& path, const wxString& fileName, bool autoCommit)
{
    // make sure database is open
    try {
        OpenDatabase(path);

        if(autoCommit) { m_db->Begin(); }

        wxString sql;
        sql << "delete from tags where File='" << fileName << "'";
        m_db->ExecuteUpdate(sql);

        if(autoCommit) m_db->Commit();
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
        if(autoCommit) { m_db->Rollback(); }
    }
}

wxSQLite3ResultSet TagsStorageSQLite::Query(const wxString& sql, const wxFileName& path)
{
    // make sure database is open
    try {
        OpenDatabase(path);
        return m_db->ExecuteQuery(sql);
    } catch(wxSQLite3Exception& e) {
        clWARNING() << "Query error:" << sql << "." << e.GetMessage();
        if(e.GetMessage().Contains("disk I/O error")) { ReOpenDatabase(); }
    }
    return wxSQLite3ResultSet();
}

void TagsStorageSQLite::ExecuteUpdate(const wxString& sql)
{
    try {
        m_db->ExecuteUpdate(sql);
    } catch(wxSQLite3Exception& e) {
        clWARNING() << "ExecuteUpdate error:" << sql << "." << e.GetMessage();
    }
}

const bool TagsStorageSQLite::IsOpen() const { return m_db->IsOpen(); }

void TagsStorageSQLite::GetFilesForCC(const wxString& userTyped, wxArrayString& matches)
{
    try {
        wxString query;
        wxString tmpName(userTyped);

        // Files are kept in native format in the database
        // so it only makes sense to search them with the correct path
        // separator
        tmpName.Replace("\\", "/");
        tmpName.Replace("/", wxString() << wxFILE_SEP_PATH);
        tmpName.Replace(wxT("_"), wxT("^_"));
        query << wxT("select * from files where file like '%%") << tmpName << wxT("%%' ESCAPE '^' ")
              << wxT("order by file");

        wxString pattern = userTyped;
        pattern.Replace("\\", "/");

        wxSQLite3ResultSet res = m_db->ExecuteQuery(query);
        while(res.NextRow()) {
            // Keep the part from where the user typed and until the end of the file name
            wxString matchedFile = res.GetString(1);
            matchedFile.Replace("\\", "/");

            int where = matchedFile.Find(pattern);
            if(where == wxNOT_FOUND) continue;
            matchedFile = matchedFile.Mid(where);
            matches.Add(matchedFile);
        }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::GetFiles(const wxString& partialName, std::vector<FileEntryPtr>& files)
{
    try {
        bool match_path = (!partialName.IsEmpty() && partialName.Last() == wxFileName::GetPathSeparator());

        wxString query;
        wxString tmpName(partialName);
        tmpName.Replace(wxT("_"), wxT("^_"));
        query << wxT("select * from files where file like '%%") << tmpName << wxT("%%' ESCAPE '^' ")
              << wxT("order by file");

        wxSQLite3ResultSet res = m_db->ExecuteQuery(query);
        while(res.NextRow()) {

            FileEntryPtr fe(new FileEntry());
            fe->SetId(res.GetInt(0));
            fe->SetFile(res.GetString(1));
            fe->SetLastRetaggedTimestamp(res.GetInt(2));

            wxFileName fileName(fe->GetFile());
            wxString match = match_path ? fileName.GetFullPath() : fileName.GetFullName();

// Under Windows, all files are stored as lower case in the
// database (see fc_fileopener.cpp normalize_path method
#ifdef __WXMSW__
            wxString lowerCasePartialName(partialName);
            lowerCasePartialName.MakeLower();
            match.MakeLower();
#else
            wxString lowerCasePartialName(partialName);
#endif
            if(match.StartsWith(lowerCasePartialName)) { files.push_back(fe); }
        }
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

long TagsStorageSQLite::LastRowId() const
{
    wxLongLong id = m_db->GetLastRowId();
    return id.ToLong();
}

void TagsStorageSQLite::DeleteByFilePrefix(const wxFileName& dbpath, const wxString& filePrefix)
{
    // make sure database is open

    try {
        OpenDatabase(dbpath);
        wxString sql;
        wxString name(filePrefix);
        name.Replace(wxT("_"), wxT("^_"));

        sql << wxT("delete from tags where file like '") << name << wxT("%%' ESCAPE '^' ");
        m_db->ExecuteUpdate(sql);

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::GetFiles(std::vector<FileEntryPtr>& files)
{
    try {
        wxString query(wxT("select * from files order by file"));
        wxSQLite3ResultSet res = m_db->ExecuteQuery(query);

        // Pre allocate a reasonable amount of entries
        files.reserve(5000);

        while(res.NextRow()) {
            FileEntryPtr fe(new FileEntry());
            fe->SetId(res.GetInt(0));
            fe->SetFile(res.GetString(1));
            fe->SetLastRetaggedTimestamp(res.GetInt(2));

            files.push_back(fe);
        }
        // release unneeded memory
        files.shrink_to_fit();

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::DeleteFromFiles(const wxArrayString& files)
{
    if(files.IsEmpty()) { return; }

    wxString query;
    query << wxT("delete from FILES where file in (");

    for(size_t i = 0; i < files.GetCount(); i++) {
        query << wxT("'") << files.Item(i) << wxT("',");
    }

    // remove last ','
    query.RemoveLast();
    query << wxT(")");

    try {
        m_db->ExecuteQuery(query);
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::DeleteFromFilesByPrefix(const wxFileName& dbpath, const wxString& filePrefix)
{
    // make sure database is open

    try {
        OpenDatabase(dbpath);
        wxString sql;
        wxString name(filePrefix);
        name.Replace(wxT("_"), wxT("^_"));

        sql << wxT("delete from FILES where file like '") << name << wxT("%%' ESCAPE '^' ");
        m_db->ExecuteUpdate(sql);

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::PPTokenFromSQlite3ResultSet(wxSQLite3ResultSet& rs, PPToken& token)
{
    // set the name
    token.name = rs.GetString(3);

    bool isFunctionLike = rs.GetInt(4) == 0 ? false : true;

    // set the flags
    token.flags = PPToken::IsValid;
    if(isFunctionLike) token.flags |= PPToken::IsFunctionLike;

    token.line = rs.GetInt(2);
    token.replacement = rs.GetString(5);

    wxString sig = rs.GetString(6);
    sig.Replace(wxT("("), wxT(""));
    sig.Replace(wxT(")"), wxT(""));
    token.args = wxStringTokenize(sig, wxT(","), wxTOKEN_STRTOK);
}

TagEntry* TagsStorageSQLite::FromSQLite3ResultSet(wxSQLite3ResultSet& rs)
{
    TagEntry* entry = new TagEntry();
    entry->SetId(rs.GetInt(0));
    entry->SetName(rs.GetString(1));
    entry->SetFile(rs.GetString(2));
    entry->SetLine(rs.GetInt(3));
    entry->SetKind(rs.GetString(4));
    entry->SetAccess(rs.GetString(5));
    entry->SetSignature(rs.GetString(6));
    entry->SetPattern(rs.GetString(7));
    entry->SetParent(rs.GetString(8));
    entry->SetInherits(rs.GetString(9));
    entry->SetPath(rs.GetString(10));
    entry->SetTyperef(rs.GetString(11));
    entry->SetScope(rs.GetString(12));
    entry->SetReturnValue(rs.GetString(13));
    return entry;
}

void TagsStorageSQLite::DoFetchTags(const wxString& sql, std::vector<TagEntryPtr>& tags)
{
    if(GetUseCache()) {
        clDEBUG1() << "Testing cache for" << sql << clEndl;
        if(m_cache.Get(sql, tags) == true) {
            clDEBUG1() << "[CACHED ITEMS]" << sql << clEndl;
            return;
        }
    }

    clDEBUG1() << "Entry not found in cache" << sql << clEndl;
    clDEBUG1() << "Fetching from disk..." << clEndl;
    tags.reserve(500);
    try {
        wxSQLite3ResultSet ex_rs;
        ex_rs = Query(sql);

        // add results from external database to the workspace database
        while(ex_rs.NextRow()) {
            // Construct a TagEntry from the rescord set
            TagEntryPtr tag(FromSQLite3ResultSet(ex_rs));
            // conver the path to be real path
            tags.push_back(tag);
        }
        ex_rs.Finalize();
    } catch(wxSQLite3Exception& e) {
        clWARNING() << "TagsStorageSQLite::DoFetchTags() error:" << e.GetMessage() << clEndl;
    }
    clDEBUG1() << "Fetching from disk...done" << clEndl;
    if(GetUseCache()) {
        clDEBUG1() << "Updating cache" << clEndl;
        m_cache.Store(sql, tags);
        clDEBUG1() << "Updating cache...done (" << tags.size() << "entries)" << clEndl;
    }
}

void TagsStorageSQLite::DoFetchTags(const wxString& sql, std::vector<TagEntryPtr>& tags, const wxArrayString& kinds)
{
    if(GetUseCache()) {
        CL_DEBUG1(wxT("Testing cache for: %s"), sql);
        if(m_cache.Get(sql, kinds, tags) == true) {
            CL_DEBUG1(wxT("[CACHED ITEMS] %s"), sql);
            return;
        }
    }

    CL_DEBUG1("Fetching from disk");
    try {
        wxSQLite3ResultSet ex_rs;
        ex_rs = Query(sql);

        // add results from external database to the workspace database
        while(ex_rs.NextRow()) {
            // check if this kind is accepted
            if(kinds.Index(ex_rs.GetString(4)) != wxNOT_FOUND) {

                // Construct a TagEntry from the rescord set
                TagEntryPtr tag(FromSQLite3ResultSet(ex_rs));

                // conver the path to be real path
                tags.push_back(tag);
            }
        }
        ex_rs.Finalize();

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
    CL_DEBUG1("Fetching from disk...done");
    if(GetUseCache()) {
        CL_DEBUG1("updating cache");
        m_cache.Store(sql, kinds, tags);
        CL_DEBUG1("updating cache...done");
    }
}

void TagsStorageSQLite::GetTagsByScopeAndName(const wxString& scope, const wxString& name, bool partialNameAllowed,
                                              std::vector<TagEntryPtr>& tags)
{
    if(name.IsEmpty()) return;

    wxString sql;
    sql << wxT("select * from tags where ");

    // did we get scope?
    if(scope.IsEmpty() || scope == wxT("<global>")) {
        sql << wxT("ID IN (select tag_id from global_tags where ");
        DoAddNamePartToQuery(sql, name, partialNameAllowed, false);
        sql << wxT(" ) ");

    } else {
        sql << " scope = '" << scope << "' ";
        DoAddNamePartToQuery(sql, name, partialNameAllowed, true);
    }

    sql << wxT(" LIMIT ") << this->GetSingleSearchLimit();

    // get get the tags
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByScope(const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    wxString sql;

    // Build the SQL statement
    sql << wxT("select * from tags where scope='") << scope << wxT("' ORDER BY NAME limit ") << GetSingleSearchLimit();

    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByKind(const wxArrayString& kinds, const wxString& orderingColumn, int order,
                                      std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where kind in (");
    for(size_t i = 0; i < kinds.GetCount(); i++) {
        sql << wxT("'") << kinds.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(") ");

    if(orderingColumn.IsEmpty() == false) {
        sql << wxT("order by ") << orderingColumn;
        switch(order) {
        case ITagsStorage::OrderAsc:
            sql << wxT(" ASC");
            break;
        case ITagsStorage::OrderDesc:
            sql << wxT(" DESC");
            break;
        case ITagsStorage::OrderNone:
        default:
            break;
        }
    }

    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByPath(const wxArrayString& path, std::vector<TagEntryPtr>& tags)
{
    if(path.empty()) return;

    wxString sql;

    sql << wxT("select * from tags where path IN(");
    for(size_t i = 0; i < path.GetCount(); i++) {
        sql << wxT("'") << path.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByNameAndParent(const wxString& name, const wxString& parent,
                                               std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where name='") << name << wxT("' LIMIT ") << GetSingleSearchLimit();

    std::vector<TagEntryPtr> tmpResults;
    DoFetchTags(sql, tmpResults);

    // Filter by parent
    for(size_t i = 0; i < tmpResults.size(); i++) {
        if(tmpResults.at(i)->GetParent() == parent) { tags.push_back(tmpResults.at(i)); }
    }
}

void TagsStorageSQLite::GetTagsByKindAndPath(const wxArrayString& kinds, const wxString& path,
                                             std::vector<TagEntryPtr>& tags)
{
    if(kinds.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where path='") << path << wxT("' LIMIT ") << GetSingleSearchLimit();

    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByFileAndLine(const wxString& file, int line, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where file='") << file << wxT("' and line=") << line << wxT(" ");
    DoFetchTags(sql, tags);
}

TagEntryPtr TagsStorageSQLite::GetTagAboveFileAndLine(const wxString& file, int line)
{
    wxString sql;
    sql << wxT("select * from tags where file='") << file << wxT("' and line<=") << line << wxT(" LIMIT 1");
    TagEntryPtrVector_t tags;
    DoFetchTags(sql, tags);
    if(!tags.empty()) { return tags.at(0); }
    return NULL;
}

void TagsStorageSQLite::GetTagsByScopeAndKind(const wxString& scope, const wxArrayString& kinds,
                                              std::vector<TagEntryPtr>& tags, bool applyLimit)
{
    if(kinds.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where scope='") << scope << wxT("' ");
    if(applyLimit) { sql << wxT(" LIMIT ") << GetSingleSearchLimit(); }
    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByKindAndFile(const wxArrayString& kind, const wxString& fileName,
                                             const wxString& orderingColumn, int order, std::vector<TagEntryPtr>& tags)
{
    if(kind.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where file='") << fileName << wxT("' and kind in (");

    for(size_t i = 0; i < kind.GetCount(); i++) {
        sql << wxT("'") << kind.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");

    if(orderingColumn.IsEmpty() == false) {
        sql << wxT("order by ") << orderingColumn;
        switch(order) {
        case ITagsStorage::OrderAsc:
            sql << wxT(" ASC");
            break;
        case ITagsStorage::OrderDesc:
            sql << wxT(" DESC");
            break;
        case ITagsStorage::OrderNone:
        default:
            break;
        }
    }
    DoFetchTags(sql, tags);
}

int TagsStorageSQLite::DeleteFileEntry(const wxString& filename)
{
    try {
        wxSQLite3Statement statement = m_db->GetPrepareStatement(wxT("DELETE FROM FILES WHERE FILE=?"));
        statement.Bind(1, filename);
        statement.ExecuteUpdate();

    } catch(wxSQLite3Exception& exc) {
        if(exc.ErrorCodeAsString(exc.GetErrorCode()) == wxT("SQLITE_CONSTRAINT")) return TagExist;
        return TagError;
    }
    return TagOk;
}

int TagsStorageSQLite::InsertFileEntry(const wxString& filename, int timestamp)
{
    try {
        wxSQLite3Statement statement =
            m_db->GetPrepareStatement(wxT("INSERT OR REPLACE INTO FILES VALUES(NULL, ?, ?)"));
        statement.Bind(1, filename);
        statement.Bind(2, timestamp);
        statement.ExecuteUpdate();

    } catch(wxSQLite3Exception& exc) {
        return TagError;
    }
    return TagOk;
}

int TagsStorageSQLite::UpdateFileEntry(const wxString& filename, int timestamp)
{
    try {
        wxSQLite3Statement statement =
            m_db->GetPrepareStatement(wxT("UPDATE OR REPLACE FILES SET last_retagged=? WHERE file=?"));
        statement.Bind(1, timestamp);
        statement.Bind(2, filename);
        statement.ExecuteUpdate();

    } catch(wxSQLite3Exception& exc) {
        return TagError;
    }
    return TagOk;
}

int TagsStorageSQLite::DoInsertTagEntry(const TagEntry& tag)
{
    // If this node is a dummy, (IsOk() == false) we dont insert it to database
    if(!tag.IsOk()) return TagOk;

    // does not matter if we insert or update, the cache must be cleared for any related tags
    if(GetUseCache()) { ClearCache(); }

    try {
        wxSQLite3Statement statement = m_db->GetPrepareStatement(
            wxT("INSERT OR REPLACE INTO TAGS VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"));
        statement.Bind(1, tag.GetName());
        statement.Bind(2, tag.GetFile());
        statement.Bind(3, tag.GetLine());
        statement.Bind(4, tag.GetKind());
        statement.Bind(5, tag.GetAccess());
        statement.Bind(6, tag.GetSignature());
        statement.Bind(7, tag.GetPattern());
        statement.Bind(8, tag.GetParent());
        statement.Bind(9, tag.GetInheritsAsString());
        statement.Bind(10, tag.GetPath());
        statement.Bind(11, tag.GetTyperef());
        statement.Bind(12, tag.GetScope());
        statement.Bind(13, tag.GetReturnValue());
        statement.ExecuteUpdate();
    } catch(wxSQLite3Exception& exc) {
        return TagError;
    }
    return TagOk;
}

bool TagsStorageSQLite::IsTypeAndScopeContainer(wxString& typeName, wxString& scope)
{
    wxString sql;

    // Break the typename to 'name' and scope
    wxString typeNameNoScope(typeName.AfterLast(wxT(':')));
    wxString scopeOne(typeName.BeforeLast(wxT(':')));

    if(scopeOne.EndsWith(wxT(":"))) scopeOne.RemoveLast();

    wxString combinedScope;

    if(scope != wxT("<global>")) combinedScope << scope;

    if(scopeOne.IsEmpty() == false) {
        if(combinedScope.IsEmpty() == false) combinedScope << wxT("::");
        combinedScope << scopeOne;
    }

    sql << wxT("select scope,kind from tags where name='") << typeNameNoScope << wxT("'");

    bool found_global(false);

    try {
        wxSQLite3ResultSet rs = Query(sql);
        while(rs.NextRow()) {
            wxString scopeFounded(rs.GetString(0));
            wxString kindFounded(rs.GetString(1));

            bool containerKind = kindFounded == wxT("struct") || kindFounded == wxT("class") || kindFounded == "cenum";
            if(scopeFounded == combinedScope && containerKind) {
                scope = combinedScope;
                typeName = typeNameNoScope;
                // we got an exact match
                return true;

            } else if(scopeFounded == scopeOne && containerKind) {
                // this is equal to cases like this:
                // class A {
                // typedef std::list<int> List;
                // List l;
                // };
                // the combinedScope will be: 'A::std'
                // however, the actual scope is 'std'
                scope = scopeOne;
                typeName = typeNameNoScope;
                // we got an exact match
                return true;

            } else if(containerKind && scopeFounded == wxT("<global>")) {
                found_global = true;
            }
        }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }

    // if we reached here, it means we did not find any exact match
    if(found_global) {
        scope = wxT("<global>");
        typeName = typeNameNoScope;
        return true;
    }

    return false;
}

bool TagsStorageSQLite::IsTypeAndScopeExist(wxString& typeName, wxString& scope)
{
    wxString sql;
    wxString strippedName;
    wxString secondScope;
    wxString bestScope;
    wxString parent;
    wxString tmpScope(scope);

    strippedName = typeName.AfterLast(wxT(':'));
    secondScope = typeName.BeforeLast(wxT(':'));

    if(secondScope.EndsWith(wxT(":"))) secondScope.RemoveLast();

    if(strippedName.IsEmpty()) return false;

    sql << wxT("select scope,parent from tags where name='") << strippedName
        << wxT("' and kind in ('class', 'struct', 'typedef') LIMIT 50");
    int foundOther(0);
    wxString scopeFounded;
    wxString parentFounded;

    if(secondScope.IsEmpty() == false) tmpScope << wxT("::") << secondScope;

    parent = tmpScope.AfterLast(wxT(':'));

    try {
        wxSQLite3ResultSet rs = Query(sql);
        while(rs.NextRow()) {

            scopeFounded = rs.GetString(0);
            parentFounded = rs.GetString(1);

            if(scopeFounded == tmpScope) {
                // exact match
                scope = scopeFounded;
                typeName = strippedName;
                return true;

            } else if(parentFounded == parent) {
                bestScope = scopeFounded;

            } else {
                foundOther++;
            }
        }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }

    // if we reached here, it means we did not find any exact match
    if(bestScope.IsEmpty() == false) {
        scope = bestScope;
        typeName = strippedName;
        return true;

    } else if(foundOther == 1) {
        scope = scopeFounded;
        typeName = strippedName;
        return true;
    }
    return false;
}

void TagsStorageSQLite::GetScopesFromFileAsc(const wxFileName& fileName, std::vector<wxString>& scopes)
{
    wxString sql;
    sql << wxT("select distinct scope from tags where file = '") << fileName.GetFullPath() << wxT("' ")
        << wxT(" and kind in('prototype', 'function', 'enum')") << wxT(" order by scope ASC");

    // we take the first entry
    try {
        wxSQLite3ResultSet rs = Query(sql);
        while(rs.NextRow()) {
            scopes.push_back(rs.GetString(0));
        }
        rs.Finalize();
    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::GetTagsByFileScopeAndKind(const wxFileName& fileName, const wxString& scopeName,
                                                  const wxArrayString& kind, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where file = '") << fileName.GetFullPath() << wxT("' ") << wxT(" and scope='")
        << scopeName << wxT("' ");

    if(kind.IsEmpty() == false) {
        sql << wxT(" and kind in(");
        for(size_t i = 0; i < kind.GetCount(); i++) {
            sql << wxT("'") << kind.Item(i) << wxT("',");
        }
        sql.RemoveLast();
        sql << wxT(")");
    }

    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetAllTagsNames(wxArrayString& names)
{
    try {

        wxString query(wxT("SELECT distinct name FROM tags order by name ASC LIMIT "));
        query << GetMaxWorkspaceTagToColour();

        wxSQLite3ResultSet res = Query(query);
        while(res.NextRow()) {
            // add unique strings only
            names.Add(res.GetString(0));
        }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::GetTagsNames(const wxArrayString& kind, wxArrayString& names)
{
    if(kind.IsEmpty()) return;
    try {

        wxString whereClause;
        whereClause << wxT(" kind IN (");
        for(size_t i = 0; i < kind.GetCount(); i++) {
            whereClause << wxT("'") << kind.Item(i) << wxT("',");
        }

        whereClause = whereClause.BeforeLast(wxT(','));
        whereClause << wxT(") ");

        wxString query(wxT("SELECT distinct name FROM tags WHERE "));
        query << whereClause << wxT(" order by name ASC LIMIT ") << GetMaxWorkspaceTagToColour();

        wxSQLite3ResultSet res = Query(query);
        while(res.NextRow()) {
            // add unique strings only
            names.Add(res.GetString(0));
        }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
}

void TagsStorageSQLite::GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds,
                                               std::vector<TagEntryPtr>& tags)
{
    if(kinds.empty() || scopes.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where scope in (");
    for(size_t i = 0; i < scopes.GetCount(); i++) {
        sql << wxT("'") << scopes.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(") ORDER BY NAME ");
    DoAddLimitPartToQuery(sql, tags);
    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByScopesAndKindNoLimit(const wxArrayString& scopes, const wxArrayString& kinds,
                                                      std::vector<TagEntryPtr>& tags)
{
    if(kinds.empty() || scopes.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where scope in (");
    for(size_t i = 0; i < scopes.GetCount(); i++) {
        sql << wxT("'") << scopes.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(") ORDER BY NAME");

    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByTyperefAndKind(const wxArrayString& typerefs, const wxArrayString& kinds,
                                                std::vector<TagEntryPtr>& tags)
{
    if(kinds.empty() || typerefs.empty()) { return; }

    wxString sql;
    sql << wxT("select * from tags where typeref in (");
    for(size_t i = 0; i < typerefs.GetCount(); i++) {
        sql << wxT("'") << typerefs.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(") ORDER BY NAME ");
    DoAddLimitPartToQuery(sql, tags);
    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByPath(const wxString& path, std::vector<TagEntryPtr>& tags, int limit)
{
    if(path.empty()) return;

    wxString sql;
    sql << wxT("select * from tags where path ='") << path << wxT("' LIMIT ") << limit;
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByScopeAndName(const wxArrayString& scope, const wxString& name, bool partialNameAllowed,
                                              std::vector<TagEntryPtr>& tags)
{
    if(scope.empty()) return;
    if(name.IsEmpty()) return;

    wxArrayString scopes = scope;

    // Check the given scopes and remove the '<global>' scope from it
    // we use the more specialized method for the <global> scope by quering the
    // GLOBAL_TAGS table
    int where = scopes.Index(wxT("<global>"));
    if(where != wxNOT_FOUND) {
        scopes.RemoveAt(where);
        GetTagsByScopeAndName(wxString(wxT("<global>")), name, partialNameAllowed, tags);
    }

    if(scopes.IsEmpty() == false) {
        wxString sql;
        sql << wxT("select * from tags where scope in(");

        for(size_t i = 0; i < scopes.GetCount(); i++) {
            sql << wxT("'") << scopes.Item(i) << wxT("',");
        }
        sql.RemoveLast();
        sql << wxT(") ");

        DoAddNamePartToQuery(sql, name, partialNameAllowed, true);
        DoAddLimitPartToQuery(sql, tags);
        // get get the tags
        DoFetchTags(sql, tags);
    }
}

void TagsStorageSQLite::GetGlobalFunctions(std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where scope = '<global>' AND kind IN ('function', 'prototype')");
    DoAddLimitPartToQuery(sql, tags);
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByFiles(const wxArrayString& files, std::vector<TagEntryPtr>& tags)
{
    if(files.IsEmpty()) return;

    wxString sql;
    sql << wxT("select * from tags where file in (");
    for(size_t i = 0; i < files.GetCount(); i++) {
        sql << wxT("'") << files.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByFilesAndScope(const wxArrayString& files, const wxString& scope,
                                               std::vector<TagEntryPtr>& tags)
{
    if(files.IsEmpty()) return;

    wxString sql;
    sql << wxT("select * from tags where file in (");
    for(size_t i = 0; i < files.GetCount(); i++) {
        sql << wxT("'") << files.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");

    sql << wxT(" AND scope='") << scope << wxT("'");
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetTagsByFilesKindAndScope(const wxArrayString& files, const wxArrayString& kinds,
                                                   const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    if(files.IsEmpty()) return;

    wxString sql;
    sql << wxT("select * from tags where file in (");
    for(size_t i = 0; i < files.GetCount(); i++) {
        sql << wxT("'") << files.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");

    sql << wxT(" AND scope='") << scope << wxT("'");
    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByFilesScopeTyperefAndKind(const wxArrayString& files, const wxArrayString& kinds,
                                                          const wxString& scope, const wxString& typeref,
                                                          std::vector<TagEntryPtr>& tags)
{
    if(files.IsEmpty()) return;

    wxString sql;
    sql << wxT("select * from tags where file in (");
    for(size_t i = 0; i < files.GetCount(); i++) {
        sql << wxT("'") << files.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(")");

    sql << wxT(" AND scope='") << scope << wxT("'");
    sql << wxT(" AND typeref='") << typeref << wxT("'");
    DoFetchTags(sql, tags, kinds);
}

void TagsStorageSQLite::GetTagsByKindLimit(const wxArrayString& kinds, const wxString& orderingColumn, int order,
                                           int limit, const wxString& partName, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where kind in (");
    for(size_t i = 0; i < kinds.GetCount(); i++) {
        sql << wxT("'") << kinds.Item(i) << wxT("',");
    }
    sql.RemoveLast();
    sql << wxT(") ");

    if(orderingColumn.IsEmpty() == false) {
        sql << wxT("order by ") << orderingColumn;
        switch(order) {
        case ITagsStorage::OrderAsc:
            sql << wxT(" ASC");
            break;
        case ITagsStorage::OrderDesc:
            sql << wxT(" DESC");
            break;
        case ITagsStorage::OrderNone:
        default:
            break;
        }
    }

    DoAddNamePartToQuery(sql, partName, true, true);
    if(limit > 0) { sql << wxT(" LIMIT ") << limit; }

    DoFetchTags(sql, tags);
}
bool TagsStorageSQLite::IsTypeAndScopeExistLimitOne(const wxString& typeName, const wxString& scope)
{
    wxString sql;
    wxString path;

    // Build the path
    if(scope.IsEmpty() == false && scope != wxT("<global>")) path << scope << wxT("::");

    path << typeName;
    sql << wxT("select ID from tags where path='") << path
        << wxT("' and kind in ('class', 'struct', 'typedef') LIMIT 1");

    try {
        wxSQLite3ResultSet rs = Query(sql);
        if(rs.NextRow()) { return true; }

    } catch(wxSQLite3Exception& e) {
        wxUnusedVar(e);
    }
    return false;
}

void TagsStorageSQLite::GetDereferenceOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where scope ='") << scope << wxT("' and name like 'operator%->%' LIMIT 1");
    DoFetchTags(sql, tags);
}

void TagsStorageSQLite::GetSubscriptOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    sql << wxT("select * from tags where scope ='") << scope << wxT("' and name like 'operator%[%]%' LIMIT 1");
    DoFetchTags(sql, tags);
}

//---------------------------------------------------------------------
//-----------------------------TagsStorageSQLiteCache -----------------
//---------------------------------------------------------------------

TagsStorageSQLiteCache::TagsStorageSQLiteCache() {}

TagsStorageSQLiteCache::~TagsStorageSQLiteCache() { m_cache.clear(); }

bool TagsStorageSQLiteCache::Get(const wxString& sql, std::vector<TagEntryPtr>& tags) { return DoGet(sql, tags); }

bool TagsStorageSQLiteCache::Get(const wxString& sql, const wxArrayString& kind, std::vector<TagEntryPtr>& tags)
{
    wxString key;
    key << sql;
    for(size_t i = 0; i < kind.GetCount(); i++) {
        key << wxT("@") << kind.Item(i);
    }

    return DoGet(key, tags);
}

void TagsStorageSQLiteCache::Store(const wxString& sql, const std::vector<TagEntryPtr>& tags) { DoStore(sql, tags); }

void TagsStorageSQLiteCache::Clear()
{
    // CL_DEBUG1(wxT("[CACHE CLEARED]"));
    m_cache.clear();
}

void TagsStorageSQLiteCache::Store(const wxString& sql, const wxArrayString& kind, const std::vector<TagEntryPtr>& tags)
{
    wxString key;
    key << sql;
    for(size_t i = 0; i < kind.GetCount(); i++) {
        key << wxT("@") << kind.Item(i);
    }
    DoStore(key, tags);
}

bool TagsStorageSQLiteCache::DoGet(const wxString& key, std::vector<TagEntryPtr>& tags)
{
    std::unordered_map<wxString, std::vector<TagEntryPtr>>::iterator iter = m_cache.find(key);
    if(iter != m_cache.end()) {
        // Append the results to the output tags
        tags.insert(tags.end(), iter->second.begin(), iter->second.end());
        return true;
    }
    return false;
}

void TagsStorageSQLiteCache::DoStore(const wxString& key, const std::vector<TagEntryPtr>& tags)
{
    m_cache[key].reserve(tags.size());
    m_cache[key] = tags;
}

void TagsStorageSQLite::ClearCache() { m_cache.Clear(); }

void TagsStorageSQLite::SetUseCache(bool useCache) { ITagsStorage::SetUseCache(useCache); }

PPToken TagsStorageSQLite::GetMacro(const wxString& name)
{
    PPToken token;
    try {
        wxString sql;
        sql << wxT("select * from MACROS where name = '") << name << wxT("'");
        wxSQLite3ResultSet res = m_db->ExecuteQuery(sql);
        if(res.NextRow()) {
            PPTokenFromSQlite3ResultSet(res, token);
            return token;
        }
    } catch(wxSQLite3Exception& exc) {
        wxUnusedVar(exc);
    }

    return token;
}

void TagsStorageSQLite::StoreMacros(const std::map<wxString, PPToken>& table)
{
    try {
        wxSQLite3Statement stmntCC =
            m_db->GetPrepareStatement(wxT("insert or replace into MACROS values(NULL, ?, ?, ?, ?, ?, ?)"));
        wxSQLite3Statement stmntSimple =
            m_db->GetPrepareStatement(wxT("insert or replace into SIMPLE_MACROS values(NULL, ?, ?)"));

        std::map<wxString, PPToken>::const_iterator iter = table.begin();
        for(; iter != table.end(); ++iter) {
            wxString replac = iter->second.replacement;
            replac.Trim().Trim(false);

            // Since we are using the MACROS table mainly for the replacement
            // field, dont insert into the database entries which dont have
            // a replacement
            // we take only macros that their replacement is not a number or a string
            if(replac.IsEmpty() || replac.find_first_of(wxT("0123456789")) == 0) {
                // Insert it into the SIMPLE_MACRO instead
                stmntSimple.Bind(1, iter->second.fileName);
                stmntSimple.Bind(2, iter->second.name);
                stmntSimple.ExecuteUpdate();
                stmntSimple.Reset();
            } else {
                // macros with replacement.
                stmntCC.Bind(1, iter->second.fileName);
                stmntCC.Bind(2, iter->second.line);
                stmntCC.Bind(3, iter->second.name);
                stmntCC.Bind(4, iter->second.flags & PPToken::IsFunctionLike ? 1 : 0);
                stmntCC.Bind(5, replac);
                stmntCC.Bind(6, iter->second.signature());
                stmntCC.ExecuteUpdate();
                stmntCC.Reset();
            }
        }

    } catch(wxSQLite3Exception& exc) {
        wxUnusedVar(exc);
    }
}

void TagsStorageSQLite::GetMacrosDefined(const std::set<std::string>& files, const std::set<wxString>& usedMacros,
                                         wxArrayString& defMacros)
{
    if(files.empty() || usedMacros.empty()) { return; }

    // Create the file list SQL string, used for IN operator
    wxString sFileList;
    for(std::set<std::string>::const_iterator itFile = files.begin(); itFile != files.end(); ++itFile) {
        sFileList << wxT("'") << wxString::From8BitData(itFile->c_str()) << wxT("',");
    }
    sFileList.RemoveLast();

    // Create the used macros list SQL string, used for IN operator
    wxString sMacroList;
    for(std::set<wxString>::const_iterator itUsedMacro = usedMacros.begin(); itUsedMacro != usedMacros.end();
        ++itUsedMacro) {
        sMacroList << wxT("'") << *itUsedMacro << wxT("',");
    }
    sMacroList.RemoveLast();

    try {
        // Step 1 : Retrieve defined macros in MACROS table
        wxString req;
        req << wxT("select name from MACROS where file in (") << sFileList << wxT(")") << wxT(" and name in (")
            << sMacroList << wxT(")");
        wxSQLite3ResultSet res = m_db->ExecuteQuery(req);
        while(res.NextRow()) {
            defMacros.push_back(res.GetString(0));
        }

        // Step 2 : Retrieve defined macros in SIMPLE_MACROS table
        req.Clear();
        req << wxT("select name from SIMPLE_MACROS where file in (") << sFileList << wxT(")") << wxT(" and name in (")
            << sMacroList << wxT(")");
        res = m_db->ExecuteQuery(req);
        while(res.NextRow()) {
            defMacros.push_back(res.GetString(0));
        }
    } catch(wxSQLite3Exception& exc) {
        CL_DEBUG(wxT("%s"), exc.GetMessage().c_str());
    }
}

void TagsStorageSQLite::GetTagsByName(const wxString& prefix, std::vector<TagEntryPtr>& tags, bool exactMatch)
{
    try {
        if(prefix.IsEmpty()) return;

        wxString sql;
        sql << wxT("select * from tags where ");
        DoAddNamePartToQuery(sql, prefix, !exactMatch, false);
        DoAddLimitPartToQuery(sql, tags);
        DoFetchTags(sql, tags);

    } catch(wxSQLite3Exception& e) {
        CL_DEBUG(wxT("%s"), e.GetMessage().c_str());
    }
}

void TagsStorageSQLite::DoAddNamePartToQuery(wxString& sql, const wxString& name, bool partial, bool prependAnd)
{
    if(name.empty()) return;
    if(prependAnd) { sql << wxT(" AND "); }

    if(m_enableCaseInsensitive) {
        wxString tmpName(name);
        tmpName.Replace(wxT("_"), wxT("^_"));
        if(partial) {
            sql << wxT(" name LIKE '") << tmpName << wxT("%%' ESCAPE '^' ");
        } else {
            sql << wxT(" name ='") << name << wxT("' ");
        }
    } else {
        // Don't use LIKE
        wxString from = name;
        wxString until = name;

        wxChar ch = until.Last();
        until.SetChar(until.length() - 1, ch + 1);

        // add the name condition
        if(partial) {
            sql << wxT(" name >= '") << from << wxT("' AND  name < '") << until << wxT("'");
        } else {
            sql << wxT(" name ='") << name << wxT("' ");
        }
    }
}

void TagsStorageSQLite::DoAddLimitPartToQuery(wxString& sql, const std::vector<TagEntryPtr>& tags)
{
    if(tags.size() >= (size_t)GetSingleSearchLimit()) {
        sql << wxT(" LIMIT 1 ");
    } else {
        sql << wxT(" LIMIT ") << (size_t)GetSingleSearchLimit() - tags.size();
    }
}

TagEntryPtr TagsStorageSQLite::GetTagsByNameLimitOne(const wxString& name)
{
    try {
        if(name.IsEmpty()) return NULL;

        std::vector<TagEntryPtr> tags;
        wxString sql;
        sql << wxT("select * from tags where ");
        DoAddNamePartToQuery(sql, name, false, false);
        sql << wxT(" LIMIT 1 ");

        DoFetchTags(sql, tags);
        if(tags.size() == 1)
            return tags.at(0);
        else
            return NULL;

    } catch(wxSQLite3Exception& e) {
        CL_DEBUG(wxT("%s"), e.GetMessage().c_str());
    }
    return NULL;
}

void TagsStorageSQLite::GetTagsByPartName(const wxString& partname, std::vector<TagEntryPtr>& tags)
{
    try {
        if(partname.IsEmpty()) return;

        wxString tmpName(partname);
        tmpName.Replace(wxT("_"), wxT("^_"));

        wxString sql;
        sql << wxT("select * from tags where name like '%%") << tmpName << wxT("%%' ESCAPE '^' ");
        DoAddLimitPartToQuery(sql, tags);
        DoFetchTags(sql, tags);

    } catch(wxSQLite3Exception& e) {
        CL_DEBUG(wxT("%s"), e.GetMessage().c_str());
    }
}

void TagsStorageSQLite::RemoveNonWorkspaceSymbols(const std::vector<wxString>& symbols,
                                                  std::vector<wxString>& workspaceSymbols,
                                                  std::vector<wxString>& nonWorkspaceSymbols)
{
    wxString sql;
    try {
        workspaceSymbols.clear();
        nonWorkspaceSymbols.clear();
        if(symbols.empty()) { return; }

        // an example query
        // SELECT distinct name FROM 'main'.'tags' where name in ('LoadList')
        wxString kindSQL;
        kindSQL << " AND KIND IN ('class', 'enum', 'cenum', 'prototype', 'macro', 'namespace', 'function', "
                   "'struct','typedef')";

        // Split the input vector into arrays of up to 500 elements each
        std::vector<std::vector<wxString>> v;
        int chunks = (symbols.size() / 250) + 1;
        int offset = 0;
        int left = symbols.size();
        for(int i = 0; i < chunks; ++i) {
            int amountToCopy = left > 250 ? 250 : left;
            left -= amountToCopy;
            if(amountToCopy > 0) {
                std::vector<wxString> vChunk(symbols.begin() + offset, symbols.begin() + (offset + amountToCopy));
                offset += amountToCopy;
                v.push_back(vChunk);
            }
        }

        std::vector<wxString> allSymbols;
        for(size_t i = 0; i < v.size(); ++i) {
            sql.Clear();
            sql << "SELECT distinct name,kind FROM tags where name in (";
            for(size_t n = 0; n < v[i].size(); ++n) {
                sql << "'" << v[i][n] << "',";
            }

            // remove the last comma
            sql.RemoveLast();
            sql << ")";
            sql << kindSQL;

            // Run the query
            wxSQLite3ResultSet res = m_db->ExecuteQuery(sql);
            while(res.NextRow()) {
                wxString name = res.GetString(0);
                wxString kind = res.GetString(1);
                allSymbols.push_back(name);
                if((kind != "function") && (kind != "prototype") && (kind != "macro")) {
                    workspaceSymbols.push_back(name);
                }
            }
        }

        std::sort(workspaceSymbols.begin(), workspaceSymbols.end());
        std::sort(allSymbols.begin(), allSymbols.end());
        std::set_difference(symbols.begin(), symbols.end(), allSymbols.begin(), allSymbols.end(),
                            std::back_inserter(nonWorkspaceSymbols));

    } catch(wxSQLite3Exception& e) {
        clDEBUG() << "SplitSymbols error:" << sql << ":" << e.GetMessage() << clEndl;
    }
}

const wxString& TagsStorageSQLite::GetVersion() const
{
    static const wxString gTagsDatabaseVersion(wxT("CodeLite Version 11.1"));
    return gTagsDatabaseVersion;
}

void TagsStorageSQLite::GetTagsByPartName(const wxArrayString& parts, std::vector<TagEntryPtr>& tags)
{
    wxString sql;
    try {
        if(parts.IsEmpty()) { return; }

        wxString filterQuery = "where ";
        for(size_t i = 0; i < parts.size(); ++i) {
            wxString tmpName = parts.Item(i);
            tmpName.Replace(wxT("_"), wxT("^_"));
            filterQuery << "path like '%%" << tmpName << "%%' " << ((i == (parts.size() - 1)) ? "" : "AND ");
        }

        sql << "select * from tags " << filterQuery << " ESCAPE '^' ";
        DoAddLimitPartToQuery(sql, tags);
        DoFetchTags(sql, tags);

    } catch(wxSQLite3Exception& e) {
        clWARNING() << sql << ":" << e.GetMessage() << clEndl;
    }
}

void TagsStorageSQLite::ReOpenDatabase()
{
    // Did we get a file name to use?
    if(!m_fileName.IsOk()) return;

    clDEBUG() << "ReOpenDatabase called for file:" << m_fileName;
    // Close database first
    clDEBUG() << "Closing database first";
    try {
        if(m_db) {
            m_db->Close();
            delete m_db;
            m_db = nullptr;
        }
    } catch(...) {
    }

    clDEBUG() << "Open is called for file:" << m_fileName;
    try {
        // First time we open the db
        m_db->Open(m_fileName.GetFullPath());
        m_db->SetBusyTimeout(10);
        CreateSchema();
    } catch(wxSQLite3Exception& e) {
        clWARNING() << "Failed to reopen file:" << m_fileName.GetFullPath() << "." << e.GetMessage();
    }
    clDEBUG() << "Database reopened successfully";
}