summaryrefslogtreecommitdiffstats
path: root/database/sqlite/sqlite_health.c
blob: 7d79ff70b348e3b5bb40f9564500db7e98ab42d5 (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
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
// SPDX-License-Identifier: GPL-3.0-or-later

#include "sqlite_health.h"
#include "sqlite_functions.h"
#include "sqlite_db_migration.h"

#define MAX_HEALTH_SQL_SIZE 2048
#define SQLITE3_BIND_STRING_OR_NULL(res, key, param)                                                                   \
    ((key) ? sqlite3_bind_text(res, param, string2str(key), -1, SQLITE_STATIC) : sqlite3_bind_null(res, param))

#define SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, param)                                                                   \
    ({                                                                                                                 \
        int _param = (param);                                                                                          \
        sqlite3_column_type((res), (_param)) != SQLITE_NULL ?                                                          \
            string_strdupz((char *)sqlite3_column_text((res), (_param))) :                                             \
            NULL;                                                                                                      \
    })

/* Health related SQL queries
   Updates an entry in the table
*/
#define SQL_UPDATE_HEALTH_LOG                                                                                          \
    "UPDATE health_log_detail SET updated_by_id = @updated_by, flags = @flags, exec_run_timestamp = @exec_time, "      \
    "exec_code = @exec_code WHERE unique_id = @unique_id AND alarm_id = @alarm_id AND transition_id = @transaction"

static void sql_health_alarm_log_update(RRDHOST *host, ALARM_ENTRY *ae)
{
    sqlite3_stmt *res = NULL;
    int rc;

    if (unlikely(!db_meta)) {
        if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
            error_report("HEALTH [%s]: Database has not been initialized", rrdhost_hostname(host));
        return;
    }

    rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_HEALTH_LOG, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("HEALTH [%s]: Failed to prepare statement for SQL_UPDATE_HEALTH_LOG", rrdhost_hostname(host));
        return;
    }

    rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) ae->updated_by_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind updated_by_id parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) ae->flags);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind flags parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 3, (sqlite3_int64) ae->exec_run_timestamp);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind exec_run_timestamp parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int(res, 4, ae->exec_code);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind exec_code parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 5, (sqlite3_int64) ae->unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 6, (sqlite3_int64) ae->alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_UPDATE_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 7, &ae->transition_id, sizeof(ae->transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id for SQL_UPDATE_HEALTH_LOG.");
        goto failed;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("HEALTH [%s]: Failed to update health log, rc = %d", rrdhost_hostname(host), rc);
    }

failed:
    if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
        error_report("HEALTH [%s]: Failed to finalize the prepared statement for updating health log.", rrdhost_hostname(host));
}

/* Health related SQL queries
   Inserts an entry in the table
*/

#define SQL_INSERT_HEALTH_LOG                                                                                          \
    "INSERT INTO health_log (host_id, alarm_id, "                                                                      \
    "config_hash_id, name, chart, exec, recipient, units, chart_context, last_transition_id, chart_name) "             \
    "VALUES (@host_id,@alarm_id, @config_hash_id,@name,@chart,@exec,@recipient,@units,@chart_context,"                 \
    "@last_transition_id,@chart_name) ON CONFLICT (host_id, alarm_id) DO UPDATE "                                      \
    "SET last_transition_id = excluded.last_transition_id, chart_name = excluded.chart_name RETURNING health_log_id"

#define SQL_INSERT_HEALTH_LOG_DETAIL                                                                                         \
    "INSERT INTO health_log_detail (health_log_id, unique_id, alarm_id, alarm_event_id, "                                    \
    "updated_by_id, updates_id, when_key, duration, non_clear_duration, flags, exec_run_timestamp, delay_up_to_timestamp, "  \
    "info, exec_code, new_status, old_status, delay, new_value, old_value, last_repeat, transition_id, global_id, summary) " \
    "VALUES (@health_log_id,@unique_id,@alarm_id,@alarm_event_id,@updated_by_id,@updates_id,@when_key,@duration,"            \
    "@non_clear_duration,@flags,@exec_run_timestamp,@delay_up_to_timestamp, @info,@exec_code,@new_status,@old_status,"       \
    "@delay,@new_value,@old_value,@last_repeat,@transition_id,@global_id,@summary)"

static void sql_health_alarm_log_insert(RRDHOST *host, ALARM_ENTRY *ae) {
    sqlite3_stmt *res = NULL;
    int rc;
    uint64_t health_log_id = 0;

    if (unlikely(!db_meta)) {
        if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
            error_report("HEALTH [%s]: Database has not been initialized", rrdhost_hostname(host));
        return;
    }

    rc = sqlite3_prepare_v2(db_meta, SQL_INSERT_HEALTH_LOG, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("HEALTH [%s]: Failed to prepare statement for SQL_INSERT_HEALTH_LOG", rrdhost_hostname(host));
        return;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id for SQL_INSERT_HEALTH_LOG.");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) ae->alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_id parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 3, &ae->config_hash_id, sizeof(ae->config_hash_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind config_hash_id parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->name, 4);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind name parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->chart, 5);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind chart parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->exec, 6);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind exec parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->recipient, 7);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind recipient parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->units, 8);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter to store node instance information");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->chart_context, 9);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind chart_context parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 10, &ae->transition_id, sizeof(ae->transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind transition_id parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->chart_name, 11);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind chart_name parameter for SQL_INSERT_HEALTH_LOG");
        goto failed;
    }

    rc = sqlite3_step_monitored(res);
    if (likely(rc == SQLITE_ROW))
        health_log_id = (size_t) sqlite3_column_int64(res, 0);
    else {
        error_report("HEALTH [%s]: Failed to execute SQL_INSERT_HEALTH_LOG, rc = %d", rrdhost_hostname(host), rc);
        goto failed;
    }

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("HEALTH [%s]: Failed to finalize the prepared statement for inserting to health log.", rrdhost_hostname(host));

    rc = sqlite3_prepare_v2(db_meta, SQL_INSERT_HEALTH_LOG_DETAIL, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("HEALTH [%s]: Failed to prepare statement for SQL_INSERT_HEALTH_LOG_DETAIL", rrdhost_hostname(host));
        return;
    }

    rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) health_log_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) ae->unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 3, (sqlite3_int64) ae->alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 4, (sqlite3_int64) ae->alarm_event_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_event_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 5, (sqlite3_int64) ae->updated_by_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind updated_by_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 6, (sqlite3_int64) ae->updates_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind updates_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 7, (sqlite3_int64) ae->when);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind when parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 8, (sqlite3_int64) ae->duration);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind duration parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 9, (sqlite3_int64) ae->non_clear_duration);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind non_clear_duration parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 10, (sqlite3_int64) ae->flags);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind flags parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 11, (sqlite3_int64) ae->exec_run_timestamp);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind exec_run_timestamp parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 12, (sqlite3_int64) ae->delay_up_to_timestamp);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind delay_up_to_timestamp parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->info, 13);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind info parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int(res, 14, ae->exec_code);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind exec_code parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int(res, 15, ae->new_status);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind new_status parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int(res, 16, ae->old_status);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind old_status parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int(res, 17, ae->delay);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind delay parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_double(res, 18, ae->new_value);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind new_value parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_double(res, 19, ae->old_value);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind old_value parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 20, (sqlite3_int64) ae->last_repeat);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind last_repeat parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 21, &ae->transition_id, sizeof(ae->transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind transition_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 22, (sqlite3_int64) ae->global_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind global_id parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, ae->summary, 23);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind summary parameter for SQL_INSERT_HEALTH_LOG_DETAIL");
        goto failed;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("HEALTH [%s]: Failed to execute SQL_INSERT_HEALTH_LOG_DETAIL, rc = %d", rrdhost_hostname(host), rc);
        goto failed;
    }

    ae->flags |= HEALTH_ENTRY_FLAG_SAVED;

failed:
    if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
        error_report("HEALTH [%s]: Failed to finalize the prepared statement for inserting to health log.", rrdhost_hostname(host));
}

void sql_health_alarm_log_save(RRDHOST *host, ALARM_ENTRY *ae)
{
    if (ae->flags & HEALTH_ENTRY_FLAG_SAVED)
        sql_health_alarm_log_update(host, ae);
    else {
        sql_health_alarm_log_insert(host, ae);
#ifdef ENABLE_ACLK
        if (netdata_cloud_enabled) {
            sql_queue_alarm_to_aclk(host, ae, false);
        }
#endif
    }
}

/*
 *
 * Health related SQL queries
 * Cleans up the health_log_detail table on a non-claimed or claimed host
 *
 */

#define SQL_CLEANUP_HEALTH_LOG_DETAIL_NOT_CLAIMED                                                                      \
    "DELETE FROM health_log_detail WHERE health_log_id IN "                                                            \
    "(SELECT health_log_id FROM health_log WHERE host_id = @host_id) AND when_key < UNIXEPOCH() - @history "           \
    "AND updated_by_id <> 0 AND transition_id NOT IN "                                                                 \
    "(SELECT last_transition_id FROM health_log hl WHERE hl.host_id = @host_id)"

#define SQL_CLEANUP_HEALTH_LOG_DETAIL_CLAIMED(guid)                                                                    \
    "DELETE from health_log_detail WHERE unique_id NOT IN "                                                            \
    "(SELECT filtered_alert_unique_id FROM aclk_alert_%s) "                                                            \
    "AND unique_id IN (SELECT hld.unique_id FROM health_log hl, health_log_detail hld WHERE "                          \
    "hl.host_id = @host_id AND hl.health_log_id = hld.health_log_id) "                                                 \
    "AND health_log_id IN (SELECT health_log_id FROM health_log WHERE host_id = @host_id) "                            \
    "AND when_key < unixepoch() - @history "                                                                           \
    "AND updated_by_id <> 0 AND transition_id NOT IN "                                                                 \
    "(SELECT last_transition_id FROM health_log hl WHERE hl.host_id = @host_id)",                                      \
        guid

void sql_health_alarm_log_cleanup(RRDHOST *host, bool claimed) {
    sqlite3_stmt *res = NULL;
    int rc;
    char command[MAX_HEALTH_SQL_SIZE + 1];

    if (unlikely(!db_meta)) {
        if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
            error_report("Database has not been initialized");
        return;
    }

    char uuid_str[UUID_STR_LEN];
    uuid_unparse_lower_fix(&host->host_uuid, uuid_str);
    snprintfz(command, sizeof(command) - 1, "aclk_alert_%s", uuid_str);

    bool aclk_table_exists = table_exists_in_database(db_meta, command);

    char *sql = SQL_CLEANUP_HEALTH_LOG_DETAIL_NOT_CLAIMED;

    if (claimed && aclk_table_exists) {
        snprintfz(command, sizeof(command) - 1, SQL_CLEANUP_HEALTH_LOG_DETAIL_CLAIMED(uuid_str));
        sql = command;
    }

    rc = sqlite3_prepare_v2(db_meta, sql, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to cleanup health log detail table (claimed)");
        return;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind first host_id for sql_health_alarm_log_cleanup.");
        goto done;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64)host->health_log.health_log_history);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind health log history for sql_health_alarm_log_cleanup.");
        goto done;
    }

    rc = sqlite3_step_monitored(res);
    if (unlikely(rc != SQLITE_DONE))
        error_report("Failed to cleanup health log detail table, rc = %d", rc);

    if (aclk_table_exists)
        sql_aclk_alert_clean_dead_entries(host);

done:
    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to finalize the prepared statement to cleanup health log detail table (claimed)");
}

#define SQL_INJECT_REMOVED                                                                                                      \
    "INSERT INTO health_log_detail (health_log_id, unique_id, alarm_id, alarm_event_id, updated_by_id, updates_id, when_key, "  \
    "duration, non_clear_duration, flags, exec_run_timestamp, delay_up_to_timestamp, info, exec_code, new_status, old_status, " \
    "delay, new_value, old_value, last_repeat, transition_id, global_id, summary) "                                             \
    "SELECT health_log_id, ?1, ?2, ?3, 0, ?4, UNIXEPOCH(), 0, 0, flags, exec_run_timestamp, UNIXEPOCH(), info, exec_code, -2, " \
    "new_status, delay, NULL, new_value, 0, ?5, NOW_USEC(0), summary FROM health_log_detail WHERE unique_id = ?6 AND transition_id = ?7"

#define SQL_INJECT_REMOVED_UPDATE_DETAIL                                                                               \
    "UPDATE health_log_detail SET flags = flags | ?1, updated_by_id = ?2 WHERE unique_id = ?3 AND transition_id = ?4"

#define SQL_INJECT_REMOVED_UPDATE_LOG                                                                                  \
    "UPDATE health_log SET last_transition_id = ?1 WHERE alarm_id = ?2 AND last_transition_id = ?3 AND host_id = ?4"

void sql_inject_removed_status(
    RRDHOST *host,
    uint32_t alarm_id,
    uint32_t alarm_event_id,
    uint32_t unique_id,
    uint32_t max_unique_id,
    uuid_t *prev_transition_id)
{
    int rc;

    if (!alarm_id || !alarm_event_id || !unique_id || !max_unique_id)
        return;

    sqlite3_stmt *res = NULL;

    rc = sqlite3_prepare_v2(db_meta, SQL_INJECT_REMOVED, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to inject removed event");
        return;
    }

    rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) max_unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind max_unique_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 3, (sqlite3_int64) alarm_event_id + 1);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_event_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 4, (sqlite3_int64) unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    uuid_t transition_id;
    uuid_generate_random(transition_id);
    rc = sqlite3_bind_blob(res, 5, &transition_id, sizeof(transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind config_hash_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 6, (sqlite3_int64) unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INJECT_REMOVED");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 7, prev_transition_id, sizeof(*prev_transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_INJECT_REMOVED.");
        goto failed;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("HEALTH [N/A]: Failed to execute SQL_INJECT_REMOVED, rc = %d", rc);
        goto failed;
    }

    if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
        error_report("HEALTH [N/A]: Failed to finalize the prepared statement for injecting removed event.");

    //update the old entry in health_log_detail
    rc = sqlite3_prepare_v2(db_meta, SQL_INJECT_REMOVED_UPDATE_DETAIL, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to update health_log_detail during inject removed event");
        return;
    }

    rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) HEALTH_ENTRY_FLAG_UPDATED);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind flags parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) max_unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind max_unique_id parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 3, (sqlite3_int64) unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 4, prev_transition_id, sizeof(*prev_transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("HEALTH [N/A]: Failed to execute SQL_INJECT_REMOVED_UPDATE_DETAIL, rc = %d", rc);
        goto failed;
    }

    //update the health_log_table
    rc = sqlite3_prepare_v2(db_meta, SQL_INJECT_REMOVED_UPDATE_LOG, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to update health_log during inject removed event");
        return;
    }

    rc = sqlite3_bind_blob(res, 1, &transition_id, sizeof(transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_INJECT_REMOVED_UPDATE_LOG");
        goto failed;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 3, prev_transition_id, sizeof(*prev_transition_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_INJECT_REMOVED_UPDATE_LOG");
        goto failed;
    }

    rc = sqlite3_bind_blob(res, 4, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_INJECT_REMOVED_UPDATE_DETAIL");
        goto failed;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE))
        error_report("HEALTH [N/A]: Failed to execute SQL_INJECT_REMOVED_UPDATE_DETAIL, rc = %d", rc);

failed:
    if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
        error_report("HEALTH [N/A]: Failed to finalize the prepared statement for injecting removed event.");
}

#define SQL_SELECT_MAX_UNIQUE_ID                                                                                       \
    "SELECT MAX(hld.unique_id) FROM health_log_detail hld, health_log hl "                                             \
    "WHERE hl.host_id = @host_id AND hl.health_log_id = hld.health_log_id"

uint32_t sql_get_max_unique_id (RRDHOST *host)
{
    int rc;
    uint32_t max_unique_id = 0;

    sqlite3_stmt *res = NULL;

    rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_MAX_UNIQUE_ID, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to get max unique id");
        return 0;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_SELECT_MAX_UNIQUE_ID.");
        sqlite3_finalize(res);
        return 0;
    }

     while (sqlite3_step_monitored(res) == SQLITE_ROW) {
         max_unique_id = (uint32_t) sqlite3_column_int64(res, 0);
     }

     rc = sqlite3_finalize(res);
     if (unlikely(rc != SQLITE_OK))
         error_report("Failed to finalize the statement");

     return max_unique_id;
}

#define SQL_SELECT_LAST_STATUSES                                                                                       \
     "SELECT hld.new_status, hld.unique_id, hld.alarm_id, hld.alarm_event_id, hld.transition_id FROM health_log hl, "  \
     "health_log_detail hld WHERE hl.host_id = @host_id AND hl.last_transition_id = hld.transition_id"

void sql_check_removed_alerts_state(RRDHOST *host)
{
    int rc;
    uint32_t max_unique_id = 0;
    sqlite3_stmt *res = NULL;
    uuid_t transition_id;

    rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_LAST_STATUSES, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to check removed statuses");
        return;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_SELECT_LAST_STATUSES.");
        sqlite3_finalize(res);
        return;
    }

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        uint32_t alarm_id, alarm_event_id, unique_id;
        RRDCALC_STATUS status;

        status = (RRDCALC_STATUS)sqlite3_column_int(res, 0);
        unique_id = (uint32_t)sqlite3_column_int64(res, 1);
        alarm_id = (uint32_t)sqlite3_column_int64(res, 2);
        alarm_event_id = (uint32_t)sqlite3_column_int64(res, 3);
        uuid_copy(transition_id, *((uuid_t *)sqlite3_column_blob(res, 4)));

        if (unlikely(status != RRDCALC_STATUS_REMOVED)) {
           if (unlikely(!max_unique_id))
               max_unique_id = sql_get_max_unique_id(host);

           sql_inject_removed_status(host, alarm_id, alarm_event_id, unique_id, ++max_unique_id, &transition_id);
        }
    }

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to finalize the statement");
}

/* Health related SQL queries
   Load from the health log table
*/
#define SQL_LOAD_HEALTH_LOG                                                                                            \
    "SELECT hld.unique_id, hld.alarm_id, hld.alarm_event_id, hl.config_hash_id, hld.updated_by_id, "                   \
    "hld.updates_id, hld.when_key, hld.duration, hld.non_clear_duration, hld.flags, hld.exec_run_timestamp, "          \
    "hld.delay_up_to_timestamp, hl.name, hl.chart, hl.exec, hl.recipient, ah.source, hl.units, "                       \
    "hld.info, hld.exec_code, hld.new_status, hld.old_status, hld.delay, hld.new_value, hld.old_value, "               \
    "hld.last_repeat, ah.class, ah.component, ah.type, hl.chart_context, hld.transition_id, hld.global_id, "           \
    "hl.chart_name, hld.summary FROM health_log hl, alert_hash ah, health_log_detail hld "                             \
    "WHERE hl.config_hash_id = ah.hash_id and hl.host_id = @host_id and hl.last_transition_id = hld.transition_id"

void sql_health_alarm_log_load(RRDHOST *host)
{
    sqlite3_stmt *res = NULL;
    int ret;
    ssize_t errored = 0, loaded = 0;

    if (unlikely(!db_meta)) {
        if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
            error_report("HEALTH [%s]: Database has not been initialized", rrdhost_hostname(host));
        return;
    }

    sql_check_removed_alerts_state(host);

    ret = sqlite3_prepare_v2(db_meta, SQL_LOAD_HEALTH_LOG, -1, &res, 0);
    if (unlikely(ret != SQLITE_OK)) {
        error_report("HEALTH [%s]: Failed to prepare sql statement to load health log.", rrdhost_hostname(host));
        return;
    }

    ret = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(ret != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_LOAD_HEALTH_LOG.");
        sqlite3_finalize(res);
        return;
    }

    DICTIONARY *all_rrdcalcs = dictionary_create(
        DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE);
    RRDCALC *rc;
    foreach_rrdcalc_in_rrdhost_read(host, rc) {
        dictionary_set(all_rrdcalcs, rrdcalc_name(rc), rc, sizeof(*rc));
    }
    foreach_rrdcalc_in_rrdhost_done(rc);

    rw_spinlock_read_lock(&host->health_log.spinlock);

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        ALARM_ENTRY *ae = NULL;

        // check that we have valid ids
        uint32_t unique_id = (uint32_t) sqlite3_column_int64(res, 0);
        if(!unique_id) {
            error_report("HEALTH [%s]: Got invalid unique id. Ignoring it.", rrdhost_hostname(host));
            errored++;
            continue;
        }

        uint32_t alarm_id = (uint32_t) sqlite3_column_int64(res, 1);
        if(!alarm_id) {
            error_report("HEALTH [%s]: Got invalid alarm id. Ignoring it.", rrdhost_hostname(host));
            errored++;
            continue;
        }

        //need name and chart
        if (sqlite3_column_type(res, 12) == SQLITE_NULL) {
            error_report("HEALTH [%s]: Got null name field. Ignoring it.", rrdhost_hostname(host));
            errored++;
            continue;
        }

        if (sqlite3_column_type(res, 13) == SQLITE_NULL) {
            error_report("HEALTH [%s]: Got null chart field. Ignoring it.", rrdhost_hostname(host));
            errored++;
            continue;
        }

        // Check if we got last_repeat field
        time_t last_repeat = (time_t)sqlite3_column_int64(res, 25);

        rc = dictionary_get(all_rrdcalcs, (char *) sqlite3_column_text(res, 13));
        if(unlikely(rc)) {
            if (rrdcalc_isrepeating(rc)) {
                rc->last_repeat = last_repeat;
                // We iterate through repeating alarm entries only to
                // find the latest last_repeat timestamp. Otherwise,
                // there is no need to keep them in memory.
                continue;
            }
        }

        ae = callocz(1, sizeof(ALARM_ENTRY));

        ae->unique_id = unique_id;
        ae->alarm_id = alarm_id;

        if (sqlite3_column_type(res, 3) != SQLITE_NULL)
            uuid_copy(ae->config_hash_id, *((uuid_t *) sqlite3_column_blob(res, 3)));

        ae->alarm_event_id = (uint32_t) sqlite3_column_int64(res, 2);
        ae->updated_by_id = (uint32_t) sqlite3_column_int64(res, 4);
        ae->updates_id = (uint32_t) sqlite3_column_int64(res, 5);

        ae->when = (time_t) sqlite3_column_int64(res, 6);
        ae->duration = (time_t) sqlite3_column_int64(res, 7);
        ae->non_clear_duration = (time_t) sqlite3_column_int64(res, 8);

        ae->flags = (uint32_t) sqlite3_column_int64(res, 9);
        ae->flags |= HEALTH_ENTRY_FLAG_SAVED;

        ae->exec_run_timestamp = (time_t) sqlite3_column_int64(res, 10);
        ae->delay_up_to_timestamp = (time_t) sqlite3_column_int64(res, 11);

        ae->name   = string_strdupz((char *) sqlite3_column_text(res, 12));
        ae->chart  = string_strdupz((char *) sqlite3_column_text(res, 13));

        ae->exec = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 14);
        ae->recipient = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 15);
        ae->source = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 16);
        ae->units = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 17);
        ae->info = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 18);

        ae->exec_code   = (int) sqlite3_column_int(res, 19);
        ae->new_status  = (RRDCALC_STATUS) sqlite3_column_int(res, 20);
        ae->old_status  = (RRDCALC_STATUS)sqlite3_column_int(res, 21);
        ae->delay       = (int) sqlite3_column_int(res, 22);

        ae->new_value   = (NETDATA_DOUBLE) sqlite3_column_double(res, 23);
        ae->old_value   = (NETDATA_DOUBLE) sqlite3_column_double(res, 24);

        ae->last_repeat = last_repeat;

        ae->classification = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 26);
        ae->component = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 27);
        ae->type = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 28);
        ae->chart_context = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 29);

        if (sqlite3_column_type(res, 30) != SQLITE_NULL)
            uuid_copy(ae->transition_id, *((uuid_t *)sqlite3_column_blob(res, 30)));

        if (sqlite3_column_type(res, 31) != SQLITE_NULL)
            ae->global_id = sqlite3_column_int64(res, 31);

        ae->chart_name = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 32);
        ae->summary = SQLITE3_COLUMN_STRINGDUP_OR_NULL(res, 33);

        char value_string[100 + 1];
        string_freez(ae->old_value_string);
        string_freez(ae->new_value_string);
        ae->old_value_string = string_strdupz(format_value_and_unit(value_string, 100, ae->old_value, ae_units(ae), -1));
        ae->new_value_string = string_strdupz(format_value_and_unit(value_string, 100, ae->new_value, ae_units(ae), -1));

        ae->next = host->health_log.alarms;
        host->health_log.alarms = ae;

        if(unlikely(ae->unique_id > host->health_max_unique_id))
            host->health_max_unique_id = ae->unique_id;

        if(unlikely(ae->alarm_id >= host->health_max_alarm_id))
            host->health_max_alarm_id = ae->alarm_id;

        loaded++;
    }

    rw_spinlock_read_unlock(&host->health_log.spinlock);

    dictionary_destroy(all_rrdcalcs);
    all_rrdcalcs = NULL;

    if(!host->health_max_unique_id) host->health_max_unique_id = (uint32_t)now_realtime_sec();
    if(!host->health_max_alarm_id)  host->health_max_alarm_id  = (uint32_t)now_realtime_sec();

    host->health_log.next_log_id = host->health_max_unique_id + 1;
    if (unlikely(!host->health_log.next_alarm_id || host->health_log.next_alarm_id <= host->health_max_alarm_id))
        host->health_log.next_alarm_id = host->health_max_alarm_id + 1;

    nd_log(NDLS_DAEMON, errored ? NDLP_WARNING : NDLP_DEBUG,
           "[%s]: Table health_log, loaded %zd alarm entries, errors in %zd entries.",
           rrdhost_hostname(host), loaded, errored);

    ret = sqlite3_finalize(res);
    if (unlikely(ret != SQLITE_OK))
        error_report("Failed to finalize the health log read statement");
}

/*
 * Store an alert config hash in the database
 */
#define SQL_STORE_ALERT_CONFIG_HASH                                                                                     \
    "insert or replace into alert_hash (hash_id, date_updated, alarm, template, "                                       \
    "on_key, class, component, type, os, hosts, lookup, every, units, calc, plugin, module, "                           \
    "charts, green, red, warn, crit, exec, to_key, info, delay, options, repeat, host_labels, "                         \
    "p_db_lookup_dimensions, p_db_lookup_method, p_db_lookup_options, p_db_lookup_after, "                              \
    "p_db_lookup_before, p_update_every, source, chart_labels, summary) values (@hash_id,UNIXEPOCH(),@alarm,@template," \
    "@on_key,@class,@component,@type,@os,@hosts,@lookup,@every,@units,@calc,@plugin,@module,"                           \
    "@charts,@green,@red,@warn,@crit,@exec,@to_key,@info,@delay,@options,@repeat,@host_labels,"                         \
    "@p_db_lookup_dimensions,@p_db_lookup_method,@p_db_lookup_options,@p_db_lookup_after,"                              \
    "@p_db_lookup_before,@p_update_every,@source,@chart_labels,@summary)"

int sql_store_alert_config_hash(uuid_t *hash_id, struct alert_config *cfg)
{
    static __thread sqlite3_stmt *res = NULL;
    int rc, param = 0;

    if (unlikely(!db_meta)) {
        if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE)
            return 0;
        error_report("Database has not been initialized");
        return 1;
    }

    if (unlikely(!res)) {
        rc = prepare_statement(db_meta, SQL_STORE_ALERT_CONFIG_HASH, &res);
        if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to prepare statement to store alert configuration, rc = %d", rc);
            return 1;
        }
    }

    rc = sqlite3_bind_blob(res, ++param, hash_id, sizeof(*hash_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->alarm, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->template_key, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->on, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->classification, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->component, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->type, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->os, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->host, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->lookup, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->every, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->units, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->calc, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->plugin, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->module, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->charts, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->green, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->red, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->warn, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->crit, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->exec, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->to, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->info, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->delay, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->options, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->repeat, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->host_labels, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    if (cfg->p_db_lookup_after) {
        rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->p_db_lookup_dimensions, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->p_db_lookup_method, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_int(res, ++param, (int) cfg->p_db_lookup_options);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_int(res, ++param, (int) cfg->p_db_lookup_after);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_int(res, ++param, (int) cfg->p_db_lookup_before);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;
    } else {
        rc = sqlite3_bind_null(res, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_null(res, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_null(res, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_null(res, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;

        rc = sqlite3_bind_null(res, ++param);
        if (unlikely(rc != SQLITE_OK))
            goto bind_fail;
    }

    rc = sqlite3_bind_int(res, ++param, cfg->p_update_every);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->source, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->chart_labels, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = SQLITE3_BIND_STRING_OR_NULL(res, cfg->summary, ++param);
    if (unlikely(rc != SQLITE_OK))
        goto bind_fail;

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE))
        error_report("Failed to store alert config, rc = %d", rc);

    rc = sqlite3_reset(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to reset statement in alert hash_id store function, rc = %d", rc);

    return 0;

bind_fail:
    error_report("Failed to bind parameter %d to store alert hash_id, rc = %d", param, rc);
    rc = sqlite3_reset(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to reset statement in alert hash_id store function, rc = %d", rc);
    return 1;
}

/*
  alert hashes are used for cloud communication.
  if cloud is disabled or openssl is not available (which will prevent cloud connectivity)
  skip hash calculations
*/
#if defined ENABLE_HTTPS
#define DIGEST_ALERT_CONFIG_VAL(v) ((v) ? EVP_DigestUpdate(evpctx, (string2str(v)), string_strlen((v))) : EVP_DigestUpdate(evpctx, "", 1))
#endif
int alert_hash_and_store_config(
    uuid_t hash_id,
    struct alert_config *cfg,
    int store_hash)
{
#if defined ENABLE_HTTPS
    EVP_MD_CTX *evpctx;
    unsigned char hash_value[EVP_MAX_MD_SIZE];
    unsigned int hash_len;
    evpctx = EVP_MD_CTX_create();
    EVP_DigestInit_ex(evpctx, EVP_sha256(), NULL);

    DIGEST_ALERT_CONFIG_VAL(cfg->alarm);
    DIGEST_ALERT_CONFIG_VAL(cfg->template_key);
    DIGEST_ALERT_CONFIG_VAL(cfg->os);
    DIGEST_ALERT_CONFIG_VAL(cfg->host);
    DIGEST_ALERT_CONFIG_VAL(cfg->on);
    DIGEST_ALERT_CONFIG_VAL(cfg->plugin);
    DIGEST_ALERT_CONFIG_VAL(cfg->module);
    DIGEST_ALERT_CONFIG_VAL(cfg->charts);
    DIGEST_ALERT_CONFIG_VAL(cfg->lookup);
    DIGEST_ALERT_CONFIG_VAL(cfg->calc);
    DIGEST_ALERT_CONFIG_VAL(cfg->every);
    DIGEST_ALERT_CONFIG_VAL(cfg->green);
    DIGEST_ALERT_CONFIG_VAL(cfg->red);
    DIGEST_ALERT_CONFIG_VAL(cfg->warn);
    DIGEST_ALERT_CONFIG_VAL(cfg->crit);
    DIGEST_ALERT_CONFIG_VAL(cfg->exec);
    DIGEST_ALERT_CONFIG_VAL(cfg->to);
    DIGEST_ALERT_CONFIG_VAL(cfg->units);
    DIGEST_ALERT_CONFIG_VAL(cfg->info);
    DIGEST_ALERT_CONFIG_VAL(cfg->classification);
    DIGEST_ALERT_CONFIG_VAL(cfg->component);
    DIGEST_ALERT_CONFIG_VAL(cfg->type);
    DIGEST_ALERT_CONFIG_VAL(cfg->delay);
    DIGEST_ALERT_CONFIG_VAL(cfg->options);
    DIGEST_ALERT_CONFIG_VAL(cfg->repeat);
    DIGEST_ALERT_CONFIG_VAL(cfg->host_labels);
    DIGEST_ALERT_CONFIG_VAL(cfg->chart_labels);
    DIGEST_ALERT_CONFIG_VAL(cfg->summary);

    EVP_DigestFinal_ex(evpctx, hash_value, &hash_len);
    EVP_MD_CTX_destroy(evpctx);
    fatal_assert(hash_len > sizeof(uuid_t));

    char uuid_str[UUID_STR_LEN];
    uuid_unparse_lower(*((uuid_t *)&hash_value), uuid_str);
    uuid_copy(hash_id, *((uuid_t *)&hash_value));

    /* store everything, so it can be recreated when not in memory or just a subset ? */
    if (store_hash)
        (void)sql_store_alert_config_hash( (uuid_t *)&hash_value, cfg);
#else
    UNUSED(hash_id);
    UNUSED(cfg);
    UNUSED(store_hash);
#endif

    return 1;
}

#define SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT                                                                          \
    "SELECT hld.new_status FROM health_log hl, health_log_detail hld "                                                 \
    "WHERE hl.host_id = @host_id AND hl.alarm_id = @alarm_id AND hld.unique_id != @unique_id AND hld.flags & @flags "  \
    "AND hl.health_log_id = hld.health_log_id ORDER BY hld.unique_id DESC LIMIT 1"

int sql_health_get_last_executed_event(RRDHOST *host, ALARM_ENTRY *ae, RRDCALC_STATUS *last_executed_status)
{
    int rc = 0, ret = -1;
    sqlite3_stmt *res = NULL;

    rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to get last executed status");
        return ret;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT.");
        goto done;
    }

    rc = sqlite3_bind_int(res, 2, (int) ae->alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_id parameter for SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT.");
        goto done;
    }

    rc = sqlite3_bind_int(res, 3, (int) ae->unique_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT.");
        goto done;
    }

    rc = sqlite3_bind_int(res, 4, (uint32_t) HEALTH_ENTRY_FLAG_EXEC_RUN);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind unique_id parameter for SQL_SELECT_HEALTH_LAST_EXECUTED_EVENT.");
        goto done;
    }

    ret = 0;
    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        *last_executed_status  = (RRDCALC_STATUS) sqlite3_column_int(res, 0);
        ret = 1;
    }

done:
     rc = sqlite3_finalize(res);
     if (unlikely(rc != SQLITE_OK))
         error_report("Failed to finalize the statement.");

     return ret;
}

#define SQL_SELECT_HEALTH_LOG                                                                                          \
     "SELECT hld.unique_id, hld.alarm_id, hld.alarm_event_id, hl.config_hash_id, hld.updated_by_id, hld.updates_id, "  \
     "hld.when_key, hld.duration, hld.non_clear_duration, hld.flags, hld.exec_run_timestamp, "                         \
     "hld.delay_up_to_timestamp, hl.name, hl.chart, hl.exec, hl.recipient, ah.source, "                                \
     "hl.units, hld.info, hld.exec_code, hld.new_status, hld.old_status, hld.delay, hld.new_value, hld.old_value, "    \
     "hld.last_repeat, ah.class, ah.component, ah.type, hl.chart_context, hld.transition_id, hld.summary "             \
     "FROM health_log hl, alert_hash ah, health_log_detail hld WHERE hl.config_hash_id = ah.hash_id and "              \
     "hl.health_log_id = hld.health_log_id and hl.host_id = @host_id AND hld.unique_id > @after "

void sql_health_alarm_log2json(RRDHOST *host, BUFFER *wb, time_t after, const char *chart)
{
     unsigned int max = host->health_log.max;

     static __thread sqlite3_stmt *stmt_no_chart = NULL;
     static __thread sqlite3_stmt *stmt_with_chart = NULL;

     sqlite3_stmt **active_stmt;
     sqlite3_stmt *stmt_query;

     int rc;

     active_stmt = chart ? &stmt_with_chart : &stmt_no_chart;

     if (!*active_stmt) {

         BUFFER *command = buffer_create(MAX_HEALTH_SQL_SIZE, NULL);
         buffer_sprintf(command, SQL_SELECT_HEALTH_LOG);

         if (chart)
            buffer_strcat(command, " AND hl.chart = @chart ");

         buffer_strcat(command, " ORDER BY hld.unique_id DESC LIMIT @limit");

         rc = prepare_statement(db_meta, buffer_tostring(command), active_stmt);
         buffer_free(command);

         if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to prepare statement SQL_SELECT_HEALTH_LOG");
            return;
         }
     }

     stmt_query = *active_stmt;

     int param = 0;
     rc = sqlite3_bind_blob(stmt_query, ++param, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
     if (unlikely(rc != SQLITE_OK)) {
         error_report("Failed to bind host_id for SQL_SELECT_HEALTH_LOG.");
         goto finish;
     }

     rc = sqlite3_bind_int64(stmt_query, ++param, after);
     if (unlikely(rc != SQLITE_OK)) {
         error_report("Failed to bind after for SQL_SELECT_HEALTH_LOG.");
         goto finish;
     }

     if (chart) {
         rc = sqlite3_bind_text(stmt_query, ++param, chart, -1, SQLITE_STATIC);
         if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to bind after for SQL_SELECT_HEALTH_LOG.");
            goto finish;
         }
     }

     rc = sqlite3_bind_int64(stmt_query, ++param, max);
     if (unlikely(rc != SQLITE_OK)) {
         error_report("Failed to bind max lines for SQL_SELECT_HEALTH_LOG.");
         goto finish;
     }

     buffer_json_initialize(wb, "\"", "\"", 0, false, BUFFER_JSON_OPTIONS_DEFAULT);
     buffer_json_member_add_array(wb, NULL);

     while (sqlite3_step(stmt_query) == SQLITE_ROW) {
         char old_value_string[100 + 1];
         char new_value_string[100 + 1];

         char config_hash_id[UUID_STR_LEN];
         uuid_unparse_lower(*((uuid_t *)sqlite3_column_blob(stmt_query, 3)), config_hash_id);

         char transition_id[UUID_STR_LEN] = {0};
         if (sqlite3_column_type(stmt_query, 30) != SQLITE_NULL)
            uuid_unparse_lower(*((uuid_t *)sqlite3_column_blob(stmt_query, 30)), transition_id);

         char *edit_command = sqlite3_column_bytes(stmt_query, 16) > 0 ?
                                  health_edit_command_from_source((char *)sqlite3_column_text(stmt_query, 16)) :
                                  strdupz("UNKNOWN=0=UNKNOWN");

        buffer_json_add_array_item_object(wb); // this node

        buffer_json_member_add_string_or_empty(wb, "hostname",             rrdhost_hostname(host));
                  buffer_json_member_add_int64(wb, "utc_offset",           (int64_t)host->utc_offset);
        buffer_json_member_add_string_or_empty(wb, "timezone",             rrdhost_abbrev_timezone(host));
                  buffer_json_member_add_int64(wb, "unique_id",            (int64_t) sqlite3_column_int64(stmt_query, 0));
                  buffer_json_member_add_int64(wb, "alarm_id",             (int64_t) sqlite3_column_int64(stmt_query, 1));
                  buffer_json_member_add_int64(wb, "alarm_event_id",       (int64_t) sqlite3_column_int64(stmt_query, 2));
        buffer_json_member_add_string_or_empty(wb, "config_hash_id",       config_hash_id);
        buffer_json_member_add_string_or_empty(wb, "transition_id",        transition_id);
        buffer_json_member_add_string_or_empty(wb, "name",                 (const char *) sqlite3_column_text(stmt_query, 12));
        buffer_json_member_add_string_or_empty(wb, "chart",                (const char *) sqlite3_column_text(stmt_query, 13));
        buffer_json_member_add_string_or_empty(wb, "context",              (const char *) sqlite3_column_text(stmt_query, 29));
        buffer_json_member_add_string_or_empty(wb, "class",                sqlite3_column_text(stmt_query, 26) ? (const char *) sqlite3_column_text(stmt_query, 26) : (char *) "Unknown");
        buffer_json_member_add_string_or_empty(wb, "component",            sqlite3_column_text(stmt_query, 27) ? (const char *) sqlite3_column_text(stmt_query, 27) : (char *) "Unknown");
        buffer_json_member_add_string_or_empty(wb, "type",                 sqlite3_column_text(stmt_query, 28) ? (const char *) sqlite3_column_text(stmt_query, 28) : (char *) "Unknown");
                buffer_json_member_add_boolean(wb, "processed",            (sqlite3_column_int64(stmt_query, 9) & HEALTH_ENTRY_FLAG_PROCESSED));
                buffer_json_member_add_boolean(wb, "updated",              (sqlite3_column_int64(stmt_query, 9) & HEALTH_ENTRY_FLAG_UPDATED));
                  buffer_json_member_add_int64(wb, "exec_run",             (int64_t)sqlite3_column_int64(stmt_query, 10));
                buffer_json_member_add_boolean(wb, "exec_failed",          (sqlite3_column_int64(stmt_query, 9) & HEALTH_ENTRY_FLAG_EXEC_FAILED));
        buffer_json_member_add_string_or_empty(wb, "exec",                 sqlite3_column_text(stmt_query, 14) ? (const char *) sqlite3_column_text(stmt_query, 14) : string2str(host->health.health_default_exec));
        buffer_json_member_add_string_or_empty(wb, "recipient",            sqlite3_column_text(stmt_query, 15) ? (const char *) sqlite3_column_text(stmt_query, 15) : string2str(host->health.health_default_recipient));
                  buffer_json_member_add_int64(wb, "exec_code",            sqlite3_column_int(stmt_query, 19));
        buffer_json_member_add_string_or_empty(wb, "source",               sqlite3_column_text(stmt_query, 16) ? (const char *) sqlite3_column_text(stmt_query, 16) : (char *) "Unknown");
        buffer_json_member_add_string_or_empty(wb, "command",              edit_command);
        buffer_json_member_add_string_or_empty(wb, "units",                (const char *) sqlite3_column_text(stmt_query, 17));
                  buffer_json_member_add_int64(wb, "when",                 (int64_t)sqlite3_column_int64(stmt_query, 6));
                  buffer_json_member_add_int64(wb, "duration",             (int64_t)sqlite3_column_int64(stmt_query, 7));
                  buffer_json_member_add_int64(wb, "non_clear_duration",   (int64_t)sqlite3_column_int64(stmt_query, 8));
        buffer_json_member_add_string_or_empty(wb, "status",               rrdcalc_status2string(sqlite3_column_int(stmt_query, 20)));
        buffer_json_member_add_string_or_empty(wb, "old_status",           rrdcalc_status2string(sqlite3_column_int(stmt_query, 21)));
                  buffer_json_member_add_int64(wb, "delay",                sqlite3_column_int(stmt_query, 22));
                  buffer_json_member_add_int64(wb, "delay_up_to_timestamp",(int64_t)sqlite3_column_int64(stmt_query, 11));
                  buffer_json_member_add_int64(wb, "updated_by_id",        (unsigned int)sqlite3_column_int64(stmt_query, 4));
                  buffer_json_member_add_int64(wb, "updates_id",           (unsigned int)sqlite3_column_int64(stmt_query, 5));
        buffer_json_member_add_string_or_empty(wb, "value_string",         sqlite3_column_type(stmt_query, 23) == SQLITE_NULL ? "-" :
                                                                                      format_value_and_unit(new_value_string, 100, sqlite3_column_double(stmt_query, 23), (char *) sqlite3_column_text(stmt_query, 17), -1));
        buffer_json_member_add_string_or_empty(wb, "old_value_string",     sqlite3_column_type(stmt_query, 24) == SQLITE_NULL ? "-" :
                                                                                      format_value_and_unit(old_value_string, 100, sqlite3_column_double(stmt_query, 24), (char *) sqlite3_column_text(stmt_query, 17), -1));
                  buffer_json_member_add_int64(wb, "last_repeat",          (int64_t)sqlite3_column_int64(stmt_query, 25));
                buffer_json_member_add_boolean(wb, "silenced",             (sqlite3_column_int64(stmt_query, 9) & HEALTH_ENTRY_FLAG_SILENCED));
        buffer_json_member_add_string_or_empty(wb, "summary",              (const char *) sqlite3_column_text(stmt_query, 31));
        buffer_json_member_add_string_or_empty(wb, "info",                 (const char *) sqlite3_column_text(stmt_query, 18));
                buffer_json_member_add_boolean(wb, "no_clear_notification",(sqlite3_column_int64(stmt_query, 9) & HEALTH_ENTRY_FLAG_NO_CLEAR_NOTIFICATION));

        if (sqlite3_column_type(stmt_query, 23) == SQLITE_NULL)
            buffer_json_member_add_string(wb, "value", NULL);
        else
            buffer_json_member_add_double(wb, "value", sqlite3_column_double(stmt_query, 23));

        if (sqlite3_column_type(stmt_query, 24) == SQLITE_NULL)
            buffer_json_member_add_string(wb, "old_value", NULL);
        else
            buffer_json_member_add_double(wb, "old_value", sqlite3_column_double(stmt_query, 23));

        freez(edit_command);

        buffer_json_object_close(wb);
    }

    buffer_json_array_close(wb);
    buffer_json_finalize(wb);

finish:
     rc = sqlite3_reset(stmt_query);
     if (unlikely(rc != SQLITE_OK))
         error_report("Failed to reset statement for SQL_SELECT_HEALTH_LOG");
}

#define SQL_COPY_HEALTH_LOG(table) "INSERT OR IGNORE INTO health_log (host_id, alarm_id, config_hash_id, name, chart, family, exec, recipient, units, chart_context) SELECT ?1, alarm_id, config_hash_id, name, chart, family, exec, recipient, units, chart_context from %s", table
#define SQL_COPY_HEALTH_LOG_DETAIL(table) "INSERT INTO health_log_detail (unique_id, alarm_id, alarm_event_id, updated_by_id, updates_id, when_key, duration, non_clear_duration, flags, exec_run_timestamp, delay_up_to_timestamp, info, exec_code, new_status, old_status, delay, new_value, old_value, last_repeat, transition_id, global_id, host_id) SELECT unique_id, alarm_id, alarm_event_id, updated_by_id, updates_id, when_key, duration, non_clear_duration, flags, exec_run_timestamp, delay_up_to_timestamp, info, exec_code, new_status, old_status, delay, new_value, old_value, last_repeat, transition_id, now_usec(1), ?1 from %s", table
#define SQL_UPDATE_HEALTH_LOG_DETAIL_TRANSITION_ID "update health_log_detail set transition_id = uuid_random() where transition_id is null"
#define SQL_UPDATE_HEALTH_LOG_DETAIL_HEALTH_LOG_ID "update health_log_detail set health_log_id = (select health_log_id from health_log where host_id = ?1 and alarm_id = health_log_detail.alarm_id) where health_log_id is null and host_id = ?2"
#define SQL_UPDATE_HEALTH_LOG_LAST_TRANSITION_ID "update health_log set last_transition_id = (select transition_id from health_log_detail where health_log_id = health_log.health_log_id and alarm_id = health_log.alarm_id group by (alarm_id) having max(alarm_event_id)) where host_id = ?1"
int health_migrate_old_health_log_table(char *table) {
    if (!table)
        return 0;

    //table should contain guid. We need to
    //keep it in the new table along with it's data
    //health_log_XXXXXXXX_XXXX_XXXX_XXXX_XXXXXXXXXXXX
    if (strnlen(table, 46) != 46) {
        return 0;
    }

    char *uuid_from_table = strdupz(table + 11);
    uuid_t uuid;
    if (uuid_parse_fix(uuid_from_table, uuid)) {
        freez(uuid_from_table);
        return 0;
    }

    int rc;
    char command[MAX_HEALTH_SQL_SIZE + 1];
    sqlite3_stmt *res = NULL;
    snprintfz(command, sizeof(command) - 1, SQL_COPY_HEALTH_LOG(table));
    rc = sqlite3_prepare_v2(db_meta, command, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to copy health log, rc = %d", rc);
        freez(uuid_from_table);
        return 0;
    }

    rc = sqlite3_bind_blob(res, 1, &uuid, sizeof(uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to copy health log table, rc = %d", rc);
        freez(uuid_from_table);
        return 0;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("Failed to execute SQL_COPY_HEALTH_LOG, rc = %d", rc);
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to copy health log table, rc = %d", rc);
        freez(uuid_from_table);
    }

    //detail
    snprintfz(command, sizeof(command) - 1, SQL_COPY_HEALTH_LOG_DETAIL(table));
    rc = sqlite3_prepare_v2(db_meta, command, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to copy health log detail, rc = %d", rc);
        return 0;
    }

    rc = sqlite3_bind_blob(res, 1, &uuid, sizeof(uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to copy health log detail, rc = %d", rc);
        return 0;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("Failed to execute SQL_COPY_HEALTH_LOG_DETAIL, rc = %d", rc);
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to copy health log detail table, rc = %d", rc);
        return 0;
    }

    //update transition ids
    rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_HEALTH_LOG_DETAIL_TRANSITION_ID, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to update health log detail with transition ids, rc = %d", rc);
        return 0;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("Failed to execute SQL_UPDATE_HEALTH_LOG_DETAIL_TRANSITION_ID, rc = %d", rc);
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log detail table with transition ids, rc = %d", rc);
        return 0;
    }

    //update health_log_id
    rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_HEALTH_LOG_DETAIL_HEALTH_LOG_ID, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to update health log detail with health log ids, rc = %d", rc);
        return 0;
    }

    rc = sqlite3_bind_blob(res, 1, &uuid, sizeof(uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log detail with health log ids, rc = %d", rc);
        return 0;
    }

    rc = sqlite3_bind_blob(res, 2, &uuid, sizeof(uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log detail with health log ids, rc = %d", rc);
        return 0;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("Failed to execute SQL_UPDATE_HEALTH_LOG_DETAIL_HEALTH_LOG_ID, rc = %d", rc);
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log detail table with health log ids, rc = %d", rc);
    }

    //update last transition id
    rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_HEALTH_LOG_LAST_TRANSITION_ID, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to update health log  with last transition id, rc = %d", rc);
        return 0;
    }

    rc = sqlite3_bind_blob(res, 1, &uuid, sizeof(uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log with last transition id, rc = %d", rc);
        return 0;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE)) {
        error_report("Failed to execute SQL_UPDATE_HEALTH_LOG_LAST_TRANSITION_ID, rc = %d", rc);
        rc = sqlite3_finalize(res);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to reset statement to update health log table with last transition id, rc = %d", rc);
    }

    return 1;
}

#define SQL_GET_EVENT_ID                                                                                               \
    "SELECT MAX(alarm_event_id)+1 FROM health_log_detail WHERE health_log_id = @health_log_id AND alarm_id = @alarm_id"

static uint32_t get_next_alarm_event_id(uint64_t health_log_id, uint32_t alarm_id)
{
    int rc;
    sqlite3_stmt *res = NULL;
    uint32_t next_event_id = 0;

    rc = sqlite3_prepare_v2(db_meta, SQL_GET_EVENT_ID, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to get an event id");
        return alarm_id;
    }

    rc = sqlite3_bind_int64(res, 1, (sqlite3_int64) health_log_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_GET_EVENT_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = sqlite3_bind_int64(res, 2, (sqlite3_int64) alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind char parameter for SQL_GET_EVENT_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        next_event_id = (uint32_t) sqlite3_column_int64(res, 0);
    }

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to finalize the statement while getting an alarm id.");

    return next_event_id;
}

#define SQL_GET_ALARM_ID                                                                                               \
    "SELECT alarm_id, health_log_id FROM health_log WHERE host_id = @host_id AND chart = @chart "                      \
    "AND name = @name AND config_hash_id = @config_hash_id"

uint32_t sql_get_alarm_id(RRDHOST *host, STRING *chart, STRING *name, uint32_t *next_event_id, uuid_t *config_hash_id)
{
    int rc = 0;
    sqlite3_stmt *res = NULL;
    uint32_t alarm_id = 0;
    uint64_t health_log_id = 0;

    rc = sqlite3_prepare_v2(db_meta, SQL_GET_ALARM_ID, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to get an alarm id");
        return alarm_id;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_GET_ALARM_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, chart, 2);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind char parameter for SQL_GET_ALARM_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, name, 3);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind name parameter for SQL_GET_ALARM_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = sqlite3_bind_blob(res, 4, config_hash_id, sizeof(*config_hash_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind config_hash_id parameter for SQL_GET_ALARM_ID.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        alarm_id = (uint32_t) sqlite3_column_int64(res, 0);
        health_log_id = (uint64_t) sqlite3_column_int64(res, 1);
    }

     rc = sqlite3_finalize(res);
     if (unlikely(rc != SQLITE_OK))
         error_report("Failed to finalize the statement while getting an alarm id.");

     if (alarm_id)
           *next_event_id = get_next_alarm_event_id(health_log_id, alarm_id);

     return alarm_id;
}

#define SQL_UPDATE_ALARM_ID_WITH_CONFIG_HASH                                                                           \
     "UPDATE health_log SET config_hash_id = @config_hash_id WHERE host_id = @host_id AND alarm_id = @alarm_id "       \
     "AND health_log_id = @health_log_id"

void sql_update_alarm_with_config_hash(RRDHOST *host, uint32_t alarm_id, uint64_t health_log_id, uuid_t *config_hash_id)
{
    int rc = 0;
    sqlite3_stmt *res = NULL;

    rc = sqlite3_prepare_v2(db_meta, SQL_UPDATE_ALARM_ID_WITH_CONFIG_HASH, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to update an alarm id with a config hash.");
        return;
    }

    rc = sqlite3_bind_blob(res, 1, config_hash_id, sizeof(*config_hash_id), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind config_hash_id parameter for SQL_UPDATE_ALARM_ID_WITH_CONFIG_HASH.");
        goto done;
    }

    rc = sqlite3_bind_blob(res, 2, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_UPDATE_ALARM_ID_WITH_CONFIG_HASH.");
        goto done;
    }

    rc = sqlite3_bind_int64(res, 3, (sqlite3_int64) alarm_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_id parameter for SQL_GET_ALARM_ID.");
        goto done;
    }

    rc = sqlite3_bind_int64(res, 4, (sqlite3_int64) health_log_id);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind alarm_id parameter for SQL_GET_ALARM_ID.");
        goto done;
    }

    rc = execute_insert(res);
    if (unlikely(rc != SQLITE_DONE))
        error_report("Failed to execute SQL_UPDATE_ALARM_ID_WITH_CONFIG_HASH, rc = %d", rc);

done:
     rc = sqlite3_finalize(res);
     if (unlikely(rc != SQLITE_OK))
        error_report("Failed to reset statement to update health log detail table with config hash ids, rc = %d", rc);

}

#define SQL_GET_ALARM_ID_CHECK_ZERO_HASH                                                                               \
     "SELECT alarm_id, health_log_id FROM health_log WHERE host_id = @host_id AND chart = @chart "                     \
     "AND name = @name AND (config_hash_id IS NULL OR config_hash_id = ZEROBLOB(16))"

uint32_t sql_get_alarm_id_check_zero_hash(RRDHOST *host, STRING *chart, STRING *name, uint32_t *next_event_id, uuid_t *config_hash_id)
{
    int rc = 0;
    sqlite3_stmt *res = NULL;
    uint32_t alarm_id = 0;
    uint64_t health_log_id = 0;

    rc = sqlite3_prepare_v2(db_meta, SQL_GET_ALARM_ID_CHECK_ZERO_HASH, -1, &res, 0);
    if (rc != SQLITE_OK) {
        error_report("Failed to prepare statement when trying to get an alarm id with zero hash");
        return alarm_id;
    }

    rc = sqlite3_bind_blob(res, 1, &host->host_uuid, sizeof(host->host_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind host_id parameter for SQL_GET_ALARM_ID_CHECK_ZERO_HASH.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, chart, 2);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind char parameter for SQL_GET_ALARM_ID_CHECK_ZERO_HASH.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    rc = SQLITE3_BIND_STRING_OR_NULL(res, name, 3);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind name parameter for SQL_GET_ALARM_ID_CHECK_ZERO_HASH.");
        sqlite3_finalize(res);
        return alarm_id;
    }

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        alarm_id = (uint32_t) sqlite3_column_int64(res, 0);
        health_log_id = (uint64_t) sqlite3_column_int64(res, 1);
    }

     rc = sqlite3_finalize(res);
     if (unlikely(rc != SQLITE_OK))
         error_report("Failed to finalize the statement while getting an alarm id.");

     if (alarm_id) {
         sql_update_alarm_with_config_hash(host, alarm_id, health_log_id, config_hash_id);
         *next_event_id = get_next_alarm_event_id(health_log_id, alarm_id);
     }

     return alarm_id;
}

#define SQL_GET_ALARM_ID_FROM_TRANSITION_ID                                                                            \
     "SELECT hld.alarm_id, hl.host_id, hl.chart_context FROM health_log_detail hld, health_log hl "                    \
     "WHERE hld.transition_id = @transition_id "                                                                       \
     "AND hld.health_log_id = hl.health_log_id"

bool sql_find_alert_transition(
    const char *transition,
    void (*cb)(const char *machine_guid, const char *context, time_t alert_id, void *data),
    void *data)
{
    static __thread sqlite3_stmt *res = NULL;

    char machine_guid[UUID_STR_LEN];

    int rc;
    uuid_t transition_uuid;
    if (uuid_parse(transition, transition_uuid))
        return false;

    if (unlikely(!res)) {
        rc = prepare_statement(db_meta, SQL_GET_ALARM_ID_FROM_TRANSITION_ID, &res);
        if (unlikely(rc != SQLITE_OK)) {
             error_report("Failed to prepare statement when trying to get transition id");
             return false;
        }
    }

    bool ok = false;

    rc = sqlite3_bind_blob(res, 1, &transition_uuid, sizeof(transition_uuid), SQLITE_STATIC);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind transition");
        goto done;
    }

    while (sqlite3_step_monitored(res) == SQLITE_ROW) {
        ok = true;
        uuid_unparse_lower(*(uuid_t *) sqlite3_column_blob(res, 1), machine_guid);
        cb(machine_guid, (const char *) sqlite3_column_text(res, 2), sqlite3_column_int(res, 0), data);
    }

done:
    rc = sqlite3_reset(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to reset the statement when trying to find transition");

    return ok;
}

#define SQL_BUILD_ALERT_TRANSITION "CREATE TEMP TABLE IF NOT EXISTS v_%p (host_id blob)"

#define SQL_POPULATE_TEMP_ALERT_TRANSITION_TABLE "INSERT INTO v_%p (host_id) VALUES (@host_id)"

#define SQL_SEARCH_ALERT_TRANSITION_SELECT                                                                                    \
    "SELECT h.host_id, h.alarm_id, h.config_hash_id, h.name, h.chart, h.chart_name, h.family, h.recipient, h.units, h.exec, " \
    "h.chart_context,  d.when_key, d.duration, d.non_clear_duration, d.flags, d.delay_up_to_timestamp, "                      \
    "d.info, d.exec_code, d.new_status, d.old_status, d.delay, d.new_value, d.old_value, d.last_repeat, "                     \
    "d.transition_id, d.global_id, ah.class, ah.type, ah.component, d.exec_run_timestamp, d.summary"

#define SQL_SEARCH_ALERT_TRANSITION_COMMON_WHERE "h.config_hash_id = ah.hash_id AND h.health_log_id = d.health_log_id"

#define SQL_SEARCH_ALERT_TRANSITION                                                                                    \
    SQL_SEARCH_ALERT_TRANSITION_SELECT                                                                                 \
        " FROM health_log h, health_log_detail d, v_%p t, alert_hash ah "                                              \
        " WHERE h.host_id = t.host_id AND " SQL_SEARCH_ALERT_TRANSITION_COMMON_WHERE                                   \
        " AND ( d.new_status > 2 OR d.old_status > 2 ) AND d.global_id BETWEEN @after AND @before "

#define SQL_SEARCH_ALERT_TRANSITION_DIRECT                                                                             \
    SQL_SEARCH_ALERT_TRANSITION_SELECT " FROM health_log h, health_log_detail d, alert_hash ah "                       \
                                       " WHERE " SQL_SEARCH_ALERT_TRANSITION_COMMON_WHERE                              \
                                       " AND transition_id = @transition "

void sql_alert_transitions(
    DICTIONARY *nodes,
    time_t after,
    time_t before,
    const char *context,
    const char *alert_name,
    const char *transition,
    void (*cb)(struct sql_alert_transition_data *, void *),
    void *data,
    bool debug __maybe_unused)
{
    uuid_t transition_uuid;
    char sql[512];
    int rc;
    sqlite3_stmt *res = NULL;
    BUFFER *command = NULL;

    if (unlikely(!nodes))
        return;

    if (transition) {
        if (uuid_parse(transition, transition_uuid)) {
            error_report("Invalid transition given %s", transition);
            return;
        }

        rc = sqlite3_prepare_v2(db_meta, SQL_SEARCH_ALERT_TRANSITION_DIRECT, -1, &res, 0);

        rc = sqlite3_bind_blob(res, 1, &transition_uuid, sizeof(transition_uuid), SQLITE_STATIC);
        if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to bind transition_id parameter");
            goto done;
        }
        goto run_query;
    }

    snprintfz(sql, sizeof(sql) - 1, SQL_BUILD_ALERT_TRANSITION, nodes);
    rc = db_execute(db_meta, sql);
    if (rc)
        return;

    snprintfz(sql, sizeof(sql) - 1, SQL_POPULATE_TEMP_ALERT_TRANSITION_TABLE, nodes);

    // Prepare statement to add things
    rc = sqlite3_prepare_v2(db_meta, sql, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to INSERT into v_%p", nodes);
        goto done_only_drop;
    }

    void *t;
    dfe_start_read(nodes, t) {
        uuid_t host_uuid;
        uuid_parse( t_dfe.name, host_uuid);

        rc = sqlite3_bind_blob(res, 1, &host_uuid, sizeof(host_uuid), SQLITE_STATIC);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to bind host_id parameter.");

        rc = sqlite3_step_monitored(res);
        if (rc != SQLITE_DONE)
            error_report("Error while populating temp table");

        rc = sqlite3_reset(res);
        if (rc != SQLITE_OK)
            error_report("Error while resetting parameters");
    }
    dfe_done(t);

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK)) {
        // log error but continue
        error_report("Failed to finalize statement for sql_alert_transitions temp table population");
    }

    command = buffer_create(MAX_HEALTH_SQL_SIZE, NULL);

    buffer_sprintf(command, SQL_SEARCH_ALERT_TRANSITION, nodes);

    if (context)
        buffer_sprintf(command, " AND h.chart_context = @context");

    if (alert_name)
        buffer_sprintf(command, " AND h.name = @alert_name");

    buffer_strcat(command, " ORDER BY d.global_id DESC");

    rc = sqlite3_prepare_v2(db_meta, buffer_tostring(command), -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement sql_alert_transitions");
        goto done_only_drop;
    }

    int param = 1;
    rc = sqlite3_bind_int64(res, param++, (sqlite3_int64)(after * USEC_PER_SEC));
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind after parameter");
        goto done;
    }

    rc = sqlite3_bind_int64(res, param++, (sqlite3_int64)(before * USEC_PER_SEC));
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to bind before parameter");
        goto done;
    }

    if (context) {
        rc = sqlite3_bind_text(res, param++, context, -1, SQLITE_STATIC);
        if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to bind context parameter");
            goto done;
        }
    }

    if (alert_name) {
        rc = sqlite3_bind_text(res, param++, alert_name, -1, SQLITE_STATIC);
        if (unlikely(rc != SQLITE_OK)) {
            error_report("Failed to bind alert_name parameter");
            goto done;
        }
    }

run_query:;

    struct sql_alert_transition_data atd = {0 };

    while (sqlite3_step(res) == SQLITE_ROW) {
        atd.host_id = (uuid_t *) sqlite3_column_blob(res, 0);
        atd.alarm_id = sqlite3_column_int64(res, 1);
        atd.config_hash_id = (uuid_t *)sqlite3_column_blob(res, 2);
        atd.alert_name = (const char *) sqlite3_column_text(res, 3);
        atd.chart = (const char *) sqlite3_column_text(res, 4);
        atd.chart_name = (const char *) sqlite3_column_text(res, 5);
        atd.family = (const char *) sqlite3_column_text(res, 6);
        atd.recipient = (const char *) sqlite3_column_text(res, 7);
        atd.units = (const char *) sqlite3_column_text(res, 8);
        atd.exec = (const char *) sqlite3_column_text(res, 9);
        atd.chart_context = (const char *) sqlite3_column_text(res, 10);
        atd.when_key = sqlite3_column_int64(res, 11);
        atd.duration = sqlite3_column_int64(res, 12);
        atd.non_clear_duration = sqlite3_column_int64(res, 13);
        atd.flags = sqlite3_column_int64(res, 14);
        atd.delay_up_to_timestamp = sqlite3_column_int64(res, 15);
        atd.info = (const char *) sqlite3_column_text(res, 16);
        atd.exec_code = sqlite3_column_int(res, 17);
        atd.new_status = sqlite3_column_int(res, 18);
        atd.old_status = sqlite3_column_int(res, 19);
        atd.delay = (int) sqlite3_column_int(res, 20);
        atd.new_value = (NETDATA_DOUBLE) sqlite3_column_double(res, 21);
        atd.old_value = (NETDATA_DOUBLE) sqlite3_column_double(res, 22);
        atd.last_repeat = sqlite3_column_int64(res, 23);
        atd.transition_id = (uuid_t *) sqlite3_column_blob(res, 24);
        atd.global_id = sqlite3_column_int64(res, 25);
        atd.classification = (const char *) sqlite3_column_text(res, 26);
        atd.type = (const char *) sqlite3_column_text(res, 27);
        atd.component = (const char *) sqlite3_column_text(res, 28);
        atd.exec_run_timestamp = sqlite3_column_int64(res, 29);
        atd.summary = (const char *) sqlite3_column_text(res, 30);

        cb(&atd, data);
    }

done:
    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to finalize statement for sql_alert_transitions");

done_only_drop:
    if (likely(!transition)) {
        (void)snprintfz(sql, sizeof(sql) - 1, "DROP TABLE IF EXISTS v_%p", nodes);
        (void)db_execute(db_meta, sql);
        buffer_free(command);
    }
}

#define SQL_BUILD_CONFIG_TARGET_LIST "CREATE TEMP TABLE IF NOT EXISTS c_%p (hash_id blob)"

#define SQL_POPULATE_TEMP_CONFIG_TARGET_TABLE "INSERT INTO c_%p (hash_id) VALUES (@hash_id)"

#define SQL_SEARCH_CONFIG_LIST                                                                                         \
    "SELECT ah.hash_id, alarm, template, on_key, class, component, type, os, hosts, lookup, every, "                   \
    " units, calc, families, plugin, module, charts, green, red, warn, crit, "                                         \
    " exec, to_key, info, delay, options, repeat, host_labels, p_db_lookup_dimensions, p_db_lookup_method, "           \
    " p_db_lookup_options, p_db_lookup_after, p_db_lookup_before, p_update_every, source, chart_labels, summary "      \
    " FROM alert_hash ah, c_%p t where ah.hash_id = t.hash_id"

int sql_get_alert_configuration(
    DICTIONARY *configs,
    void (*cb)(struct sql_alert_config_data *, void *),
    void *data,
    bool debug __maybe_unused)
{
    int added = -1;
    char sql[512];
    int rc;
    sqlite3_stmt *res = NULL;
    BUFFER *command = NULL;

    if (unlikely(!configs))
        return added;

    snprintfz(sql, sizeof(sql) - 1, SQL_BUILD_CONFIG_TARGET_LIST, configs);
    rc = db_execute(db_meta, sql);
    if (rc)
        return added;

    snprintfz(sql, sizeof(sql) - 1, SQL_POPULATE_TEMP_CONFIG_TARGET_TABLE, configs);

    // Prepare statement to add things
    rc = sqlite3_prepare_v2(db_meta, sql, -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement to INSERT into c_%p", configs);
        goto fail_only_drop;
    }

    void *t;
    dfe_start_read(configs, t) {
        uuid_t hash_id;
        uuid_parse( t_dfe.name, hash_id);

        rc = sqlite3_bind_blob(res, 1, &hash_id, sizeof(hash_id), SQLITE_STATIC);
        if (unlikely(rc != SQLITE_OK))
            error_report("Failed to bind host_id parameter.");

        rc = sqlite3_step_monitored(res);
        if (rc != SQLITE_DONE)
            error_report("Error while populating temp table");

        rc = sqlite3_reset(res);
        if (rc != SQLITE_OK)
            error_report("Error while resetting parameters");
    }
    dfe_done(t);

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK)) {
        // log error but continue
        error_report("Failed to finalize statement for sql_get_alert_configuration temp table population");
    }

    command = buffer_create(MAX_HEALTH_SQL_SIZE, NULL);

    buffer_sprintf(command, SQL_SEARCH_CONFIG_LIST, configs);

    rc = sqlite3_prepare_v2(db_meta, buffer_tostring(command), -1, &res, 0);
    if (unlikely(rc != SQLITE_OK)) {
        error_report("Failed to prepare statement sql_get_alert_configuration");
        goto fail_only_drop;
    }

    struct sql_alert_config_data acd = {0 };

    added = 0;
    int param;
    while (sqlite3_step(res) == SQLITE_ROW) {
        param = 0;
        acd.config_hash_id = (uuid_t *) sqlite3_column_blob(res, param++);
        acd.name = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.on_template = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.on_key = (const char *) sqlite3_column_text(res, param++);
        acd.classification = (const char *) sqlite3_column_text(res, param++);
        acd.component = (const char *) sqlite3_column_text(res, param++);
        acd.type = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.os = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.hosts = (const char *) sqlite3_column_text(res, param++);
        acd.value.db.lookup = (const char *) sqlite3_column_text(res, param++);
        acd.value.every = (const char *) sqlite3_column_text(res, param++);
        acd.value.units = (const char *) sqlite3_column_text(res, param++);
        acd.value.calc = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.families = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.plugin = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.module = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.charts = (const char *) sqlite3_column_text(res, param++);
        acd.status.green = (const char *) sqlite3_column_text(res, param++);
        acd.status.red = (const char *) sqlite3_column_text(res, param++);
        acd.status.warn = (const char *) sqlite3_column_text(res, param++);
        acd.status.crit = (const char *) sqlite3_column_text(res, param++);
        acd.notification.exec = (const char *) sqlite3_column_text(res, param++);
        acd.notification.to_key = (const char *) sqlite3_column_text(res, param++);
        acd.info = (const char *) sqlite3_column_text(res, param++);
        acd.notification.delay = (const char *) sqlite3_column_text(res, param++);
        acd.notification.options = (const char *) sqlite3_column_text(res, param++);
        acd.notification.repeat = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.host_labels = (const char *) sqlite3_column_text(res, param++);
        acd.value.db.dimensions = (const char *) sqlite3_column_text(res, param++);
        acd.value.db.method = (const char *) sqlite3_column_text(res, param++);
        acd.value.db.options = (uint32_t) sqlite3_column_int(res, param++);
        acd.value.db.after = (int32_t) sqlite3_column_int(res, param++);
        acd.value.db.before = (int32_t) sqlite3_column_int(res, param++);
        acd.value.update_every = (int32_t) sqlite3_column_int(res, param++);
        acd.source = (const char *) sqlite3_column_text(res, param++);
        acd.selectors.chart_labels = (const char *) sqlite3_column_text(res, param++);
        acd.summary = (const char *) sqlite3_column_text(res, param++);

        cb(&acd, data);
        added++;
    }

    rc = sqlite3_finalize(res);
    if (unlikely(rc != SQLITE_OK))
        error_report("Failed to finalize statement for sql_get_alert_configuration");

fail_only_drop:
    (void)snprintfz(sql, sizeof(sql) - 1, "DROP TABLE IF EXISTS c_%p", configs);
    (void)db_execute(db_meta, sql);
    buffer_free(command);
    return added;
}