summaryrefslogtreecommitdiff
path: root/src/components/policy/policy_external/src/sql_pt_ext_representation.cc
blob: a43b22a3b8c8c9894ee78daccd5932cbd4e095db (plain)
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
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
/*
 Copyright (c) 2015, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */
#include <algorithm>
#include <utility>
#include "utils/logger.h"
#include "policy/sql_pt_ext_representation.h"
#include "policy/sql_wrapper.h"
#include "policy/sql_pt_queries.h"
#include "policy/sql_pt_ext_queries.h"
#include "policy/policy_helper.h"
#include "policy/cache_manager.h"

namespace policy {

CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")

SQLPTExtRepresentation::SQLPTExtRepresentation() {}
SQLPTExtRepresentation::SQLPTExtRepresentation(bool in_memory)
    : SQLPTRepresentation(in_memory) {}

bool SQLPTExtRepresentation::CanAppKeepContext(const std::string& app_id) {
  utils::dbms::SQLQuery query(db());
  if (query.Prepare(sql_pt_ext::kSelectKeepContext)) {
    query.Bind(0, app_id);
    if (query.Exec()) {
      return query.GetBoolean(0);
    }
  }
  return false;
}

bool SQLPTExtRepresentation::CanAppStealFocus(const std::string& app_id) {
  utils::dbms::SQLQuery query(db());
  if (query.Prepare(sql_pt_ext::kSelectStealFocus)) {
    query.Bind(0, app_id);
    if (query.Exec()) {
      return query.GetBoolean(0);
    }
  }
  return false;
}

bool SQLPTExtRepresentation::ResetUserConsent() {
  return ResetDeviceConsents() && ResetAppConsents();
}

bool SQLPTExtRepresentation::ResetDeviceConsents() {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kResetDeviceConsents)) {
    LOG4CXX_WARN(logger_, "Incorrect delete statement from device_consents.");
    return false;
  }
  return query.Exec();
}

bool SQLPTExtRepresentation::ResetAppConsents() {
  return utils::dbms::SQLQuery(db()).Exec(sql_pt_ext::kResetAppConsents);
}

bool SQLPTExtRepresentation::GetUserPermissionsForDevice(
    const std::string& device_id,
    StringArray* consented_groups,
    StringArray* disallowed_groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
    LOG4CXX_WARN(logger_, "Incorrect select from device consented groups");
    return false;
  }
  query.Bind(0, device_id);
  while (query.Next()) {
    if (query.GetBoolean(2)) {
      if (!consented_groups) {
        continue;
      }
      consented_groups->push_back(query.GetString(1));
    } else {
      if (!disallowed_groups) {
        continue;
      }
      disallowed_groups->push_back(query.GetString(1));
    }
  }

  return true;
}

bool SQLPTExtRepresentation::GetPermissionsForApp(
    const std::string& device_id,
    const std::string& policy_app_id,
    FunctionalIdType* group_types) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (!group_types) {
    LOG4CXX_WARN(logger_, "Input parameter for group types is null.");
    return false;
  }
  // Get all app groups for specified device and application
  FunctionalGroupIDs all_groups;
  if (!GetAllAppGroups(policy_app_id, all_groups)) {
    return false;
  }
  // Get preconsented group
  FunctionalGroupIDs preconsented_groups;
  if (!GetPreconsentedGroups(policy_app_id, preconsented_groups)) {
    return false;
  }
  // Get consented (allowed/disallowed) groups
  FunctionalGroupIDs allowed_groups;
  FunctionalGroupIDs disallowed_groups;
  if (!GetConsentedGroups(
          policy_app_id, device_id, allowed_groups, disallowed_groups)) {
    return false;
  }
  // Get all default groups
  FunctionalGroupIDs default_groups;
  if (!GetAllAppGroups(kDefaultId, default_groups)) {
    return false;
  }

  // Get all pre_DataConsent groups
  FunctionalGroupIDs predataconsented_groups;
  if (!GetAllAppGroups(kPreDataConsentId, predataconsented_groups)) {
    return false;
  }

  // Get all device groups
  FunctionalGroupIDs device_groups;
  if (!GetAllAppGroups(kDeviceId, device_groups)) {
    return false;
  }

  (*group_types)[kTypeDefault] = default_groups;
  (*group_types)[kTypeAllowed] = allowed_groups;
  (*group_types)[kTypeDisallowed] = disallowed_groups;
  (*group_types)[kTypePreconsented] = preconsented_groups;
  (*group_types)[kTypeGeneral] = all_groups;
  (*group_types)[kTypePreDataConsented] = predataconsented_groups;
  (*group_types)[kTypeDevice] = device_groups;

  return true;
}

bool SQLPTExtRepresentation::GetDeviceGroupsFromPolicies(
    policy_table::Strings* groups, policy_table::Strings* preconsented_groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (groups) {
    GatherAppGroup(kDeviceId, groups);
  }
  if (preconsented_groups) {
    GatherPreconsentedGroup(kDeviceId, preconsented_groups);
  }
  return true;
}

bool SQLPTExtRepresentation::SetDeviceData(const std::string& device_id,
                                           const std::string& hardware,
                                           const std::string& firmware,
                                           const std::string& os,
                                           const std::string& os_version,
                                           const std::string& carrier,
                                           const uint32_t number_of_ports,
                                           const std::string& connection_type) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery count_query(db());
  if (!count_query.Prepare(sql_pt_ext::kCountDevice)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for count of device.");
    return false;
  }

  count_query.Bind(0, device_id);

  if (!count_query.Exec()) {
    LOG4CXX_WARN(logger_, "Incorrect count of device.");
    return false;
  }

  bool update = count_query.GetInteger(0);

  // Update old value
  if (update) {
    utils::dbms::SQLQuery update_query(db());
    if (!update_query.Prepare(sql_pt_ext::kUpdateDevice)) {
      LOG4CXX_WARN(logger_, "Incorrect statement for udpate device.");
      return false;
    }

    update_query.Bind(0, hardware);
    update_query.Bind(1, firmware);
    update_query.Bind(2, os);
    update_query.Bind(3, os_version);
    update_query.Bind(4, carrier);
    update_query.Bind(5, static_cast<int>(number_of_ports));
    update_query.Bind(6, device_id);
    update_query.Bind(7, connection_type);

    if (!update_query.Exec() || !update_query.Reset()) {
      LOG4CXX_WARN(logger_, "Incorrect update for device.");
      return false;
    }

    return true;
  }

  // Insert new data
  utils::dbms::SQLQuery insert_query(db());
  if (!insert_query.Prepare(sql_pt_ext::kInsertDevice)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for device.");
    return false;
  }

  insert_query.Bind(0, device_id);
  insert_query.Bind(1, hardware);
  insert_query.Bind(2, firmware);
  insert_query.Bind(3, os);
  insert_query.Bind(4, os_version);
  insert_query.Bind(5, carrier);
  insert_query.Bind(6, static_cast<int>(number_of_ports));
  insert_query.Bind(7, connection_type);

  if (!insert_query.Exec() || !insert_query.Reset()) {
    LOG4CXX_WARN(logger_, "Incorrect insert to device.");
    return false;
  }

  SetPreloaded(false);

  return true;
}

bool SQLPTExtRepresentation::SetUserPermissionsForDevice(
    const std::string& device_id,
    const StringArray& consented_groups,
    const StringArray& disallowed_groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery count_query(db());
  if (!count_query.Prepare(sql_pt_ext::kCountDeviceConsentGroup)) {
    LOG4CXX_WARN(logger_, "Incorrect count of device consented groups");
    return false;
  }

  count_query.Bind(0, device_id);

  if (!count_query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed count of device consented groups");
    return false;
  }

  bool update = count_query.GetInteger(0);

  // TODO(AOleynik): Split to several methods?
  utils::dbms::SQLQuery query(db());
  // Update old values
  if (update) {
    if (!query.Prepare(sql_pt_ext::kUpdateDeviceConsentedGroup)) {
      LOG4CXX_WARN(
          logger_,
          "Incorrect statement for updating consented groups on device");
      return false;
    }

    StringArray::const_iterator it_consented_groups = consented_groups.begin();
    StringArray::const_iterator it_consented_groups_end =
        consented_groups.end();
    for (; it_consented_groups != it_consented_groups_end;
         ++it_consented_groups) {
      query.Bind(0, true);
      query.Bind(1, std::string("GUI"));
      query.Bind(2, device_id);
      query.Bind(3, *it_consented_groups);
      // TODO(AOleynik): Get this info from external data
      if (!query.Exec() || !query.Reset()) {
        LOG4CXX_WARN(logger_,
                     "Failed update of device allowed consented groups.");
        return false;
      }
    }

    StringArray::const_iterator it_disallowed_groups =
        disallowed_groups.begin();
    StringArray::const_iterator it_disallowed_groups_end =
        disallowed_groups.end();
    for (; it_disallowed_groups != it_disallowed_groups_end;
         ++it_disallowed_groups) {
      query.Bind(0, false);
      query.Bind(1);
      query.Bind(2, device_id);
      query.Bind(3, *it_disallowed_groups);
      if (!query.Exec() || !query.Reset()) {
        LOG4CXX_WARN(logger_,
                     "Failed update of device disallowed consented groups.");
        return false;
      }
    }

    return true;
  }

  // Insert new values
  if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect statement of inserting to device consented groups");
    return false;
  }

  StringArray::const_iterator it_consented_groups = consented_groups.begin();
  StringArray::const_iterator it_consented_groups_end = consented_groups.end();
  for (; it_consented_groups != it_consented_groups_end;
       ++it_consented_groups) {
    query.Bind(0, device_id);
    query.Bind(1, *it_consented_groups);
    query.Bind(2, true);
    // TODO(AOleynik): Get this info from external data
    query.Bind(3, std::string("GUI"));
    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_,
                   "Failed insert to device allowed consented groups.");
      return false;
    }
  }

  StringArray::const_iterator it_disallowed_groups = disallowed_groups.begin();
  StringArray::const_iterator it_disallowed_groups_end =
      disallowed_groups.end();
  for (; it_disallowed_groups != it_disallowed_groups_end;
       ++it_disallowed_groups) {
    query.Bind(0, device_id);
    query.Bind(1, *it_disallowed_groups);
    query.Bind(2, false);
    query.Bind(3);
    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_,
                   "Failed insert to device disallowed consented groups.");
      return false;
    }
  }

  return true;
}

bool SQLPTExtRepresentation::ReactOnUserDevConsentForApp(
    const std::string& app_id, bool is_device_allowed) {
  bool result = true;
  if (is_device_allowed) {
    // If app has pre_DataConsented groups it should be 'promoted' to default
    // If app has only pre_DataConsented flag it should be only set to false and
    // all groups get restored automatically
    if (IsPredataPolicy(app_id)) {
      utils::dbms::SQLQuery query(db());
      if (!query.Prepare(sql_pt_ext::kHasAppPreloadedGroups)) {
        LOG4CXX_WARN(logger_,
                     "Incorrect statement for has app preloaded groups");
        return false;
      }
      query.Bind(0, app_id);
      query.Bind(1, kPreDataConsentId);
      if (!query.Exec()) {
        LOG4CXX_WARN(logger_,
                     "Incorrect select for app has predataconsted groups");
        return false;
      }
      if (query.GetInteger(0) > 0) {
        result = result && SetDefaultPolicy(app_id);
      } else {
        result = result && SetIsPredata(app_id, false);
      }
    }
  } else {
    // If app has default groups change them to pre_DataConsented
    // If app has 'normal' groups leave them as is and set
    // pre_DataConsented flag to true.
    if (IsDefaultPolicy(app_id)) {
      result = result && SetPredataPolicy(app_id);
    } else {
      result = result && SetIsPredata(app_id, true);
    }
  }
  return result;
}

bool SQLPTExtRepresentation::SetUserPermissionsForApp(
    const PermissionConsent& permissions) {
  LOG4CXX_AUTO_TRACE(logger_);
  // TODO(AOleynik): Handle situation, when no application was specified, i.e.
  // general permissions were set
  std::vector<FunctionalGroupPermission>::const_iterator it =
      permissions.group_permissions.begin();
  std::vector<FunctionalGroupPermission>::const_iterator it_end =
      permissions.group_permissions.end();

  utils::dbms::SQLQuery query(db());
  for (; it != it_end; ++it) {
    utils::dbms::SQLQuery counter(db());
    if (!counter.Prepare(sql_pt_ext::kCountAppConsents)) {
      LOG4CXX_WARN(logger_, "Incorrect statement for consent group count.");
      return false;
    }

    counter.Bind(0, permissions.device_id);
    counter.Bind(1, permissions.policy_app_id);
    counter.Bind(2, static_cast<int>((*it).group_id));
    if (!counter.Exec()) {
      LOG4CXX_WARN(logger_, "Incorrent count on consent groups.");
      return false;
    }

    bool update_required = counter.GetInteger(0);

    // Update already present consent record
    if (update_required) {
      if (!query.Prepare(sql_pt_ext::kUpdateGroupPermissions)) {
        LOG4CXX_WARN(logger_, "Incorrect statement for update consent groups.");
        return false;
      }

      // Skip consent saving, if user didn't choose any state
      if (policy::kGroupUndefined == (*it).state) {
        continue;
      }
      query.Bind(0, (*it).state == kGroupAllowed ? 1 : 0);
      query.Bind(1, permissions.consent_source);
      query.Bind(2, permissions.policy_app_id);
      query.Bind(3, static_cast<int>((*it).group_id));
      query.Bind(4, permissions.device_id);

      if (!query.Exec() || !query.Reset()) {
        LOG4CXX_WARN(logger_,
                     "Incorrect update on user defined permissions "
                     "for app groups.");
        return false;
      }
      continue;
    }

    // Insert new consent record
    if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
      LOG4CXX_WARN(logger_,
                   "Incorrect statement for update app group permissions.");
      return false;
    }

    // Skip consent saving, if user didn't choose any state
    if (policy::kGroupUndefined == (*it).state) {
      continue;
    }
    query.Bind(0, permissions.device_id);
    query.Bind(1, permissions.policy_app_id);
    query.Bind(2, static_cast<int>((*it).group_id));
    query.Bind(3, (*it).state == kGroupAllowed ? 1 : 0);
    query.Bind(4, permissions.consent_source);

    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_,
                   "Incorrect insert to user defined permissions "
                   "for app groups.");
      return false;
    }
    continue;
  }
  return true;
}

std::vector<UserFriendlyMessage> SQLPTExtRepresentation::GetUserFriendlyMsg(
    const std::vector<std::string>& msg_codes, const std::string& language) {
  utils::dbms::SQLQuery query(db());
  std::vector<UserFriendlyMessage> result;
  if (!query.Prepare(sql_pt_ext::kSelectFriendlyMsg)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
    return result;
  }

  const std::string fallback_language = "en-us";
  std::vector<std::string>::const_iterator it = msg_codes.begin();
  std::vector<std::string>::const_iterator it_end = msg_codes.end();
  for (; it != it_end; ++it) {
    std::string msg_language = language;
    // If message has no records with required language, fallback language
    // should be used instead.
    if (!IsMsgLanguagePresent((*it), language)) {
      msg_language = fallback_language;
    }
    query.Bind(0, *it);
    query.Bind(1, msg_language);

    if (!query.Exec()) {
      LOG4CXX_WARN(logger_, "Incorrect select from friendly messages.");
      return result;
    }

    UserFriendlyMessage msg;

    msg.message_code = *it;
    msg.tts = query.GetString(0);
    msg.label = query.GetString(1);
    msg.line1 = query.GetString(2);
    msg.line2 = query.GetString(3);
    msg.text_body = query.GetString(4);

    result.push_back(msg);

    if (!query.Reset()) {
      LOG4CXX_WARN(logger_,
                   "Failed reset statement for selecting friendly "
                   "messages.");
      return result;
    }
  }

  return result;
}

bool SQLPTExtRepresentation::GatherConsumerFriendlyMessages(
    policy_table::ConsumerFriendlyMessages* messages) const {
  if (NULL == messages) {
    LOG4CXX_ERROR(logger_, "NULL pointer has been passed to fill");
    return false;
  }

  if (!SQLPTRepresentation::GatherConsumerFriendlyMessages(messages)) {
    return false;
  }

  utils::dbms::SQLQuery query(db());
  bool result = query.Prepare(sql_pt_ext::kCollectFriendlyMsg);

  if (result) {
    while (query.Next()) {
      UserFriendlyMessage msg;

      msg.tts = query.GetString(1);
      msg.label = query.GetString(2);
      msg.line1 = query.GetString(3);
      msg.line2 = query.GetString(4);
      msg.text_body = query.GetString(5);
      msg.message_code = query.GetString(7);

      std::string language = query.GetString(6);
      if (!msg.tts.empty()) {
        *(*messages->messages)[msg.message_code].languages[language].tts =
            msg.tts;
      }
      if (!msg.label.empty()) {
        *(*messages->messages)[msg.message_code].languages[language].label =
            msg.label;
      }
      if (!msg.line1.empty()) {
        *(*messages->messages)[msg.message_code].languages[language].line1 =
            msg.line1;
      }
      if (!msg.line2.empty()) {
        *(*messages->messages)[msg.message_code].languages[language].line2 =
            msg.line2;
      }
      if (!msg.text_body.empty()) {
        *(*messages->messages)[msg.message_code].languages[language].textBody =
            msg.text_body;
      }
    }
  } else {
    LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
  }
  return result;
}

bool SQLPTExtRepresentation::SetMetaInfo(const std::string& ccpu_version,
                                         const std::string& wers_country_code,
                                         const std::string& language) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateMetaParams)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for insert to module meta.");
    return false;
  }

  query.Bind(0, ccpu_version);
  query.Bind(1, wers_country_code);
  query.Bind(2, language);

  if (!query.Exec() || !query.Reset()) {
    LOG4CXX_WARN(logger_, "Incorrect insert to module meta.");
    return false;
  }
  return true;
}

bool SQLPTExtRepresentation::IsMetaInfoPresent() {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectMetaParams)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for selecting meta info.");
    return false;
  }

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Incorrect select from module meta.");
    return false;
  }

  return !query.IsNull(0) && !query.IsNull(1) && !query.IsNull(2);
}

bool SQLPTExtRepresentation::SetSystemLanguage(const std::string& language) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateMetaLanguage)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for update meta language.");
    return false;
  }

  query.Bind(0, language);

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Incorrect update for meta language.");
    return false;
  }

  return true;
}

bool SQLPTExtRepresentation::SaveApplicationPoliciesSection(
    const policy_table::ApplicationPoliciesSection& policies) {
  LOG4CXX_INFO(logger_, "SaveApplicationPolicies ext");
  utils::dbms::SQLQuery query_delete(db());
  if (!query_delete.Exec(sql_pt::kDeleteAppGroup)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from app_group.");
    return false;
  }

  utils::dbms::SQLQuery query_delete_preconsented(db());
  if (!query_delete_preconsented.Exec(sql_pt_ext::kDeletePreconsentedGroups)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from preconsented_group.");
    return false;
  }

  if (!query_delete.Exec(sql_pt::kDeleteApplication)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from application.");
    return false;
  }

  if (!query_delete.Exec(sql_pt::kDeleteRequestType)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from request type.");
    return false;
  }

  if (!query_delete.Exec(sql_pt::kDeleteRequestSubType)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from request subtype.");
    return false;
  }

  // First, all predefined apps (e.g. default, pre_DataConsent) should be saved,
  // otherwise another app with the predefined permissions can get incorrect
  // permissions
  policy_table::ApplicationPolicies::const_iterator it_default =
      policies.apps.find(kDefaultId);
  if (policies.apps.end() != it_default) {
    if (!SaveSpecificAppPolicy(*it_default)) {
      return false;
    }
  }
  policy_table::ApplicationPolicies::const_iterator it_pre_data_consent =
      policies.apps.find(kPreDataConsentId);
  if (policies.apps.end() != it_pre_data_consent) {
    if (!SaveSpecificAppPolicy(*it_pre_data_consent)) {
      return false;
    }
  }

  if (!SaveDevicePolicy(policies.device)) {
    return false;
  }

  policy_table::ApplicationPolicies::const_iterator it;
  for (it = policies.apps.begin(); it != policies.apps.end(); ++it) {
    // Skip saving of predefined app, since they should be saved before
    if (IsPredefinedApp(*it)) {
      continue;
    }
    if (!SaveSpecificAppPolicy(*it)) {
      return false;
    }
  }

  return true;
}

bool SQLPTExtRepresentation::SaveSpecificAppPolicy(
    const policy_table::ApplicationPolicies::value_type& app) {
  if (app.second.is_string()) {
    if (kDefaultId.compare(app.second.get_string()) == 0) {
      if (!SetDefaultPolicy(app.first)) {
        return false;
      }
    } else if (kPreDataConsentId.compare(app.second.get_string()) == 0) {
      if (!SetPredataPolicy(app.first)) {
        return false;
      }
    }
    if (!SaveRequestType(app.first, *app.second.RequestType)) {
      return false;
    }
    if (!SaveRequestSubType(app.first, *app.second.RequestSubType)) {
      return false;
    }
    // Stop saving other params, since predefined permissions already set
    return true;
  }

  SetIsDefault(app.first, false);
  SetIsPredata(app.first, false);

  utils::dbms::SQLQuery app_query(db());
  if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
    return false;
  }

  app_query.Bind(0, app.first);
  app_query.Bind(1, app.second.keep_context);
  app_query.Bind(2, app.second.steal_focus);
  app_query.Bind(
      3, std::string(policy_table::EnumToJsonString(app.second.default_hmi)));
  app_query.Bind(
      4, std::string(policy_table::EnumToJsonString(app.second.priority)));
  app_query.Bind(5, app.second.is_null());
  app_query.Bind(6, *app.second.memory_kb);
  app_query.Bind(7, static_cast<int64_t>(*app.second.heart_beat_timeout_ms));

  if (!app_query.Exec() || !app_query.Reset()) {
    LOG4CXX_WARN(logger_, "Incorrect insert into application.");
    return false;
  }

  if (!SaveAppGroup(app.first, app.second.groups)) {
    return false;
  }

  bool denied = !app.second.moduleType->is_initialized();
  if (!SaveRemoteControlDenied(app.first, denied) ||
      !SaveModuleType(app.first, *app.second.moduleType)) {
    return false;
  }

  if (!SaveNickname(app.first, *app.second.nicknames)) {
    return false;
  }
  if (!SaveAppType(app.first, *app.second.AppHMIType)) {
    return false;
  }
  if (!SavePreconsentedGroup(app.first, *app.second.preconsented_groups)) {
    return false;
  }

  if (!SaveRequestType(app.first, *app.second.RequestType)) {
    return false;
  }

  if (!SaveRequestSubType(app.first, *app.second.RequestSubType)) {
    return false;
  }

  return true;
}

bool policy::SQLPTExtRepresentation::SaveDevicePolicy(
    const policy_table::DevicePolicy& device) {
  utils::dbms::SQLQuery app_query(db());
  if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect insert statement into application (device).");
    return false;
  }
  app_query.Bind(0, kDeviceId);
  app_query.Bind(1, device.keep_context);
  app_query.Bind(2, device.steal_focus);
  app_query.Bind(
      3, std::string(policy_table::EnumToJsonString(device.default_hmi)));
  app_query.Bind(4,
                 std::string(policy_table::EnumToJsonString(device.priority)));
  app_query.Bind(5, false);
  app_query.Bind(6, 0);
  app_query.Bind(7, 0);

  if (!app_query.Exec() || !app_query.Reset()) {
    LOG4CXX_WARN(logger_, "Incorrect insert into application.");
    return false;
  }

  if (!SaveAppGroup(kDeviceId, device.groups)) {
    return false;
  }
  if (!SavePreconsentedGroup(kDeviceId, *device.preconsented_groups)) {
    return false;
  }

  return true;
}

bool SQLPTExtRepresentation::GatherApplicationPoliciesSection(
    policy_table::ApplicationPoliciesSection* policies) const {
  LOG4CXX_INFO(logger_, "Gather applications policies");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectAppPolicies)) {
    LOG4CXX_WARN(logger_, "Incorrect select from app_policies");
    return false;
  }

  while (query.Next()) {
    rpc::Nullable<policy_table::ApplicationParams> params;
    const std::string& app_id = query.GetString(0);
    if (IsApplicationRevoked(app_id)) {
      params.set_to_null();
      (*policies).apps[app_id] = params;
      continue;
    }
    if (IsDefaultPolicy(app_id)) {
      (*policies).apps[app_id].set_to_string(kDefaultId);
    }
    if (IsPredataPolicy(app_id)) {
      (*policies).apps[app_id].set_to_string(kPreDataConsentId);
    }
    if (kDeviceId == app_id) {
      policy_table::DevicePolicy device_policy;
      policy_table::Priority priority;
      policy_table::EnumFromJsonString(query.GetString(1), &priority);
      device_policy.priority = priority;
      policy_table::HmiLevel hmi;
      policy_table::EnumFromJsonString(query.GetString(2), &hmi);
      device_policy.default_hmi = hmi;
      device_policy.keep_context = query.GetBoolean(3);
      device_policy.steal_focus = query.GetBoolean(4);
      if (!GatherAppGroup(app_id, &device_policy.groups)) {
        return false;
      }
      GatherPreconsentedGroup(app_id, &*device_policy.preconsented_groups);
      (*policies).device = device_policy;
      continue;
    }
    policy_table::Priority priority;
    policy_table::EnumFromJsonString(query.GetString(1), &priority);
    params.priority = priority;
    policy_table::HmiLevel hmi;
    policy_table::EnumFromJsonString(query.GetString(2), &hmi);
    params.default_hmi = hmi;
    params.keep_context = query.GetBoolean(3);
    params.steal_focus = query.GetBoolean(4);
    *params.memory_kb = query.GetInteger(5);
    *params.heart_beat_timeout_ms = query.GetUInteger(6);

    const auto& gather_app_id = ((*policies).apps[app_id].is_string())
                                    ? (*policies).apps[app_id].get_string()
                                    : app_id;
    // Data should be gathered from db by  "default" key if application has
    // default policies

    if (!GatherAppGroup(gather_app_id, &params.groups)) {
      return false;
    }

    bool denied = false;
    if (!GatherRemoteControlDenied(gather_app_id, &denied)) {
      return false;
    }
    if (!denied) {
      if (!GatherModuleType(gather_app_id, &*params.moduleType)) {
        return false;
      }
    }

    if (!GatherNickName(gather_app_id, &*params.nicknames)) {
      return false;
    }
    if (!GatherAppType(gather_app_id, &*params.AppHMIType)) {
      return false;
    }
    if (!GatherRequestType(gather_app_id, &*params.RequestType)) {
      return false;
    }
    if (!GatherRequestSubType(gather_app_id, &*params.RequestSubType)) {
      return false;
    }
    GatherPreconsentedGroup(gather_app_id, &*params.preconsented_groups);
    (*policies).apps[app_id] = params;
  }
  return true;
}

void SQLPTExtRepresentation::GatherPreconsentedGroup(
    const std::string& app_id, policy_table::Strings* groups) const {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroups)) {
    LOG4CXX_WARN(logger_, "Incorrect select from preconsented group");
    return;
  }

  query.Bind(0, app_id);
  while (query.Next()) {
    groups->push_back(query.GetString(0));
  }
}

bool SQLPTExtRepresentation::GatherUsageAndErrorCounts(
    policy_table::UsageAndErrorCounts* counts) const {
  LOG4CXX_INFO(logger_, "Gather Usage and Error Counts.");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectUsageAndErrorCount) || !query.Exec()) {
    LOG4CXX_INFO(logger_, "Failed select from user_and_error_count");
    return false;
  }

  *counts->count_of_iap_buffer_full = query.GetInteger(0);
  *counts->count_sync_out_of_memory = query.GetInteger(1);
  *counts->count_of_sync_reboots = query.GetInteger(2);

  return GatherAppLevels(&*counts->app_level);
}

bool SQLPTExtRepresentation::GatherAppLevels(
    policy_table::AppLevels* apps) const {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectAppLevels)) {
    LOG4CXX_INFO(logger_,
                 "Failed select from app_level. SQLError = "
                     << query.LastError().text());
    return false;
  }
  while (query.Next()) {
    policy_table::AppLevel level;
    // value of time fields database is seconds
    level.minutes_in_hmi_full = query.GetInteger(1);
    level.minutes_in_hmi_limited = query.GetInteger(2);
    level.minutes_in_hmi_background = query.GetInteger(3);
    level.minutes_in_hmi_none = query.GetInteger(4);
    level.count_of_user_selections = query.GetInteger(5);
    level.count_of_rejections_sync_out_of_memory = query.GetInteger(6);
    level.count_of_rejections_nickname_mismatch = query.GetInteger(7);
    level.count_of_rejections_duplicate_name = query.GetInteger(8);
    level.count_of_rejected_rpc_calls = query.GetInteger(9);
    level.count_of_rpcs_sent_in_hmi_none = query.GetInteger(10);
    level.count_of_removals_for_bad_behavior = query.GetInteger(11);
    level.count_of_run_attempts_while_revoked = query.GetInteger(12);
    level.app_registration_language_gui = query.GetString(13);
    level.app_registration_language_vui = query.GetString(14);
    level.count_of_tls_errors = query.GetInteger(15);
    (*apps)[query.GetString(0)] = level;
  }

  return true;
}

void SQLPTExtRepresentation::GatherDeviceData(
    policy_table::DeviceData* data) const {
  LOG4CXX_INFO(logger_, "Gather device data.");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectDeviceData)) {
    LOG4CXX_WARN(logger_, "Incorrect select statement for device data.");
    return;
  }
  data->mark_initialized();
  while (query.Next()) {
    policy_table::DeviceParams* specific_device = &(*data)[query.GetString(0)];
    *specific_device->hardware = query.GetString(1);
    *specific_device->firmware_rev = query.GetString(2);
    *specific_device->os = query.GetString(3);
    *specific_device->os_version = query.GetString(4);
    *specific_device->carrier = query.GetString(5);
    *specific_device->max_number_rfcom_ports = query.GetInteger(6);

    // TODO(IKozyrenko): Check logic if optional container is missing
    GatherConsentGroup(query.GetString(0),
                       &(*specific_device->user_consent_records));
  }
}

void SQLPTExtRepresentation::GatherConsentGroup(
    const std::string& device_id,
    policy_table::UserConsentRecords* records) const {
  LOG4CXX_INFO(logger_, "Gather consent records.");
  utils::dbms::SQLQuery query(db());
  // Fill data for device
  if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect select statement for device consented groups.");
    return;
  }

  query.Bind(0, device_id);

  // Fill device_data -> user_consent_records -> "device"
  while (query.Next()) {
    policy_table::ConsentRecords* device_consent_records =
        &(*records)[kDeviceId];
    // TODO(IKozyrenko): Check logic if optional container is missing
    policy_table::ConsentGroups& consent_groups =
        *device_consent_records->consent_groups;
    consent_groups[query.GetString(1)] = query.GetBoolean(2);
    policy_table::Input input;
    policy_table::EnumFromJsonString(query.GetString(3), &input);
    *device_consent_records->input = input;
    *device_consent_records->time_stamp = query.GetString(4);
  }

  if (!query.Reset()) {
    return;
  }

  // Fill data for applications
  if (!query.Prepare(sql_pt_ext::kSelectConsentGroup)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect select statement for app consented groups.");
    return;
  }

  query.Bind(0, device_id);

  // Fill device_data -> user_consent_records -> <app_id>
  while (query.Next()) {
    policy_table::ConsentRecords* app_consent_records =
        &(*records)[query.GetString(1)];
    // TODO(IKozyrenko): Check logic if optional container is missing
    policy_table::ConsentGroups& consent_groups =
        *app_consent_records->consent_groups;

    consent_groups[query.GetString(2)] = query.GetBoolean(3);
    policy_table::Input input;
    policy_table::EnumFromJsonString(query.GetString(4), &input);
    *app_consent_records->input = input;
    *app_consent_records->time_stamp = query.GetString(5);
    app_consent_records->consent_last_updated = query.GetInteger(6);
  }
  if (!query.Reset()) {
    return;
  }

  // Fill data for ExternalConsent consents
  if (!query.Prepare(sql_pt_ext::kSelectExternalConsentStatusGroup)) {
    LOG4CXX_WARN(
        logger_,
        "Incorrect select statement for ExternalConsent consented groups.");
    return;
  }

  query.Bind(0, device_id);

  // Fill device_data -> user_consent_records -> <app_id> ->
  // external_consent_status_groups
  while (query.Next()) {
    policy_table::ConsentRecords* app_consent_records =
        &(*records)[query.GetString(1)];
    policy_table::ConsentGroups& external_consent_status_groups =
        *app_consent_records->external_consent_status_groups;
    external_consent_status_groups[query.GetString(2)] = query.GetBoolean(3);
    policy_table::Input input;
    policy_table::EnumFromJsonString(query.GetString(4), &input);
    app_consent_records->ext_consent_last_updated = query.GetInteger(6);
  }
}

bool SQLPTExtRepresentation::SaveDeviceData(
    const policy_table::DeviceData& devices) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery drop_device_query(db());
  const std::string drop_device = "DELETE FROM `device`";
  if (!drop_device_query.Exec(drop_device)) {
    LOG4CXX_WARN(logger_, "Could not clear device table.");
    return false;
  }

  utils::dbms::SQLQuery drop_device_consents_query(db());
  const std::string drop_device_consents = "DELETE FROM `device_consent_group`";
  if (!drop_device_consents_query.Exec(drop_device_consents)) {
    LOG4CXX_WARN(logger_, "Could not clear device consents.");
    return false;
  }

  utils::dbms::SQLQuery drop_user_consents_query(db());
  const std::string drop_user_consents = "DELETE FROM `consent_group`";
  if (!drop_user_consents_query.Exec(drop_user_consents)) {
    LOG4CXX_WARN(logger_, "Could not clear user consents.");
    return false;
  }

  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kInsertDeviceData)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for device data.");
    return false;
  }

  policy_table::DeviceData::const_iterator it = devices.begin();
  policy_table::DeviceData::const_iterator it_end = devices.end();
  for (; it != it_end; ++it) {
    query.Bind(0, it->first);
    query.Bind(1, *(it->second.hardware));
    query.Bind(2, *(it->second.firmware_rev));
    query.Bind(3, *(it->second.os));
    query.Bind(4, *(it->second.os_version));
    query.Bind(5, *(it->second.carrier));
    query.Bind(6, *(it->second.max_number_rfcom_ports));
    query.Bind(7, *(it->second.connection_type));

    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_, "Incorrect insert into device data.");
      return false;
    }

    // TODO(IKozyrenko): Check logic if optional container is missing
    if (!SaveConsentGroup(it->first, *it->second.user_consent_records)) {
      return false;
    }
  }

  return true;
}

bool SQLPTExtRepresentation::SaveConsentGroup(
    const std::string& device_id,
    const policy_table::UserConsentRecords& records) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());

  policy_table::UserConsentRecords::const_iterator it = records.begin();
  policy_table::UserConsentRecords::const_iterator it_end = records.end();
  for (; it != it_end; ++it) {
    // TODO(IKozyrenko): Check logic if optional container is missing
    policy_table::ConsentGroups::const_iterator it_groups =
        it->second.consent_groups->begin();
    policy_table::ConsentGroups::const_iterator it_groups_end =
        it->second.consent_groups->end();
    for (; it_groups != it_groups_end; ++it_groups) {
      if (kDeviceId == it->first) {
        if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
          LOG4CXX_WARN(logger_,
                       "Incorrect insert statement for device consent group.");
          return false;
        }
        query.Bind(0, device_id);
        query.Bind(1, it_groups->first);
        query.Bind(2, it_groups->second);
        query.Bind(
            3,
            std::string(policy_table::EnumToJsonString(*(it->second.input))));
        query.Bind(4, std::string(*(it->second.time_stamp)));
        LOG4CXX_INFO(logger_,
                     "Device:"
                         << "time stamp "
                         << std::string(*(it->second.time_stamp)) << " group "
                         << it_groups->first << " consent "
                         << it_groups->second);
      } else {
        if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
          LOG4CXX_WARN(logger_,
                       "Incorrect insert statement for consent group.");
          return false;
        }
        query.Bind(0, device_id);
        query.Bind(1, it->first);
        query.Bind(2, it_groups->first);
        query.Bind(3, it_groups->second);
        query.Bind(
            4,
            std::string(policy_table::EnumToJsonString(*(it->second.input))));
        query.Bind(5, std::string(*(it->second.time_stamp)));
        query.Bind(6, (it->second.consent_last_updated));
        LOG4CXX_INFO(logger_,
                     "Device:"
                         << "time stamp "
                         << std::string(*(it->second.time_stamp)) << " group "
                         << it_groups->first << " consent "
                         << it_groups->second);
      }

      if (!query.Exec() || !query.Reset()) {
        LOG4CXX_WARN(logger_, "Incorrect insert into consent group.");
        return false;
      }
    }

    policy_table::ConsentGroups::const_iterator it_external_consent_consent =
        it->second.external_consent_status_groups->begin();
    policy_table::ConsentGroups::const_iterator end_external_consent_consent =
        it->second.external_consent_status_groups->end();

    for (; end_external_consent_consent != it_external_consent_consent;
         ++it_external_consent_consent) {
      if (!query.Prepare(sql_pt_ext::kInsertExternalConsentStatusGroups)) {
        LOG4CXX_WARN(logger_,
                     "Incorrect insert statement for external consent group.");
        return false;
      }
      query.Bind(0, device_id);
      query.Bind(1, it->first);
      query.Bind(2, it_external_consent_consent->first);
      query.Bind(3, it_external_consent_consent->second);
      query.Bind(
          4, std::string(policy_table::EnumToJsonString(*(it->second.input))));
      query.Bind(5, std::string(*(it->second.time_stamp)));
      query.Bind(6, (it->second.ext_consent_last_updated));
      LOG4CXX_INFO(logger_,
                   "Device:"
                       << "time stamp " << std::string(*(it->second.time_stamp))
                       << " group " << it_external_consent_consent->first
                       << " consent " << it_external_consent_consent->second);

      if (!query.Exec() || !query.Reset()) {
        LOG4CXX_WARN(logger_, "Incorrect insert into external consent group.");
        return false;
      }
    }  // external_consent_consent_group
  }

  return true;
}

bool SQLPTExtRepresentation::SavePreconsentedGroup(
    const std::string& app_id, const policy_table::Strings& groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kInsertPreconsentedGroups)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for preconsented groups");
    return false;
  }

  policy_table::Strings::const_iterator it;
  for (it = groups.begin(); it != groups.end(); ++it) {
    query.Bind(0, app_id);
    query.Bind(1, *it);
    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_, "Incorrect insert into preconsented groups.");
      return false;
    }
  }

  return true;
}

void SQLPTExtRepresentation::GatherModuleMeta(
    policy_table::ModuleMeta* meta) const {
  LOG4CXX_INFO(logger_, "Gather Module Meta Info");
  utils::dbms::SQLQuery query(db());
  if (query.Prepare(sql_pt_ext::kSelectModuleMeta) && query.Next()) {
    *meta->ccpu_version = query.GetString(0);
    *meta->language = query.GetString(1);
    *meta->wers_country_code = query.GetString(2);
    *meta->pt_exchanged_at_odometer_x = query.GetInteger(3);
    *meta->pt_exchanged_x_days_after_epoch = query.GetInteger(4);
    *meta->ignition_cycles_since_last_exchange = query.GetInteger(5);
    *meta->vin = query.GetString(6);
  }
}

void SQLPTExtRepresentation::Increment(const std::string& type) const {
  utils::dbms::SQLQuery query(db());
  std::string update_counter =
      "UPDATE `usage_and_error_count` SET `" + type + "` = `" + type + "` + 1";
  if (!query.Exec(update_counter)) {
    LOG4CXX_INFO(logger_, "Failed updating global counter");
  }
}

bool SQLPTExtRepresentation::IsExistAppLevel(const std::string& app_id) const {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kCountAppLevel)) {
    LOG4CXX_INFO(logger_, "Incorrect statement of count app_level");
    return false;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Failed count app_level");
    return false;
  }
  return query.GetInteger(0) > 0;
}

bool SQLPTExtRepresentation::GetAllAppGroups(const std::string& policy_app_id,
                                             FunctionalGroupIDs& all_groups) {
  LOG4CXX_INFO(logger_, "GetAllAppGroups for '" << policy_app_id << "'");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectAppGroupsId)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for select app groups id.");
    return false;
  }

  query.Bind(0, policy_app_id);

  while (query.Next()) {
    all_groups.push_back(query.GetInteger(0));
  }

  return true;
}

bool SQLPTExtRepresentation::GetConsentedGroups(
    const std::string& policy_app_id,
    const std::string& device_id,
    FunctionalGroupIDs& allowed_groups,
    FunctionalGroupIDs& disallowed_groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectConsentedGroupsId)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for select consent groups id.");
    return false;
  }

  query.Bind(0, policy_app_id);
  query.Bind(1, device_id);

  while (query.Next()) {
    if (query.GetBoolean(1)) {
      allowed_groups.push_back(query.GetInteger(0));
    } else {
      disallowed_groups.push_back(query.GetInteger(0));
    }
  }

  return true;
}

bool SQLPTExtRepresentation::GetPreconsentedGroups(
    const std::string& policy_app_id, FunctionalGroupIDs& preconsented_groups) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroupsId)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect statement for select preconsented groups id.");
    return false;
  }

  query.Bind(0, policy_app_id);

  while (query.Next()) {
    preconsented_groups.push_back(query.GetInteger(0));
  }

  return true;
}

bool SQLPTExtRepresentation::GetFunctionalGroupNames(
    FunctionalGroupNames& names) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectFunctionalGroupNames)) {
    LOG4CXX_WARN(logger_,
                 "Incorrect statement for select functional groups names.");
    return false;
  }

  while (query.Next()) {
    // Some of functional grous doesn't have filled user_consent_prompt
    if (query.IsNull(1)) {
      names[query.GetInteger(0)] =
          std::make_pair<std::string, std::string>("", query.GetString(2));
    } else {
      names[query.GetInteger(0)] = std::make_pair<std::string, std::string>(
          query.GetString(1), query.GetString(2));
    }
  }

  return true;
}

void SQLPTExtRepresentation::FillFunctionalGroupPermissions(
    FunctionalGroupIDs& ids,
    FunctionalGroupNames& names,
    GroupConsent state,
    std::vector<FunctionalGroupPermission>& permissions) {
  FunctionalGroupIDs::const_iterator it = ids.begin();
  FunctionalGroupIDs::const_iterator it_end = ids.end();
  for (; it != it_end; ++it) {
    FunctionalGroupPermission current_group;
    current_group.group_id = *it;
    current_group.group_alias = names[*it].first;
    current_group.group_name = names[*it].second;
    current_group.state = state;
    permissions.push_back(current_group);
  }
}

void SQLPTExtRepresentation::Increment(const std::string& app_id,
                                       const std::string& type) const {
  utils::dbms::SQLQuery query(db());
  std::string sql_counter;
  if (IsExistAppLevel(app_id)) {
    // update
    sql_counter = "UPDATE `app_level` SET `" + type + "` = `" + type +
                  "` + 1 WHERE `application_id` = ?";
  } else {
    // insert
    sql_counter = "INSERT INTO `app_level` (`application_id`, `" + type +
                  "`) "
                  "VALUES (?, 1)";
  }
  if (!query.Prepare(sql_counter)) {
    LOG4CXX_INFO(logger_, "Incorrect statement of update app counter");
    return;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Failed updating app counter");
  }
}

void SQLPTExtRepresentation::Set(const std::string& app_id,
                                 const std::string& type,
                                 const std::string& value) const {
  utils::dbms::SQLQuery query(db());
  std::string sql_info;
  if (IsExistAppLevel(app_id)) {
    // update
    sql_info = "UPDATE `app_level` SET `" + type +
               "` = ? "
               "WHERE `application_id` = ?";
  } else {
    // insert
    sql_info = "INSERT INTO `app_level` (`" + type +
               "`, `application_id`) "
               "VALUES (?, ?)";
  }
  if (!query.Prepare(sql_info)) {
    LOG4CXX_INFO(logger_, "Incorrect statement of update app info");
    return;
  }
  query.Bind(0, value);
  query.Bind(1, app_id);
  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Failed updating app info");
  }
}

void SQLPTExtRepresentation::Add(const std::string& app_id,
                                 const std::string& type,
                                 int seconds) const {
  utils::dbms::SQLQuery query(db());
  std::string sql_stopwatch;
  if (IsExistAppLevel(app_id)) {
    // update
    sql_stopwatch = "UPDATE `app_level` SET `" + type + "` = `" + type +
                    "` + ? WHERE `application_id` = ?";
  } else {
    // insert
    sql_stopwatch = "INSERT INTO `app_level` (`" + type +
                    "`, `application_id`) "
                    "VALUES (?, ?)";
  }
  if (!query.Prepare(sql_stopwatch)) {
    LOG4CXX_INFO(logger_, "Incorrect statement of update app stopwatch");
    return;
  }
  query.Bind(0, seconds);
  query.Bind(1, app_id);
  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Failed updating app stopwatch");
  }
}

bool SQLPTExtRepresentation::GetDefaultHMI(const std::string& policy_app_id,
                                           std::string* default_hmi) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectDefaultHmi)) {
    LOG4CXX_INFO(logger_, "Incorrect statement for default hmi.");
    return false;
  }

  query.Bind(0, policy_app_id);

  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Error during default hmi getting.");
    return false;
  }

  if (query.IsNull(0)) {
    default_hmi->clear();
    return true;
  }

  default_hmi->assign(query.GetString(0));

  return true;
}

bool SQLPTExtRepresentation::CountUnconsentedGroups(
    const std::string& policy_app_id,
    const std::string& device_id,
    int* result) const {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kCountUnconsentedGroups)) {
    LOG4CXX_WARN(logger_, "Incorrect select for unconsented groups.");
    return false;
  }

  query.Bind(0, policy_app_id);
  query.Bind(1, device_id);
  query.Bind(2, kDefaultId);
  query.Bind(3, kPreDataConsentId);

  if (!query.Exec()) {
    LOG4CXX_INFO(logger_, "Error during executing unconsented groups.");
    return false;
  }
  *result = query.GetInteger(0);
  return true;
}

bool SQLPTExtRepresentation::IsMsgLanguagePresent(const std::string& message,
                                                  const std::string& language) {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kHasMsgLanguageCode)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for message language check.");
    return false;
  }

  query.Bind(0, message);
  query.Bind(1, language);

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed to check message language code.");
    return false;
  }

  return query.GetInteger(0) != 0;
}

bool SQLPTExtRepresentation::SaveMessageString(
    const std::string& type,
    const std::string& lang,
    const policy_table::MessageString& strings) {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt::kInsertMessageString)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for message.");
    return false;
  }

  if (strings.tts.is_initialized()) {
    query.Bind(0, *strings.tts);
  }
  if (strings.label.is_initialized()) {
    query.Bind(1, *strings.label);
  }
  if (strings.line1.is_initialized()) {
    query.Bind(2, *strings.line1);
  }
  if (strings.line2.is_initialized()) {
    query.Bind(3, *strings.line2);
  }
  query.Bind(4, lang);
  query.Bind(5, type);
  if (strings.textBody.is_initialized()) {
    query.Bind(6, *strings.textBody);
  }

  if (!query.Exec() || !query.Reset()) {
    LOG4CXX_WARN(logger_, "Incorrect insert into message.");
    return false;
  }

  return true;
}

bool SQLPTExtRepresentation::SaveUsageAndErrorCounts(
    const policy_table::UsageAndErrorCounts& counts) {
  return SaveAppCounters(*counts.app_level) && SaveGlobalCounters(counts);
}

bool SQLPTExtRepresentation::SaveModuleMeta(
    const policy_table::ModuleMeta& meta) {
  utils::dbms::SQLQuery query(db());

  if (!query.Prepare(sql_pt_ext::kSaveModuleMeta)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for module_meta.");
    return false;
  }
  const int64_t odometer = *(meta.pt_exchanged_at_odometer_x);

  query.Bind(0, *(meta.ccpu_version));
  query.Bind(1, *(meta.language));
  query.Bind(2, *(meta.wers_country_code));
  query.Bind(3, odometer);
  query.Bind(4, *(meta.pt_exchanged_x_days_after_epoch));
  query.Bind(5, *(meta.ignition_cycles_since_last_exchange));
  query.Bind(6, *(meta.vin));

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Incorrect update for module_meta.");
    return false;
  }

  return true;
}

bool SQLPTExtRepresentation::SaveAppCounters(
    const rpc::policy_table_interface_base::AppLevels& app_levels) {
  utils::dbms::SQLQuery query(db());
  if (!query.Exec(sql_pt::kDeleteAppLevel)) {
    LOG4CXX_WARN(logger_, "Incorrect delete from app level.");
    return false;
  }
  if (!query.Prepare(sql_pt::kInsertAppLevel)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for app level.");
    return false;
  }

  policy_table::AppLevels::const_iterator it;
  for (it = app_levels.begin(); it != app_levels.end(); ++it) {
    query.Bind(0, it->first);
    query.Bind(1, it->second.minutes_in_hmi_full);
    query.Bind(2, it->second.minutes_in_hmi_limited);
    query.Bind(3, it->second.minutes_in_hmi_background);
    query.Bind(4, it->second.minutes_in_hmi_none);
    query.Bind(5, it->second.count_of_user_selections);
    query.Bind(6, it->second.count_of_rejections_sync_out_of_memory);
    query.Bind(7, it->second.count_of_rejections_nickname_mismatch);
    query.Bind(8, it->second.count_of_rejections_duplicate_name);
    query.Bind(9, it->second.count_of_rejected_rpc_calls);
    query.Bind(10, it->second.count_of_rpcs_sent_in_hmi_none);
    query.Bind(11, it->second.count_of_removals_for_bad_behavior);
    query.Bind(12, it->second.count_of_run_attempts_while_revoked);
    query.Bind(13, it->second.app_registration_language_gui);
    query.Bind(14, it->second.app_registration_language_vui);
    query.Bind(15, it->second.count_of_tls_errors);

    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_WARN(logger_, "Incorrect insert into app level.");
      return false;
    }
  }
  return true;
}

bool SQLPTExtRepresentation::SaveGlobalCounters(
    const rpc::policy_table_interface_base::UsageAndErrorCounts& counts) {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateGlobalCounters)) {
    LOG4CXX_WARN(logger_, "Incorrect insert statement for global counters.");
    return false;
  }

  query.Bind(0, *counts.count_of_iap_buffer_full);
  query.Bind(1, *counts.count_sync_out_of_memory);
  query.Bind(2, *counts.count_of_sync_reboots);

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Incorrect insert into global counters.");
    return false;
  }

  return true;
}

bool SQLPTExtRepresentation::CleanupUnpairedDevices(
    const DeviceIds& device_ids) const {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery delete_device_query(db());
  if (!delete_device_query.Prepare(sql_pt::kDeleteDevice)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for device delete.");
    return true;
  }

  utils::dbms::SQLQuery delete_device_consent_query(db());
  if (!delete_device_consent_query.Prepare(sql_pt_ext::kDeleteDeviceConsent)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for delete device consent.");
    return false;
  }

  utils::dbms::SQLQuery delete_app_consent_query(db());
  if (!delete_app_consent_query.Prepare(sql_pt_ext::kDeleteAppConsent)) {
    LOG4CXX_WARN(logger_, "Incorrect statement for delete app consent.");
    return false;
  }

  DeviceIds::const_iterator it = device_ids.begin();
  DeviceIds::const_iterator it_end = device_ids.end();
  for (; it != it_end; ++it) {
    delete_device_query.Bind(0, (*it));
    if (!delete_device_query.Exec() || !delete_device_query.Reset()) {
      LOG4CXX_WARN(logger_, "Failed to delete from device");
      return false;
    }

    delete_device_consent_query.Bind(0, (*it));
    if (!delete_device_consent_query.Exec() ||
        !delete_device_consent_query.Reset()) {
      LOG4CXX_WARN(logger_, "Failed to delete from device consent.");
      return false;
    }

    delete_app_consent_query.Bind(0, (*it));
    if (!delete_app_consent_query.Exec() || !delete_app_consent_query.Reset()) {
      LOG4CXX_WARN(logger_, "Failed to delete from app consent.");
      return false;
    }
  }
  return true;
}

bool SQLPTExtRepresentation::SetDefaultPolicy(const std::string& app_id) {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
    LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
    return false;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
    return false;
  }

  if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
    LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
    return false;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
    return false;
  }

  if (!CopyApplication(kDefaultId, app_id)) {
    return false;
  }

  SetPreloaded(false);

  policy_table::Strings default_groups;
  policy_table::Strings default_preconsented_groups;
  GatherAppGroup(kDefaultId, &default_groups);
  GatherPreconsentedGroup(kDefaultId, &default_preconsented_groups);
  if (SaveAppGroup(app_id, default_groups) &&
      SavePreconsentedGroup(app_id, default_preconsented_groups)) {
    return SetIsDefault(app_id, true) && SetIsPredata(app_id, false);
  }

  return false;
}

bool SQLPTExtRepresentation::SetPredataPolicy(const std::string& app_id) {
  LOG4CXX_INFO(logger_,
               "SQLPTExtRepresentation::SetPredataPolicy for " << app_id);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
    LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
    return false;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
    return false;
  }

  if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
    LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
    return false;
  }
  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
    return false;
  }

  if (!CopyApplication(kPreDataConsentId, app_id)) {
    return false;
  }

  SetPreloaded(false);

  policy_table::Strings predataconsent_groups;
  policy_table::Strings predataconsent_preconsented_groups;
  GatherAppGroup(kPreDataConsentId, &predataconsent_groups);
  GatherPreconsentedGroup(kPreDataConsentId, &predataconsent_groups);
  if (SaveAppGroup(app_id, predataconsent_groups) &&
      SavePreconsentedGroup(app_id, predataconsent_groups)) {
    return SetIsDefault(app_id, false) && SetIsPredata(app_id, true);
  }
  return false;
}

bool SQLPTExtRepresentation::IsPredataPolicy(const std::string& app_id) const {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectApplicationIsPreData)) {
    LOG4CXX_WARN(logger_, "Incorrect select application is pre_dataConsented");
    return false;
  }

  query.Bind(0, app_id);
  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed select application is pre_dataConsented");
    return false;
  }
  return query.IsNull(0) ? false : query.GetBoolean(0);
}

bool SQLPTExtRepresentation::SetIsPredata(const std::string& app_id,
                                          bool is_pre_data) {
  LOG4CXX_TRACE(logger_, "Set flag is_predata of application");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateIsPredata)) {
    LOG4CXX_WARN(logger_, "Incorect statement for updating is_predata");
    return false;
  }

  query.Bind(0, is_pre_data);
  query.Bind(1, app_id);
  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed update is_predata");
    return false;
  }
  return true;
}

bool SQLPTExtRepresentation::SetUnpairedDevice(const std::string& device_id,
                                               bool unpaired) const {
  LOG4CXX_TRACE(logger_, "Set unpaired device: " << device_id);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateUnpairedDevice)) {
    LOG4CXX_WARN(logger_, "Incorect statement for updating unpaired device");
    return false;
  }

  query.Bind(0, unpaired);
  query.Bind(1, device_id);
  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed update unpaired device");
    return false;
  }
  return true;
}

bool SQLPTExtRepresentation::UnpairedDevicesList(DeviceIds* device_ids) const {
  LOG4CXX_TRACE(logger_, "Get list of unpaired devices");
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectUnpairedDevices)) {
    LOG4CXX_WARN(logger_, "Incorect statement for selecting unpaired devices");
    return false;
  }

  while (query.Next()) {
    device_ids->push_back(query.GetString(0));
  }
  return true;
}

bool SQLPTExtRepresentation::SetVINValue(const std::string& value) {
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kUpdateModuleMetaVinParam)) {
    LOG4CXX_WARN(logger_, "Incorect statement for updating module_meta params");
    return false;
  }

  query.Bind(0, value);
  const bool result = query.Exec();

  if (!result) {
    LOG4CXX_WARN(logger_, "Failed update module_meta");
  }
  return result;
}

bool SQLPTExtRepresentation::SaveExternalConsentStatus(
    const ExternalConsentStatus& status) const {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kInsertExternalConsentStatus)) {
    LOG4CXX_ERROR(logger_,
                  "Incorrect statement for saving external consent status.");
    return false;
  }

  ExternalConsentStatus::const_iterator it = status.begin();
  ExternalConsentStatus::const_iterator end = status.end();
  for (; end != it; ++it) {
    query.Bind(0, static_cast<int>(it->entity_type_));
    query.Bind(1, static_cast<int>(it->entity_id_));
    // Due to query structure need to provide that twice
    query.Bind(2, static_cast<int>(it->entity_type_));
    query.Bind(3, static_cast<int>(it->entity_id_));
    query.Bind(4,
               policy::kStatusOn == it->status_ ? std::string("ON")
                                                : std::string("OFF"));
    if (!query.Exec() || !query.Reset()) {
      LOG4CXX_ERROR(logger_, "Error during ExternalConsent status saving.");
      return false;
    }
  }

  return true;
}

ExternalConsentStatus SQLPTExtRepresentation::GetExternalConsentStatus() const {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kSelectExternalConsentStatus)) {
    LOG4CXX_ERROR(logger_,
                  "Incorrect statement for selecting external consent status.");
    return ExternalConsentStatus();
  }

  ExternalConsentStatus status;
  while (query.Next()) {
    const policy::EntityStatus on_off =
        query.GetString(2) == "ON" ? policy::kStatusOn : policy::kStatusOff;
    ExternalConsentStatusItem item(static_cast<uint32_t>(query.GetInteger(0)),
                                   static_cast<uint32_t>(query.GetInteger(1)),
                                   on_off);
    status.insert(item);
  }

  return status;
}

bool SQLPTExtRepresentation::RemoveAppConsentForGroup(
    const std::string& policy_app_id,
    const std::string& functional_group_name) const {
  utils::dbms::SQLQuery query_group_id(db());
  if (!query_group_id.Prepare(sql_pt_ext::kSelectGroupId)) {
    LOG4CXX_WARN(logger_, "Incorect statement for select group name.");
    return false;
  }

  query_group_id.Bind(0, functional_group_name);

  if (!query_group_id.Exec()) {
    LOG4CXX_WARN(logger_, "Failed to select group id.");
    return false;
  }

  const int id = query_group_id.GetInteger(0);

  utils::dbms::SQLQuery query(db());
  if (!query.Prepare(sql_pt_ext::kDeleteAppGroupConsent)) {
    LOG4CXX_WARN(logger_, "Incorect statement for remove app consent.");
    return false;
  }

  query.Bind(0, policy_app_id);
  query.Bind(1, id);

  if (!query.Exec()) {
    LOG4CXX_WARN(logger_, "Failed to remove app consent.");
    return false;
  }

  return true;
}

}  // namespace policy