aboutsummaryrefslogtreecommitdiffstats
path: root/mdbc-server/src/main/java/org/onap/music/mdbc/mixins/MusicMixin.java
blob: e87f7e485c8cf2ec233f72dc098a2a9b1db573fc (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
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
/*
 * ============LICENSE_START====================================================
 * org.onap.music.mdbc
 * =============================================================================
 * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
 * =============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END======================================================
 */
package org.onap.music.mdbc.mixins;

import java.io.IOException;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.*;

import com.datastax.driver.core.*;
import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONObject;
import org.onap.music.datastore.Condition;
import org.onap.music.datastore.MusicDataStore;
import org.onap.music.datastore.MusicDataStoreHandle;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.exceptions.MDBCServiceException;
import org.onap.music.exceptions.MusicLockingException;
import org.onap.music.exceptions.MusicQueryException;
import org.onap.music.exceptions.MusicServiceException;
import org.onap.music.logging.EELFLoggerDelegate;
import org.onap.music.main.MusicCore;
import org.onap.music.main.ResultType;
import org.onap.music.main.ReturnType;
import org.onap.music.mdbc.DatabasePartition;
import org.onap.music.mdbc.MDBCUtils;
import org.onap.music.mdbc.Range;
import org.onap.music.mdbc.StateManager;
import org.onap.music.mdbc.TableInfo;
import org.onap.music.mdbc.ownership.Dag;
import org.onap.music.mdbc.ownership.DagNode;
import org.onap.music.mdbc.query.SQLOperationType;
import org.onap.music.mdbc.tables.MriReference;
import org.onap.music.mdbc.tables.MusicRangeInformationRow;
import org.onap.music.mdbc.tables.MusicTxDigestId;
import org.onap.music.mdbc.tables.RangeDependency;
import org.onap.music.mdbc.tables.StagingTable;
import org.onap.music.mdbc.tables.TxCommitProgress;

/**
 * This class provides the methods that MDBC needs to access Cassandra directly in order to provide persistence
 * to calls to the user's DB.  It does not do any table or row locking.
 *
 * <p>This code only supports the following limited list of H2 and Cassandra data types:</p>
 * <table summary="">
 * <tr><th>H2 Data Type</th><th>Mapped to Cassandra Data Type</th></tr>
 * <tr><td>BIGINT</td><td>BIGINT</td></tr>
 * <tr><td>BOOLEAN</td><td>BOOLEAN</td></tr>
 * <tr><td>CLOB</td><td>BLOB</td></tr>
 * <tr><td>DOUBLE</td><td>DOUBLE</td></tr>
 * <tr><td>INTEGER</td><td>INT</td></tr>
 *  <tr><td>TIMESTAMP</td><td>TIMESTAMP</td></tr>
 * <tr><td>VARBINARY</td><td>BLOB</td></tr>
 * <tr><td>VARCHAR</td><td>VARCHAR</td></tr>
 * </table>
 *
 * @author Robert P. Eby
 */
public class MusicMixin implements MusicInterface {
    /** The property name to use to identify this replica to MusicSqlManager */
    public static final String KEY_MY_ID              = "myid";
    /** The property name to use for the comma-separated list of replica IDs. */
    public static final String KEY_REPLICAS           = "replica_ids";
    /** The property name to use to identify the IP address for Cassandra. */
    public static final String KEY_MUSIC_ADDRESS      = "cassandra.host";
    /** The property name to use to provide the replication factor for Cassandra. */
    public static final String KEY_MUSIC_RFACTOR      = "music_rfactor";
    /** The property name to use to provide the replication factor for Cassandra. */
    public static final String KEY_MUSIC_NAMESPACE = "music_namespace";
    /**  The property name to use to provide a timeout to mdbc (ownership) */
    public static final String KEY_TIMEOUT = "mdbc_timeout";
    /**  The property name to use to provide a flag indicating if compression is required */
    public static final String KEY_COMPRESSION = "mdbc_compression";
    /**  The property name to use to provide a flag indicating if mri row splits is allowable */
    public static final String KEY_SPLIT = "partition_splitting";
    /** Namespace for the tables in MUSIC (Cassandra) */
    public static final String DEFAULT_MUSIC_NAMESPACE = "namespace";
    /** The default property value to use for the Cassandra IP address. */
    public static final String DEFAULT_MUSIC_ADDRESS  = "localhost";
    /** The default property value to use for the Cassandra replication factor. */
    public static final int    DEFAULT_MUSIC_RFACTOR  = 1;
    /** The default property value to use for the MDBC timeout */
    public static final long DEFAULT_TIMEOUT = 5*60*60*1000;//default of 5 hours
    /** The default primary string column, if none is provided. */
    public static final String MDBC_PRIMARYKEY_NAME = "mdbc_cuid";
    /** Type of the primary key, if none is defined by the user */
    public static final String MDBC_PRIMARYKEY_TYPE = "uuid";
    public static final boolean DEFAULT_COMPRESSION = true;
    //TODO: Control network topology strategy with a configuration file entry
    public static final boolean ENABLE_NETWORK_TOPOLOGY_STRATEGY = false;

    //\TODO Add logic to change the names when required and create the tables when necessary
    private String musicTxDigestTableName = "musictxdigest";
    private String musicEventualTxDigestTableName = "musicevetxdigest";
    public static final String musicRangeInformationTableName = "musicrangeinformation";
    private String musicRangeDependencyTableName = "musicrangedependency";
    private String musicNodeInfoTableName = "musicnodeinfo";
    /** Table mapping mdbc nodes to their current checkpoint status */
    private String musicMdbcCheckpointsTableName = "musicmdbccheckpoints";

    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicMixin.class);



    private class RangeMriRow{
        private MusicRangeInformationRow currentRow;
        private List<MusicRangeInformationRow> oldRows;
        private final Range range;
        public RangeMriRow(Range range) {
            this.range = range;
            oldRows = new ArrayList<>();
        }
        Range getRange(){
            return range;
        }
        public MusicRangeInformationRow getCurrentRow(){
            return currentRow;
        }
        public void setCurrentRow(MusicRangeInformationRow row){
            currentRow=row;
        }
        public void addOldRow(MusicRangeInformationRow row){
            oldRows.add(row);
        }
        public List<MusicRangeInformationRow> getOldRows(){
            return oldRows;
        }
    }


    private static final Map<Integer, String> typemap         = new HashMap<>();
    static {
        // We only support the following type mappings currently (from DB -> Cassandra).
        // Anything else will likely cause a NullPointerException
        typemap.put(Types.BIGINT,    "BIGINT"); // aka. IDENTITY
        typemap.put(Types.BLOB,      "VARCHAR");
        typemap.put(Types.BOOLEAN,   "BOOLEAN");
        typemap.put(Types.CLOB,      "BLOB");
        typemap.put(Types.DATE,      "VARCHAR");
        typemap.put(Types.DOUBLE,    "DOUBLE");
        typemap.put(Types.DECIMAL,   "DECIMAL");
        typemap.put(Types.INTEGER,   "INT");
        //typemap.put(Types.TIMESTAMP, "TIMESTAMP");
        typemap.put(Types.SMALLINT, "SMALLINT");
        typemap.put(Types.TIMESTAMP, "VARCHAR");
        typemap.put(Types.VARBINARY, "BLOB");
        typemap.put(Types.VARCHAR,   "VARCHAR");
        typemap.put(Types.CHAR,      "VARCHAR");
        //The "Hacks", these don't have a direct mapping
        //typemap.put(Types.DATE,        "VARCHAR");
        //typemap.put(Types.DATE,        "TIMESTAMP");
    }


    protected final String music_ns;
    protected final String myId;
    protected final String[] allReplicaIds;
    protected ExecutorService commitExecutorThreads;

    private final String musicAddress;
    private final int    music_rfactor;
    private MusicConnector mCon        = null;
    private Session musicSession       = null;
    private boolean keyspace_created   = false;
    private Map<String, PreparedStatement> ps_cache = new HashMap<>();
    private Set<String> in_progress    = Collections.synchronizedSet(new HashSet<String>());
    private StateManager stateManager;
    private boolean useCompression;
    private boolean splitAllowed;

    public MusicMixin() {
        //this.logger         = null;
        this.musicAddress   = null;
        this.music_ns       = null;
        this.music_rfactor  = 0;
        this.myId           = null;
        this.allReplicaIds  = null;
    }

    public MusicMixin(StateManager stateManager, String mdbcServerName, Properties info) throws MDBCServiceException {
        // Default values -- should be overridden in the Properties
        // Default to using the host_ids of the various peers as the replica IDs (this is probably preferred)
        this.musicAddress   = info.getProperty(KEY_MUSIC_ADDRESS, DEFAULT_MUSIC_ADDRESS);
        logger.info(EELFLoggerDelegate.applicationLogger,"MusicSqlManager: musicAddress="+musicAddress);
        MusicDataStore dsHandle = null;
        try {
            dsHandle = MusicDataStoreHandle.getDSHandle();
        } catch (MusicServiceException e) {
            e.printStackTrace();
        }

        this.myId           = info.getProperty(KEY_MY_ID,    getMyHostId());
        logger.info(EELFLoggerDelegate.applicationLogger,"MusicSqlManager: myId="+myId);

        this.allReplicaIds  = info.getProperty(KEY_REPLICAS, getAllHostIds()).split(",");
        logger.info(EELFLoggerDelegate.applicationLogger,"MusicSqlManager: allReplicaIds="+info.getProperty(KEY_REPLICAS, this.myId));

        this.music_ns       = info.getProperty(KEY_MUSIC_NAMESPACE,DEFAULT_MUSIC_NAMESPACE);
        logger.info(EELFLoggerDelegate.applicationLogger,"MusicSqlManager: music_ns="+music_ns);

        this.stateManager = stateManager;
        
        String c = info.getProperty(KEY_COMPRESSION);
        this.useCompression = (c == null) ? DEFAULT_COMPRESSION: Boolean.parseBoolean(c);

        String s            = info.getProperty(KEY_MUSIC_RFACTOR);
        this.music_rfactor  = (s == null) ? DEFAULT_MUSIC_RFACTOR : Integer.parseInt(s);

        String split = info.getProperty(KEY_SPLIT);
        this.splitAllowed = (split == null) ? true: Boolean.parseBoolean(split);
        
        initializeMetricTables();
        commitExecutorThreads = Executors.newFixedThreadPool(4);
    }

    public String getMusicTxDigestTableName(){
        return musicTxDigestTableName;
    }

    public String getMusicRangeInformationTableName(){
        return musicRangeInformationTableName;
    }

    /**
     * This method creates a keyspace in Music/Cassandra to store the data corresponding to the SQL tables.
     * The keyspace name comes from the initialization properties passed to the JDBC driver.
     */
    @Override
    public void createKeyspace() throws MDBCServiceException {
        createKeyspace(this.music_ns,this.music_rfactor);
    }

    public static void createKeyspace(String keyspace, int replicationFactor) throws MDBCServiceException {
        Map<String,Object> replicationInfo = new HashMap<>();
        replicationInfo.put("'class'", "'NetworkTopologyStrategy'");

        if (ENABLE_NETWORK_TOPOLOGY_STRATEGY && replicationFactor==3) {
            replicationInfo.put("'dc1'", 1);
            replicationInfo.put("'dc2'", 1);
            replicationInfo.put("'dc3'", 1);
        } else {
            replicationInfo.put("'class'", "'SimpleStrategy'");
            replicationInfo.put("'replication_factor'", replicationFactor);
        }

        PreparedQueryObject queryObject = new PreparedQueryObject();
        queryObject.appendQueryString(
            "CREATE KEYSPACE IF NOT EXISTS " + keyspace +
                " WITH REPLICATION = " + replicationInfo.toString().replaceAll("=", ":"));

        try {
            MusicCore.nonKeyRelatedPut(queryObject, "eventual");
        } catch (MusicServiceException e) {
            if (!e.getMessage().equals("Keyspace "+keyspace+" already exists")) {
                throw new MDBCServiceException("Error creating namespace: "+keyspace+". Internal error:"+e.getErrorMessage(),
                    e);
            }
        }
    }

    private String getMyHostId() {
        ResultSet rs = null;
        try {
            rs = executeMusicRead("SELECT HOST_ID FROM SYSTEM.LOCAL");
        } catch (MDBCServiceException e) {
            return "UNKNOWN";
        }
        Row row = rs.one();
        return (row == null) ? "UNKNOWN" : row.getUUID("HOST_ID").toString();
    }
    private String getAllHostIds() {
        ResultSet results = null;
        try {
            results = executeMusicRead("SELECT HOST_ID FROM SYSTEM.PEERS");
        } catch (MDBCServiceException e) {
        }
        StringBuilder sb = new StringBuilder(myId);
        if(results!=null) {
            for (Row row : results) {
                sb.append(",");
                sb.append(row.getUUID("HOST_ID").toString());
            }
        }
        return sb.toString();
    }

    /**
     * Get the name of this MusicInterface mixin object.
     * @return the name
     */
    @Override
    public String getMixinName() {
        return "cassandra";
    }
    /**
     * Do what is needed to close down the MUSIC connection.
     */
    @Override
    public void close() {
        if (musicSession != null) {
            musicSession.close();
            musicSession = null;
        }
    }

    /**
     * This function is used to created all the required data structures, both local
     */
    private void initializeMetricTables() throws MDBCServiceException {
        createKeyspace();
        try {
            createMusicTxDigest();//\TODO If we start partitioning the data base, we would need to use the redotable number
            createMusicEventualTxDigest();
            createMusicNodeInfoTable();
            createMusicRangeInformationTable(this.music_ns,this.musicRangeInformationTableName);
            createMusicRangeDependencyTable(this.music_ns,this.musicRangeDependencyTableName);
            createMusicMdbcCheckpointTable();
        }
        catch(MDBCServiceException e){
            logger.error(EELFLoggerDelegate.errorLogger,"Error creating tables in MUSIC: " + e.getErrorMessage());
        }
    }

    /**
     * This method performs all necessary initialization in Music/Cassandra to store the table <i>tableName</i>.
     * @param tableName the table to initialize MUSIC for
     */
    @Override
    public void initializeMusicForTable(TableInfo ti, String tableName) {
        /**
         * This code creates two tables for every table in SQL:
         * (i) a table with the exact same name as the SQL table storing the SQL data.
         * (ii) a "dirty bits" table that stores the keys in the Cassandra table that are yet to be
         * updated in the SQL table (they were written by some other node).
         */
        StringBuilder fields = new StringBuilder();
        StringBuilder prikey = new StringBuilder();
        String pfx = "", pfx2 = "";
        for (int i = 0; i < ti.columns.size(); i++) {
            fields.append(pfx)
                .append(ti.columns.get(i))
                .append(" ")
                .append(typemap.get(ti.coltype.get(i)));
            if (ti.iskey.get(i)) {
                // Primary key column
                prikey.append(pfx2).append(ti.columns.get(i));
                pfx2 = ", ";
            }
            pfx = ", ";
        }
        if (prikey.length()==0) {
            fields.append(pfx).append(MDBC_PRIMARYKEY_NAME)
                .append(" ")
                .append(MDBC_PRIMARYKEY_TYPE);
            prikey.append(MDBC_PRIMARYKEY_NAME);
        }
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));", music_ns, tableName, fields.toString(), prikey.toString());
        executeMusicWriteQuery(cql);
    }

    // **************************************************
    // Dirty Tables (in MUSIC) methods
    // **************************************************

    /**
     * Create a <i>dirty row</i> table for the real table <i>tableName</i>.  The primary keys columns from the real table are recreated in
     * the dirty table, along with a "REPLICA__" column that names the replica that should update it's internal state from MUSIC.
     * @param tableName the table to create a "dirty" table for
     */
    @Override
    public void createDirtyRowTable(TableInfo ti, String tableName) {
        // create dirtybitsTable at all replicas
//      for (String repl : allReplicaIds) {
////            String dirtyRowsTableName = "dirty_"+tableName+"_"+allReplicaIds[i];
////            String dirtyTableQuery = "CREATE TABLE IF NOT EXISTS "+music_ns+"."+ dirtyRowsTableName+" (dirtyRowKeys text PRIMARY KEY);";
//          cql = String.format("CREATE TABLE IF NOT EXISTS %s.DIRTY_%s_%s (dirtyRowKeys TEXT PRIMARY KEY);", music_ns, tableName, repl);
//          executeMusicWriteQuery(cql);
//      }
        StringBuilder ddl = new StringBuilder("REPLICA__ TEXT");
        StringBuilder cols = new StringBuilder("REPLICA__");
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                // Only use the primary keys columns in the "Dirty" table
                ddl.append(", ")
                    .append(ti.columns.get(i))
                    .append(" ")
                    .append(typemap.get(ti.coltype.get(i)));
                cols.append(", ").append(ti.columns.get(i));
            }
        }
        if(cols.length()==0) {
            //fixme
            System.err.println("Create dirty row table found no primary key");
        }
        ddl.append(", PRIMARY KEY(").append(cols).append(")");
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.DIRTY_%s (%s);", music_ns, tableName, ddl.toString());
        executeMusicWriteQuery(cql);
    }
    /**
     * Drop the dirty row table for <i>tableName</i> from MUSIC.
     * @param tableName the table being dropped
     */
    @Override
    public void dropDirtyRowTable(String tableName) {
        String cql = String.format("DROP TABLE %s.DIRTY_%s;", music_ns, tableName);
        executeMusicWriteQuery(cql);
    }
    /**
     * Mark rows as "dirty" in the dirty rows table for <i>tableName</i>.  Rows are marked for all replicas but
     * this one (this replica already has the up to date data).
     * @param tableName the table we are marking dirty
     * @param keys an ordered list of the values being put into the table.  The values that correspond to the tables'
     * primary key are copied into the dirty row table.
     */
    @Override
    public void markDirtyRow(TableInfo ti, String tableName, JSONObject keys) {
        Object[] keyObj = getObjects(ti,tableName, keys);
        StringBuilder cols = new StringBuilder("REPLICA__");
        PreparedQueryObject pQueryObject = null;
        StringBuilder vals = new StringBuilder("?");
        List<Object> vallist = new ArrayList<Object>();
        vallist.add(""); // placeholder for replica
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                cols.append(", ").append(ti.columns.get(i));
                vals.append(", ").append("?");
                vallist.add(keyObj[i]);
            }
        }
        if(cols.length()==0) {
            //FIXME
            System.err.println("markDIrtyRow need to fix primary key");
        }
        String cql = String.format("INSERT INTO %s.DIRTY_%s (%s) VALUES (%s);", music_ns, tableName, cols.toString(), vals.toString());
        /*Session sess = getMusicSession();
        PreparedStatement ps = getPreparedStatementFromCache(cql);*/
        String primaryKey;
        if(ti.hasKey()) {
            primaryKey = getMusicKeyFromRow(ti,tableName, keys);
        }
        else {
            primaryKey = getMusicKeyFromRowWithoutPrimaryIndexes(ti,tableName, keys);
        }
        System.out.println("markDirtyRow: PK value: "+primaryKey);

        Object pkObj = null;
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                pkObj = keyObj[i];
            }
        }
        for (String repl : allReplicaIds) {
            pQueryObject = new PreparedQueryObject();
            pQueryObject.appendQueryString(cql);
            pQueryObject.addValue(tableName);
            pQueryObject.addValue(repl);
            pQueryObject.addValue(pkObj);
            updateMusicDB(tableName, primaryKey, pQueryObject);
            //if (!repl.equals(myId)) {
                /*logger.info(EELFLoggerDelegate.applicationLogger,"Executing MUSIC write:"+ cql);
                vallist.set(0, repl);
                BoundStatement bound = ps.bind(vallist.toArray());
                bound.setReadTimeoutMillis(60000);
                synchronized (sess) {
                    sess.execute(bound);
                }*/
            //}

        }
    }
    /**
     * Remove the entries from the dirty row (for this replica) that correspond to a set of primary keys
     * @param tableName the table we are removing dirty entries from
     * @param keys the primary key values to use in the DELETE.  Note: this is *only* the primary keys, not a full table row.
     */
    @Override
    public void cleanDirtyRow(TableInfo ti, String tableName, JSONObject keys) {
        Object[] keysObjects = getObjects(ti,tableName,keys);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        StringBuilder cols = new StringBuilder("REPLICA__=?");
        List<Object> vallist = new ArrayList<Object>();
        vallist.add(myId);
        int n = 0;
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                cols.append(" AND ").append(ti.columns.get(i)).append("=?");
                vallist.add(keysObjects[n++]);
                pQueryObject.addValue(keysObjects[n++]);
            }
        }
        String cql = String.format("DELETE FROM %s.DIRTY_%s WHERE %s;", music_ns, tableName, cols.toString());
        logger.debug(EELFLoggerDelegate.applicationLogger,"Executing MUSIC write:"+ cql);
        pQueryObject.appendQueryString(cql);
        ReturnType rt = MusicCore.eventualPut(pQueryObject);
        if(rt.getResult().getResult().toLowerCase().equals("failure")) {
            System.out.println("Failure while cleanDirtyRow..."+rt.getMessage());
        }
        /*Session sess = getMusicSession();
        PreparedStatement ps = getPreparedStatementFromCache(cql);
        BoundStatement bound = ps.bind(vallist.toArray());
        bound.setReadTimeoutMillis(60000);
        synchronized (sess) {
            sess.execute(bound);
        }*/
    }
    /**
     * Get a list of "dirty rows" for a table.  The dirty rows returned apply only to this replica,
     * and consist of a Map of primary key column names and values.
     * @param tableName the table we are querying for
     * @return a list of maps; each list item is a map of the primary key names and values for that "dirty row".
     */
    @Override
    public List<Map<String,Object>> getDirtyRows(TableInfo ti, String tableName) {
        String cql = String.format("SELECT * FROM %s.DIRTY_%s WHERE REPLICA__=?;", music_ns, tableName);
        ResultSet results = null;
        logger.debug(EELFLoggerDelegate.applicationLogger,"Executing MUSIC write:"+ cql);
        
        /*Session sess = getMusicSession();
        PreparedStatement ps = getPreparedStatementFromCache(cql);
        BoundStatement bound = ps.bind(new Object[] { myId });
        bound.setReadTimeoutMillis(60000);
        synchronized (sess) {
            results = sess.execute(bound);
        }*/
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        try {
            results = MusicCore.get(pQueryObject);
        } catch (MusicServiceException e) {

            e.printStackTrace();
        }

        ColumnDefinitions cdef = results.getColumnDefinitions();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (Row row : results) {
            Map<String,Object> objs = new HashMap<String,Object>();
            for (int i = 0; i < cdef.size(); i++) {
                String colname = cdef.getName(i).toUpperCase();
                String coltype = cdef.getType(i).getName().toString().toUpperCase();
                if (!colname.equals("REPLICA__")) {
                    switch (coltype) {
                        case "BIGINT":
                            objs.put(colname, row.getLong(colname));
                            break;
                        case "BOOLEAN":
                            objs.put(colname, row.getBool(colname));
                            break;
                        case "BLOB":
                            objs.put(colname, row.getString(colname));
                            break;
                        case "DATE":
                            objs.put(colname, row.getString(colname));
                            break;
                        case "DOUBLE":
                            objs.put(colname, row.getDouble(colname));
                            break;
                        case "DECIMAL":
                            objs.put(colname, row.getDecimal(colname));
                            break;
                        case "INT":
                            objs.put(colname, row.getInt(colname));
                            break;
                        case "TIMESTAMP":
                            objs.put(colname, row.getTimestamp(colname));
                            break;
                        case "VARCHAR":
                        default:
                            objs.put(colname, row.getString(colname));
                            break;
                    }
                }
            }
            list.add(objs);
        }
        return list;
    }

    /**
     * Drops the named table and its dirty row table (for all replicas) from MUSIC.  The dirty row table is dropped first.
     * @param tableName This is the table that has been dropped
     */
    @Override
    public void clearMusicForTable(String tableName) {
        dropDirtyRowTable(tableName);
        String cql = String.format("DROP TABLE %s.%s;", music_ns, tableName);
        executeMusicWriteQuery(cql);
    }
    /**
     * This function is called whenever there is a DELETE to a row on a local SQL table, wherein it updates the
     * MUSIC/Cassandra tables (both dirty bits and actual data) corresponding to the SQL write. MUSIC propagates
     * it to the other replicas.
     *
     * @param tableName This is the table that has changed.
     * @param oldRow This is a copy of the old row being deleted
     */
    @Override
    public void deleteFromEntityTableInMusic(TableInfo ti, String tableName, JSONObject oldRow) {
        Object[] objects = getObjects(ti,tableName,oldRow);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        if (ti.hasKey()) {
            assert(ti.columns.size() == objects.length);
        } else {
            assert(ti.columns.size()+1 == objects.length);
        }

        StringBuilder where = new StringBuilder();
        List<Object> vallist = new ArrayList<Object>();
        String pfx = "";
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                where.append(pfx)
                    .append(ti.columns.get(i))
                    .append("=?");
                vallist.add(objects[i]);
                pQueryObject.addValue(objects[i]);
                pfx = " AND ";
            }
        }
        if (!ti.hasKey()) {
            where.append(MDBC_PRIMARYKEY_NAME + "=?");
            //\FIXME this is wrong, old row is not going to contain the UUID, this needs to be fixed
            vallist.add(UUID.fromString((String) objects[0]));
            pQueryObject.addValue(UUID.fromString((String) objects[0]));
        }

        String cql = String.format("DELETE FROM %s.%s WHERE %s;", music_ns, tableName, where.toString());
        logger.error(EELFLoggerDelegate.errorLogger,"Executing MUSIC write:"+ cql);
        pQueryObject.appendQueryString(cql);
        
        /*PreparedStatement ps = getPreparedStatementFromCache(cql);
        BoundStatement bound = ps.bind(vallist.toArray());
        bound.setReadTimeoutMillis(60000);
        Session sess = getMusicSession();
        synchronized (sess) {
            sess.execute(bound);
        }*/
        String primaryKey = getMusicKeyFromRow(ti,tableName, oldRow);

        updateMusicDB(tableName, primaryKey, pQueryObject);

        // Mark the dirty rows in music for all the replicas but us
        markDirtyRow(ti,tableName, oldRow);
    }

    public Set<String> getMusicTableSet(String ns) {
        Set<String> set = new TreeSet<String>();
        String cql = String.format("SELECT TABLE_NAME FROM SYSTEM_SCHEMA.TABLES WHERE KEYSPACE_NAME = '%s'", ns);
        ResultSet rs = null;
        try {
            rs = executeMusicRead(cql);
        } catch (MDBCServiceException e) {
            e.printStackTrace();
        }
        if(rs!=null) {
            for (Row row : rs) {
                set.add(row.getString("TABLE_NAME"));
            }
        }
        return set;
    }
    /**
     * This method is called whenever there is a SELECT on a local SQL table, wherein it first checks the local
     * dirty bits table to see if there are any keys in Cassandra whose value has not yet been sent to SQL
     * @param tableName This is the table on which the select is being performed
     */
    @Override
    public void readDirtyRowsAndUpdateDb(DBInterface dbi, String tableName) {
        // Read dirty rows of this table from Music
        TableInfo ti = dbi.getTableInfo(tableName);
        List<Map<String,Object>> objlist = getDirtyRows(ti,tableName);
        PreparedQueryObject pQueryObject = null;
        String pre_cql = String.format("SELECT * FROM %s.%s WHERE ", music_ns, tableName);
        List<Object> vallist = new ArrayList<Object>();
        StringBuilder sb = new StringBuilder();
        //\TODO Perform a batch operation instead of each row at a time
        for (Map<String,Object> map : objlist) {
            pQueryObject = new PreparedQueryObject();
            sb.setLength(0);
            vallist.clear();
            String pfx = "";
            for (String key : map.keySet()) {
                sb.append(pfx).append(key).append("=?");
                vallist.add(map.get(key));
                pQueryObject.addValue(map.get(key));
                pfx = " AND ";
            }

            String cql = pre_cql + sb.toString();
            System.out.println("readDirtyRowsAndUpdateDb: cql: "+cql);
            pQueryObject.appendQueryString(cql);
            ResultSet dirtyRows = null;
            try {
                //\TODO Why is this an eventual put?, this should be an atomic
                dirtyRows = MusicCore.get(pQueryObject);
            } catch (MusicServiceException e) {

                e.printStackTrace();
            }
            /*
            Session sess = getMusicSession();
            PreparedStatement ps = getPreparedStatementFromCache(cql);
            BoundStatement bound = ps.bind(vallist.toArray());
            bound.setReadTimeoutMillis(60000);
            ResultSet dirtyRows = null;
            synchronized (sess) {
                dirtyRows = sess.execute(bound);
            }*/
            List<Row> rows = dirtyRows.all();
            if (rows.isEmpty()) {
                // No rows, the row must have been deleted
                deleteRowFromSqlDb(dbi,tableName, map);
            } else {
                for (Row row : rows) {
                    writeMusicRowToSQLDb(dbi,tableName, row);
                }
            }
        }
    }

    private void deleteRowFromSqlDb(DBInterface dbi, String tableName, Map<String, Object> map) {
        dbi.deleteRowFromSqlDb(tableName, map);
        TableInfo ti = dbi.getTableInfo(tableName);
        List<Object> vallist = new ArrayList<Object>();
        for (int i = 0; i < ti.columns.size(); i++) {
            if (ti.iskey.get(i)) {
                String col = ti.columns.get(i);
                Object val = map.get(col);
                vallist.add(val);
            }
        }
        cleanDirtyRow(ti, tableName, new JSONObject(vallist));
    }
    /**
     * This functions copies the contents of a row in Music into the corresponding row in the SQL table
     * @param tableName This is the name of the table in both Music and swl
     * @param musicRow This is the row in Music that is being copied into SQL
     */
    private void writeMusicRowToSQLDb(DBInterface dbi, String tableName, Row musicRow) {
        // First construct the map of columns and their values
        TableInfo ti = dbi.getTableInfo(tableName);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Object> vallist = new ArrayList<Object>();
        String rowid = tableName;
        for (String col : ti.columns) {
            Object val = getValue(musicRow, col);
            map.put(col, val);
            if (ti.iskey(col)) {
                vallist.add(val);
                rowid += "_" + val.toString();
            }
        }

        logger.debug("Blocking rowid: "+rowid);
        in_progress.add(rowid);         // Block propagation of the following INSERT/UPDATE

        dbi.insertRowIntoSqlDb(tableName, map);

        logger.debug("Unblocking rowid: "+rowid);
        in_progress.remove(rowid);      // Unblock propagation

//      try {
//          String sql = String.format("INSERT INTO %s (%s) VALUES (%s);", tableName, fields.toString(), values.toString());
//          executeSQLWrite(sql);
//      } catch (SQLException e) {
//          logger.debug("Insert failed because row exists, do an update");
//          // TODO - rewrite this UPDATE command should not update key fields
//          String sql = String.format("UPDATE %s SET (%s) = (%s) WHERE %s", tableName, fields.toString(), values.toString(), where.toString());
//          try {
//              executeSQLWrite(sql);
//          } catch (SQLException e1) {
//              e1.printStackTrace();
//          }
//      }

        ti = dbi.getTableInfo(tableName);
        cleanDirtyRow(ti, tableName, new JSONObject(vallist));

//      String selectQuery = "select "+ primaryKeyName+" FROM "+tableName+" WHERE "+primaryKeyName+"="+primaryKeyValue+";";
//      java.sql.ResultSet rs = executeSQLRead(selectQuery);
//      String dbWriteQuery=null;
//      try {
//          if(rs.next()){//this entry is there, do an update
//              dbWriteQuery = "UPDATE "+tableName+" SET "+columnNameString+" = "+ valueString +"WHERE "+primaryKeyName+"="+primaryKeyValue+";";
//          }else
//              dbWriteQuery = "INSERT INTO "+tableName+" VALUES"+valueString+";";
//          executeSQLWrite(dbWriteQuery);
//      } catch (SQLException e) {
//          // ZZTODO Auto-generated catch block
//          e.printStackTrace();
//      }

        //clean the music dirty bits table
//      String dirtyRowIdsTableName = music_ns+".DIRTY_"+tableName+"_"+myId;
//      String deleteQuery = "DELETE FROM "+dirtyRowIdsTableName+" WHERE dirtyRowKeys=$$"+primaryKeyValue+"$$;";
//      executeMusicWriteQuery(deleteQuery);
    }
    private Object getValue(Row musicRow, String colname) {
        ColumnDefinitions cdef = musicRow.getColumnDefinitions();
        DataType colType;
        try {
            colType= cdef.getType(colname);
        }
        catch(IllegalArgumentException e) {
            logger.warn("Colname is not part of table metadata: "+e);
            throw e;
        }
        String typeStr = colType.getName().toString().toUpperCase();
        switch (typeStr) {
            case "BIGINT":
                return musicRow.getLong(colname);
            case "BOOLEAN":
                return musicRow.getBool(colname);
            case "BLOB":
                return musicRow.getString(colname);
            case "DATE":
                return musicRow.getString(colname);
            case "DECIMAL":
                return musicRow.getDecimal(colname);
            case "DOUBLE":
                return musicRow.getDouble(colname);
            case "SMALLINT":
            case "INT":
                return musicRow.getInt(colname);
            case "TIMESTAMP":
                return musicRow.getTimestamp(colname);
            case "UUID":
                return musicRow.getUUID(colname);
            default:
                logger.error(EELFLoggerDelegate.errorLogger, "UNEXPECTED COLUMN TYPE: columname="+colname+", columntype="+typeStr);
                // fall thru
            case "VARCHAR":
                return musicRow.getString(colname);
        }
    }

    /**
     * This method is called whenever there is an INSERT or UPDATE to a local SQL table, wherein it updates the
     * MUSIC/Cassandra tables (both dirty bits and actual data) corresponding to the SQL write. Music propagates
     * it to the other replicas.
     *
     * @param tableName This is the table that has changed.
     * @param changedRow This is information about the row that has changed
     */
    @Override
    public void updateDirtyRowAndEntityTableInMusic(TableInfo ti, String tableName, JSONObject changedRow) {
        // Build the CQL command
        Object[] objects = getObjects(ti,tableName,changedRow);
        StringBuilder fields = new StringBuilder();
        StringBuilder values = new StringBuilder();
        String rowid = tableName;
        Object[] newrow = new Object[objects.length];
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        String pfx = "";
        int keyoffset=0;
        for (int i = 0; i < objects.length; i++) {
            if (!ti.hasKey() && i==0) {
                //We need to tack on cassandra's uid in place of a primary key
                fields.append(MDBC_PRIMARYKEY_NAME);
                values.append("?");
                newrow[i] = UUID.fromString((String) objects[i]);
                pQueryObject.addValue(newrow[i]);
                keyoffset=-1;
                pfx = ", ";
                continue;
            }
            fields.append(pfx).append(ti.columns.get(i+keyoffset));
            values.append(pfx).append("?");
            pfx = ", ";
            if (objects[i] instanceof byte[]) {
                // Cassandra doesn't seem to have a Codec to translate a byte[] to a ByteBuffer
                newrow[i] = ByteBuffer.wrap((byte[]) objects[i]);
                pQueryObject.addValue(newrow[i]);
            } else if (objects[i] instanceof Reader) {
                // Cassandra doesn't seem to have a Codec to translate a Reader to a ByteBuffer either...
                newrow[i] = ByteBuffer.wrap(readBytesFromReader((Reader) objects[i]));
                pQueryObject.addValue(newrow[i]);
            } else {
                newrow[i] = objects[i];
                pQueryObject.addValue(newrow[i]);
            }
            if (i+keyoffset>=0 && ti.iskey.get(i+keyoffset)) {
                rowid += "_" + newrow[i].toString();
            }
        }

        if (in_progress.contains(rowid)) {
            // This call to updateDirtyRowAndEntityTableInMusic() was called as a result of a Cassandra -> H2 update; ignore
            logger.debug(EELFLoggerDelegate.applicationLogger, "updateDirtyRowAndEntityTableInMusic: bypassing MUSIC update on "+rowid);

        } else {
            // Update local MUSIC node. Note: in Cassandra you can insert again on an existing key..it becomes an update
            String cql = String.format("INSERT INTO %s.%s (%s) VALUES (%s);", music_ns, tableName, fields.toString(), values.toString());

            pQueryObject.appendQueryString(cql);
            String primaryKey = getMusicKeyFromRow(ti,tableName, changedRow);
            updateMusicDB(tableName, primaryKey, pQueryObject);
            
            /*PreparedStatement ps = getPreparedStatementFromCache(cql);
            BoundStatement bound = ps.bind(newrow);
            bound.setReadTimeoutMillis(60000);
            Session sess = getMusicSession();
            synchronized (sess) {
                sess.execute(bound);
            }*/
            // Mark the dirty rows in music for all the replicas but us
            markDirtyRow(ti,tableName, changedRow);
        }
    }



    private byte[] readBytesFromReader(Reader rdr) {
        StringBuilder sb = new StringBuilder();
        try {
            int ch;
            while ((ch = rdr.read()) >= 0) {
                sb.append((char)ch);
            }
        } catch (IOException e) {
            logger.warn("readBytesFromReader: "+e);
        }
        return sb.toString().getBytes();
    }

    protected PreparedStatement getPreparedStatementFromCache(String cql) {
        // Note: have to hope that the Session never changes!
        if (!ps_cache.containsKey(cql)) {
            Session sess = getMusicSession();
            PreparedStatement ps = sess.prepare(cql);
            ps_cache.put(cql, ps);
        }
        return ps_cache.get(cql);
    }

    /**
     * This method gets a connection to Music
     * @return the Cassandra Session to use
     */
    protected Session getMusicSession() {
        // create cassandra session
        if (musicSession == null) {
            logger.info(EELFLoggerDelegate.applicationLogger, "Creating New Music Session");
            mCon = new MusicConnector(musicAddress);
            musicSession = mCon.getSession();
        }
        return musicSession;
    }

    /**
     * This method executes a write query in Music
     * @param cql the CQL to be sent to Cassandra
     */
    protected void executeMusicWriteQuery(String cql) {
        logger.debug(EELFLoggerDelegate.applicationLogger, "Executing MUSIC write:"+ cql);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        ReturnType rt = MusicCore.eventualPut(pQueryObject);
        if(rt.getResult().getResult().toLowerCase().equals("failure")) {
            logger.error(EELFLoggerDelegate.errorLogger, "Failure while eventualPut...: "+rt.getMessage());
        }
        
    }

    /**
     * This method executes a read query in Music
     * @param cql the CQL to be sent to Cassandra
     * @return a ResultSet containing the rows returned from the query
     */
    protected ResultSet executeMusicRead(String cql) throws MDBCServiceException {
        logger.debug(EELFLoggerDelegate.applicationLogger, "Executing MUSIC read:"+ cql);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        ResultSet results = null;
        try {
            results = MusicCore.get(pQueryObject);
        } catch (MusicServiceException e) {
            logger.error("Error executing music get operation for query: ["+cql+"]");
            throw new MDBCServiceException("Error executing get: "+e.getMessage(), e);
        }
        return results;
    }
    
    /**
     * This method executes a read query in Music
     * @param pQueryObject the PreparedQueryObject to be sent to Cassandra
     * @return a ResultSet containing the rows returned from the query
     */
    protected ResultSet executeMusicRead(PreparedQueryObject pQueryObject) throws MDBCServiceException {
        logger.debug(EELFLoggerDelegate.applicationLogger, "Executing MUSIC read:"+ pQueryObject.getQuery());
        ResultSet results = null;
        try {
            results = MusicCore.get(pQueryObject);
        } catch (MusicServiceException e) {
            logger.error("Error executing music get operation for query: ["+pQueryObject.getQuery()+"]");
            throw new MDBCServiceException("Error executing get: "+e.getMessage(), e);
        }
        return results;
    }

    /**
     * Returns the default primary key name that this mixin uses
     */
    public String getMusicDefaultPrimaryKeyName() {
        return MDBC_PRIMARYKEY_NAME;
    }

    /**
     * Return the function for cassandra's primary key generation
     */
    @Override
    public UUID generateUniqueKey() {
        return MDBCUtils.generateUniqueKey();
    }

    @Override
    public String getMusicKeyFromRowWithoutPrimaryIndexes(TableInfo ti, String table, JSONObject dbRow) {
        //\TODO this operation is super expensive to perform, both latency and BW
        // it is better to add additional where clauses, and have the primary key
        // to be composed of known columns of the table
        // Adding this primary indexes would be an additional burden to the developers, which spanner
        // also does, but otherwise performance is really bad
        // At least it should have a set of columns that are guaranteed to be unique
        StringBuilder cqlOperation = new StringBuilder();
        cqlOperation.append("SELECT * FROM ")
            .append(music_ns)
            .append(".")
            .append(table);
        ResultSet musicResults = null;
        try {
            musicResults = executeMusicRead(cqlOperation.toString());
        } catch (MDBCServiceException e) {
            return null;
        }
        Object[] dbRowObjects = getObjects(ti,table,dbRow);
        while (!musicResults.isExhausted()) {
            Row musicRow = musicResults.one();
            if (rowIs(ti, musicRow, dbRowObjects)) {
                return ((UUID)getValue(musicRow, MDBC_PRIMARYKEY_NAME)).toString();
            }
        }
        //should never reach here
        return null;
    }

    /**
     * Checks to see if this row is in list of database entries
     * @param ti
     * @param musicRow
     * @param dbRow
     * @return
     */
    private boolean rowIs(TableInfo ti, Row musicRow, Object[] dbRow) {
        boolean sameRow=true;
        for (int i=0; i<ti.columns.size(); i++) {
            Object val = getValue(musicRow, ti.columns.get(i));
            if (!dbRow[i].equals(val)) {
                sameRow=false;
                break;
            }
        }
        return sameRow;
    }

    @Override
    public String getMusicKeyFromRow(TableInfo ti, String tableName, JSONObject row) {
        List<String> keyCols = ti.getKeyColumns();
        if(keyCols.isEmpty()){
            throw new IllegalArgumentException("Table doesn't have defined primary indexes ");
        }
        StringBuilder key = new StringBuilder();
        String pfx = "";
        for(String keyCol: keyCols) {
            key.append(pfx);
            key.append(row.get(keyCol));
            pfx = ",";
        }
        String keyStr = key.toString();
        return keyStr;
    }

    public void updateMusicDB(String tableName, String primaryKey, PreparedQueryObject pQObject) {
        ReturnType rt = MusicCore.eventualPut(pQObject);
        if(rt.getResult().getResult().toLowerCase().equals("failure")) {
            System.out.println("Failure while critical put..."+rt.getMessage());
        }
    }

    /**
     * Build a preparedQueryObject that appends a transaction to the mriTable
     * @param mriTable
     * @param uuid
     * @param table
     * @param redoUuid
     * @return
     */
    private PreparedQueryObject createAppendMtxdIndexToMriQuery(String mriTable, UUID uuid, String table, UUID redoUuid){
        PreparedQueryObject query = new PreparedQueryObject();
        StringBuilder appendBuilder = new StringBuilder();
        appendBuilder.append("UPDATE ")
            .append(music_ns)
            .append(".")
            .append(mriTable)
            .append(" SET txredolog = txredolog +[('")
            .append(table)
            .append("',")
            .append(redoUuid)
            .append(")] WHERE rangeid = ")
            .append(uuid)
            .append(";");
        query.appendQueryString(appendBuilder.toString());
        return query;
    }

    private PreparedQueryObject createChangeIsLatestToMriQuery(String mriTable, UUID uuid, String table, boolean isLatest){
         PreparedQueryObject query = new PreparedQueryObject();
        StringBuilder appendBuilder = new StringBuilder();
        appendBuilder.append("UPDATE ")
            .append(music_ns)
            .append(".")
            .append(mriTable)
            .append(" SET islatest =")
            .append(isLatest)
            .append(" WHERE rangeid = ")
            .append(uuid)
            .append(";");
        query.appendQueryString(appendBuilder.toString());
        return query;
    }

    protected ReturnType acquireLock(String fullyQualifiedKey, String lockId) throws MDBCServiceException{
        ReturnType lockReturn;
        //\TODO Handle better failures to acquire locks
        try {
            lockReturn = MusicCore.acquireLock(fullyQualifiedKey,lockId);
        } catch (MusicLockingException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Lock was not acquire correctly for key "+fullyQualifiedKey);
            throw new MDBCServiceException("Lock was not acquire correctly for key "+fullyQualifiedKey, e);
        } catch (MusicServiceException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Error in music, when locking key: "+fullyQualifiedKey);
            throw new MDBCServiceException("Error in music, when locking: "+fullyQualifiedKey, e);
        } catch (MusicQueryException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Error in executing query music, when locking key: "+fullyQualifiedKey);
            throw new MDBCServiceException("Error in executing query music, when locking: "+fullyQualifiedKey, e);
        }
        return lockReturn;
    }

    private void addRange(Map<UUID,List<Range>> container, UUID index, Range range){
        if(!container.containsKey(index)){
            container.put(index,new ArrayList<Range>());
        }
        container.get(index).add(range);
    }

    private void addRows(Map<UUID,List<Range>> container, RangeMriRow newRow, Range range){
        //First add current row
        MusicRangeInformationRow currentRow = newRow.getCurrentRow();
        addRange(container,currentRow.getPartitionIndex(),range);
        for(MusicRangeInformationRow row : newRow.getOldRows()){
            addRange(container,row.getPartitionIndex(),range);
        }
    }

    private NavigableMap<UUID, List<Range>> getPendingRows(Map<Range, RangeMriRow> rangeRows){
        NavigableMap<UUID,List<Range>> pendingRows = new TreeMap<>();
        rangeRows.forEach((key, value) -> {
            addRows(pendingRows,value,key);
        });
        return pendingRows;
    }

    private List<Range> lockRow(LockRequest request,Map.Entry<UUID, Set<Range>> pending,Map<UUID, String> currentLockRef,
                         String fullyQualifiedKey, String lockId, List<Range> pendingToLock,
                         Map<UUID, LockResult> alreadyHeldLocks)
        throws MDBCServiceException{
        List<Range> newRanges = new ArrayList<>();
        String newFullyQualifiedKey = music_ns + "." + musicRangeInformationTableName + "." + pending.getKey().toString();
        String newLockId;
        boolean success;
        if (currentLockRef.containsKey(pending.getKey())) {
            newLockId = currentLockRef.get(pending.getKey());
            success = (MusicCore.whoseTurnIsIt(newFullyQualifiedKey) == newLockId);
        } else {
            newLockId = MusicCore.createLockReference(newFullyQualifiedKey);
            ReturnType newLockReturn = acquireLock(fullyQualifiedKey, lockId);
            success = newLockReturn.getResult().compareTo(ResultType.SUCCESS) == 0;
        }
        if (!success) {
            pendingToLock.addAll(pending.getValue());
            currentLockRef.put(pending.getKey(), newLockId);
        } else {
            if(alreadyHeldLocks.containsKey(pending.getKey())){
                throw new MDBCServiceException("Adding key that already exist");
            }
            alreadyHeldLocks.put(pending.getKey(),new LockResult(pending.getKey(), newLockId, true,
                pending.getValue()));
            newRanges.addAll(pending.getValue());
        }
        return newRanges;
    }

    private boolean isDifferent(NavigableMap<UUID, List<Range>> previous, NavigableMap<UUID, List<Range>> current){
        return previous.keySet().equals(current.keySet());
    }

    protected String createAndAssignLock(String fullyQualifiedKey, DatabasePartition partition) throws MDBCServiceException {
        UUID mriIndex = partition.getMRIIndex();
        String lockId;
        lockId = MusicCore.createLockReference(fullyQualifiedKey);
        if(lockId==null) {
           throw new MDBCServiceException("lock reference is null");
        }
        ReturnType lockReturn;
        int counter=0;
        do {
            if(counter > 0){
                //TODO: Improve backoff
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    logger.warn("Error sleeping for acquiring the lock");
                }
                logger.warn("Error acquiring lock id: ["+lockId+"] for key: ["+fullyQualifiedKey+"]");
            }
            lockReturn = acquireLock(fullyQualifiedKey,lockId);
        }while((lockReturn == null||lockReturn.getResult().compareTo(ResultType.SUCCESS) != 0 )&&(counter++<3));

        //\TODO this is wrong, we should have a better way to obtain a lock forcefully, clean the queue and obtain the lock
        if(lockReturn.getResult().compareTo(ResultType.SUCCESS) != 0 ) {
            logger.error("Lock acquire returned invalid error: "+lockReturn.getResult().name());
            return null;
        }
        partition.setLockId(lockId);
        return lockId;
    }

    protected void changeIsLatestToMRI(UUID mrirow, boolean isLatest, String lockref) throws MDBCServiceException{
       
        if(lockref == null)
            return;
        PreparedQueryObject appendQuery = createChangeIsLatestToMriQuery(musicRangeInformationTableName, mrirow,
            musicTxDigestTableName, isLatest);
        ReturnType returnType = MusicCore.criticalPut(music_ns, musicRangeInformationTableName, mrirow.toString(),
            appendQuery, 
            lockref
            , null);
        if(returnType.getResult().compareTo(ResultType.SUCCESS) != 0 ){
            logger.error(EELFLoggerDelegate.errorLogger, "Error when executing change isLatest operation with return type: "+returnType.getMessage());
            throw new MDBCServiceException("Error when executing change isLatest operation with return type: "+returnType.getMessage());
        }
    }

    public void createAndAddTxDigest(final StagingTable transactionDigest, UUID digestId)
        throws MDBCServiceException {
        ByteBuffer serializedTransactionDigest;
        serializedTransactionDigest = transactionDigest.getSerializedStagingAndClean();
        if(useCompression){
            serializedTransactionDigest = StagingTable.Compress(serializedTransactionDigest);
        }
        addTxDigest(digestId, serializedTransactionDigest);
    }

    /**
     * Writes the transaction information to metric's txDigest and musicRangeInformation table
     * This officially commits the transaction globally
     */
    @Override
    public void commitLog(DatabasePartition partition,Set<Range> eventualRanges,  StagingTable transactionDigest,
                          String txId ,TxCommitProgress progressKeeper) throws MDBCServiceException {
        
        // first deal with commit for eventually consistent tables
        filterAndAddEventualTxDigest(eventualRanges, transactionDigest, txId, progressKeeper);
        
        if(partition==null){
            logger.warn("Trying tcommit log with null partition");
            return;
        }

        Set<Range> snapshot = partition.getSnapshot();
        if(snapshot==null || snapshot.isEmpty()){
            logger.warn("Trying to commit log with empty ranges");
            return;
        }

        //Add creation type of transaction digest
        if(transactionDigest == null || transactionDigest.isEmpty()) {
            return;
        }
        
        UUID mriIndex = partition.getMRIIndex();
        String fullyQualifiedMriKey = music_ns+"."+ this.musicRangeInformationTableName+"."+mriIndex;
        //0. See if reference to lock was already created
        String lockId = partition.getLockId();
        if(mriIndex==null || lockId == null || lockId.isEmpty()) {
            throw new MDBCServiceException("Not able to commit, as you are no longer the lock-holder for this partition");
        }


        final MusicTxDigestId digestId = new MusicTxDigestId(MDBCUtils.generateUniqueKey(), -1);
        Callable<Boolean> insertDigestCallable =()-> {
            try {
                createAndAddTxDigest(transactionDigest,digestId.transactionId);
                return true;
            } catch (MDBCServiceException e) {
                logger.error(EELFLoggerDelegate.errorLogger, "Error creating and pushing tx digest to music",e);
                return false;
            }
        };
        Callable<Boolean> appendCallable=()-> {
            try {
                appendToRedoLog(music_ns, mriIndex, digestId.transactionId, lockId, musicTxDigestTableName,
                    musicRangeInformationTableName);
                return true;
            } catch (MDBCServiceException e) {
                logger.error(EELFLoggerDelegate.errorLogger, "Error creating and pushing tx digest to music",e);
                return false;
            }
        };

        Future<Boolean> appendResultFuture = commitExecutorThreads.submit(appendCallable);
        Future<Boolean> digestFuture = commitExecutorThreads.submit(insertDigestCallable);
        try {
            //Boolean appendResult = appendResultFuture.get();
            Boolean digestResult = digestFuture.get();
            if(/*!appendResult ||*/ !digestResult){
                logger.error(EELFLoggerDelegate.errorLogger, "Error appending to log or adding tx digest");
                throw new MDBCServiceException("Error appending to log or adding tx digest");
            }
        } catch (InterruptedException|ExecutionException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Error executing futures for creating and pushing tx " +
                "digest to music",e);
            throw new MDBCServiceException("Failure when retrieving futures for execution of digestion creation and append", e);
        }

        if (progressKeeper != null) {
            progressKeeper.setRecordId(txId, digestId);
        }
        Set<Range> ranges = partition.getSnapshot();
        for(Range r : ranges) {
            Map<Range, Pair<MriReference, Integer>> alreadyApplied = stateManager.getOwnAndCheck().getAlreadyApplied();
            if(!alreadyApplied.containsKey(r)){
                throw new MDBCServiceException("already applied data structure was not updated correctly and range "
                    +r+" is not contained");
            }
            Pair<MriReference, Integer> rowAndIndex = alreadyApplied.get(r);
            MriReference key = rowAndIndex.getKey();
            if(!mriIndex.equals(key.index)){
                throw new MDBCServiceException("already applied data structure was not updated correctly and range "+
                    r+" is not pointing to row: "+mriIndex.toString());
            }
            alreadyApplied.put(r, Pair.of(new MriReference(mriIndex), rowAndIndex.getValue()+1));
        }
    }    

    private void filterAndAddEventualTxDigest(Set<Range> eventualRanges,
                                              StagingTable transactionDigest, String txId,
                                              TxCommitProgress progressKeeper) throws MDBCServiceException {
        
        if(eventualRanges == null || eventualRanges.isEmpty()) {
            return;
        }

        if(!transactionDigest.areEventualContained(eventualRanges)){
            throw new MDBCServiceException();
        }
        
        if(!transactionDigest.isEventualEmpty()) {
            ByteBuffer serialized = transactionDigest.getSerializedEventuallyStagingAndClean();

            if (serialized!=null && useCompression) {
                serialized = StagingTable.Compress(serialized);
            }

            if (serialized != null) {
                MusicTxDigestId digestId = new MusicTxDigestId(MDBCUtils.generateUniqueKey(), -1);
                addEventualTxDigest(digestId, serialized);
            }
        }
        
    }

    /**
     * @param tableName
     * @param string
     * @param rowValues
     * @return
     */
    @SuppressWarnings("unused")
    private String getUid(String tableName, String string, Object[] rowValues) {
        //
        // Update local MUSIC node. Note: in Cassandra you can insert again on an existing key..it becomes an update
        String cql = String.format("SELECT * FROM %s.%s;", music_ns, tableName);
        PreparedStatement ps = getPreparedStatementFromCache(cql);
        BoundStatement bound = ps.bind();
        bound.setReadTimeoutMillis(60000);
        Session sess = getMusicSession();
        ResultSet rs;
        synchronized (sess) {
            rs = sess.execute(bound);
        }

        //should never reach here
        logger.error(EELFLoggerDelegate.errorLogger, "Could not find the row in the primary key");
        return null;
    }

    public Object[] getObjects(TableInfo ti, String tableName, JSONObject row) {
        // \FIXME: we may need to add the primary key of the row if it was autogenerated by MUSIC
        List<String> cols = ti.columns;
        int size = cols.size();
        boolean hasDefault = false;
        if(row.has(getMusicDefaultPrimaryKeyName())) {
            size++;
            hasDefault = true;
        }

        Object[] objects = new Object[size];
        int idx = 0;
        if(hasDefault) {
            objects[idx++] = row.getString(getMusicDefaultPrimaryKeyName());
        }
        for(String col : ti.columns) {
            objects[idx]=row.get(col);
        }
        return objects;
    }

    @Override
    public List<UUID> getPartitionIndexes() throws MDBCServiceException {
        ArrayList<UUID> partitions = new ArrayList<UUID>();
        String cql = String.format("SELECT rangeid FROM %s.%s", music_ns, musicRangeInformationTableName);
        ResultSet rs = executeMusicRead(cql);
        for (Row r: rs) {
            partitions.add(r.getUUID("rangeid"));
        }
        return partitions;
    }


    public List<Range> getRanges(Row newRow){
        List<Range> partitions = new ArrayList<>();
        Set<String> tables = newRow.getSet("keys",String.class);
        for (String table:tables){
            partitions.add(new Range(table));
        }
        return partitions;
    }

    static public MusicRangeInformationRow getMRIRowFromCassandraRow(Row newRow){
        UUID partitionIndex = newRow.getUUID("rangeid");
        List<TupleValue> log = newRow.getList("txredolog",TupleValue.class);
        List<MusicTxDigestId> digestIds = new ArrayList<>();
        int index=0;
        for(TupleValue t: log){
            //final String tableName = t.getString(0);
            final UUID id = t.getUUID(1);
            digestIds.add(new MusicTxDigestId(partitionIndex,id,index++));
        }
        Set<Range> partitions = new HashSet<>();
        Set<String> tables = newRow.getSet("keys",String.class);
        for (String table:tables){
            partitions.add(new Range(table));
        }
        return new MusicRangeInformationRow(new DatabasePartition(partitions, partitionIndex, ""),
            digestIds, newRow.getBool("islatest"), newRow.getSet("prevmrirows", UUID.class));
    }

    public RangeDependency getRangeDependenciesFromCassandraRow(Row newRow){
        if(newRow == null) return null;
        String base = newRow.getString("range");
        Range baseRange = new Range(base);
        Set<String> dependencies = newRow.getSet("dependencies", String.class);
        List<Range> rangeDependencies = new ArrayList<>();
        for(String dependency: dependencies){
            rangeDependencies.add(new Range(dependency));
        }
        return new RangeDependency(baseRange,rangeDependencies);
    }

    @Override
    public MusicRangeInformationRow getMusicRangeInformation(UUID partitionIndex) throws MDBCServiceException {
        //TODO: verify that lock id is valid before calling the database operations function
        //UUID id = partition.getMusicRangeInformationIndex();

        String cql = String.format("SELECT * FROM %s.%s WHERE rangeid = ?;", music_ns, musicRangeInformationTableName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        pQueryObject.addValue(partitionIndex);
        Row newRow;
        try {
            newRow = executeMusicUnlockedQuorumGet(pQueryObject);
        } catch (MDBCServiceException e) {
            logger.error("Get operationt error: Failure to get row from MRI "+musicRangeInformationTableName);
            throw new MDBCServiceException("Initialization error:Failure to add new row to transaction information", e);
        }

        return getMRIRowFromCassandraRow(newRow);
    }

    @Override
    public RangeDependency getMusicRangeDependency(Range baseRange) throws MDBCServiceException {
        String cql = String.format("SELECT * FROM %s.%s WHERE range = ?;", music_ns, musicRangeDependencyTableName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        pQueryObject.addValue(baseRange.getTable());
        Row newRow;
        //TODO Change this when music fix the "." problem in the primary key
        final String table = baseRange.getTable();
        final String tableWithoutDot = table.replaceAll("\\.","");
        try {
            newRow = executeMusicLockedGet(music_ns, musicRangeDependencyTableName,pQueryObject,tableWithoutDot,null);
        } catch (MDBCServiceException e) {
            logger.error("Get operation  error: Failure to get row from " + musicRangeDependencyTableName + " trying for table " + tableWithoutDot);
            throw new MDBCServiceException("Initialization error:Failure to add new row to transaction information for table "+tableWithoutDot, e);
        }
        return getRangeDependenciesFromCassandraRow(newRow);
    }

    /**
     * This function creates the TransactionInformation table. It contain information related
     * to the transactions happening in a given partition.
     *   * The schema of the table is
     *      * Id, uiid.
     *      * Partition, uuid id of the partition
     *      * LatestApplied, int indicates which values from the redologtable wast the last to be applied to the data tables
     *      * Applied: boolean, indicates if all the values in this redo log table where already applied to data tables
     *      * Redo: list of uiids associated to the Redo Records Table
     *
     */
    public static void createMusicRangeInformationTable(String namespace, String tableName) throws MDBCServiceException {
        String priKey = "rangeid";
        StringBuilder fields = new StringBuilder();
        fields.append("rangeid uuid, ");
        fields.append("keys set<text>, ");
        fields.append("prevmrirows set<uuid>, ");
        fields.append("islatest boolean, ");
        //TODO: Frozen is only needed for old versions of cassandra, please update correspondingly
        fields.append("txredolog list<frozen<tuple<text,uuid>>> ");
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));",
           namespace, tableName, fields, priKey);
        try {
            executeMusicWriteQuery(namespace,tableName,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create transaction information table");
            throw(e);
        }
    }


    @Override
    public DatabasePartition createLockedMRIRow(MusicRangeInformationRow info) throws MDBCServiceException {
        DatabasePartition newPartition = info.getDBPartition();

        String fullyQualifiedMriKey = music_ns+"."+ musicRangeInformationTableName+"."+newPartition.getMRIIndex().toString();
        String lockId;
        int counter=0;
        do {
            lockId = createAndAssignLock(fullyQualifiedMriKey, newPartition);
            //TODO: fix this retry logic
        } while ((lockId ==null||lockId.isEmpty())&&(counter++<3));
        if (lockId == null || lockId.isEmpty()) {
            throw new MDBCServiceException("Error initializing music range information, error creating a lock for a new row" +
                "for key "+fullyQualifiedMriKey) ;
        }
        logger.info("Creating MRI " + newPartition.getMRIIndex() + " for ranges " + newPartition.getSnapshot());
        newPartition.setLockId(lockId);
        
        createEmptyMriRow(info);
        return newPartition;
    }

    @Override
    public void createMusicRangeDependency(RangeDependency rangeAndDependencies) throws MDBCServiceException {
        StringBuilder insert = new StringBuilder("INSERT INTO ")
                .append(this.music_ns)
                .append('.')
                .append(this.musicRangeDependencyTableName)
                .append(" (range,dependencies) VALUES ")
                .append("(")
                .append(rangeAndDependencies.getRange().getTable())
                .append(",{");
        boolean first=true;
        for (Range r: rangeAndDependencies.dependentRanges()) {
            if(first){ first=false; }
            else {
                insert.append(',');
            }
            insert.append("'").append(r.toString()).append("'");
        }
        insert.append("};");
        PreparedQueryObject query = new PreparedQueryObject();
        query.appendQueryString(insert.toString());
        MusicCore.eventualPut(query);
    }

    /**
     * Creates a new empty MRI row
     * @param processId id of the process that is going to own initially this.
     * @return uuid associated to the new row
     */
    public void createEmptyMriRow(MusicRangeInformationRow rowToCreate) throws MDBCServiceException {
                StringBuilder insert = new StringBuilder("INSERT INTO ")
                    .append(this.music_ns)
                    .append('.')
                    .append(this.musicRangeInformationTableName)
                    .append(" (rangeid,keys,islatest,prevmrirows,txredolog) VALUES ")
                    .append("(")
                    .append(rowToCreate.getPartitionIndex())
                    .append(",{");
                String sep = "";
                for (Range r: rowToCreate.getDBPartition().getSnapshot()) {
                    insert.append(sep).append("'").append(r.toString()).append("'");
                    sep = ",";
                }
                insert.append("},").append(rowToCreate.getIsLatest())
                    .append(",{");
                sep = "";
                for (UUID prevIndex: rowToCreate.getPrevRowIndexes()) {
                    insert.append(sep).append(prevIndex);
                    sep = ",";
                }
                    insert.append("},[]);");
                PreparedQueryObject query = new PreparedQueryObject();
                query.appendQueryString(insert.toString());
                try {
                    executeMusicLockedPut(this.music_ns,this.musicRangeInformationTableName,
                            rowToCreate.getPartitionIndex().toString(),query,
                            rowToCreate.getDBPartition().getLockId(),null);
                } catch (MDBCServiceException e) {
                    throw new MDBCServiceException("Initialization error:Failure to add new row to transaction information", e);
                }
    }
    
    /**
     * Creates a new empty MRI row
     * @param processId id of the process that is going to own initially this.
     * @return uuid associated to the new row
     * @deprecated
     */
    public static UUID createEmptyMriRow(String musicNamespace, String mriTableName, UUID id, String processId,
        String lockId, List<Range> ranges, boolean isLatest)
        throws MDBCServiceException{
        StringBuilder insert = new StringBuilder("INSERT INTO ")
            .append(musicNamespace)
            .append('.')
            .append(mriTableName)
            .append(" (rangeid,keys,islatest,prevmrirows,txredolog) VALUES ")
            .append("(")
            .append(id)
            .append(",{");
        String sep = "";
        for (Range r: ranges) {
            insert.append(sep).append("'").append(r.toString()).append("'");
            sep = ",";
        }
        insert.append("},").append(isLatest)
            .append(",{");
            insert.append("},[]);");
        PreparedQueryObject query = new PreparedQueryObject();
        query.appendQueryString(insert.toString());
        try {
            executeMusicLockedPut(musicNamespace,mriTableName,id.toString(),query,lockId,null);
        } catch (MDBCServiceException e) {
            throw new MDBCServiceException("Initialization error:Failure to add new row to transaction information", e);
        }
        return id;
    }

    @Override
    public void appendToRedoLog(UUID MRIIndex,  String lockId, MusicTxDigestId newRecord) throws MDBCServiceException {
        logger.debug("Appending to redo log for partition " + MRIIndex + " txId=" + newRecord.transactionId);
        appendToRedoLog(music_ns,MRIIndex,newRecord.transactionId,lockId,musicTxDigestTableName,
            musicRangeInformationTableName);
    }

    public void appendToRedoLog(String musicNamespace, UUID MRIIndex, UUID transactionId, String lockId,
                                        String musicTxDigestTableName, String musicRangeInformationTableName)
        throws MDBCServiceException{
        PreparedQueryObject appendQuery = createAppendMtxdIndexToMriQuery(musicRangeInformationTableName, MRIIndex,
            musicTxDigestTableName, transactionId);
        ReturnType returnType = MusicCore.criticalPut(musicNamespace, musicRangeInformationTableName, MRIIndex.toString(),
            appendQuery, lockId, null);
        //returnType.getExecutionInfo()
        if (returnType.getResult().compareTo(ResultType.SUCCESS) != 0) {
            logger.error(EELFLoggerDelegate.errorLogger, "Error when executing append operation with return type: "+returnType.getMessage());
            throw new MDBCServiceException("Error when executing append operation with return type: "+returnType.getMessage());
        }
    }

    public void createMusicTxDigest() throws MDBCServiceException {
        createMusicTxDigest(this.musicTxDigestTableName,this.music_ns,-1);
    }
    
    public void createMusicEventualTxDigest() throws MDBCServiceException {
        createMusicEventualTxDigest(musicEventualTxDigestTableName,music_ns,-1);
    }


    /**
     * This function creates the MusicEveTxDigest table. It contain information related to each eventual transaction committed
     *  * LeaseId: id associated with the lease, text
     *  * LeaseCounter: transaction number under this lease, bigint \TODO this may need to be a varint later
     *  * TransactionDigest: text that contains all the changes in the transaction
     */
    public static void createMusicEventualTxDigest(String musicEventualTxDigestTableName, String musicNamespace, int musicTxDigestTableNumber) throws MDBCServiceException {
        String tableName = musicEventualTxDigestTableName;
        if (musicTxDigestTableNumber >= 0) {
            tableName = tableName +
                "-" +
                Integer.toString(musicTxDigestTableNumber);
        }
        String priKey = "txTimeId, year";
        StringBuilder fields = new StringBuilder();
        fields.append("txid uuid, ");
        fields.append("transactiondigest blob, ");
        fields.append("compressed boolean, ");
        fields.append("year int, ");
        fields.append("txTimeId TIMEUUID ");//notice lack of ','
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));", musicNamespace, tableName, fields, priKey);
        try {
            executeMusicWriteQuery(musicNamespace,tableName,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create eventual tx digest table");
            throw(e);
        }
    }
    
    
    /**
     * This function creates the MusicTxDigest table. It contain information related to each transaction committed
     *  * LeaseId: id associated with the lease, text
     *  * LeaseCounter: transaction number under this lease, bigint \TODO this may need to be a varint later
     *  * TransactionDigest: text that contains all the changes in the transaction
     */
    public static void createMusicTxDigest(String musicTxDigestTableName, String musicNamespace, int musicTxDigestTableNumber) throws MDBCServiceException {
        String tableName = musicTxDigestTableName;
        if (musicTxDigestTableNumber >= 0) {
            tableName = tableName +
                "-" +
                Integer.toString(musicTxDigestTableNumber);
        }
        String priKey = "txid";
        StringBuilder fields = new StringBuilder();
        fields.append("txid uuid, ");
        fields.append("compressed boolean, ");
        fields.append("transactiondigest blob ");//notice lack of ','
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));", musicNamespace,
            tableName, fields, priKey);
        try {
            executeMusicWriteQuery(musicNamespace,tableName,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create redo records table");
            throw(e);
        }
    }

    public static void createMusicRangeDependencyTable(String musicNamespace,String musicRangeDependencyTableName)
        throws MDBCServiceException {
        String tableName = musicRangeDependencyTableName;
        String priKey = "range";
        StringBuilder fields = new StringBuilder();
        fields.append("range text, ");
        fields.append("dependencies set<text> ");//notice lack of ','
        String cql = String.format("CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));", musicNamespace, tableName,
            fields, priKey);
        try {
            executeMusicWriteQuery(musicNamespace,tableName,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create redo records table");
            throw(e);
        }
    }
    
    private void createMusicMdbcCheckpointTable() throws MDBCServiceException {
        createMusicMdbcCheckpointTable(this.music_ns, this.musicMdbcCheckpointsTableName);
    }
    
    public static void createMusicMdbcCheckpointTable(String namespace, String checkpointTable) throws MDBCServiceException {
        String priKey = "txid";
        StringBuilder fields = new StringBuilder();
        fields.append("txid uuid, ");
        fields.append("compressed boolean, ");
        fields.append("transactiondigest blob ");//notice lack of ','
        String cql =
                String.format("CREATE TABLE IF NOT EXISTS %s.%s (mdbcnode UUID, mridigest UUID, digestindex int, PRIMARY KEY (mdbcnode));",
                        namespace, checkpointTable);
        try {
            executeMusicWriteQuery(namespace,checkpointTable,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create redo records table");
            throw(e);
        }
    }

    /**
     * Writes the transaction history to the txDigest
     */
    @Override
    public void addTxDigest(MusicTxDigestId newId, ByteBuffer transactionDigest) throws MDBCServiceException {
        //\TODO: Save Prepared query to history
        addTxDigest(newId.transactionId,transactionDigest);
    }

    private void addTxDigest(UUID digestId, ByteBuffer transactionDigest) throws MDBCServiceException{
        PreparedQueryObject query = new PreparedQueryObject();
        String cql = String.format("INSERT INTO %s.%s (txid,transactiondigest,compressed ) VALUES (?,?,?);",this.music_ns,
            this.musicTxDigestTableName);
        query.appendQueryString(cql);
        query.addValue(digestId);
        query.addValue(transactionDigest);
        query.addValue(useCompression);
        //\TODO check if I am not shooting on my own foot
        try {
            MusicCore.nonKeyRelatedPut(query,"critical");
        } catch (MusicServiceException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Transaction Digest serialization was invalid for digest id "+digestId.toString()+ "with error "+e.getErrorMessage());
            throw new MDBCServiceException("Transaction Digest serialization for digest id "+digestId.toString(), e);
        }
    }
    
    /**
     * Writes the Eventual transaction history to the evetxDigest
     */
    @Override
    public void addEventualTxDigest(MusicTxDigestId newId, ByteBuffer transactionDigest) throws MDBCServiceException {
        //createTxDigestRow(music_ns,musicTxDigestTable,newId,transactionDigest);
        PreparedQueryObject query = new PreparedQueryObject();
        int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
        
        String cql = String.format("INSERT INTO %s.%s (txid,transactiondigest,compressed,year,txTimeId ) VALUES (?,?,?,?,now());",this.music_ns,
                this.musicEventualTxDigestTableName);
            query.appendQueryString(cql);
            query.addValue( newId.transactionId);
            query.addValue(transactionDigest);
            query.addValue(useCompression);
            query.addValue(year);
           // query.appendQueryString(cqlQuery);
        //\TODO check if I am not shooting on my own foot
        try {
            MusicCore.nonKeyRelatedPut(query,"critical");
        } catch (MusicServiceException e) {
            logger.error(EELFLoggerDelegate.errorLogger, "Transaction Digest serialization was invalid for commit "+newId.transactionId.toString()+ "with error "+e.getErrorMessage());
            throw new MDBCServiceException("Transaction Digest serialization for commit "+newId.transactionId.toString(), e);
        }
    }


    @Override
    public StagingTable getTxDigest(MusicTxDigestId id) throws MDBCServiceException {
        String cql = String.format("SELECT * FROM %s.%s WHERE txid = ?;", music_ns, musicTxDigestTableName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        pQueryObject.addValue(id.transactionId);
        Row newRow;
        try {
            newRow = executeMusicUnlockedQuorumGet(pQueryObject);
        } catch (MDBCServiceException e) {
            logger.error("Get operation error: Failure to get row from txdigesttable with id:"+id.transactionId);
            throw new MDBCServiceException("Initialization error:Failure to add new row to transaction information", e);
        }
        ByteBuffer digest = newRow.getBytes("transactiondigest");
        Boolean compressed = newRow.getBool("compressed");
        StagingTable changes;
        try {
            if(compressed){
                digest = StagingTable.Decompress(digest);
            }
            changes = new StagingTable(digest);
        } catch (MDBCServiceException e) {
            logger.error("Deserializng digest failed with an exception:"+e.getErrorMessage());
            throw e;
        }
        return changes;
    }

    @Override
    public LinkedHashMap<UUID, StagingTable> getEveTxDigest(String nodeName) throws MDBCServiceException {
        int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
        StringBuffer yearSb = new StringBuffer();
        String sep = "";
        for (int y=2019; y<=year; y++) {
            yearSb.append(sep);
            yearSb.append(y);
            sep = ",";
        }

        StagingTable changes;
        String cql;
        LinkedHashMap<UUID, StagingTable> ecDigestInformation = new LinkedHashMap<>();
        UUID musicevetxdigestNodeinfoTimeID = getTxTimeIdFromNodeInfo(nodeName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();

        if (musicevetxdigestNodeinfoTimeID != null) {
            // this will fetch only few records based on the time-stamp condition.
            cql = String.format("SELECT * FROM %s.%s WHERE year in (%s) AND txtimeid > ? LIMIT 10 ALLOW FILTERING;", music_ns, this.musicEventualTxDigestTableName, yearSb.toString());
            pQueryObject.appendQueryString(cql);
            pQueryObject.addValue(musicevetxdigestNodeinfoTimeID);
        } else {
            // This is going to Fetch all the Transactiondigest records from the musicevetxdigest table.
            cql = String.format("SELECT * FROM %s.%s WHERE year in (%s) LIMIT 10 ALLOW FILTERING;", music_ns, this.musicEventualTxDigestTableName, yearSb.toString());
            pQueryObject.appendQueryString(cql);
        }

        // I need to get a ResultSet of all the records and give each row to the below HashMap.
        ResultSet rs = executeMusicRead(pQueryObject);
        while (!rs.isExhausted()) {
            Row row = rs.one();
            ByteBuffer digest = row.getBytes("transactiondigest");
            Boolean compressed = row.getBool("compressed");
            //String txTimeId = row.getString("txtimeid"); //???
            UUID txTimeId = row.getUUID("txtimeid");

            try {
                if(compressed){
                    digest=StagingTable.Decompress(digest);
                }
                changes = new StagingTable(digest);
            } catch (MDBCServiceException e) {
                logger.error("Deserializng digest failed: "+e.getErrorMessage());
                throw e;
            }
            ecDigestInformation.put(txTimeId, changes);
        }
        return ecDigestInformation;
    }

    ResultSet getAllMriCassandraRows() throws MDBCServiceException {
        StringBuilder cqlOperation = new StringBuilder();
        cqlOperation.append("SELECT * FROM ")
            .append(music_ns)
            .append(".")
            .append(musicRangeInformationTableName);
        return executeMusicRead(cqlOperation.toString());
    }

    @Override
    public List<MusicRangeInformationRow> getAllMriRows() throws MDBCServiceException{
        List<MusicRangeInformationRow> rows = new ArrayList<>();
        final ResultSet mriCassandraRows = getAllMriCassandraRows();
        while (!mriCassandraRows.isExhausted()) {
            Row musicRow = mriCassandraRows.one();
            final MusicRangeInformationRow mriRow = getMRIRowFromCassandraRow(musicRow);
            rows.add(mriRow);
        }
        return rows;
    }

    /**
     * This function is used to find all the related uuids associated with the required ranges
     * @param ranges ranges to be find
     * @return a map that associates each MRI row to the corresponding ranges
     */
    private Map<Range,RangeMriRow> findRangeRows(List<Range> ranges) throws MDBCServiceException {
        /* \TODO this function needs to be improved, by creating an additional index, or at least keeping a local cache
         Additionally, we should at least used pagination and the token function, to avoid retrieving the whole table at
         once, this can become problematic if we have too many connections in the overall METRIC system */
        Map<Range,RangeMriRow> result = new HashMap<>();
        for(Range r:ranges){
            result.put(r,null);
        }
        int counter=0;
        final ResultSet musicResults = getAllMriCassandraRows();
        while (!musicResults.isExhausted()) {
            Row musicRow = musicResults.one();
            final MusicRangeInformationRow mriRow = getMRIRowFromCassandraRow(musicRow);
            final List<Range> musicRanges = getRanges(musicRow);
            //\TODO optimize this for loop to avoid redudant access
            for(Range retrievedRange : musicRanges) {
                for(Map.Entry<Range,RangeMriRow> e : result.entrySet()) {
                    Range range = e.getKey();
                    if (retrievedRange.overlaps(range)) {
                        RangeMriRow r = e.getValue();
                        if(r==null){
                            counter++;
                            RangeMriRow newMriRow = new RangeMriRow(range);
                            newMriRow.setCurrentRow(mriRow);
                            result.replace(range,newMriRow);
                        }
                        else if(r.getCurrentRow().getTimestamp() < mriRow.getTimestamp()){
                            r.addOldRow(r.getCurrentRow());
                            r.setCurrentRow(mriRow);
                        }
                        else{
                            r.addOldRow(mriRow);
                        }
                    }
                }
            }
        }

        if(ranges.size() != counter){
            logger.error("Row in MRI doesn't exist for "+Integer.toString(counter)+" ranges");
            throw new MDBCServiceException("MRI row doesn't exist for "+Integer.toString(counter)+" ranges");
        }
        return result;
    }

    private void unlockKeyInMusic(String table, String key, String lockref) throws MDBCServiceException {
        String fullyQualifiedKey= music_ns+"."+ table+"."+key;
        try {
            MusicCore.voluntaryReleaseLock(fullyQualifiedKey,lockref);
        } catch (MusicLockingException e) {
            throw new MDBCServiceException(e.getMessage(), e);
        }
    }

    @Override
    public void releaseLocks(Map<UUID,LockResult> newLocks) throws MDBCServiceException{
        for(Map.Entry<UUID,LockResult> lock : newLocks.entrySet()) {
            unlockKeyInMusic(musicRangeInformationTableName, lock.getKey().toString(), lock.getValue().getLockId());
        }
    }

    private void releaseLocks(List<MusicRangeInformationRow> changed, Map<UUID,LockResult> newLocks) throws MDBCServiceException{
        
        for(MusicRangeInformationRow r : changed) {
            LockResult lock = newLocks.get(r.getPartitionIndex());
            if(lock == null)
                continue;
            unlockKeyInMusic(musicRangeInformationTableName, r.getPartitionIndex().toString(),
                lock.getLockId());
            newLocks.remove(r.getPartitionIndex());
        }
    }

    private void releaseAllLocksExcept(UUID finalRow, Map<UUID,LockResult> newLocks) throws MDBCServiceException {
        Set<UUID> toErase = new HashSet<>();
        for(Map.Entry<UUID,LockResult> lock : newLocks.entrySet()) {
            UUID id = lock.getKey();
            if(id!=finalRow){
                unlockKeyInMusic(musicRangeInformationTableName, id.toString(), lock.getValue().getLockId());
                toErase.add(id);
            }
        }
        for(UUID id:toErase){
           newLocks.remove(id);
        }
    }

    /**
     * Get a list of ranges and their range dependencies
     * @param range
     * @return
     * @throws MDBCServiceException
     */
    @Override
    public Set<Range> getRangeDependencies(Set<Range> range) throws MDBCServiceException{
        Set<Range> extendedRange = new HashSet<>();
        for(Range r: range){
            extendedRange.add(r);
            RangeDependency dependencies = getMusicRangeDependency(r);
            if(dependencies!=null){
               extendedRange.addAll(dependencies.dependentRanges());
            }
        }
        return extendedRange;
    }

    @Override
    public String createLock(LockRequest request) throws MDBCServiceException{
        String fullyQualifiedKey= music_ns+"."+ musicRangeInformationTableName + "." + request.getId();
        boolean isWrite = (request.getLockType()==SQLOperationType.WRITE);
        String lockId = MusicCore.createLockReference(fullyQualifiedKey, isWrite);
        return lockId;
    }

    @Override
    public LockResult acquireLock(LockRequest request, String lockId) throws MDBCServiceException{
        String fullyQualifiedKey= music_ns+"."+ musicRangeInformationTableName + "." + request.getId();
        ReturnType lockReturn = acquireLock(fullyQualifiedKey,lockId);
        if(lockReturn.getResult() == ResultType.FAILURE) {
            //\TODO Improve the exponential backoff
            int n = request.getNumOfAttempts();
            int low = 1;
            int high = 1000;
            Random r = new Random();
            long backOffTimems = ((int) Math.round(Math.pow(2, n)) * 1000)
                    + (r.nextInt(high - low) + low);
            return new LockResult(false, backOffTimems);
        }
        return new LockResult(true, request.getId(),lockId,true,null);
    }


    /**
     *  fixes the DAG in case the previous owner failed while trying to own the row
     * @param latestDag
     * @param locks
     * @throws MDBCServiceException
     */
    private void recoverFromFailureAndUpdateDag(Dag latestDag, Map<UUID,LockResult> locks) throws MDBCServiceException {
        Pair<Set<Range>, Set<DagNode>> rangesAndDependents = latestDag.getIncompleteRangesAndDependents();
        if(rangesAndDependents.getKey()==null || rangesAndDependents.getKey().size()==0 ||
            rangesAndDependents.getValue()==null || rangesAndDependents.getValue().size() == 0){
            return;
        }
        
        Set<UUID> prevPartitions = new HashSet<>();
        for (DagNode dagnode: rangesAndDependents.getRight()) {
            prevPartitions.add(dagnode.getId());
        }
        
        MusicRangeInformationRow r = createAndAssignLock(rangesAndDependents.getKey(), prevPartitions);
        locks.put(r.getPartitionIndex(),new LockResult(r.getPartitionIndex(),r.getDBPartition().getLockId(),true,rangesAndDependents.getKey()));
        latestDag.addNewNode(r,new ArrayList<>(rangesAndDependents.getValue()));
    }


    private List<MusicRangeInformationRow> setReadOnlyAnyDoubleRow(Dag latestDag,Map<UUID,LockResult> locks)
        throws MDBCServiceException{
        List<MusicRangeInformationRow> returnInfo = new ArrayList<>();
        List<DagNode> toDisable = latestDag.getOldestDoubles();
        for(DagNode node : toDisable){
            LockResult lockToDisable = locks.get(node.getId());
            if (lockToDisable!=null) {
                changeIsLatestToMRI(node.getRow().getPartitionIndex(),false,lockToDisable.getLockId());
            }
            latestDag.setIsLatest(node.getId(),false);
            returnInfo.add(node.getRow());
        }
        return returnInfo;
    }

    /**
     * Create a set of previous partitions to their uuids
     * @param latestRows
     * @return
     */
    private Set<UUID> extractPreviousPartitions(List<MusicRangeInformationRow> latestRows) {
        Set<UUID> prevMRIRow = new HashSet<>();
        for (MusicRangeInformationRow mriRow: latestRows) {
            prevMRIRow.add(mriRow.getPartitionIndex());
        }
        return prevMRIRow;
    }

    @Override
    public OwnershipReturn mergeLatestRowsIfNecessary(Dag currentlyOwned, Map<UUID, LockResult> locksForOwnership, UUID ownershipId) throws MDBCServiceException {
        recoverFromFailureAndUpdateDag(currentlyOwned,locksForOwnership);

        if (locksForOwnership.keySet().size()==1) {
            //reuse if overlapping single partition, no merge necessary
            for (UUID uuid: locksForOwnership.keySet()) {
                return new OwnershipReturn(ownershipId, locksForOwnership.get(uuid).getLockId(), uuid,
                        currentlyOwned.getNode(uuid).getRangeSet(), currentlyOwned);
            }
        }
        
        //merge is necessary
        List<MusicRangeInformationRow> changed = setReadOnlyAnyDoubleRow(currentlyOwned, locksForOwnership);
        releaseLocks(changed, locksForOwnership);
        
        Set<Range> ranges = extractRangesToOwn(currentlyOwned, locksForOwnership.keySet());
        
        MusicRangeInformationRow createdRow = createAndAssignLock(ranges, locksForOwnership.keySet());
        currentlyOwned.addNewNodeWithSearch(createdRow, ranges);
        changed = setReadOnlyAnyDoubleRow(currentlyOwned, locksForOwnership);
        releaseLocks(locksForOwnership);
        return new OwnershipReturn(ownershipId, createdRow.getDBPartition().getLockId(), createdRow.getPartitionIndex(),
                createdRow.getDBPartition().getSnapshot(), currentlyOwned);
    }
    
    
    @Override
    public DatabasePartition splitPartitionIfNecessary(DatabasePartition partition, Set<Range> rangesUsed)
            throws MDBCServiceException {
        if (!this.splitAllowed) {
            return partition;
        }
        Set<Range> rangesOwned = partition.getSnapshot();
        if (rangesOwned==null || rangesUsed==null) {
            return partition;
        }
        if (!rangesOwned.containsAll(rangesUsed)) {
            throw new MDBCServiceException("Transaction was unable to acquire all necessary ranges.");
        }

        if (rangesUsed.containsAll(rangesOwned)) {
            //using all ranges in this partition
            return partition;
        }

        //split partition
        logger.info(EELFLoggerDelegate.applicationLogger, "Full partition not being used need (" + rangesUsed
                +") and own (" + rangesOwned + ", splitting the partition");
        Set<UUID> prevPartitions = new HashSet<>();
        prevPartitions.add(partition.getMRIIndex());
        MusicRangeInformationRow usedRow = createAndAssignLock(rangesUsed, prevPartitions);
        rangesOwned.removeAll(rangesUsed);
        Set<Range> rangesNotUsed = rangesOwned;
        MusicRangeInformationRow unusedRow = createAndAssignLock(rangesNotUsed, prevPartitions);

        changeIsLatestToMRI(partition.getMRIIndex(), false, partition.getLockId());

        Map<Range, Pair<MriReference, Integer>> alreadyApplied = stateManager.getOwnAndCheck().getAlreadyApplied();
        for (Range range: rangesUsed) {
            alreadyApplied.put(range, Pair.of(new MriReference(usedRow.getPartitionIndex()), -1));
        }
        for (Range range: rangesNotUsed) {
            alreadyApplied.put(range, Pair.of(new MriReference(unusedRow.getPartitionIndex()), -1));
        }

        //release/update old partition info
        relinquish(unusedRow.getDBPartition());
        relinquish(partition);

        return usedRow.getDBPartition();
    }
    

    private MusicRangeInformationRow createAndAssignLock(Set<Range> ranges, Set<UUID> prevPartitions) throws MDBCServiceException {
        UUID newUUID = MDBCUtils.generateTimebasedUniqueKey();
        DatabasePartition newPartition = new DatabasePartition(ranges,newUUID,null);
        MusicRangeInformationRow row = new MusicRangeInformationRow(newPartition, true, prevPartitions);
        createLockedMRIRow(row);
        return row;
    }

    private Set<Range> extractRangesToOwn(Dag currentlyOwned, Set<UUID> UUIDs) {
        HashSet<Range> ranges = new HashSet<>();
        for (UUID uuid: UUIDs) {
            ranges.addAll(currentlyOwned.getNode(uuid).getRow().getDBPartition().getSnapshot());
        }
        return ranges;
    }

    /**
     * This function is used to check if we need to create a new row in MRI, beacause one of the new ranges is not contained
     * @param ranges ranges that should be contained in the partition
     * @param partition currently own partition
     * @return
     */
    public boolean isAppendRequired(List<Range> ranges, DatabasePartition partition){
        for(Range r: ranges){
            if(!partition.isContained(r)){
                return true;
            }
        }
        return false;
    }


    @Override
    public void relinquish(DatabasePartition partition) throws MDBCServiceException {
        String lockId = partition.getLockId();
        String rangeId = partition.getMRIIndex().toString();
        if(lockId==null||lockId.isEmpty()||rangeId==null||rangeId.isEmpty()){
            return;
        }
        unlockKeyInMusic(musicRangeInformationTableName, rangeId, lockId);
        partition.setLockId(null);
    }

    @Override
    public void relinquish(String lockId, String rangeId) throws MDBCServiceException{
        if(lockId==null||lockId.isEmpty()||rangeId==null||rangeId.isEmpty()){
            return;
        }
        
        unlockKeyInMusic(musicRangeInformationTableName, rangeId, lockId);
        
    }

    /**
     * This function is used to rate the number of times we relinquish at the end of a transaction
     * @return true if we should try to relinquish, else should avoid relinquishing in this iteration
     */
    private boolean canTryRelinquishing(){
        //\TODO: Fix this!!!! REALLY IMPORTANT TO BE FIX
        // This should actually have some mechanism to relinquish ownership
        return true;
    }

    @Override
    public void relinquishIfRequired(DatabasePartition partition) throws MDBCServiceException {
        if(!canTryRelinquishing() || !partition.isLocked()){
            return;
        }
        long lockQueueSize;
        try {
            String fullyQualifiedKey= music_ns+"."+ this.musicRangeInformationTableName+"."+partition.getMRIIndex().toString();
            lockQueueSize = MusicCore.getLockQueueSize(fullyQualifiedKey);
        } catch (MusicServiceException|MusicQueryException|MusicLockingException e) {
            logger.error("Error obtaining the lock queue size");
            throw new MDBCServiceException("Error obtaining lock queue size: " + e.getMessage(), e);
        }
        if(lockQueueSize> 1){
            //If there is any other node waiting, we just relinquish ownership
            try {
                relinquish(partition);
            } catch (MDBCServiceException e) {
                logger.error("Error relinquishing lock, will use timeout to solve");
            }
            partition.setLockId("");
        }
    }

    /**
     * This method executes a write query in Music
     * @param cql the CQL to be sent to Cassandra
     */
    private static void executeMusicWriteQuery(String keyspace, String table, String cql)
            throws MDBCServiceException {
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        ResultType rt = null;
        try {
            rt = MusicCore.createTable(keyspace,table,pQueryObject,"critical");
        } catch (MusicServiceException e) {
            //\TODO: handle better, at least transform into an MDBCServiceException
            e.printStackTrace();
        }
        String result = rt.getResult();
        if (result==null || result.toLowerCase().equals("failure")) {
            throw new MDBCServiceException("Music eventual put failed");
        }
    }

    private static Row executeMusicLockedGet(String keyspace, String table, PreparedQueryObject cqlObject, String primaryKey,
                                             String lock)
        throws MDBCServiceException{
        ResultSet result = null;
        int triesRemaining = 3;
        while (result==null && triesRemaining>0) {
            if(lock != null && !lock.isEmpty()) {
                try {
                    result = MusicCore.criticalGet(keyspace, table, primaryKey, cqlObject, lock);
                } catch (MusicServiceException e) {
                    e.printStackTrace();
                    throw new MDBCServiceException("Error executing critical get", e);
                }
            }
            else{
                try {
                    result = MusicCore.atomicGet(keyspace,table,primaryKey,cqlObject);
                } catch (MusicServiceException|MusicLockingException|MusicQueryException e) {
                    e.printStackTrace();
                    throw new MDBCServiceException("Error executing atomic get", e);
                }
            }
            triesRemaining--;
        }
        if(result==null){
            throw new MDBCServiceException("Error executing atomic get for primary key: " + primaryKey + " and lock: " + lock);
        }
        if(result.isExhausted()){
            return null;
        }
        return result.one();
    }

    private static Row executeMusicUnlockedQuorumGet(PreparedQueryObject cqlObject) throws MDBCServiceException{
        ResultSet result = MusicCore.quorumGet(cqlObject);
        if(result == null || result.isExhausted()){
            throw new MDBCServiceException("There is not a row that matches the query: ["+cqlObject.getQuery()+"]");
        }
        return result.one();
    }

    private static void executeMusicLockedPut(String namespace, String tableName,
                                       String primaryKeyWithoutDomain, PreparedQueryObject queryObject, String lockId,
                                       Condition conditionInfo) throws MDBCServiceException {
        ReturnType rt ;
        if(lockId==null) {
            try {
                rt = MusicCore.atomicPut(namespace, tableName, primaryKeyWithoutDomain, queryObject, conditionInfo);
            } catch (MusicLockingException e) {
                logger.error("Music locked put failed");
                throw new MDBCServiceException("Music locked put failed", e);
            } catch (MusicServiceException e) {
                logger.error("Music service fail: Music locked put failed");
                throw new MDBCServiceException("Music service fail: Music locked put failed", e);
            } catch (MusicQueryException e) {
                logger.error("Music query fail: locked put failed");
                throw new MDBCServiceException("Music query fail: Music locked put failed", e);
            }
        }
        else {
            rt = MusicCore.criticalPut(namespace, tableName, primaryKeyWithoutDomain, queryObject, lockId, conditionInfo);
        }
        if (rt.getResult().getResult().toLowerCase().equals("failure")) {
            throw new MDBCServiceException("Music locked put failed");
        }
    }

    private void executeMusicLockedDelete(String namespace, String tableName, String primaryKeyValue, String lockId
        ) throws MDBCServiceException{
        StringBuilder delete = new StringBuilder("DELETE FROM ")
            .append(namespace)
            .append('.')
            .append(tableName)
            .append(" WHERE rangeid= ")
            .append(primaryKeyValue)
            .append(";");
        PreparedQueryObject query = new PreparedQueryObject();
        query.appendQueryString(delete.toString());
        executeMusicLockedPut(namespace,tableName,primaryKeyValue,query,lockId,null);
    }

    @Override
    public void replayTransaction(StagingTable digest) throws MDBCServiceException{
        //\TODO: implement logic to move data from digests to Music Data Tables
        //throw new NotImplementedException("Error, replay transaction in music mixin needs to be implemented");
        return;
    }

    @Override
    public void deleteOldMriRows(Map<UUID, String> oldRowsAndLocks) throws MDBCServiceException {
        //\TODO Do this operations in parallel or combine in only query to cassandra
        for(Map.Entry<UUID,String> rows : oldRowsAndLocks.entrySet()){
            //\TODO handle music delete correctly so we can delete the other rows
            executeMusicLockedDelete(music_ns,musicRangeInformationTableName,rows.getKey().toString(),rows.getValue());
        }
    }
    
    @Override
    public void updateNodeInfoTableWithTxTimeIDKey(UUID txTimeID, String nodeName) throws MDBCServiceException{
        
           String cql = String.format("UPDATE %s.%s SET txtimeid = %s, txupdatedatetime = now() WHERE nodename = ?;", music_ns, this.musicNodeInfoTableName, txTimeID);
            PreparedQueryObject pQueryObject = new PreparedQueryObject();
            pQueryObject.appendQueryString(cql);
            pQueryObject.addValue(nodeName);
            
            ReturnType rt = MusicCore.eventualPut(pQueryObject);
            if(rt.getResult().getResult().toLowerCase().equals("failure")) {
                logger.error(EELFLoggerDelegate.errorLogger, "Failure while eventualPut...: "+rt.getMessage());
            }
            else logger.info("Successfully updated nodeinfo table with txtimeid value: " + txTimeID + " against the node:" + nodeName);
            
        
    }
    
    public void createMusicNodeInfoTable() throws MDBCServiceException {
        createMusicNodeInfoTable(musicNodeInfoTableName,music_ns,-1);
    }
    
    /**
     * This function creates the NodeInfo table. It contain information related
     * to the nodes along with the updated transactionDigest details.
     *   * The schema of the table is
     *      * nodeId, uuid. 
     *      * nodeName, text or varchar?? for now I am going ahead with "text".
     *      * createDateTime, TIMEUUID.
     *      * TxUpdateDateTime, TIMEUUID.
     *      * TxTimeID, TIMEUUID.
     *      * LastTxDigestID, uuid. (not needed as of now!!)
     */
    public static void createMusicNodeInfoTable(String musicNodeInfoTableName, String musicNamespace, int nodeInfoTableNumber) throws MDBCServiceException {
        String tableName = musicNodeInfoTableName;
        if(nodeInfoTableNumber >= 0) {
            tableName = tableName +
                "-" +
                Integer.toString(nodeInfoTableNumber);
        }

        String priKey = "nodename";
        StringBuilder fields = new StringBuilder();
        fields.append("nodename text, ");
        fields.append("createdatetime TIMEUUID, ");
        fields.append("txupdatedatetime TIMEUUID, ");
        fields.append("txtimeid TIMEUUID ");
        //fields.append("LastTxDigestID uuid ");// Not needed as of now!     
        
        String cql = String.format(
                "CREATE TABLE IF NOT EXISTS %s.%s (%s, PRIMARY KEY (%s));",
                musicNamespace,
                tableName,
                fields,
                priKey);
        
        try {
            executeMusicWriteQuery(musicNamespace,tableName,cql);
        } catch (MDBCServiceException e) {
            logger.error("Initialization error: Failure to create node information table");
            throw(e);
        }
    }
    
    public UUID getTxTimeIdFromNodeInfo(String nodeName) throws MDBCServiceException {
            // expecting NodeName from base-0.json file: which is : NJNode
            //String nodeName = MdbcServer.stateManager.getMdbcServerName(); 
            // this retrieves the NJNode row from Cassandra's NodeInfo table so that I can retrieve TimeStamp for further processing.
        String cql = String.format("SELECT txtimeid FROM %s.%s WHERE nodeName = ?;", music_ns, musicNodeInfoTableName);  
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        pQueryObject.addValue(nodeName);
        Row newRow;
        try {
            newRow = executeMusicUnlockedQuorumGet(pQueryObject);
        } catch (MDBCServiceException e) {
            logger.error("Get operation error: Failure to get row from nodeinfo with nodename:"+nodeName);
            // TODO check underlying exception if no data and return empty string
            return null;
            //throw new MDBCServiceException("error:Failure to retrive nodeinfo details information", e);
        }
        
        return newRow.getUUID("txtimeid");

    }


    @Override
    public void deleteMriRow(MusicRangeInformationRow row) throws MDBCServiceException{
        String cql = String.format("DELETE FROM %s.%s WHERE rangeid = ?;", music_ns, musicRangeInformationTableName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        pQueryObject.addValue(row.getPartitionIndex());
        ReturnType rt ;
        try {
            rt = MusicCore.atomicPut(music_ns, musicRangeInformationTableName, row.getPartitionIndex().toString(),
                pQueryObject, null);
        } catch (MusicLockingException|MusicQueryException|MusicServiceException e) {
            logger.error("Failure when deleting mri row");
            new MDBCServiceException("Error deleting mri row",e);
        }
    }

    @Deprecated //used only in testing, should use other method instead
	public StateManager getStateManager() {
		return stateManager;
	}

    @Override
    public void createPartitionIfNeeded(Range rangeToCreate) throws MDBCServiceException {
        List<MusicRangeInformationRow> allRows = getAllMriRows();
        for (MusicRangeInformationRow row: allRows) {
            if (row.getDBPartition().getSnapshot().contains(rangeToCreate)) {
                //range already in MRI row, do not re-create
                return;
            }
        }

        MusicRangeInformationRow mriRow =
                createAndAssignLock(new HashSet<Range>(Arrays.asList(rangeToCreate)), new HashSet<UUID>());
        //TODO: should make sure we didn't create 2 new rows simultaneously, while we still own the lock
        unlockKeyInMusic(musicRangeInformationTableName, mriRow.getPartitionIndex().toString(),
                mriRow.getDBPartition().getLockId());
    }

    @Override
    public void updateCheckpointLocations(Range r, Pair<UUID, Integer> playbackPointer) {
        String cql = String.format("INSERT INTO %s.%s (mdbcnode, mridigest, digestindex) VALUES ("
                + this.myId + ", " + playbackPointer.getLeft() + ", " + playbackPointer.getRight() + ");",
                music_ns, this.musicMdbcCheckpointsTableName);
        PreparedQueryObject pQueryObject = new PreparedQueryObject();
        pQueryObject.appendQueryString(cql);
        try {
            MusicCore.nonKeyRelatedPut(pQueryObject,"eventual");
        } catch (MusicServiceException e) {
            logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to update the checkpoint location", e);
        }
    }
    
    
}