summaryrefslogtreecommitdiff
path: root/tcejdb/ejdb.c
blob: a81356ebaed66f76c7abb1d9e83bd0ca3cc12f35 (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
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530

#include "bson.h"


#include <regex.h>
#include "ejdb_private.h"
#include "ejdbutl.h"

/* private macros */
#define JBLOCKMETHOD(JB_ejdb, JB_wr)                            \
  ((JB_ejdb)->mmtx ? _ejdblockmethod((JB_ejdb), (JB_wr)) : true)
#define JBUNLOCKMETHOD(JB_ejdb)                         \
  ((JB_ejdb)->mmtx ? _ejdbunlockmethod(JB_ejdb) : true)

#define JBCLOCKMETHOD(JB_col, JB_wr)                            \
  ((JB_col)->mmtx ? _ejcollockmethod((JB_col), (JB_wr)) : true)
#define JBCUNLOCKMETHOD(JB_col)                         \
  ((JB_col)->mmtx ? _ejcollunlockmethod(JB_col) : true)

#define JBISOPEN(JB_jb) ((JB_jb) && (JB_jb)->metadb && (JB_jb)->metadb->open) ? true : false

#define JBISVALCOLNAME(JB_cname) ((JB_cname) && strlen(JB_cname) < JBMAXCOLNAMELEN && !index((JB_cname), '.'))

#define JBENSUREOPENLOCK(JB_jb, JB_lock, JB_ret)  \
                            assert(JB_jb); \
                            if (!JBLOCKMETHOD((JB_jb), (JB_lock))) return JB_ret; \
                            if (!JBISOPEN(JB_jb)) { \
                                _ejdbsetecode((JB_jb), TCEINVALID, __FILE__, __LINE__, __func__); \
                                JBUNLOCKMETHOD(JB_jb); \
                                return JB_ret; \
                            }

/* Default size of stack allocated buffer for string conversions eg. tcicaseformat() */
#define JBSTRINOPBUFFERSZ 512

/* Default size (16K) of tmp bson buffer on stack for field stripping in _pushstripbson() */
#define JBSBUFFERSZ 16384

/* string processing/conversion flags */
typedef enum {
    JBICASE = 1
} txtflags_t;

/* ejdb number */
typedef union {
    int64_t inum;
    double dnum;
} _EJDBNUM;

/* opaque data for `_bsonipathrowldr()` and `_bsonfpathrowldr()` functions */
typedef struct {
    EJCOLL *jcoll; //current collection
    bool icase; //ignore case normalization
} _BSONIPATHROWLDR;

/* private function prototypes */
static void _ejdbsetecode(EJDB *jb, int ecode, const char *filename, int line, const char *func);
static bool _ejdbsetmutex(EJDB *ejdb);
static bool _ejdblockmethod(EJDB *ejdb, bool wr);
static bool _ejdbunlockmethod(EJDB *ejdb);
static bool _ejdbcolsetmutex(EJCOLL *coll);
static bool _ejcollockmethod(EJCOLL *coll, bool wr);
static bool _ejcollunlockmethod(EJCOLL *coll);
static bool _bsonoidkey(bson *bs, bson_oid_t *oid);
static char* _bsonitstrval(EJDB *jb, bson_iterator *it, int *vsz, TCLIST *tokens, txtflags_t flags);
static char* _bsonipathrowldr(TCLIST *tokens, const char *pkbuf, int pksz, const char *rowdata, int rowdatasz,
        const char *ipath, int ipathsz, void *op, int *vsz);
static char* _bsonfpathrowldr(TCLIST *tokens, const char *rowdata, int rowdatasz,
        const char *fpath, int fpathsz, void *op, int *vsz);
EJDB_INLINE bool _isvalidoidstr(const char *oid);
static void _ejdbclear(EJDB *jb);
static bool _createcoldb(const char *colname, EJDB *jb, EJCOLLOPTS *opts, TCTDB** res);
static bool _addcoldb0(const char *colname, EJDB *jb, EJCOLLOPTS *opts, EJCOLL **res);
static void _delcoldb(EJCOLL *cdb);
static void _delqfdata(const EJQ *q, const EJQF *ejqf);
static bool _updatebsonidx(EJCOLL *jcoll, const bson_oid_t *oid, const bson *bs, const void *obsdata, int obsdatasz);
static bool _metasetopts(EJDB *jb, const char *colname, EJCOLLOPTS *opts);
static bool _metagetopts(EJDB *jb, const char *colname, EJCOLLOPTS *opts);
static bson* _metagetbson(EJDB *jb, const char *colname, int colnamesz, const char *mkey);
static bson* _metagetbson2(EJCOLL *jcoll, const char *mkey);
static bool _metasetbson(EJDB *jb, const char *colname, int colnamesz,
        const char *mkey, bson *val, bool merge, bool mergeoverwrt);
static bool _metasetbson2(EJCOLL *jcoll, const char *mkey, bson *val, bool merge, bool mergeoverwrt);
static bson* _imetaidx(EJCOLL *jcoll, const char *ipath);
static void _qrypreprocess(EJCOLL *jcoll, EJQ *ejq, int qflags, EJQF **mqf, TCMAP **ifields);
static TCMAP* _parseqobj(EJDB *jb, EJQ *q, bson *qspec);
static int _parse_qobj_impl(EJDB *jb, EJQ *q, bson_iterator *it, TCMAP *qmap, TCLIST *pathStack, EJQF *pqf);
static int _ejdbsoncmp(const TCLISTDATUM *d1, const TCLISTDATUM *d2, void *opaque);
static bool _qrycondcheckstrand(const char *vbuf, const TCLIST *tokens);
static bool _qrycondcheckstror(const char *vbuf, const TCLIST *tokens);
static bool _qrybsvalmatch(const EJQF *qf, bson_iterator *it, bool expandarrays);
static bool _qrybsmatch(const EJQF *qf, const void *bsbuf, int bsbufsz);
static bool _qryormatch(EJCOLL *jcoll, EJQ *ejq, const void *pkbuf, int pkbufsz, const void *bsbuf, int bsbufsz);
static bool _qryallcondsmatch(bool onlycount, int anum, EJCOLL *jcoll, const EJQF **qfs, int qfsz,
        const void *pkbuf, int pkbufsz, void **bsbuf, int *bsbufsz);
static void _qrydup(const EJQ *src, EJQ *target, uint32_t qflags);
static void _qrydel(EJQ *q, bool freequery);
static void _pushstripbson(TCLIST *rs, TCMAP *ifields, void *bsbuf, int bsbufsz);
static TCLIST* _qryexecute(EJCOLL *jcoll, const EJQ *q, uint32_t *count, int qflags, TCXSTR *log);
EJDB_INLINE void _nufetch(_EJDBNUM *nu, const char *sval, bson_type bt);
EJDB_INLINE int _nucmp(_EJDBNUM *nu, const char *sval, bson_type bt);
EJDB_INLINE int _nucmp2(_EJDBNUM *nu1, _EJDBNUM *nu2, bson_type bt);
static EJCOLL* _getcoll(EJDB *jb, const char *colname);


extern const char *utf8proc_errmsg(ssize_t errcode);

EJDB_EXPORT const char* ejdberrmsg(int ecode) {
    if (ecode > -6 && ecode < 0) { //Hook for negative error codes of utf8proc library
        return utf8proc_errmsg(ecode);
    }
    switch (ecode) {
        case JBEINVALIDCOLNAME: return "invalid collection name";
        case JBEINVALIDBSON: return "invalid bson object";
        case JBEQINVALIDQCONTROL: return "invalid query control field starting with '$'";
        case JBEQINOPNOTARRAY: return "$strand, $stror, $in, $nin, $bt keys requires not empty array value";
        case JBEMETANVALID: return "inconsistent database metadata";
        case JBEFPATHINVALID: return "invalid JSON field path value";
        case JBEQINVALIDQRX: return "invalid query regexp value";
        case JBEQRSSORTING: return "result set sorting error";
        case JBEQERROR: return "query generic error";
        default: return tcerrmsg(ecode);
    }
}

/* Get the last happened error code of a database object. */
EJDB_EXPORT int ejdbecode(EJDB *jb) {
    assert(jb && jb->metadb);
    return tctdbecode(jb->metadb);
}

EJDB_EXPORT EJDB* ejdbnew(void) {
    EJDB *jb;
    TCMALLOC(jb, sizeof (*jb));
    _ejdbclear(jb);
    jb->metadb = tctdbnew();
    tctdbsetcache(jb->metadb, 1024, 0, 0);
#ifdef _DEBUG
    tchdbsetdbgfd(jb->metadb->hdb, fileno(stderr));
#endif
    if (!_ejdbsetmutex(jb)) {
        tctdbdel(jb->metadb);
        TCFREE(jb);
        return NULL;
    }
    return jb;
}

EJDB_EXPORT void ejdbdel(EJDB *jb) {
    assert(jb && jb->metadb);
    if (JBISOPEN(jb)) ejdbclose(jb);
    for (int i = 0; i < jb->cdbsnum; ++i) {
        _delcoldb(jb->cdbs + i);
    }
    TCFREE(jb->cdbs);
    jb->cdbsnum = 0;
    if (jb->mmtx) {
        pthread_rwlock_destroy(jb->mmtx);
        TCFREE(jb->mmtx);
    }
    tctdbdel(jb->metadb);
    TCFREE(jb);
}

EJDB_EXPORT bool ejdbclose(EJDB *jb) {
    JBENSUREOPENLOCK(jb, true, false);
    bool rv = true;
    for (int i = 0; i < jb->cdbsnum; ++i) {
        if (!tctdbclose(jb->cdbs[i].tdb)) {
            rv = false;
        }
    }
    if (!tctdbclose(jb->metadb)) {
        rv = false;
    }
    JBUNLOCKMETHOD(jb);
    return rv;
}

EJDB_EXPORT bool ejdbisopen(EJDB *jb) {
    return JBISOPEN(jb);
}

EJDB_EXPORT bool ejdbopen(EJDB *jb, const char *path, int mode) {
    assert(jb && path);
    assert(jb->metadb);
    if (!JBLOCKMETHOD(jb, true)) return false;
    if (JBISOPEN(jb)) {
        _ejdbsetecode(jb, TCEINVALID, __FILE__, __LINE__, __func__);
        JBUNLOCKMETHOD(jb);
        return false;
    }
    bool rv = tctdbopen(jb->metadb, path, mode);
    if (!rv) {
        goto finish;
    }
    TCMALLOC(jb->cdbs, 1);
    jb->cdbsnum = 0;
    TCTDB *mdb = jb->metadb;
    rv = tctdbiterinit(mdb);
    if (!rv) {
        goto finish;
    }
    char *colname = NULL;
    for (int i = 0; i < mdb->hdb->rnum && (colname = tctdbiternext2(mdb)) != NULL; ++i) {
        EJCOLL *cdb;
        EJCOLLOPTS opts;
        _metagetopts(jb, colname, &opts);
        _addcoldb0(colname, jb, &opts, &cdb);
        TCFREE(colname);
    }
finish:
    JBUNLOCKMETHOD(jb);
    return rv;
}

EJDB_EXPORT EJCOLL* ejdbgetcoll(EJDB *jb, const char *colname) {
    assert(colname);
    EJCOLL *coll = NULL;
    JBENSUREOPENLOCK(jb, false, NULL);
    coll = _getcoll(jb, colname);
    JBUNLOCKMETHOD(jb);
    return coll;
}

EJDB_EXPORT EJCOLL* ejdbcreatecoll(EJDB *jb, const char *colname, EJCOLLOPTS *opts) {
    assert(colname);
    EJCOLL *coll = ejdbgetcoll(jb, colname);
    if (coll) {
        return coll;
    }
    if (!JBISVALCOLNAME(colname)) {
        _ejdbsetecode(jb, JBEINVALIDCOLNAME, __FILE__, __LINE__, __func__);
        return NULL;
    }
    JBENSUREOPENLOCK(jb, true, NULL);
    TCTDB *meta = jb->metadb;
    char *row = tcsprintf("name\t%s", colname);
    if (!tctdbput3(meta, colname, row)) {
        goto finish;
    }
    if (!_addcoldb0(colname, jb, opts, &coll)) {
        tctdbout2(meta, colname); //cleaning
        goto finish;
    }
    _metasetopts(jb, colname, opts);
finish:
    JBUNLOCKMETHOD(jb);
    if (row) {
        TCFREE(row);
    }
    return coll;
}

EJDB_EXPORT bool ejdbrmcoll(EJDB *jb, const char *colname, bool unlinkfile) {
    assert(colname);
    JBENSUREOPENLOCK(jb, true, false);
    bool rv = true;
    EJCOLL *coll = _getcoll(jb, colname);
    if (!coll) {
        goto finish;
    }
    EJCOLL *cdbs = jb->cdbs;
    for (int i = 0; i < jb->cdbsnum; ++i) {
        coll = jb->cdbs + i;
        if (!strcmp(colname, coll->cname)) {
            if (!JBCLOCKMETHOD(coll, true)) return false;
            jb->cdbsnum--;
            memmove(cdbs + i, cdbs + i + 1, sizeof (*cdbs) * (jb->cdbsnum - i));
            tctdbout2(jb->metadb, colname);
            tctdbvanish(coll->tdb);
            TCLIST *paths = tclistnew2(10);
            tclistpush2(paths, coll->tdb->hdb->path);
            for (int j = 0; j < coll->tdb->inum; ++j) {
                TDBIDX *idx = coll->tdb->idxs + j;
                const char *ipath = tcbdbpath(idx->db);
                if (ipath) {
                    tclistpush2(paths, ipath);
                }
            }
            tctdbclose(coll->tdb);
            if (unlinkfile) {
                for (int j = 0; j < TCLISTNUM(paths); ++j) {
                    unlink(tclistval2(paths, j));
                }
            }
            tclistdel(paths);
            JBCUNLOCKMETHOD(coll);
            _delcoldb(coll);
            break;
        }
    }
finish:
    JBUNLOCKMETHOD(jb);
    return rv;
}

/* Save/Update BSON into 'coll' */
EJDB_EXPORT bool ejdbsavebson(EJCOLL *jcoll, bson *bs, bson_oid_t *oid) {
    assert(jcoll);
    if (!bs || bs->err || !bs->finished) {
        _ejdbsetecode(jcoll->jb, JBEINVALIDBSON, __FILE__, __LINE__, __func__);
        return false;
    }
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    if (!JBCLOCKMETHOD(jcoll, true)) return false;
    bool rv = false;
    bson *nbs = NULL;
    if (!_bsonoidkey(bs, oid)) { //no _id regenerate new BSON with _id primary key
        bson_oid_gen(oid);
        nbs = bson_create();
        bson_init_size(nbs, bson_size(bs) + (strlen(JDBIDKEYNAME) + 1/*key*/ + 1/*type*/ + sizeof (*oid)));
        bson_append_oid(nbs, JDBIDKEYNAME, oid);
        bson_ensure_space(nbs, bson_size(bs) - 4);
        bson_append(nbs, bson_data(bs) + 4, bson_size(bs) - (4 + 1/*BSON_EOO*/));
        bson_finish(nbs);
        bs = nbs;
    }
    TCTDB *tdb = jcoll->tdb;
    TCMAP *rowm = (tdb->hdb->rnum > 0) ? tctdbget(tdb, oid, sizeof (*oid)) : NULL;
    char *obsdata = NULL; //Old bson
    int obsdatasz = 0;
    if (rowm) { //Save the copy of old bson data
        const void *obs = tcmapget(rowm, JDBCOLBSON, JDBCOLBSONL, &obsdatasz);
        if (obs && obsdatasz > 0) {
            TCMALLOC(obsdata, obsdatasz);
            memmove(obsdata, obs, obsdatasz);
        }
    } else {
        rowm = tcmapnew2(64);
    }
    tcmapput(rowm, JDBCOLBSON, JDBCOLBSONL, bson_data(bs), bson_size(bs));
    if (!tctdbput(tdb, oid, sizeof (*oid), rowm)) {
        goto finish;
    }
    //Update indexes
    rv = _updatebsonidx(jcoll, oid, bs, obsdata, obsdatasz);
finish:
    JBCUNLOCKMETHOD(jcoll);
    if (rowm) {
        tcmapdel(rowm);
    }
    if (obsdata) {
        TCFREE(obsdata);
    }
    if (nbs) {
        bson_del(nbs);
    }
    return rv;
}

EJDB_EXPORT bool ejdbrmbson(EJCOLL *jcoll, bson_oid_t *oid) {
    assert(jcoll && oid);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    JBCLOCKMETHOD(jcoll, true);
    bool rv = true;
    const void *olddata;
    int olddatasz = 0;
    TCMAP *rmap = tctdbget(jcoll->tdb, oid, sizeof (*oid));
    if (!rmap) {
        goto finish;
    }
    olddata = tcmapget3(rmap, JDBCOLBSON, JDBCOLBSONL, &olddatasz);
    if (!_updatebsonidx(jcoll, oid, NULL, olddata, olddatasz)) {
        rv = false;
    }
    if (!tctdbout(jcoll->tdb, oid, sizeof (*oid))) {
        rv = false;
    }
finish:
    JBCUNLOCKMETHOD(jcoll);
    if (rmap) {
        tcmapdel(rmap);
    }
    return rv;
}

EJDB_EXPORT bson* ejdbloadbson(EJCOLL *jcoll, const bson_oid_t *oid) {
    assert(jcoll && oid);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return NULL;
    }
    JBCLOCKMETHOD(jcoll, false);
    bson *ret = NULL;
    int datasz;
    void *cdata = tchdbget(jcoll->tdb->hdb, oid, sizeof (*oid), &datasz);
    if (!cdata) {
        goto finish;
    }
    void *bsdata = tcmaploadone(cdata, datasz, JDBCOLBSON, JDBCOLBSONL, &datasz);
    if (!bsdata) {
        goto finish;
    }
    if (datasz <= 4) {
        TCFREE(bsdata);
        goto finish;
    }
    ret = bson_create();
    bson_init_finished_data(ret, bsdata);
finish:
    JBCUNLOCKMETHOD(jcoll);
    if (cdata) {
        TCFREE(cdata);
    }
    return ret;
}

EJDB_EXPORT EJQ* ejdbcreatequery(EJDB *jb, bson *qobj, bson *orqobjs, int orqobjsnum, bson *hints) {
    assert(jb);
    if (!qobj || qobj->err || !qobj->finished) {
        _ejdbsetecode(jb, JBEINVALIDBSON, __FILE__, __LINE__, __func__);
        return NULL;
    }
    EJQ *q;
    TCCALLOC(q, 1, sizeof (*q));
    if (qobj) {
        q->qobjmap = _parseqobj(jb, q, qobj);
        if (!q->qobjmap) {
            goto error;
        }
    }
    if (orqobjs && orqobjsnum) {
        q->orqobjsnum = orqobjsnum;
        TCMALLOC(q->orqobjs, sizeof (*(q->orqobjs)) * q->orqobjsnum);
        for (int i = 0; i < orqobjsnum; ++i) {
            bson *oqb = (orqobjs + i);
            assert(oqb);
            EJQ *oq = ejdbcreatequery(jb, oqb, NULL, 0, NULL);
            if (oq == NULL) {
                goto error;
            }
            q->orqobjs[i] = *oq; //copy struct
            TCFREE(oq);
        }
    }
    if (hints) {
        if (hints->err || !hints->finished) {
            _ejdbsetecode(jb, JBEINVALIDBSON, __FILE__, __LINE__, __func__);
            return NULL;
        }
        q->hints = bson_create();
        if (bson_copy(q->hints, hints)) {
            goto error;
        }
    }
    return q;
error:
    ejdbquerydel(q);
    return NULL;
}

EJDB_EXPORT void ejdbquerydel(EJQ *q) {
    _qrydel(q, true);
}

/** Set index */
EJDB_EXPORT bool ejdbsetindex(EJCOLL *jcoll, const char *fpath, int flags) {
    assert(jcoll && fpath);
    bool rv = true;
    bson *imeta = NULL;
    bson_iterator it;
    int tcitype = 0; //TCDB index type
    int oldiflags = 0; //Old index flags stored in meta
    bool ibld = (flags & JBIDXREBLD);
    if (ibld) {
        flags &= ~JBIDXREBLD;
    }
    bool idrop = (flags & JBIDXDROP);
    if (idrop) {
        flags &= ~JBIDXDROP;
    }
    bool idropall = (flags & JBIDXDROPALL);
    if (idropall) {
        idrop = true;
        flags &= ~JBIDXDROPALL;
    }
    bool iop = (flags & JBIDXOP);
    if (iop) {
        flags &= ~JBIDXOP;
    }

    char ipath[BSON_MAX_FPATH_LEN + 2]; //add 2 bytes for one char prefix and '\0'term
    char ikey[BSON_MAX_FPATH_LEN + 2]; //add 2 bytes for one char prefix and '\0'term
    int fpathlen = strlen(fpath);
    if (fpathlen > BSON_MAX_FPATH_LEN) {
        _ejdbsetecode(jcoll->jb, JBEFPATHINVALID, __FILE__, __LINE__, __func__);
        rv = false;
        goto finish;
    }
    memmove(ikey + 1, fpath, fpathlen + 1);
    ikey[0] = 'i';
    memmove(ipath + 1, fpath, fpathlen + 1);
    ipath[0] = 's'; //defaulting to string index type

    JBENSUREOPENLOCK(jcoll->jb, true, false);
    imeta = _imetaidx(jcoll, fpath);
    if (!imeta) {
        if (idrop) { //Cannot drop/optimize not existent index;
            JBUNLOCKMETHOD(jcoll->jb);
            goto finish;
        }
        if (iop) {
            iop = false; //New index will be created
        }
        imeta = bson_create();
        bson_init(imeta);
        bson_append_string(imeta, "ipath", fpath);
        bson_append_int(imeta, "iflags", flags);
        bson_finish(imeta);
        rv = _metasetbson2(jcoll, ikey, imeta, false, false);
        if (!rv) {
            JBUNLOCKMETHOD(jcoll->jb);
            goto finish;
        }
    } else {
        if (bson_find(&it, imeta, "iflags") != BSON_EOO) {
            oldiflags = bson_iterator_int(&it);
        }
        if (!idrop && oldiflags != flags) { //Update index meta
            bson imetadelta;
            bson_init(&imetadelta);
            bson_append_int(&imetadelta, "iflags", flags);
            bson_finish(&imetadelta);
            rv = _metasetbson2(jcoll, ikey, &imetadelta, true, true);
            bson_destroy(&imetadelta);
            if (!rv) {
                JBUNLOCKMETHOD(jcoll->jb);
                goto finish;
            }
        }
    }
    JBUNLOCKMETHOD(jcoll->jb);

    if (idrop) {
        tcitype = TDBITVOID;
        if (idropall && oldiflags) {
            flags = oldiflags; //Drop index only for existing types
        }
    } else if (iop) {
        tcitype = TDBITOPT;
        if (oldiflags) {
            flags = oldiflags; //Optimize index for all existing types
        }
    }

    if (!JBCLOCKMETHOD(jcoll, true)) {
        rv = false;
        goto finish;
    }
    _BSONIPATHROWLDR op;
    op.icase = false;
    op.jcoll = jcoll;

    if (tcitype) {
        if (flags & JBIDXSTR) {
            ipath[0] = 's';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, tcitype, _bsonipathrowldr, &op);
        }
        if (flags & JBIDXISTR) {
            ipath[0] = 'i';
            op.icase = true;
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, tcitype, _bsonipathrowldr, &op);
        }
        if (rv && (flags & JBIDXNUM)) {
            ipath[0] = 'n';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, tcitype, _bsonipathrowldr, &op);
        }
        if (rv && (flags & JBIDXARR)) {
            ipath[0] = 'a';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, tcitype, _bsonipathrowldr, &op);
        }
        if (idrop) { //Update index meta on drop
            oldiflags &= ~flags;
            if (oldiflags) { //Index dropped only for some types
                bson imetadelta;
                bson_init(&imetadelta);
                bson_append_int(&imetadelta, "iflags", oldiflags);
                bson_finish(&imetadelta);
                rv = _metasetbson2(jcoll, ikey, &imetadelta, true, true);
                bson_destroy(&imetadelta);
            } else { //Index dropped completely
                rv = _metasetbson2(jcoll, ikey, NULL, false, false);
            }
        }
    } else {
        if ((flags & JBIDXSTR) && (ibld || !(oldiflags & JBIDXSTR))) {
            ipath[0] = 's';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, TDBITLEXICAL, _bsonipathrowldr, &op);
        }
        if ((flags & JBIDXISTR) && (ibld || !(oldiflags & JBIDXISTR))) {
            ipath[0] = 'i';
            op.icase = true;
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, TDBITLEXICAL, _bsonipathrowldr, &op);
        }
        if (rv && (flags & JBIDXNUM) && (ibld || !(oldiflags & JBIDXNUM))) {
            ipath[0] = 'n';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, TDBITDECIMAL, _bsonipathrowldr, &op);
        }
        if (rv && (flags & JBIDXARR) && (ibld || !(oldiflags & JBIDXARR))) {
            ipath[0] = 'a';
            rv = tctdbsetindexrldr(jcoll->tdb, ipath, TDBITTOKEN, _bsonipathrowldr, &op);
        }
    }
    JBCUNLOCKMETHOD(jcoll);
finish:
    if (imeta) {
        bson_del(imeta);
    }
    return rv;
}

EJDB_EXPORT TCLIST* ejdbqryexecute(EJCOLL *jcoll, const EJQ *q, uint32_t *count, int qflags, TCXSTR *log) {
    assert(jcoll && q && q->qobjmap);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return NULL;
    }
    JBCLOCKMETHOD(jcoll, (q->flags & EJQUPDATING) ? true : false);
    TCLIST *res;
    _ejdbsetecode(jcoll->jb, TCESUCCESS, __FILE__, __LINE__, __func__);
    res = _qryexecute(jcoll, q, count, qflags, log);
    JBCUNLOCKMETHOD(jcoll);
    return res;
}

EJDB_EXPORT bool ejdbsyncoll(EJCOLL *jcoll) {
    assert(jcoll);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    bool rv = false;
    if (!JBCLOCKMETHOD(jcoll, true)) return false;
    rv = tctdbsync(jcoll->tdb);
    JBCUNLOCKMETHOD(jcoll);
    return rv;
}

EJDB_EXPORT bool ejdbsyncdb(EJDB *jb) {
    assert(jb);
    JBENSUREOPENLOCK(jb, true, false);
    bool rv = true;
    EJCOLL *coll = NULL;
    for (int i = 0; i < jb->cdbsnum; ++i) {
        coll = jb->cdbs + i;
        assert(coll);
        rv = JBCLOCKMETHOD(coll, true);
        if (!rv) break;
        rv = tctdbsync(coll->tdb);
        JBCUNLOCKMETHOD(coll);
        if (!rv) break;
    }
    JBUNLOCKMETHOD(jb);
    return rv;
}

EJDB_EXPORT bool ejdbtranbegin(EJCOLL *jcoll) {
    assert(jcoll);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    for (double wsec = 1.0 / sysconf(_SC_CLK_TCK); true; wsec *= 2) {
        if (!JBCLOCKMETHOD(jcoll, true)) return false;
        if (!jcoll->tdb->open || !jcoll->tdb->wmode) {
            _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
            JBCUNLOCKMETHOD(jcoll);
            return false;
        }
        if (!jcoll->tdb->tran) break;
        JBCUNLOCKMETHOD(jcoll);
        if (wsec > 1.0) wsec = 1.0;
        tcsleep(wsec);
    }
    if (!tctdbtranbeginimpl(jcoll->tdb)) {
        JBCUNLOCKMETHOD(jcoll);
        return false;
    }
    jcoll->tdb->tran = true;
    JBCUNLOCKMETHOD(jcoll);
    return true;
}

EJDB_EXPORT bool ejdbtrancommit(EJCOLL *jcoll) {
    assert(jcoll);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    if (!JBCLOCKMETHOD(jcoll, true)) return false;
    if (!jcoll->tdb->open || !jcoll->tdb->wmode || !jcoll->tdb->tran) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        JBCUNLOCKMETHOD(jcoll);
        return false;
    }
    jcoll->tdb->tran = false;
    bool err = false;
    if (!tctdbtrancommitimpl(jcoll->tdb)) err = true;
    JBCUNLOCKMETHOD(jcoll);
    return !err;
}

EJDB_EXPORT bool ejdbtranabort(EJCOLL *jcoll) {
    assert(jcoll);
    if (!JBISOPEN(jcoll->jb)) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    if (!JBCLOCKMETHOD(jcoll, true)) return false;
    if (!jcoll->tdb->open || !jcoll->tdb->wmode || !jcoll->tdb->tran) {
        _ejdbsetecode(jcoll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        JBCUNLOCKMETHOD(jcoll);
        return false;
    }
    jcoll->tdb->tran = false;
    bool err = false;
    if (!tctdbtranabortimpl(jcoll->tdb)) err = true;
    JBCUNLOCKMETHOD(jcoll);
    return !err;
}

/*************************************************************************************************
 * private features
 *************************************************************************************************/

/* Set the error code of a table database object. */
static void _ejdbsetecode(EJDB *jb, int ecode, const char *filename, int line, const char *func) {
    assert(jb && filename && line >= 1 && func);
    tctdbsetecode(jb->metadb, ecode, filename, line, func);
}

static EJCOLL* _getcoll(EJDB *jb, const char *colname) {
    assert(colname);
    EJCOLL *coll = NULL;
    //check if collection exists
    for (int i = 0; i < jb->cdbsnum; ++i) {
        coll = jb->cdbs + i;
        assert(coll);
        if (!strcmp(colname, coll->cname)) {
            break;
        } else {
            coll = NULL;
        }
    }
    return coll;
}

/* Set mutual exclusion control of a table database object for threading. */
static bool _ejdbsetmutex(EJDB *ejdb) {
    assert(ejdb);
    if (!TCUSEPTHREAD) return true;
    if (ejdb->mmtx || JBISOPEN(ejdb)) {
        _ejdbsetecode(ejdb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    TCMALLOC(ejdb->mmtx, sizeof (pthread_rwlock_t));
    bool err = false;
    if (pthread_rwlock_init(ejdb->mmtx, NULL) != 0) err = true;
    if (err) {
        TCFREE(ejdb->mmtx);
        ejdb->mmtx = NULL;
        return false;
    }
    return true;
}

/* Lock a method of the table database object.
   `tdb' specifies the table database object.
   `wr' specifies whether the lock is writer or not.
   If successful, the return value is true, else, it is false. */
static bool _ejdblockmethod(EJDB *ejdb, bool wr) {
    assert(ejdb);
    if (wr ? pthread_rwlock_wrlock(ejdb->mmtx) != 0 : pthread_rwlock_rdlock(ejdb->mmtx) != 0) {
        _ejdbsetecode(ejdb, TCETHREAD, __FILE__, __LINE__, __func__);
        return false;
    }
    TCTESTYIELD();
    return true;
}

/* Unlock a method of the table database object.
   `tdb' specifies the table database object.
   If successful, the return value is true, else, it is false. */
static bool _ejdbunlockmethod(EJDB *ejdb) {
    assert(ejdb);
    if (pthread_rwlock_unlock(ejdb->mmtx) != 0) {
        _ejdbsetecode(ejdb, TCETHREAD, __FILE__, __LINE__, __func__);
        return false;
    }
    TCTESTYIELD();
    return true;
}

static bool _ejdbcolsetmutex(EJCOLL *coll) {
    assert(coll && coll->jb);
    if (!TCUSEPTHREAD) return true;
    if (coll->mmtx) {
        _ejdbsetecode(coll->jb, TCEINVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    TCMALLOC(coll->mmtx, sizeof (pthread_rwlock_t));
    bool err = false;
    if (pthread_rwlock_init(coll->mmtx, NULL) != 0) err = true;
    if (err) {
        TCFREE(coll->mmtx);
        coll->mmtx = NULL;
        return false;
    }
    return true;
}

static bool _ejcollockmethod(EJCOLL *coll, bool wr) {
    assert(coll && coll->jb);
    if (wr ? pthread_rwlock_wrlock(coll->mmtx) != 0 : pthread_rwlock_rdlock(coll->mmtx) != 0) {
        _ejdbsetecode(coll->jb, TCETHREAD, __FILE__, __LINE__, __func__);
        return false;
    }
    TCTESTYIELD();
    return (coll->tdb && coll->tdb->open);
}

static bool _ejcollunlockmethod(EJCOLL *coll) {
    assert(coll && coll->jb);
    if (pthread_rwlock_unlock(coll->mmtx) != 0) {
        _ejdbsetecode(coll->jb, TCETHREAD, __FILE__, __LINE__, __func__);
        return false;
    }
    TCTESTYIELD();
    return true;
}

static void _qrydel(EJQ *q, bool freequery) {
    if (!q) {
        return;
    }
    const EJQF *qf = NULL;
    if (q->qobjmap) {
        int ksz;
        const char *kbuf;
        tcmapiterinit(q->qobjmap);
        while ((kbuf = tcmapiternext(q->qobjmap, &ksz)) != NULL) {
            int vsz;
            qf = tcmapiterval(kbuf, &vsz);
            assert(qf);
            assert(vsz == sizeof (*qf));
            _delqfdata(q, qf);
        }
        tcmapdel(q->qobjmap);
        q->qobjmap = NULL;
    }
    if (q->orqobjsnum) {
        for (int i = 0; i < q->orqobjsnum; ++i) {
            _qrydel(q->orqobjs + i, false);
        }
        TCFREE(q->orqobjs);
        q->orqobjsnum = 0;
        q->orqobjs = NULL;
    }
    if (q->hints) {
        bson_del(q->hints);
        q->hints = NULL;
    }
    if (freequery) {
        TCFREE(q);
    }
}

static bool _qrybsvalmatch(const EJQF *qf, bson_iterator *it, bool expandarrays) {
    if (qf->tcop == TDBQTRUE) {
        return (true == !qf->negate);
    }
    bool rv = false;
    bson_type bt = bson_iterator_type(it);
    const char *expr = qf->expr;
    int exprsz = qf->exprsz;
    char sbuf[JBSTRINOPBUFFERSZ]; //buffer for icase comparisons
    char oidbuf[25]; //OID buffer
    char *cbuf = NULL;
    int cbufstrlen = 0;
    int fvalsz;
    const char *fval;

#define _FETCHSTRFVAL() \
    do { \
        fvalsz = (bt == BSON_STRING) ? bson_iterator_string_len(it) : 1; \
        fval = (bt == BSON_STRING) ? bson_iterator_string(it) : ""; \
        if (bt == BSON_OID) { \
            bson_oid_to_string(bson_iterator_oid(it), oidbuf); \
            fvalsz = 25; \
            fval = oidbuf; \
        } \
    } while(false)


    if (bt == BSON_ARRAY && expandarrays) { //Iterate over array
        bson_iterator sit;
        bson_iterator_subiterator(it, &sit);
        while ((bt = bson_iterator_next(&sit)) != BSON_EOO) {
            if (_qrybsvalmatch(qf, &sit, false)) {
                return true;
            }
        }
        return (false == !qf->negate);
    }
    switch (qf->tcop) {
        case TDBQCSTREQ:
        {
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = (exprsz == cbufstrlen) && (exprsz == 0 || !memcmp(expr, cbuf, exprsz));
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = (exprsz == fvalsz - 1) && (exprsz == 0 || !memcmp(expr, fval, exprsz));
            }
            break;
        }
        case TDBQCSTRINC:
        {
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = (exprsz <= cbufstrlen) && strstr(cbuf, expr);
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = (exprsz <= fvalsz) && strstr(fval, expr);
            }
            break;
        }
        case TDBQCSTRBW:
        {
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = tcstrfwm(cbuf, expr);
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = tcstrfwm(fval, expr);
            }
            break;
        }
        case TDBQCSTREW:
        {
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = tcstrbwm(cbuf, expr);
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = tcstrbwm(fval, expr);
            }
            break;
        }
        case TDBQCSTRAND:
        {
            TCLIST *tokens = qf->exprlist;
            assert(tokens);
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = _qrycondcheckstrand(cbuf, tokens);
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = _qrycondcheckstrand(fval, tokens);
            }
            break;
        }
        case TDBQCSTROR:
        {
            TCLIST *tokens = qf->exprlist;
            assert(tokens);
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    rv = _qrycondcheckstror(cbuf, tokens);
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                rv = _qrycondcheckstror(fval, tokens);
            }
            break;
        }
        case TDBQCSTROREQ:
        {
            TCLIST *tokens = qf->exprlist;
            assert(tokens);
            _FETCHSTRFVAL();
            if ((qf->flags & EJCONDICASE) && (bt == BSON_STRING)) {
                cbufstrlen = tcicaseformat(fval, fvalsz - 1, sbuf, JBSTRINOPBUFFERSZ, &cbuf);
                if (cbufstrlen < 0) {
                    _ejdbsetecode(qf->jb, cbufstrlen, __FILE__, __LINE__, __func__);
                    rv = false;
                } else {
                    for (int i = 0; i < TCLISTNUM(tokens); ++i) {
                        const char *token = TCLISTVALPTR(tokens, i);
                        int tokensz = TCLISTVALSIZ(tokens, i);
                        if (TCLISTVALSIZ(tokens, i) == cbufstrlen && !strncmp(token, cbuf, tokensz)) {
                            rv = true;
                            break;
                        }
                    }
                }
                if (cbuf && cbuf != sbuf) {
                    TCFREE(cbuf);
                }
            } else {
                for (int i = 0; i < TCLISTNUM(tokens); ++i) {
                    const char *token = TCLISTVALPTR(tokens, i);
                    int tokensz = TCLISTVALSIZ(tokens, i);
                    if (TCLISTVALSIZ(tokens, i) == (fvalsz - 1) && !strncmp(token, fval, tokensz)) {
                        rv = true;
                        break;
                    }
                }
            }
            break;
        }
        case TDBQCSTRRX:
        {
            _FETCHSTRFVAL();
            rv = qf->regex && (regexec(qf->regex, fval, 0, NULL, 0) == 0);
            break;
        }
        case TDBQCNUMEQ:
        {
            if (bt == BSON_DOUBLE) {
                rv = (qf->exprdblval == bson_iterator_double_raw(it));
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                rv = (qf->exprlongval == bson_iterator_long(it));
            } else {
                rv = false;
            }
            break;
        }
        case TDBQCNUMGT:
        {
            if (bt == BSON_DOUBLE) {
                rv = (qf->exprdblval < bson_iterator_double_raw(it));
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                rv = (qf->exprlongval < bson_iterator_long(it));
            } else {
                rv = false;
            }
            break;
        }
        case TDBQCNUMGE:
        {
            if (bt == BSON_DOUBLE) {
                rv = (qf->exprdblval <= bson_iterator_double_raw(it));
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                rv = (qf->exprlongval <= bson_iterator_long(it));
            } else {
                rv = false;
            }
            break;
        }
        case TDBQCNUMLT:
        {
            if (bt == BSON_DOUBLE) {
                rv = (qf->exprdblval > bson_iterator_double_raw(it));
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                rv = (qf->exprlongval > bson_iterator_long(it));
            } else {
                rv = false;
            }
            break;
        }
        case TDBQCNUMLE:
        {
            if (bt == BSON_DOUBLE) {
                rv = (qf->exprdblval >= bson_iterator_double_raw(it));
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                rv = (qf->exprlongval >= bson_iterator_long(it));
            } else {
                rv = false;
            }
            break;
        }
        case TDBQCNUMBT:
        {
            assert(qf->ftype == BSON_ARRAY);
            TCLIST *tokens = qf->exprlist;
            assert(tokens);
            assert(TCLISTNUM(tokens) == 2);
            if (bson_iterator_type(it) == BSON_DOUBLE) {
                double v1 = tctdbatof2(tclistval2(tokens, 0));
                double v2 = tctdbatof2(tclistval2(tokens, 1));
                double val = bson_iterator_double(it);
                rv = (v2 > v1) ? (v2 >= val && v1 <= val) : (v2 <= val && v1 >= val);
            } else {
                int64_t v1 = tctdbatoi(tclistval2(tokens, 0));
                int64_t v2 = tctdbatoi(tclistval2(tokens, 1));
                int64_t val = bson_iterator_long(it);
                rv = (v2 > v1) ? (v2 >= val && v1 <= val) : (v2 <= val && v1 >= val);
            }
            break;
        }
        case TDBQCNUMOREQ:
        {
            TCLIST *tokens = qf->exprlist;
            assert(tokens);
            if (bt == BSON_DOUBLE) {
                double nval = bson_iterator_double_raw(it);
                for (int i = 0; i < TCLISTNUM(tokens); ++i) {
                    if (tctdbatof2(TCLISTVALPTR(tokens, i)) == nval) {
                        rv = true;
                        break;
                    }
                }
            } else if (bt == BSON_INT || bt == BSON_LONG) {
                int64_t nval = bson_iterator_long(it);
                for (int i = 0; i < TCLISTNUM(tokens); ++i) {
                    if (tctdbatoi(TCLISTVALPTR(tokens, i)) == nval) {
                        rv = true;
                        break;
                    }
                }
            }
            break;
        }
    }
    return (rv == !qf->negate);

#undef _FETCHSTRFVAL
}

static bool _qrybsmatch(const EJQF *qf, const void *bsbuf, int bsbufsz) {
    if (qf->tcop == TDBQTRUE) {
        return !qf->negate;
    }
    bson_iterator it;
    bson_iterator_from_buffer(&it, bsbuf);
    bson_type bt = bson_find_fieldpath_value2(qf->fpath, qf->fpathsz, &it);
    if (bt == BSON_EOO || bt == BSON_UNDEFINED || bt == BSON_NULL) {
        return qf->negate; //Field missing
    } else if (qf->tcop == TDBQCEXIST) {
        return !qf->negate;
    }
    return _qrybsvalmatch(qf, &it, true);
}

static bool _qryormatch(EJCOLL *jcoll,
        EJQ *ejq,
        const void *pkbuf, int pkbufsz,
        const void *bsbuf, int bsbufsz) {
    if (ejq->orqobjsnum <= 0 || !ejq->orqobjs) {
        return true;
    }
    bool rv = false;
    void *nbsbuf = NULL;
    const void *kbuf = NULL;
    int kbufsz;
    if (bsbuf == NULL) {
        int cbufsz;
        int lbsbufsz;
        char *cbuf = tchdbget(jcoll->tdb->hdb, pkbuf, pkbufsz, &cbufsz);
        if (!cbuf) {
            return false;
        }
        nbsbuf = tcmaploadone(cbuf, cbufsz, JDBCOLBSON, JDBCOLBSONL, &lbsbufsz); //BSON buffer
        if (!nbsbuf) {
            TCFREE(cbuf);
            return false;
        }
        bsbufsz = lbsbufsz;
        bsbuf = nbsbuf;
    }
    if (ejq->lastmatchedorqf && _qrybsmatch(ejq->lastmatchedorqf, bsbuf, bsbufsz)) {
        rv = true;
        goto finish;
    }
    for (int i = 0; i < ejq->orqobjsnum; ++i) {
        const EJQ *oq = (ejq->orqobjs + i);
        const EJQF *qf;
        int qfsz;
        TCMAP *qobjmap = oq->qobjmap;
        assert(qobjmap);
        tcmapiterinit(qobjmap);
        while ((kbuf = tcmapiternext(qobjmap, &kbufsz)) != NULL) {
            qf = tcmapiterval(kbuf, &qfsz);
            if (qf == ejq->lastmatchedorqf) {
                continue;
            }
            assert(qfsz == sizeof (EJQF));
            if (_qrybsmatch(qf, bsbuf, bsbufsz)) {
                ejq->lastmatchedorqf = qf;
                rv = true;
                goto finish;
            }
        }
    }
finish:
    if (nbsbuf) { //BSON Buffer created by me
        TCFREE(nbsbuf);
    }
    return rv;
}

/** Caller must TCFREE(*bsbuf) if it return TRUE */
static bool _qryallcondsmatch(
        bool onlycount, int anum,
        EJCOLL *jcoll, const EJQF **qfs, int qfsz,
        const void *pkbuf, int pkbufsz,
        void **bsbuf, int *bsbufsz) {
    if (onlycount && anum < 1) {
        *bsbuf = NULL;
        *bsbufsz = 0;
        return true;
    }
    bool rv = true;
    //Load BSON
    int cbufsz;
    char *cbuf = tchdbget(jcoll->tdb->hdb, pkbuf, pkbufsz, &cbufsz);
    if (!cbuf) {
        *bsbuf = NULL;
        *bsbufsz = 0;
        return false;
    }
    *bsbuf = tcmaploadone(cbuf, cbufsz, JDBCOLBSON, JDBCOLBSONL, bsbufsz); //BSON buffer
    if (!*bsbuf) {
        TCFREE(cbuf);
        *bsbufsz = 0;
        return false;
    }
    if (anum < 1) {
        TCFREE(cbuf);
        return true;
    }
    for (int i = 0; i < qfsz; ++i) {
        const EJQF *qf = qfs[i];
        if (qf->flags & EJFEXCLUDED) continue;
        if (!_qrybsmatch(qf, *bsbuf, *bsbufsz)) {
            rv = false;
            break;
        }
    }
    TCFREE(cbuf);
    if (!rv) {
        TCFREE(*bsbuf);
        *bsbuf = NULL;
        *bsbufsz = 0;
    }
    return rv;
}

typedef struct {
    const EJQF **ofs;
    int ofsz;
} _EJBSORTCTX;

/* RS sorting comparison func */
static int _ejdbsoncmp(const TCLISTDATUM *d1, const TCLISTDATUM *d2, void *opaque) {
    _EJBSORTCTX *ctx = opaque;
    assert(ctx);
    int res = 0;
    for (int i = 0; !res && i < ctx->ofsz; ++i) {
        const EJQF *qf = ctx->ofs[i];
        if (qf->flags & EJFORDERUSED) {
            continue;
        }
        res = bson_compare(d1->ptr, d2->ptr, qf->fpath, qf->fpathsz) * (qf->order >= 0 ? 1 : -1);
    }
    return res;
}

EJDB_INLINE void _nufetch(_EJDBNUM *nu, const char *sval, bson_type bt) {
    if (bt == BSON_INT || bt == BSON_LONG) {
        nu->inum = tctdbatoi(sval);
    } else if (bt == BSON_DOUBLE) {
        nu->dnum = tctdbatof2(sval);
    } else {
        nu->inum = 0;
        assert(0);
    }
}

EJDB_INLINE int _nucmp(_EJDBNUM *nu, const char *sval, bson_type bt) {
    if (bt == BSON_INT || bt == BSON_LONG) {
        int64_t v = tctdbatoi(sval);
        return (nu->inum > v) ? 1 : (nu->inum < v ? -1 : 0);
    } else if (bt == BSON_DOUBLE) {
        double v = tctdbatof2(sval);
        return (nu->dnum > v) ? 1 : (nu->dnum < v ? -1 : 0);
    } else {
        assert(0);
    }
    return 0;
}

EJDB_INLINE int _nucmp2(_EJDBNUM *nu1, _EJDBNUM *nu2, bson_type bt) {
    if (bt == BSON_INT || bt == BSON_LONG) {
        return (nu1->inum > nu2->inum) ? 1 : (nu1->inum < nu2->inum ? -1 : 0);
    } else if (bt == BSON_DOUBLE) {
        return (nu1->dnum > nu2->dnum) ? 1 : (nu1->dnum < nu2->dnum ? -1 : 0);
    } else {
        assert(0);
    }
    return 0;
}

static void _qryfieldup(const EJQF *src, EJQF *target, uint32_t qflags) {
    assert(src && target);
    memset(target, 0, sizeof (*target));
    target->exprdblval = src->exprdblval;
    target->exprlongval = src->exprlongval;
    target->flags = src->flags;
    target->ftype = src->ftype;
    target->negate = src->negate;
    target->order = src->order;
    target->orderseq = src->orderseq;
    target->tcop = src->tcop;
    if (src->expr) {
        TCMEMDUP(target->expr, src->expr, src->exprsz);
        target->exprsz = src->exprsz;
    }
    if (src->fpath) {
        TCMEMDUP(target->fpath, src->fpath, src->fpathsz);
        target->fpathsz = src->fpathsz;
    }
    if (src->regex && (EJQINTERNAL & qflags)) {
        //We cannot do deep copy of regex_t so do shallow copy only for internal query objects
        target->regex = src->regex;
    }
    if (src->exprlist) {
        target->exprlist = tclistdup(src->exprlist);
    }
    if (src->updateobj) {
        target->updateobj = bson_dup(src->updateobj);
    }
}

/* Clone query object */
static void _qrydup(const EJQ *src, EJQ *target, uint32_t qflags) {
    assert(src && target);
    memset(target, 0, sizeof (*target));
    target->flags = src->flags | qflags;
    target->max = src->max;
    target->skip = src->skip;
    target->orqobjsnum = src->orqobjsnum;
    target->orqobjs = NULL;
    const void *kbuf;
    int ksz, vsz;
    if (src->qobjmap) {
        target->qobjmap = tcmapnew2(TCMAPRNUM(src->qobjmap));
        tcmapiterinit(src->qobjmap);
        while ((kbuf = tcmapiternext(src->qobjmap, &ksz)) != NULL) {
            EJQF qf;
            _qryfieldup(tcmapiterval(kbuf, &vsz), &qf, qflags);
            qf.q = target;
            tcmapput(target->qobjmap, kbuf, ksz, &qf, sizeof (qf));
        }
    }
    if (src->hints) {
        target->hints = bson_dup(src->hints);
    }
    if (src->orqobjsnum > 0 && src->orqobjs) {
        TCMALLOC(target->orqobjs, sizeof (*(target->orqobjs)) * src->orqobjsnum);
        for (int i = 0; i < src->orqobjsnum; ++i) {
            _qrydup(src->orqobjs + i, target->orqobjs + i, qflags);
        }
    }
}

typedef struct {
    bson *sbson;
    TCMAP *ifields;
    int nstack; //nestet object stack pos
    int matched; //number of matched include fields
} _BSONSTRIPVISITORCTX;

static bson_visitor_cmd_t _bsonstripvisitor(const char *ipath, int ipathlen, const char *key, int keylen,
        const bson_iterator *it, bool after, void *op) {
    _BSONSTRIPVISITORCTX *ictx = op;
    assert(ictx && ictx->sbson && ictx->ifields && ipath && key && it && op);
    bson_visitor_cmd_t rv = BSON_VCMD_OK;
    TCMAP *ifields = ictx->ifields;
    const void *buf;
    const char* ifpath;
    int bufsz;

    bson_type bt = bson_iterator_type(it);
    if (bt == BSON_EOO || (ictx->matched == TCMAPRNUM(ifields))) {
        return BSON_VCMD_TERMINATE;
    }
    if (bt != BSON_OBJECT && bt != BSON_ARRAY) {
        if (after) { //simple primitive case
            return BSON_VCMD_OK;
        }
        //const void *tcmapget(const TCMAP *map, const void *kbuf, int ksiz, int *sp);
        buf = tcmapget(ifields, ipath, ipathlen, &bufsz);
        if (buf) {
            ictx->matched++;
            bson_append_field_from_iterator(it, ictx->sbson);
        }
        return (BSON_VCMD_SKIP_AFTER);
    } else { //more complicated case
        if (!after) {
            buf = tcmapget(ifields, ipath, ipathlen, &bufsz);
            if (buf) { //field hitted
                bson_iterator cit = *it; //copy iterator
                bson_append_field_from_iterator(&cit, ictx->sbson);
                ictx->matched++;
                return (BSON_VCMD_SKIP_NESTED | BSON_VCMD_SKIP_AFTER);
            } else { //check prefix
                tcmapiterinit(ifields);
                //const char *tcmapiternext2(TCMAP *map);
                while ((ifpath = tcmapiternext2(ifields)) != NULL) {
                    int i = 0;
                    for (; i < ipathlen && *(ifpath + i) == *(ipath + i); ++i);
                    if (i == ipathlen) { //ipath prefixes some included field
                        ictx->nstack++;
                        if (bt == BSON_OBJECT) {
                            bson_append_start_object(ictx->sbson, key);
                        } else if (bt == BSON_ARRAY) {
                            bson_append_start_array(ictx->sbson, key);
                        } else {
                            assert(0);
                        }
                        break;
                    }
                }
            }
        } else { //after
            if (ictx->nstack > 0) {
                --ictx->nstack;
                if (bt == BSON_OBJECT) {
                    bson_append_finish_object(ictx->sbson);
                } else if (bt == BSON_ARRAY) {
                    bson_append_finish_array(ictx->sbson);
                } else {
                    assert(0);
                }
            }
        }
    }
    return rv;
}

/* push bson into rs with only fields listed in ifields */
static void _pushstripbson(TCLIST *rs, TCMAP *ifields, void *bsbuf, int bsbufsz) {
    if (!ifields || TCMAPRNUM(ifields) <= 0) {
        tclistpushmalloc(rs, bsbuf, bsbufsz);
        return;
    }
    char bstack[JBSBUFFERSZ];
    void *tmpbuf = (bsbufsz < JBSBUFFERSZ) ? bstack : MYMALLOC(bsbufsz);
    bson sbson;
    char *sdata;
    bson_reset(&sbson);
    sbson.data = tmpbuf;
    sbson.cur = sbson.data + 4;
    sbson.dataSize = MAX(bsbufsz, JBSBUFFERSZ);
    if (sbson.data == bstack) {
        sbson.flags |= BSON_FLAG_STACK_ALLOCATED;
    }

    _BSONSTRIPVISITORCTX ictx;
    ictx.sbson = &sbson;
    ictx.ifields = ifields;
    ictx.nstack = 0;
    ictx.matched = 0;

    //Now copy filtered bson fields
    bson_iterator it;
    bson_iterator_from_buffer(&it, bsbuf);
    bson_visit_fields(&it, BSON_TRAVERSE_ARRAYS_EXCLUDED, _bsonstripvisitor, &ictx);
    assert(ictx.nstack == 0);
    if (bson_finish(&sbson) == BSON_OK) {
        if (sbson.flags & BSON_FLAG_STACK_ALLOCATED) {
            sdata = sbson.data;
            TCLISTPUSH(rs, sbson.data, bson_size(&sbson));
        } else {
            sdata = NULL;
            tclistpushmalloc(rs, sbson.data, bson_size(&sbson));
        }
    } else {
        sdata = sbson.data;
        assert(0);
    }
    //Cleanup
    sbson.data = NULL; //hide allocated data from bson_destroy()
    bson_destroy(&sbson);
    if (sdata && sdata != bstack) {
        TCFREE(sdata);
    }
    TCFREE(bsbuf);
}

static bool _qryupdate(EJCOLL *jcoll, const EJQ *ejq, void *bsbuf, int bsbufsz) {
    assert(ejq->flags & EJQUPDATING);

    bool rv = true;
    bool update = false;

    const void *kbuf;
    int kbufsz;
    int qfsz;
    bson_oid_t *oid;
    bson_type bt, bt2;
    bson_iterator it, it2;
    TCMAP *qobjmap = ejq->qobjmap;
    TCMAP *rowm = NULL;

    bson src;
    bson_create_from_buffer2(&src, bsbuf, bsbufsz);

    bson bsout; //Resulting updated bson
    bsout.data = NULL;
    bsout.dataSize = 0;

    const EJQF *setqf = NULL;
    const EJQF *incqf = NULL;

    tcmapiterinit(qobjmap);
    while ((kbuf = tcmapiternext(qobjmap, &kbufsz)) != NULL) {
        const EJQF *qf = tcmapiterval(kbuf, &qfsz);
        assert(qfsz == sizeof (EJQF));
        if (qf->updateobj == NULL) {
            continue;
        }
        if (!setqf && qf->flags & EJCONDSET) { //$set
            setqf = qf;
        } else if (!incqf && qf->flags & EJCONDINC) {
            incqf = qf;
        } else {
            assert(0);
            break;
        }
    }
    if (setqf) {
        update = true;
        bson_init_size(&bsout, bsbufsz);
        if (bson_merge(&src, setqf->updateobj, true, &bsout)) {
            rv = false;
            _ejdbsetecode(jcoll->jb, JBEQUPDFAILED, __FILE__, __LINE__, __func__);
        }
    }
    if (!rv) {
        goto finish;
    }
    if (incqf) {
        if (!bsout.data) {
            bson_create_from_buffer2(&bsout, bsbuf, bsbufsz);
        }
        bson_iterator_init(&it, incqf->updateobj);
        while ((bt = bson_iterator_next(&it)) != BSON_EOO) {
            if (!BSON_IS_NUM_TYPE(bt)) {
                continue;
            }
            //bt2 = bson_find(&it2, &bsout, bson_iterator_key(&it));
            bson_iterator_init(&it2, &bsout);
            bt2 = bson_find_fieldpath_value(bson_iterator_key(&it), &it2);
            if (!BSON_IS_NUM_TYPE(bt2)) {
                continue;
            }
            if (bt2 == BSON_DOUBLE) {
                double v = bson_iterator_double(&it2);
                if (bt == BSON_DOUBLE) {
                    v += bson_iterator_double(&it);
                } else {
                    v += bson_iterator_long(&it);
                }
                if (bson_inplace_set_double(&it2, v)) {
                    rv = false;
                    _ejdbsetecode(jcoll->jb, JBEQUPDFAILED, __FILE__, __LINE__, __func__);
                    break;
                }
                update = true;
            } else {
                int64_t v = bson_iterator_long(&it2);
                v += bson_iterator_long(&it);
                if (bson_inplace_set_long(&it2, v)) {
                    rv = false;
                    _ejdbsetecode(jcoll->jb, JBEQUPDFAILED, __FILE__, __LINE__, __func__);
                    break;
                }
                update = true;
            }
        }
    }
    bson_finish(&bsout);
    if (bsout.err) {
        rv = false;
        _ejdbsetecode(jcoll->jb, JBEQUPDFAILED, __FILE__, __LINE__, __func__);
    }
    if (!update || !rv) {
        goto finish;
    }
    //Perform updating
    bt = bson_find(&it, &src, JDBIDKEYNAME);
    if (bt != BSON_OID) {
        rv = false;
        _ejdbsetecode(jcoll->jb, JBEQUPDFAILED, __FILE__, __LINE__, __func__);
        goto finish;
    }
    oid = bson_iterator_oid(&it);
    rowm = tcmapnew2(TCMAPTINYBNUM);
    tcmapput(rowm, JDBCOLBSON, JDBCOLBSONL, bson_data(&bsout), bson_size(&bsout));
    rv = tctdbput(jcoll->tdb, oid, sizeof (*oid), rowm);
    if (rv) {
        rv = _updatebsonidx(jcoll, oid, &bsout, bsbuf, bsbufsz);
    }

finish:
    bson_destroy(&src);
    bson_destroy(&bsout);
    if (rowm) {
        tcmapdel(rowm);
    }
    return rv;
}

/** Query */
static TCLIST* _qryexecute(EJCOLL *jcoll, const EJQ *q, uint32_t *outcount, int qflags, TCXSTR *log) {
    //Clone the query object
    EJQ *ejq;
    TCMALLOC(ejq, sizeof (*ejq));
    _qrydup(q, ejq, EJQINTERNAL);

    *outcount = 0;
    bool onlycount = (qflags & JBQRYCOUNT); //quering only for result set count
    bool all = false; //need all records

    EJQF *mqf = NULL; //main indexed query condition if exists
    TCMAP *ifields = NULL; //field names included in result set

    TCLIST *res = onlycount ? NULL : tclistnew2(4096);
    _qrypreprocess(jcoll, ejq, qflags, &mqf, &ifields);

    int anum = 0; //number of active conditions
    const EJQF **ofs = NULL; //order fields
    int ofsz = 0; //order fields count
    int aofsz = 0; //active order fields count
    const EJQF **qfs = NULL; //condition fields array
    const int qfsz = TCMAPRNUM(ejq->qobjmap); //number of all condition fields
    if (qfsz > 0) {
        TCMALLOC(qfs, qfsz * sizeof (EJQF*));
    }

    const void *kbuf;
    int kbufsz;
    const void *vbuf;
    int vbufsz;
    void *bsbuf; //BSON buffer
    int bsbufsz; //BSON buffer size
    static const bool yes = true; //Simple true const

    uint32_t count = 0; //current count
    uint32_t max = (ejq->max > 0) ? ejq->max : UINT_MAX;
    uint32_t skip = ejq->skip;
    const TDBIDX *midx = mqf ? mqf->idx : NULL;
    TCHDB *hdb = jcoll->tdb->hdb;
    assert(hdb);

    if (midx) { //Main index used for ordering
        if (mqf->orderseq == 1 &&
                !(mqf->tcop == TDBQCSTRAND || mqf->tcop == TDBQCSTROR || mqf->tcop == TDBQCSTRNUMOR)) {
            mqf->flags |= EJFORDERUSED;
        }
    }
    tcmapiterinit(ejq->qobjmap);
    for (int i = 0; i < qfsz; ++i) {
        kbuf = tcmapiternext(ejq->qobjmap, &kbufsz);
        EJQF *qf = (EJQF*) tcmapget(ejq->qobjmap, kbuf, kbufsz, &vbufsz);
        assert(qf && vbufsz == sizeof (EJQF));
        qf->jb = jcoll->jb;
        qfs[i] = qf;
        if (qf->fpathsz > 0 && !(qf->flags & EJFEXCLUDED)) {
            anum++;
        }
        if (qf->orderseq) {
            ofsz++;
            if (onlycount) {
                qf->flags |= EJFORDERUSED;
            }
        }
    }
    if (ofsz > 0) { //Collect order fields array
        TCMALLOC(ofs, ofsz * sizeof (EJQF*));
        for (int i = 0; i < ofsz; ++i) {
            for (int j = 0; j < qfsz; ++j) {
                if (qfs[j]->orderseq == i + 1) { //orderseq starts with 1
                    ofs[i] = qfs[j];
                    if (!(ofs[i]->flags & EJFORDERUSED)) {
                        aofsz++;
                        if (ifields) { //add this order field to the list of fetched
                            tcmapputkeep(ifields, ofs[i]->fpath, ofs[i]->fpathsz, &yes, sizeof (yes));
                        }
                    }
                    break;
                }
            }
        }
        for (int i = 0; i < ofsz; ++i) assert(ofs[i] != NULL);
    }

    if (!onlycount && aofsz > 0 && (!midx || mqf->orderseq != 1)) { //Main index is not the main order field
        all = true; //Need all records for ordering for some other fields
    }

    if (log) {
        tcxstrprintf(log, "UPDATING MODE: %s\n", (ejq->flags & EJQUPDATING) ? "YES" : "NO");
        tcxstrprintf(log, "MAX: %u\n", max);
        tcxstrprintf(log, "SKIP: %u\n", skip);
        tcxstrprintf(log, "COUNT ONLY: %s\n", onlycount ? "YES" : "NO");
        tcxstrprintf(log, "MAIN IDX: '%s'\n", midx ? midx->name : "NONE");
        tcxstrprintf(log, "ORDER FIELDS: %d\n", ofsz);
        tcxstrprintf(log, "ACTIVE CONDITIONS: %d\n", anum);
        tcxstrprintf(log, "$OR QUERIES: %d\n", ejq->orqobjsnum);
        tcxstrprintf(log, "FETCH ALL: %s\n", all ? "YES" : "NO");
    }
    if (max < UINT_MAX - skip) {
        max += skip;
    }
    if (max == 0) {
        goto finish;
    }
    if (!midx && (!mqf || !(mqf->flags & EJFPKMATCHING))) { //Missing main index & no PK matching
        goto fullscan;
    }
    if (log) {
        tcxstrprintf(log, "MAIN IDX TCOP: %d\n", mqf->tcop);
    }

#define JBQREGREC(_bsbuf, _bsbufsz)   \
    ++count; \
    if (ejq->flags & EJQUPDATING) { \
        _qryupdate(jcoll, ejq, (_bsbuf), (_bsbufsz)); \
    } \
    if (!onlycount && (all || count > skip)) { \
        if (ifields) {\
            _pushstripbson(res, ifields, (_bsbuf), (_bsbufsz)); \
        } else { \
            tclistpushmalloc(res, (_bsbuf), _bsbufsz); \
        } \
    } else if ((_bsbuf)) { \
        TCFREE((_bsbuf)); \
    }

    bool trim = (midx && *midx->name != '\0');
    if (anum > 0 && !(mqf->flags & EJFEXCLUDED)) {
        anum--;
        mqf->flags |= EJFEXCLUDED;
    }

    if (mqf->flags & EJFPKMATCHING) { //PK matching
        if (log) {
            tcxstrprintf(log, "PRIMARY KEY MATCHING: TRUE\n");
        }
        assert(mqf->expr);
        if (mqf->tcop == TDBQCSTREQ) {
            do {
                bson_oid_t oid;
                bson_oid_from_string(&oid, mqf->expr);
                void *cdata = tchdbget(jcoll->tdb->hdb, &oid, sizeof (oid), &bsbufsz);
                if (!cdata) {
                    break;
                }
                bsbuf = tcmaploadone(cdata, bsbufsz, JDBCOLBSON, JDBCOLBSONL, &bsbufsz);
                if (!bsbuf) {
                    TCFREE(cdata);
                    break;
                }
                bool matched = true;
                for (int i = 0; i < qfsz; ++i) {
                    const EJQF *qf = qfs[i];
                    if (qf->flags & EJFEXCLUDED) continue;
                    if (!_qrybsmatch(qf, bsbuf, bsbufsz)) {
                        matched = false;
                        break;
                    }
                }
                if (matched && (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, &oid, sizeof (oid), bsbuf, bsbufsz))) {
                    JBQREGREC(bsbuf, bsbufsz);
                } else {
                    TCFREE(bsbuf);
                }
                TCFREE(cdata);
            } while (false);
        } else if (mqf->tcop == TDBQCSTROREQ) {
            TCLIST *tokens = mqf->exprlist;
            assert(tokens);
            tclistsort(tokens);
            for (int i = 1; i < TCLISTNUM(tokens); i++) {
                if (!strcmp(TCLISTVALPTR(tokens, i), TCLISTVALPTR(tokens, i - 1))) {
                    TCFREE(tclistremove2(tokens, i));
                    i--;
                }
            }
            int tnum = TCLISTNUM(tokens);
            for (int i = 0; (all || count < max) && i < tnum; i++) {
                const char *token;
                int tsiz;
                TCLISTVAL(token, tokens, i, tsiz);
                if (tsiz < 1) {
                    continue;
                }
                bson_oid_t oid;
                bson_oid_from_string(&oid, token);
                void *cdata = tchdbget(jcoll->tdb->hdb, &oid, sizeof (oid), &bsbufsz);
                if (!cdata) {
                    continue;
                }
                bsbuf = tcmaploadone(cdata, bsbufsz, JDBCOLBSON, JDBCOLBSONL, &bsbufsz);
                if (!bsbuf) {
                    TCFREE(cdata);
                    break;
                }
                bool matched = true;
                for (int i = 0; i < qfsz; ++i) {
                    const EJQF *qf = qfs[i];
                    if (qf->flags & EJFEXCLUDED) continue;
                    if (!_qrybsmatch(qf, bsbuf, bsbufsz)) {
                        matched = false;
                        break;
                    }
                }
                if (matched && (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, &oid, sizeof (oid), bsbuf, bsbufsz))) {
                    JBQREGREC(bsbuf, bsbufsz);
                } else {
                    TCFREE(bsbuf);
                }
                TCFREE(cdata);
            }
        } else {
            assert(0);
        }
    } else if (mqf->tcop == TDBQTRUE) {
        BDBCUR *cur = tcbdbcurnew(midx->db);
        if (mqf->order >= 0) {
            tcbdbcurfirst(cur);
        } else {
            tcbdbcurlast(cur);
        }
        while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
            if (trim) kbufsz -= 3;
            vbuf = tcbdbcurval3(cur, &vbufsz);
            if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz)) {
                JBQREGREC(bsbuf, bsbufsz);
            }
            if (mqf->order >= 0) {
                tcbdbcurnext(cur);
            } else {
                tcbdbcurprev(cur);
            }
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCSTREQ) { /* string is equal to */
        assert(midx->type == TDBITLEXICAL);
        char *expr = mqf->expr;
        int exprsz = mqf->exprsz;
        BDBCUR *cur = tcbdbcurnew(midx->db);
        tcbdbcurjump(cur, expr, exprsz + trim);
        while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
            if (trim) kbufsz -= 3;
            if (kbufsz == exprsz && !memcmp(kbuf, expr, exprsz)) {
                vbuf = tcbdbcurval3(cur, &vbufsz);
                if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                        (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                    JBQREGREC(bsbuf, bsbufsz);
                }
            } else {
                break;
            }
            tcbdbcurnext(cur);
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCSTRBW) { /* string begins with */
        assert(midx->type == TDBITLEXICAL);
        char *expr = mqf->expr;
        int exprsz = mqf->exprsz;
        BDBCUR *cur = tcbdbcurnew(midx->db);
        tcbdbcurjump(cur, expr, exprsz + trim);
        while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
            if (trim) kbufsz -= 3;
            if (kbufsz >= exprsz && !memcmp(kbuf, expr, exprsz)) {
                vbuf = tcbdbcurval3(cur, &vbufsz);
                if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                        (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                    JBQREGREC(bsbuf, bsbufsz);
                }
            } else {
                break;
            }
            tcbdbcurnext(cur);
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCSTROREQ) { /* string is equal to at least one token in */
        assert(mqf->ftype == BSON_ARRAY);
        assert(midx->type == TDBITLEXICAL);
        BDBCUR *cur = tcbdbcurnew(midx->db);
        TCLIST *tokens = mqf->exprlist;
        assert(tokens);
        tclistsort(tokens);
        for (int i = 1; i < TCLISTNUM(tokens); i++) {
            if (!strcmp(TCLISTVALPTR(tokens, i), TCLISTVALPTR(tokens, i - 1))) {
                TCFREE(tclistremove2(tokens, i));
                i--;
            }
        }
        if (mqf->order < 0 && (mqf->flags & EJFORDERUSED)) {
            tclistinvert(tokens);
        }
        int tnum = TCLISTNUM(tokens);
        for (int i = 0; (all || count < max) && i < tnum; i++) {
            const char *token;
            int tsiz;
            TCLISTVAL(token, tokens, i, tsiz);
            if (tsiz < 1) continue;
            tcbdbcurjump(cur, token, tsiz + trim);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                if (trim) kbufsz -= 3;
                if (kbufsz == tsiz && !memcmp(kbuf, token, tsiz)) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                } else {
                    break;
                }
                tcbdbcurnext(cur);
            }
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCNUMEQ) { /* number is equal to */
        assert(midx->type == TDBITDECIMAL);
        char *expr = mqf->expr;
        int exprsz = mqf->exprsz;
        BDBCUR *cur = tcbdbcurnew(midx->db);
        _EJDBNUM num;
        _nufetch(&num, expr, mqf->ftype);
        tctdbqryidxcurjumpnum(cur, expr, exprsz, true);
        while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
            if (_nucmp(&num, kbuf, mqf->ftype) == 0) {
                vbuf = tcbdbcurval3(cur, &vbufsz);
                if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                        (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                    JBQREGREC(bsbuf, bsbufsz);
                }
            } else {
                break;
            }
            tcbdbcurnext(cur);
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCNUMGT || mqf->tcop == TDBQCNUMGE) {
        /* number is greater than | number is greater than or equal to */
        assert(midx->type == TDBITDECIMAL);
        char *expr = mqf->expr;
        int exprsz = mqf->exprsz;
        BDBCUR *cur = tcbdbcurnew(midx->db);
        _EJDBNUM xnum;
        _nufetch(&xnum, expr, mqf->ftype);
        if (mqf->order < 0 && (mqf->flags & EJFORDERUSED)) { //DESC
            tcbdbcurlast(cur);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                _EJDBNUM knum;
                _nufetch(&knum, kbuf, mqf->ftype);
                int cmp = _nucmp2(&knum, &xnum, mqf->ftype);
                if (cmp < 0) break;
                if (cmp > 0 || (mqf->tcop == TDBQCNUMGE && cmp >= 0)) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                }
                tcbdbcurprev(cur);
            }
        } else { //ASC
            tctdbqryidxcurjumpnum(cur, expr, exprsz, true);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                _EJDBNUM knum;
                _nufetch(&knum, kbuf, mqf->ftype);
                int cmp = _nucmp2(&knum, &xnum, mqf->ftype);
                if (cmp > 0 || (mqf->tcop == TDBQCNUMGE && cmp >= 0)) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                }
                tcbdbcurnext(cur);
            }
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCNUMLT || mqf->tcop == TDBQCNUMLE) {
        /* number is less than | number is less than or equal to */
        assert(midx->type == TDBITDECIMAL);
        char *expr = mqf->expr;
        int exprsz = mqf->exprsz;
        BDBCUR *cur = tcbdbcurnew(midx->db);
        _EJDBNUM xnum;
        _nufetch(&xnum, expr, mqf->ftype);
        if (mqf->order >= 0) { //ASC
            tcbdbcurfirst(cur);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                _EJDBNUM knum;
                _nufetch(&knum, kbuf, mqf->ftype);
                int cmp = _nucmp2(&knum, &xnum, mqf->ftype);
                if (cmp > 0) break;
                if (cmp < 0 || (cmp <= 0 && mqf->tcop == TDBQCNUMLE)) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                }
                tcbdbcurnext(cur);
            }
        } else {
            tctdbqryidxcurjumpnum(cur, expr, exprsz, false);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                _EJDBNUM knum;
                _nufetch(&knum, kbuf, mqf->ftype);
                int cmp = _nucmp2(&knum, &xnum, mqf->ftype);
                if (cmp < 0 || (cmp <= 0 && mqf->tcop == TDBQCNUMLE)) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                }
                tcbdbcurprev(cur);
            }
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCNUMBT) { /* number is between two tokens of */
        assert(mqf->ftype == BSON_ARRAY);
        assert(midx->type == TDBITDECIMAL);
        assert(mqf->exprlist);
        TCLIST *tokens = mqf->exprlist;
        assert(TCLISTNUM(tokens) == 2);
        const char *expr;
        int exprsz;
        long double lower = tctdbatof(tclistval2(tokens, 0));
        long double upper = tctdbatof(tclistval2(tokens, 1));
        expr = tclistval2(tokens, (lower > upper) ? 1 : 0);
        exprsz = strlen(expr);
        if (lower > upper) {
            long double swap = lower;
            lower = upper;
            upper = swap;
        }
        BDBCUR *cur = tcbdbcurnew(midx->db);
        tctdbqryidxcurjumpnum(cur, expr, exprsz, true);
        while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
            if (tctdbatof(kbuf) > upper) break;
            vbuf = tcbdbcurval3(cur, &vbufsz);
            if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                    (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                JBQREGREC(bsbuf, bsbufsz);
            }
            tcbdbcurnext(cur);
        }
        tcbdbcurdel(cur);
        if (!all && !onlycount && mqf->order < 0 && (mqf->flags & EJFORDERUSED)) { //DESC
            tclistinvert(res);
        }
    } else if (mqf->tcop == TDBQCNUMOREQ) { /* number is equal to at least one token in */
        assert(mqf->ftype == BSON_ARRAY);
        assert(midx->type == TDBITDECIMAL);
        BDBCUR *cur = tcbdbcurnew(midx->db);
        TCLIST *tokens = mqf->exprlist;
        assert(tokens);
        tclistsortex(tokens, tdbcmppkeynumasc);
        for (int i = 1; i < TCLISTNUM(tokens); i++) {
            if (tctdbatof(TCLISTVALPTR(tokens, i)) == tctdbatof(TCLISTVALPTR(tokens, i - 1))) {
                TCFREE(tclistremove2(tokens, i));
                i--;
            }
        }
        if (mqf->order < 0 && (mqf->flags & EJFORDERUSED)) {
            tclistinvert(tokens);
        }
        int tnum = TCLISTNUM(tokens);
        for (int i = 0; (all || count < max) && i < tnum; i++) {
            const char *token;
            int tsiz;
            TCLISTVAL(token, tokens, i, tsiz);
            if (tsiz < 1) continue;
            long double xnum = tctdbatof(token);
            tctdbqryidxcurjumpnum(cur, token, tsiz, true);
            while ((all || count < max) && (kbuf = tcbdbcurkey3(cur, &kbufsz)) != NULL) {
                if (tctdbatof(kbuf) == xnum) {
                    vbuf = tcbdbcurval3(cur, &vbufsz);
                    if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, vbuf, vbufsz, &bsbuf, &bsbufsz) &&
                            (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, vbuf, vbufsz, bsbuf, bsbufsz))) {
                        JBQREGREC(bsbuf, bsbufsz);
                    }
                } else {
                    break;
                }
                tcbdbcurnext(cur);
            }
        }
        tcbdbcurdel(cur);
    } else if (mqf->tcop == TDBQCSTRAND || mqf->tcop == TDBQCSTROR || mqf->tcop == TDBQCSTRNUMOR) {
        /* string includes all tokens in | string includes at least one token in */
        assert(midx->type == TDBITTOKEN);
        assert(mqf->ftype == BSON_ARRAY);
        TCLIST *tokens = mqf->exprlist;
        assert(tokens);
        if (mqf->tcop == TDBQCSTRNUMOR) {
            tclistsortex(tokens, tdbcmppkeynumasc);
            for (int i = 1; i < TCLISTNUM(tokens); i++) {
                if (tctdbatof(TCLISTVALPTR(tokens, i)) == tctdbatof(TCLISTVALPTR(tokens, i - 1))) {
                    TCFREE(tclistremove2(tokens, i));
                    i--;
                }
            }
        } else {
            tclistsort(tokens);
            for (int i = 1; i < TCLISTNUM(tokens); i++) {
                if (!strcmp(TCLISTVALPTR(tokens, i), TCLISTVALPTR(tokens, i - 1))) {
                    TCFREE(tclistremove2(tokens, i));
                    i--;
                }
            }
        }
        TCMAP *tres = tctdbidxgetbytokens(jcoll->tdb, midx, tokens, mqf->tcop, log);
        tcmapiterinit(tres);
        while ((all || count < max) && (kbuf = tcmapiternext(tres, &kbufsz)) != NULL) {
            if (_qryallcondsmatch(onlycount, anum, jcoll, qfs, qfsz, kbuf, kbufsz, &bsbuf, &bsbufsz) &&
                    (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, kbuf, kbufsz, bsbuf, bsbufsz))) {
                JBQREGREC(bsbuf, bsbufsz);
            }
        }
        tcmapdel(tres);
    }

    if (onlycount) {
        goto finish;
    } else {
        goto sorting;
    }

fullscan: /* Full scan */
    assert(count == 0);
    assert(!res || TCLISTNUM(res) == 0);
    if (log) {
        tcxstrprintf(log, "RUN FULLSCAN\n");
    }
    char *pkbuf;
    int pkbufsz;
    char *lkbuf = NULL;
    int lksiz = 0;
    const char *cbuf;
    int cbufsz;
    while ((all || count < max) && (pkbuf = tchdbgetnext3(hdb, lkbuf, lksiz, &pkbufsz, &cbuf, &cbufsz)) != NULL) {
        void *bsbuf = tcmaploadone(cbuf, cbufsz, JDBCOLBSON, JDBCOLBSONL, &bsbufsz);
        if (!bsbuf) continue;
        bool matched = true;
        for (int i = 0; i < qfsz; ++i) {
            const EJQF *qf = qfs[i];
            if (qf->flags & EJFEXCLUDED) continue;
            if (!_qrybsmatch(qf, bsbuf, bsbufsz)) {
                matched = false;
                break;
            }
        }
        if (matched && (ejq->orqobjsnum == 0 || _qryormatch(jcoll, ejq, pkbuf, pkbufsz, bsbuf, bsbufsz))) {
            JBQREGREC(bsbuf, bsbufsz);
        } else {
            TCFREE(bsbuf);
        }
        if (lkbuf) TCFREE(lkbuf);
        lkbuf = pkbuf;
        lksiz = pkbufsz;
    }
    if (lkbuf) TCFREE(lkbuf);

sorting: /* Sorting resultset */
    if (!res || aofsz <= 0) { //No sorting needed
        goto finish;
    }
    _EJBSORTCTX sctx; //sorting context
    sctx.ofs = ofs;
    sctx.ofsz = ofsz;
    if (ejdbtimsortlist(res, _ejdbsoncmp, &sctx)) {
        _ejdbsetecode(jcoll->jb, JBEQRSSORTING, __FILE__, __LINE__, __func__);
    }
finish:
    //revert max
    if (max < UINT_MAX && max > skip) {
        max = max - skip;
    }
    if (res) {
        if (all) { //skipping results after full sorting with skip > 0
            for (int i = 0; i < skip && res->num > 0; ++i) {
                TCFREE(res->array[res->start].ptr);
                ++(res->start);
                --(res->num);
            }
        }
        if ((res->start & 0xff) == 0 && res->start > (res->num >> 1)) {
            memmove(res->array, res->array + res->start, res->num * sizeof (res->array[0]));
            res->start = 0;
        }
        if (TCLISTNUM(res) > max) { //truncate results if max specified
            int end = res->start + res->num;
            TCLISTDATUM *array = res->array;
            for (int i = (res->start + max); i < end; i++) {
                TCFREE(array[i].ptr);
                --(res->num);
            }
        }
    }
    count = (skip < count) ? count - skip : 0;
    if (count > max) {
        count = max;
    }
    *outcount = count;
    if (log) {
        tcxstrprintf(log, "RS COUNT: %d\n", count);
        tcxstrprintf(log, "RS SIZE: %d\n", (res ? TCLISTNUM(res) : 0));
        tcxstrprintf(log, "FINAL SORTING: %s\n", (onlycount || aofsz <= 0) ? "NO" : "YES");
    }
    if (qfs) {
        TCFREE(qfs);
    }
    if (ofs) {
        TCFREE(ofs);
    }
    if (ifields) {
        tcmapdel(ifields);
    }
    ejdbquerydel(ejq);
#undef JBQREGREC
    return res;
}

static TDBIDX* _qryfindidx(EJCOLL *jcoll, EJQF *qf, bson *idxmeta) {
    TCTDB *tdb = jcoll->tdb;
    char p = '\0';
    switch (qf->tcop) {
        case TDBQCSTREQ:
        case TDBQCSTRBW:
        case TDBQCSTROREQ:
            p = (qf->flags & EJCONDICASE) ? 'i' : 's'; //lexical string index
            break;
        case TDBQCNUMEQ:
        case TDBQCNUMGT:
        case TDBQCNUMGE:
        case TDBQCNUMLT:
        case TDBQCNUMLE:
        case TDBQCNUMBT:
        case TDBQCNUMOREQ:
            p = 'n'; //number index
            break;
        case TDBQCSTRAND:
        case TDBQCSTROR:
            p = 'a'; //token index
            break;
        case TDBQTRUE:
            p = 'o'; //take first appropriate index
            break;
    }
    if (p == '\0' || !qf->fpath || !qf->fpathsz) {
        return NULL;
    }
    for (int i = 0; i < tdb->inum; ++i) {
        TDBIDX *idx = tdb->idxs + i;
        assert(idx);
        if (p == 'o') {
            if (*idx->name == 'a' || *idx->name == 'i') { //token index or icase index not the best solution here
                continue;
            }
        } else if (*idx->name != p) {
            continue;
        }
        if (!strcmp(qf->fpath, idx->name + 1)) {
            return idx;
        }
    }
    //No direct operation index. Any alternatives?
    if (idxmeta &&
            !(qf->flags & EJCONDICASE) && //if not case insensitive query
            (qf->tcop == TDBQCSTREQ || qf->tcop == TDBQCSTROREQ || qf->tcop == TDBQCNUMOREQ)) {
        bson_iterator it;
        bson_type bt = bson_find(&it, idxmeta, "iflags");
        if (bt != BSON_INT) {
            return NULL;
        }
        int iflags = bson_iterator_int(&it);
        if (iflags & JBIDXARR) { //array token index exists so convert qf into TDBQCSTROR
            for (int i = 0; i < tdb->inum; ++i) {
                TDBIDX *idx = tdb->idxs + i;
                if (!strcmp(qf->fpath, idx->name + 1)) {
                    if (qf->tcop == TDBQCSTREQ) {
                        qf->tcop = TDBQCSTROR;
                        qf->exprlist = tclistnew2(1);
                        TCLISTPUSH(qf->exprlist, qf->expr, qf->exprsz);
                        if (qf->expr) TCFREE(qf->expr);
                        qf->expr = tclistdump(qf->exprlist, &qf->exprsz);
                        qf->ftype = BSON_ARRAY;
                        return idx;
                    } else if (qf->tcop == TDBQCSTROREQ) {
                        assert(qf->ftype == BSON_ARRAY);
                        qf->tcop = TDBQCSTROR;
                        return idx;
                    } else if (qf->tcop == TDBQCNUMOREQ) {
                        assert(qf->ftype == BSON_ARRAY);
                        qf->tcop = TDBQCSTRNUMOR;
                        return idx;
                    }
                }
            }
        }
    }
    return NULL;
}

static void _qrypreprocess(EJCOLL *jcoll, EJQ *ejq, int qflags, EJQF **mqf, TCMAP **ifields) {
    assert(jcoll && ejq && ejq->qobjmap && mqf);

    *ifields = NULL;
    *mqf = NULL;

    EJQF *oqf = NULL; //Order condition
    TCMAP *qmap = ejq->qobjmap;
    tcmapiterinit(qmap);
    const void *mkey;
    int mkeysz;
    int mvalsz;
    bson_iterator it;
    bson_type bt;

    if (ejq->hints) {
        bson_type bt;
        bson_iterator it, sit;
        //Process $orderby
        bt = bson_find(&it, ejq->hints, "$orderby");
        if (bt == BSON_OBJECT) {
            int orderseq = 1;
            bson_iterator_subiterator(&it, &sit);
            while ((bt = bson_iterator_next(&sit)) != BSON_EOO) {
                if (!BSON_IS_NUM_TYPE(bt)) {
                    continue;
                }
                const char *ofield = bson_iterator_key(&sit);
                int odir = bson_iterator_int(&sit);
                odir = (odir > 0) ? 1 : (odir < 0 ? -1 : 0);
                if (!odir) {
                    continue;
                }
                EJQF nqf;
                EJQF *qf = (EJQF*) tcmapget(qmap, ofield, strlen(ofield), &mvalsz); //discard const
                if (qf == NULL) { //Create syntetic query field for orderby ops
                    memset(&nqf, 0, sizeof (EJQF));
                    nqf.fpath = tcstrdup(ofield);
                    nqf.fpathsz = strlen(nqf.fpath);
                    nqf.expr = tcstrdup("");
                    nqf.exprsz = 0;
                    nqf.tcop = TDBQTRUE; //disable any TC matching operation
                    nqf.ftype = BSON_OBJECT;
                    nqf.orderseq = orderseq++;
                    nqf.order = odir;
                    nqf.flags |= EJFEXCLUDED; //field excluded  from matching
                    qf = &nqf;
                    tcmapput(qmap, ofield, strlen(ofield), qf, sizeof (*qf));
                } else {
                    qf->orderseq = orderseq++;
                    qf->order = odir;
                }
            }
        }
        bt = bson_find(&it, ejq->hints, "$skip");
        if (BSON_IS_NUM_TYPE(bt)) {
            int64_t v = bson_iterator_long(&it);
            ejq->skip = (uint32_t) ((v < 0) ? 0 : v);
        }
        bt = bson_find(&it, ejq->hints, "$max");
        if (BSON_IS_NUM_TYPE(bt)) {
            int64_t v = bson_iterator_long(&it);
            ejq->max = (uint32_t) ((v < 0) ? 0 : v);
        }
        if (!(qflags & JBQRYCOUNT)) {
            bt = bson_find(&it, ejq->hints, "$fields"); //Collect required fields
            if (bt == BSON_OBJECT) {
                TCMAP *fmap = tcmapnew2(TCMAPTINYBNUM);
                static const bool yes = true;
                bson_iterator_subiterator(&it, &sit);
                while ((bt = bson_iterator_next(&sit)) != BSON_EOO) {
                    if (!BSON_IS_NUM_TYPE(bt) || bson_iterator_int(&sit) <= 0) {
                        continue;
                    }
                    const char *key = bson_iterator_key(&sit);
                    tcmapputkeep(fmap, key, strlen(key), &yes, sizeof (yes));
                }
                tcmapputkeep(fmap, JDBIDKEYNAME, JDBIDKEYNAMEL, &yes, sizeof (yes));
                *ifields = fmap;
            }
        }
    }

    const int scoreexact = 100;
    const int scoregtlt = 50;
    int maxiscore = 0; //Maximum index score
    int maxselectivity = 0;

    while ((mkey = tcmapiternext(qmap, &mkeysz)) != NULL) {
        int iscore = 0;
        EJQF *qf = (EJQF*) tcmapget(qmap, mkey, mkeysz, &mvalsz); //discard const
        assert(mvalsz == sizeof (EJQF));
        assert(qf->fpath);
        if (qf->flags & (EJCONDSET | EJCONDINC)) { //skip updating qfields
            continue;
        }
        //OID PK matching
        if ((qf->tcop == TDBQCSTREQ || qf->tcop == TDBQCSTROREQ) && !strcmp(JDBIDKEYNAME, qf->fpath)) {
            qf->flags |= EJFPKMATCHING;
            *mqf = qf;
            break;
        }

        bool firstorderqf = false;
        qf->idxmeta = _imetaidx(jcoll, qf->fpath);
        qf->idx = _qryfindidx(jcoll, qf, qf->idxmeta);
        if (qf->order && qf->orderseq == 1) { //Index for first 'orderby' exists
            oqf = qf;
            firstorderqf = true;
        }
        if (!qf->idx || !qf->idxmeta) {
            qf->idx = NULL;
            qf->idxmeta = NULL;
            continue;
        }
        if (qf->tcop == TDBQTRUE || qf->negate) {
            continue;
        }
        int avgreclen = -1;
        int selectivity = -1;
        bt = bson_find(&it, qf->idxmeta, "selectivity");
        if (bt == BSON_DOUBLE) {
            selectivity = (int) ((double) bson_iterator_double(&it) * 100); //Selectivity percent
        }
        bt = bson_find(&it, qf->idxmeta, "avgreclen");
        if (bt == BSON_DOUBLE) {
            avgreclen = (int) bson_iterator_double(&it);
        }
        if (selectivity > 0) {
            if (selectivity <= 20) { //Not using index at all if selectivity lesser than 20%
                continue;
            }
            iscore += selectivity;
        }
        if (firstorderqf) {
            iscore += (maxselectivity - selectivity) / 2;
        }
        if (selectivity > maxselectivity) {
            maxselectivity = selectivity;
        }
        switch (qf->tcop) {
            case TDBQCSTREQ:
            case TDBQCSTROR:
            case TDBQCNUMEQ:
            case TDBQCNUMBT:
                iscore += scoreexact;
                break;
            case TDBQCSTRBW:
            case TDBQCSTREW:
                if (avgreclen > 0 && qf->exprsz > avgreclen) {
                    iscore += scoreexact;
                }
                break;
            case TDBQCNUMGT:
            case TDBQCNUMGE:
            case TDBQCNUMLT:
            case TDBQCNUMLE:
                if (firstorderqf) {
                    iscore += scoreexact;
                } else {
                    iscore += scoregtlt;
                }
                break;
        }
        if (iscore >= maxiscore) {
            *mqf = qf;
            maxiscore = iscore;
        }
    }
    if (*mqf == NULL && (oqf && oqf->idx && !oqf->negate)) {
        *mqf = oqf;
    }
}

static bool _metasetopts(EJDB *jb, const char *colname, EJCOLLOPTS *opts) {
    bool rv = true;
    if (!opts) {
        return _metasetbson(jb, colname, strlen(colname), "opts", NULL, false, false);
    }
    bson *bsopts = bson_create();
    bson_init(bsopts);
    bson_append_bool(bsopts, "compressed", opts->compressed);
    bson_append_bool(bsopts, "large", opts->large);
    bson_append_int(bsopts, "cachedrecords", opts->cachedrecords);
    bson_append_int(bsopts, "records", opts->records);
    bson_finish(bsopts);
    rv = _metasetbson(jb, colname, strlen(colname), "opts", bsopts, false, false);
    bson_del(bsopts);
    return rv;
}

static bool _metagetopts(EJDB *jb, const char *colname, EJCOLLOPTS *opts) {
    assert(opts);
    bool rv = true;
    memset(opts, 0, sizeof (*opts));
    bson *bsopts = _metagetbson(jb, colname, strlen(colname), "opts");
    if (!bsopts) {
        return true;
    }
    bson_iterator it;
    bson_type bt = bson_find(&it, bsopts, "compressed");
    if (bt == BSON_BOOL) {
        opts->compressed = bson_iterator_bool(&it);
    }
    bt = bson_find(&it, bsopts, "large");
    if (bt == BSON_BOOL) {
        opts->large = bson_iterator_bool(&it);
    }
    bt = bson_find(&it, bsopts, "cachedrecords");
    if (BSON_IS_NUM_TYPE(bt)) {
        opts->cachedrecords = bson_iterator_long(&it);
    }
    bt = bson_find(&it, bsopts, "records");
    if (BSON_IS_NUM_TYPE(bt)) {
        opts->records = bson_iterator_long(&it);
    }
    return rv;
}

static bool _metasetbson(EJDB *jb, const char *colname, int colnamesz,
        const char *mkey, bson *val, bool merge, bool mergeoverwrt) {
    assert(jb && colname && mkey);
    bool rv = true;
    bson *bsave = NULL;
    bson *oldval = NULL;
    bson mresult;

    TCMAP *cmeta = tctdbget(jb->metadb, colname, colnamesz);
    if (!cmeta) {
        _ejdbsetecode(jb, JBEMETANVALID, __FILE__, __LINE__, __func__);
        rv = false;
        goto finish;
    }
    if (!val) {
        if (tcmapout2(cmeta, mkey)) {
            rv = tctdbput(jb->metadb, colname, colnamesz, cmeta);
        }
        goto finish;
    }
    assert(val);
    if (merge) { //Merged
        oldval = _metagetbson(jb, colname, colnamesz, mkey);
        if (oldval) {
            bson_init(&mresult);
            bson_merge(oldval, val, mergeoverwrt, &mresult);
            bson_finish(&mresult);
            bsave = &mresult;
        } else {
            bsave = val;
        }
    } else { //Rewrited
        bsave = val;
    }

    assert(bsave);
    tcmapput(cmeta, mkey, strlen(mkey), bson_data(bsave), bson_size(bsave));
    rv = tctdbput(jb->metadb, colname, colnamesz, cmeta);
finish:
    if (oldval) {
        if (merge) {
            bson_destroy(bsave);
        }
        bson_del(oldval);
    }
    if (cmeta) {
        tcmapdel(cmeta);
    }
    tctdbsync(jb->metadb);
    return rv;
}

static bool _metasetbson2(EJCOLL *jcoll, const char *mkey, bson *val, bool merge, bool mergeoverwrt) {
    assert(jcoll);
    return _metasetbson(jcoll->jb, jcoll->cname, jcoll->cnamesz, mkey, val, merge, mergeoverwrt);
}

/**Returned meta BSON data must be freed by 'bson_del' */
static bson* _metagetbson(EJDB *jb, const char *colname, int colnamesz, const char *mkey) {
    assert(jb && colname && mkey);
    bson *rv = NULL;
    TCMAP *cmeta = tctdbget(jb->metadb, colname, colnamesz);
    if (!cmeta) {
        _ejdbsetecode(jb, JBEMETANVALID, __FILE__, __LINE__, __func__);
        return NULL;
    }
    int bsz;
    const void *raw = tcmapget(cmeta, mkey, strlen(mkey), &bsz);
    if (!raw || bsz == 0) {
        goto finish;
    }
    rv = bson_create();
    bson_init_size(rv, bsz);
    bson_ensure_space(rv, bsz - 4);
    bson_append(rv, ((char*) raw) + 4, bsz - (4 + 1/*BSON_EOO*/));
    bson_finish(rv);
finish:
    tcmapdel(cmeta);
    return rv;
}

static bson* _metagetbson2(EJCOLL *jcoll, const char *mkey) {
    assert(jcoll);
    return _metagetbson(jcoll->jb, jcoll->cname, jcoll->cnamesz, mkey);
}

/**Returned index meta if not NULL it must be freed by 'bson_del' */
static bson* _imetaidx(EJCOLL *jcoll, const char *ipath) {
    assert(jcoll && ipath);
    if (*ipath == '\0') {
        return NULL;
    }
    bson *rv = NULL;
    char fpathkey[BSON_MAX_FPATH_LEN + 1];
    TCMAP *cmeta = tctdbget(jcoll->jb->metadb, jcoll->cname, jcoll->cnamesz);
    if (!cmeta) {
        _ejdbsetecode(jcoll->jb, JBEMETANVALID, __FILE__, __LINE__, __func__);
        goto finish;
    }
    int klen = snprintf(fpathkey, BSON_MAX_FPATH_LEN + 1, "i%s", ipath); //'i' prefix for all columns with index meta
    if (klen > BSON_MAX_FPATH_LEN) {
        _ejdbsetecode(jcoll->jb, JBEFPATHINVALID, __FILE__, __LINE__, __func__);
        goto finish;
    }
    int bsz;
    const void *bsdata = tcmapget(cmeta, fpathkey, klen, &bsz);
    if (bsdata) {
        rv = bson_create();
        bson_init_size(rv, bsz);
        bson_ensure_space(rv, bsz - 4);
        bson_append(rv, ((char*) bsdata) + 4, bsz - (4 + 1));
        bson_finish(rv);
    }
finish:
    if (cmeta) {
        tcmapdel(cmeta);
    }
    return rv;
}

/** Free EJQF field **/
static void _delqfdata(const EJQ *q, const EJQF *qf) {
    assert(q && qf);
    if (qf->expr) {
        TCFREE(qf->expr);
    }
    if (qf->fpath) {
        TCFREE(qf->fpath);
    }
    if (qf->idxmeta) {
        bson_del(qf->idxmeta);
    }
    if (qf->updateobj) {
        bson_del(qf->updateobj);
    }
    if (qf->regex && !(EJQINTERNAL & q->flags)) {
        //We do not clear regex_t data because it not deep copy in internal queries
        regfree(qf->regex);
        TCFREE(qf->regex);
    }
    if (qf->exprlist) {
        tclistdel(qf->exprlist);
    }
}

/**
 * Copy BSON array into new TCLIST. TCLIST must be freed by 'tclistdel'.
 * @param it BSON iterator
 * @param type[out] Detected BSON type of last element
 */
static TCLIST* _fetch_bson_str_array(EJDB *jb, bson_iterator *it, bson_type *type, txtflags_t tflags) {
    TCLIST *res = tclistnew();
    *type = BSON_EOO;
    bson_type ftype;
    for (int i = 0; (ftype = bson_iterator_next(it)) != BSON_EOO; ++i) {
        switch (ftype) {
            case BSON_STRING:
                *type = ftype;
                if (tflags & JBICASE) { //ignore case
                    char *buf = NULL;
                    char sbuf[JBSTRINOPBUFFERSZ];
                    int len = tcicaseformat(bson_iterator_string(it), bson_iterator_string_len(it) - 1, sbuf, JBSTRINOPBUFFERSZ, &buf);
                    if (len < 0) {
                        _ejdbsetecode(jb, len, __FILE__, __LINE__, __func__);
                        break;
                    }
                    tclistpush2(res, buf);
                    if (buf && buf != sbuf) {
                        TCFREE(buf);
                    }
                } else {
                    tclistpush2(res, bson_iterator_string(it));
                }
                break;
            case BSON_INT:
            case BSON_LONG:
                *type = ftype;
                tclistprintf(res, "%ld", bson_iterator_long(it));
                break;
            case BSON_DOUBLE:
                *type = ftype;
                tclistprintf(res, "%f", bson_iterator_double(it));
                break;
            case BSON_OID:
                *type = ftype;
                char xoid[25];
                bson_oid_to_string(bson_iterator_oid(it), xoid);
                tclistprintf(res, "%s", xoid);
                break;
            default:
                break;
        }
    }
    return res;
}

/** result must be freed by TCFREE */
static char* _fetch_bson_str_array2(EJDB *jb, bson_iterator *it, bson_type *type, txtflags_t tflags) {
    TCLIST *res = _fetch_bson_str_array(jb, it, type, tflags);
    char *tokens = tcstrjoin(res, ',');
    tclistdel(res);
    return tokens;
}

static int _parse_qobj_impl(EJDB *jb, EJQ *q, bson_iterator *it, TCMAP *qmap, TCLIST *pathStack, EJQF *pqf) {
    assert(it && qmap && pathStack);
    int ret = 0;
    bson_type ftype;
    while ((ftype = bson_iterator_next(it)) != BSON_EOO) {

        const char *fkey = bson_iterator_key(it);
        bool isckey = (*fkey == '$'); //Key is a control key: $in, $nin, $not, $all

        if (!isckey && pqf && pqf->ftype == BSON_ARRAY) {
            //All index keys in array are prefixed with '*'. Eg: 'store.*1.item', 'store.*2.item', ...
            char akey[TCNUMBUFSIZ];
            assert(strlen(fkey) <= TCNUMBUFSIZ - 2);
            akey[0] = '*';
            memmove(akey + 1, fkey, strlen(fkey) + 1);
            fkey = akey;
        }

        EJQF qf;
        memset(&qf, 0, sizeof (qf));
        qf.q = q;

        if (!isckey) {
            //Push key on top of path stack
            tclistpush2(pathStack, fkey);
            qf.ftype = ftype;
        } else {
            if (!strcmp("$set", fkey) || !strcmp("$inc", fkey)) {
                if (pqf) { //Top level ops
                    ret = JBEQERROR;
                    break;
                }
            } else {
                if (!pqf) { //Require parent query object
                    ret = JBEQERROR;
                    break;
                }
                qf = *pqf;
                if (!strcmp("$not", fkey)) {
                    qf.negate = !qf.negate;
                } else if (!strcmp("$gt", fkey)) {
                    qf.flags |= EJCOMPGT;
                } else if (!strcmp("$gte", fkey)) {
                    qf.flags |= EJCOMPGTE;
                } else if (!strcmp("$lt", fkey)) {
                    qf.flags |= EJCOMPLT;
                } else if (!strcmp("$lte", fkey)) {
                    qf.flags |= EJCOMPLTE;
                } else if (!strcmp("$begin", fkey)) {
                    qf.flags |= EJCONDSTARTWITH;
                } else if (!strcmp("$icase", fkey)) {
                    qf.flags |= EJCONDICASE;
                }
            }
        }

        switch (ftype) {
            case BSON_ARRAY:
            {
                if (isckey) {
                    bson_iterator sit;
                    bson_iterator_subiterator(it, &sit);
                    bson_type atype = 0;
                    TCLIST *tokens = _fetch_bson_str_array(jb, &sit, &atype, (qf.flags & EJCONDICASE) ? JBICASE : 0);
                    if (atype == 0) {
                        ret = JBEQINOPNOTARRAY;
                        tclistdel(tokens);
                        break;
                    }
                    assert(!qf.expr);
                    assert(!qf.fpath);
                    qf.ftype = BSON_ARRAY;
                    qf.expr = tclistdump(tokens, &qf.exprsz);
                    qf.exprlist = tokens;
                    if (!strcmp("$in", fkey) || !strcmp("$nin", fkey)) {
                        if (!strcmp("$nin", fkey)) {
                            qf.negate = true;
                        }
                        if (BSON_IS_NUM_TYPE(atype)) {
                            qf.tcop = TDBQCNUMOREQ;
                        } else {
                            qf.tcop = TDBQCSTROREQ;
                        }
                    } else if (!strcmp("$bt", fkey)) { //between
                        qf.tcop = TDBQCNUMBT;
                        if (TCLISTNUM(tokens) != 2) {
                            ret = JBEQINOPNOTARRAY;
                            TCFREE(qf.expr);
                            tclistdel(qf.exprlist);
                            break;
                        }
                    } else if (!strcmp("$strand", fkey)) { //$strand
                        qf.tcop = TDBQCSTRAND;
                    } else if (!strcmp("$stror", fkey)) { //$stror
                        qf.tcop = TDBQCSTROR;
                    } else {
                        ret = JBEQINVALIDQCONTROL;
                        TCFREE(qf.expr);
                        tclistdel(qf.exprlist);
                        break;
                    }
                    qf.fpath = tcstrjoin(pathStack, '.');
                    qf.fpathsz = strlen(qf.fpath);
                    tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                    break;
                } else {
                    bson_iterator sit;
                    bson_iterator_subiterator(it, &sit);
                    ret = _parse_qobj_impl(jb, q, &sit, qmap, pathStack, &qf);
                    break;
                }
            }

            case BSON_OBJECT:
            {
                if (isckey) {
                    if (pqf == NULL && !strcmp("$set", fkey)) { //top level set OP
                        qf.flags |= EJCONDSET;
                    } else if (!strcmp("$inc", fkey)) {
                        qf.flags |= EJCONDINC;
                    }
                    if ((qf.flags & (EJCONDSET | EJCONDINC))) {
                        assert(qf.updateobj == NULL);
                        qf.q->flags |= EJQUPDATING;
                        qf.updateobj = bson_create();
                        bson_init(qf.updateobj);
                        bson_type sbt;
                        bson_iterator sit;
                        bson_iterator_subiterator(it, &sit);
                        while ((sbt = bson_iterator_next(&sit)) != BSON_EOO) {
                            bson_append_field_from_iterator(&sit, qf.updateobj);
                        }
                        bson_finish(qf.updateobj);
                        if (qf.updateobj->err) {
                            ret = JBEQERROR;
                        }
                        qf.fpath = strdup(fkey);
                        qf.fpathsz = strlen(qf.fpath);
                        qf.tcop = TDBQTRUE;
                        qf.flags |= EJFEXCLUDED;
                        tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                        break;
                    }
                }
                bson_iterator sit;
                bson_iterator_subiterator(it, &sit);
                ret = _parse_qobj_impl(jb, q, &sit, qmap, pathStack, &qf);
                break;
            }
            case BSON_OID:
            {
                assert(!qf.fpath && !qf.expr);
                qf.ftype = ftype;
                TCMALLOC(qf.expr, 25 * sizeof (char));
                bson_oid_to_string(bson_iterator_oid(it), qf.expr);
                qf.exprsz = 24;
                qf.fpath = tcstrjoin(pathStack, '.');
                qf.fpathsz = strlen(qf.fpath);
                qf.tcop = TDBQCSTREQ;
                tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                break;
            }
            case BSON_STRING:
            {
                assert(!qf.fpath && !qf.expr);
                qf.ftype = ftype;
                if (qf.flags & EJCONDICASE) {
                    qf.exprsz = tcicaseformat(bson_iterator_string(it), bson_iterator_string_len(it) - 1, NULL, 0, &qf.expr);
                    if (qf.exprsz < 0) {
                        ret = qf.exprsz;
                        qf.exprsz = 0;
                        break;
                    }
                } else {
                    qf.expr = tcstrdup(bson_iterator_string(it));
                    qf.exprsz = strlen(qf.expr);
                }

                qf.fpath = tcstrjoin(pathStack, '.');
                qf.fpathsz = strlen(qf.fpath);
                if (qf.flags & EJCONDSTARTWITH) {
                    qf.tcop = TDBQCSTRBW;
                } else {
                    qf.tcop = TDBQCSTREQ;
                    if (!strcmp(JDBIDKEYNAME, fkey)) { //_id
                        qf.ftype = BSON_OID;
                    }
                }
                tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                break;
            }
            case BSON_LONG:
            case BSON_DOUBLE:
            case BSON_INT:
            {
                assert(!qf.fpath && !qf.expr);
                qf.ftype = ftype;
                qf.fpath = tcstrjoin(pathStack, '.');
                qf.fpathsz = strlen(qf.fpath);
                if (ftype == BSON_LONG || ftype == BSON_INT) {
                    qf.exprlongval = bson_iterator_long(it);
                    qf.exprdblval = qf.exprlongval;
                    qf.expr = tcsprintf("%ld", qf.exprlongval);
                } else {
                    qf.exprdblval = bson_iterator_double(it);
                    qf.exprlongval = (int64_t) qf.exprdblval;
                    qf.expr = tcsprintf("%f", qf.exprdblval);
                }
                qf.exprsz = strlen(qf.expr);
                if (qf.flags & EJCOMPGT) {
                    qf.tcop = TDBQCNUMGT;
                } else if (qf.flags & EJCOMPGTE) {
                    qf.tcop = TDBQCNUMGE;
                } else if (qf.flags & EJCOMPLT) {
                    qf.tcop = TDBQCNUMLT;
                } else if (qf.flags & EJCOMPLTE) {
                    qf.tcop = TDBQCNUMLE;
                } else {
                    qf.tcop = TDBQCNUMEQ;
                }
                tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                break;
            }
            case BSON_REGEX:
            {
                assert(!qf.fpath && !qf.expr);
                qf.ftype = ftype;
                qf.tcop = TDBQCSTRRX;
                char *re = tcstrdup(bson_iterator_regex(it));
                const char *opts = bson_iterator_regex_opts(it);
                qf.fpath = tcstrjoin(pathStack, '.');
                qf.fpathsz = strlen(qf.fpath);
                qf.expr = re;
                qf.exprsz = strlen(qf.expr);
                const char *rxstr = qf.expr;
                regex_t rxbuf;
                int rxopt = REG_EXTENDED | REG_NOSUB;
                if (strchr(opts, 'i')) {
                    rxopt |= REG_ICASE;
                }
                if (regcomp(&rxbuf, rxstr, rxopt) == 0) {
                    TCMALLOC(qf.regex, sizeof (rxbuf));
                    memcpy(qf.regex, &rxbuf, sizeof (rxbuf));
                } else {
                    ret = JBEQINVALIDQRX;
                    TCFREE(qf.fpath);
                    TCFREE(qf.expr);
                    break;
                }
                tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                break;
            }
            case BSON_NULL:
            case BSON_UNDEFINED:
                qf.ftype = ftype;
                qf.tcop = TDBQCEXIST;
                qf.negate = !qf.negate;
                qf.expr = tcstrdup(""); //Empty string as expr
                qf.exprsz = 0;
                tcmapputkeep(qmap, qf.fpath, strlen(qf.fpath), &qf, sizeof (qf));
                break;

            case BSON_BOOL:
                if (isckey && !strcmp("$exists", fkey)) {
                    qf.tcop = TDBQCEXIST;
                    qf.fpath = tcstrjoin(pathStack, '.');
                    qf.fpathsz = strlen(qf.fpath);
                    qf.expr = tcstrdup(""); //Empty string as expr
                    qf.exprsz = 0;
                    if (!bson_iterator_bool_raw(it)) {
                        qf.negate = !qf.negate;
                    }
                    tcmapputkeep(qmap, qf.fpath, qf.fpathsz, &qf, sizeof (qf));
                }
                break;
            default:
                break;
        };

        if (!isckey) {
            assert(pathStack->num > 0);
            TCFREE(tclistpop2(pathStack));
        }
        if (ret) { //cleanup on error condition
            //TODO better error reporting
            _ejdbsetecode(jb, ret, __FILE__, __LINE__, __func__);
            break;
        }
    }

    return ret;
}

/**
 * Convert bson query spec into field path -> EJQF instance.
 *  Created map instance must be freed `tcmapdel`.
 *  Each element of map must be freed by TODO
 */
static TCMAP* _parseqobj(EJDB *jb, EJQ *q, bson *qspec) {
    assert(qspec);
    int rv = 0;
    TCMAP *res = tcmapnew();
    bson_iterator it;
    bson_iterator_init(&it, qspec);
    TCLIST *pathStack = tclistnew();
    rv = _parse_qobj_impl(jb, q, &it, res, pathStack, NULL);
    if (rv) {
        tcmapdel(res);
        res = NULL;
    }
    assert(!pathStack->num);
    tclistdel(pathStack);
    return res;
}

EJDB_INLINE bool _isvalidoidstr(const char *oid) {
    if (!oid) {
        return false;
    }
    int i = 0;
    for (; oid[i] != '\0' &&
            ((oid[i] >= 0x30 && oid[i] <= 0x39) || /* 1 - 9 */
            (oid[i] >= 0x61 && oid[i] <= 0x66)); ++i); /* a - f */
    return (i == 24);
}

/**
 * Get OID value from the '_id' field of specified bson object.
 * @param bson[in] BSON object
 * @param oid[out] Pointer to OID type
 * @return True if OID value is found int _id field of bson object otherwise False.
 */
static bool _bsonoidkey(bson *bs, bson_oid_t *oid) {
    bool rv = false;
    bson_iterator it;
    bson_type t = bson_find(&it, bs, JDBIDKEYNAME);
    if (t != BSON_STRING && t != BSON_OID) {
        goto finish;
    }
    if (t == BSON_STRING) {
        const char *oidstr = bson_iterator_string(&it);
        if (_isvalidoidstr(oidstr)) {
            bson_oid_from_string(oid, oidstr);
            rv = true;
        }
    } else {
        *oid = *bson_iterator_oid(&it);
        rv = true;
    }
finish:
    return rv;
}

/**
 * Return string value representation of value pointed by 'it'.
 * Resulting value size stored into 'vsz'.
 * If returned value is not NULL it must be freed by TCFREE.
 */
static char* _bsonitstrval(EJDB *jb, bson_iterator *it, int *vsz, TCLIST *tokens, txtflags_t tflags) {
    int retlen = 0;
    char *ret = NULL;
    bson_type btype = bson_iterator_type(it);
    if (btype == BSON_STRING) {
        if (tokens) { //split string into tokens and push it into 'tokens' list
            const unsigned char *sp = (unsigned char *) bson_iterator_string(it);
            while (*sp != '\0') {
                while ((*sp != '\0' && *sp <= ' ') || *sp == ',') {
                    sp++;
                }
                const unsigned char *ep = sp;
                while (*ep > ' ' && *ep != ',') {
                    ep++;
                }
                if (ep > sp) {
                    if (tflags & JBICASE) { //ignore case mode
                        char *buf = NULL;
                        char sbuf[JBSTRINOPBUFFERSZ];
                        int len = tcicaseformat((const char*) sp, ep - sp, sbuf, JBSTRINOPBUFFERSZ, &buf);
                        if (len >= 0) { //success
                            TCLISTPUSH(tokens, buf, len);
                        } else {
                            _ejdbsetecode(jb, len, __FILE__, __LINE__, __func__);
                        }
                        if (buf && buf != sbuf) {
                            TCFREE(buf);
                        }
                    } else {
                        TCLISTPUSH(tokens, sp, ep - sp);
                    }
                }
                sp = ep;
            }
        } else {
            retlen = bson_iterator_string_len(it) - 1;
            if (tflags & JBICASE) {
                retlen = tcicaseformat(bson_iterator_string(it), retlen, NULL, 0, &ret);
            } else {
                ret = tcmemdup(bson_iterator_string(it), retlen);
            }
        }
    } else if (BSON_IS_NUM_TYPE(btype)) {
        char nbuff[TCNUMBUFSIZ];
        if (btype == BSON_INT || btype == BSON_LONG) {
            retlen = bson_numstrn(nbuff, TCNUMBUFSIZ, bson_iterator_long(it));
            if (retlen >= TCNUMBUFSIZ) {
                retlen = TCNUMBUFSIZ - 1;
            }
        } else if (btype == BSON_DOUBLE) {
            retlen = tcftoa(bson_iterator_double(it), nbuff, TCNUMBUFSIZ, 6);
            if (retlen >= TCNUMBUFSIZ) {
                retlen = TCNUMBUFSIZ - 1;
            }
        }
        if (tflags & JBICASE) {
            retlen = tcicaseformat(nbuff, retlen, NULL, 0, &ret);
        } else {
            ret = tcmemdup(nbuff, retlen);
        }
    } else if (btype == BSON_ARRAY) {
        bson_type eltype; //last element bson type
        bson_iterator sit;
        bson_iterator_subiterator(it, &sit);
        if (tokens) {
            while ((eltype = bson_iterator_next(&sit)) != BSON_EOO) {
                int vz = 0;
                char *v = _bsonitstrval(jb, &sit, &vz, NULL, tflags);
                if (v) {
                    TCLISTPUSH(tokens, v, vz);
                    TCFREE(v);
                }
            }
        } else {
            //Array elements are joined with ',' delimeter.
            ret = _fetch_bson_str_array2(jb, &sit, &eltype, tflags);
            retlen = strlen(ret);
        }
    }
    if (retlen < 0) {
        _ejdbsetecode(jb, retlen, __FILE__, __LINE__, __func__);
        ret = NULL;
        retlen = 0;
    }
    *vsz = retlen;
    return ret;
}

static char* _bsonipathrowldr(
        TCLIST *tokens,
        const char *pkbuf, int pksz,
        const char *rowdata, int rowdatasz,
        const char *ipath, int ipathsz, void *op, int *vsz) {
    assert(op);
    char *res = NULL;
    if (ipath && *ipath == '\0') { //PK TODO review
        if (tokens) {
            const unsigned char *sp = (unsigned char *) pkbuf;
            while (*sp != '\0') {
                while ((*sp != '\0' && *sp <= ' ') || *sp == ',') {
                    sp++;
                }
                const unsigned char *ep = sp;
                while (*ep > ' ' && *ep != ',') {
                    ep++;
                }
                if (ep > sp) TCLISTPUSH(tokens, sp, ep - sp);
                sp = ep;
            }
            *vsz = 0;
            return NULL;
        } else {
            TCMEMDUP(res, pkbuf, pksz);
            *vsz = pksz;
            return res;
        }
    }
    if (!ipath || ipathsz < 2 || *(ipath + 1) == '\0' || strchr("snai", *ipath) == NULL) {
        return NULL;
    }
    //skip index type prefix char with (fpath + 1)
    res = _bsonfpathrowldr(tokens, rowdata, rowdatasz, ipath + 1, ipathsz - 1, op, vsz);
    if (*vsz == 0) { //Do not allow empty strings for index opration
        if (res) TCFREE(res);
        res = NULL;
    }
    return res;
}

static char* _bsonfpathrowldr(TCLIST *tokens, const char *rowdata, int rowdatasz,
        const char *fpath, int fpathsz, void *op, int *vsz) {
    _BSONIPATHROWLDR *odata = (_BSONIPATHROWLDR*) op;
    assert(odata && odata->jcoll);
    char *ret = NULL;
    int bsize;
    bson_iterator it;
    char *bsdata = tcmaploadone(rowdata, rowdatasz, JDBCOLBSON, JDBCOLBSONL, &bsize);
    if (!bsdata) {
        *vsz = 0;
        return NULL;
    }
    bson_iterator_from_buffer(&it, bsdata);
    bson_find_fieldpath_value2(fpath, fpathsz, &it);
    ret = _bsonitstrval(odata->jcoll->jb, &it, vsz, tokens, (odata->icase ? JBICASE : 0));
    TCFREE(bsdata);
    return ret;
}

static bool _updatebsonidx(EJCOLL *jcoll, const bson_oid_t *oid, const bson *bs,
        const void *obsdata, int obsdatasz) {
    bool rv = true;
    TCMAP *cmeta = tctdbget(jcoll->jb->metadb, jcoll->cname, jcoll->cnamesz);
    if (!cmeta) {
        _ejdbsetecode(jcoll->jb, JBEMETANVALID, __FILE__, __LINE__, __func__);
        return false;
    }
    TCMAP *imap = NULL; //New index map
    TCMAP *rimap = NULL; //Remove index map
    bson_type mt = BSON_EOO;
    bson_type ft = BSON_EOO;
    bson_type oft = BSON_EOO;
    bson_iterator fit, oit, mit;
    int bsz;
    char ikey[BSON_MAX_FPATH_LEN + 2];
    const char *mkey;
    int mkeysz;

    tcmapiterinit(cmeta);
    while ((mkey = tcmapiternext(cmeta, &mkeysz)) != NULL && mkeysz > 0) {
        if (*mkey != 'i' || mkeysz > BSON_MAX_FPATH_LEN + 1) {
            continue;
        }
        const void *mraw = tcmapget(cmeta, mkey, mkeysz, &bsz);
        if (!mraw || !bsz || (mt = bson_find_from_buffer(&mit, mraw, "iflags")) != BSON_INT) {
            continue;
        }
        int iflags = bson_iterator_int(&mit);
        //OK then process index keys
        memcpy(ikey + 1, mkey + 1, mkeysz - 1);
        ikey[mkeysz] = '\0';

        int fvaluesz = 0;
        char *fvalue = NULL;
        int ofvaluesz = 0;
        char *ofvalue = NULL;
        txtflags_t textflags = (iflags & JBIDXISTR) ? JBICASE : 0;

        if (obsdata && obsdatasz > 0) {
            bson_iterator_from_buffer(&oit, obsdata);
            oft = bson_find_fieldpath_value2(mkey + 1, mkeysz - 1, &oit);
            TCLIST *tokens = (oft == BSON_ARRAY) ? tclistnew() : NULL;
            ofvalue = BSON_IS_IDXSUPPORTED_TYPE(oft) ? _bsonitstrval(jcoll->jb, &oit, &ofvaluesz, tokens, textflags) : NULL;
            if (tokens) {
                ofvalue = tclistdump(tokens, &ofvaluesz);
                tclistdel(tokens);
            }
        }
        if (bs) {
            bson_iterator_init(&fit, bs);
            ft = bson_find_fieldpath_value2(mkey + 1, mkeysz - 1, &fit);
            TCLIST *tokens = (ft == BSON_ARRAY) ? tclistnew() : NULL;
            fvalue = BSON_IS_IDXSUPPORTED_TYPE(ft) ? _bsonitstrval(jcoll->jb, &fit, &fvaluesz, tokens, textflags) : NULL;
            if (tokens) {
                fvalue = tclistdump(tokens, &fvaluesz);
                tclistdel(tokens);
            }
        }
        if (!fvalue && !ofvalue) {
            continue;
        }
        if (imap == NULL) {
            imap = tcmapnew2(TCMAPTINYBNUM);
            rimap = tcmapnew2(TCMAPTINYBNUM);
        }
        for (int i = 4; i <= 7; ++i) { /* JBIDXNUM, JBIDXSTR, JBIDXARR, JBIDXISTR */
            bool rm = false;
            int itype = (1 << i);
            if (itype == JBIDXNUM && (JBIDXNUM & iflags)) {
                ikey[0] = 'n';
            } else if (itype == JBIDXSTR && (JBIDXSTR & iflags)) {
                ikey[0] = 's';
            } else if (itype == JBIDXISTR && (JBIDXISTR & iflags)) {
                ikey[0] = 'i';
            } else if (itype == JBIDXARR && (JBIDXARR & iflags)) {
                ikey[0] = 'a';
                if (ofvalue && oft == BSON_ARRAY &&
                        (!fvalue || ft != oft || fvaluesz != ofvaluesz || memcmp(fvalue, ofvalue, fvaluesz))) {
                    tcmapput(rimap, ikey, mkeysz, ofvalue, ofvaluesz);
                    rm = true;
                }
                if (fvalue && fvaluesz > 0 && ft == BSON_ARRAY && (!ofvalue || rm)) {
                    tcmapput(imap, ikey, mkeysz, fvalue, fvaluesz);
                }
                continue;
            } else {
                continue;
            }
            if (ofvalue && oft != BSON_ARRAY &&
                    (!fvalue || ft != oft || fvaluesz != ofvaluesz || memcmp(fvalue, ofvalue, fvaluesz))) {
                tcmapput(rimap, ikey, mkeysz, ofvalue, ofvaluesz);
                rm = true;
            }
            if (fvalue && fvaluesz > 0 && ft != BSON_ARRAY && (!ofvalue || rm)) {
                tcmapput(imap, ikey, mkeysz, fvalue, fvaluesz);
            }
        }
        if (fvalue) TCFREE(fvalue);
        if (ofvalue) TCFREE(ofvalue);
    }
    tcmapdel(cmeta);
    if (rimap && !tctdbidxout2(jcoll->tdb, oid, sizeof (*oid), rimap)) rv = false;
    if (imap && !tctdbidxput2(jcoll->tdb, oid, sizeof (*oid), imap)) rv = false;
    if (imap) tcmapdel(imap);
    if (rimap) tcmapdel(rimap);
    return rv;
}

static void _delcoldb(EJCOLL *jcoll) {
    assert(jcoll);
    tctdbdel(jcoll->tdb);
    jcoll->tdb = NULL;
    jcoll->jb = NULL;
    jcoll->cnamesz = 0;
    TCFREE(jcoll->cname);
    if (jcoll->mmtx) {
        pthread_rwlock_destroy(jcoll->mmtx);
        TCFREE(jcoll->mmtx);
    }
}

static bool _addcoldb0(const char *cname, EJDB *jb, EJCOLLOPTS *opts, EJCOLL **res) {
    bool rv = true;
    TCTDB *cdb;
    rv = _createcoldb(cname, jb, opts, &cdb);
    if (!rv) {
        *res = NULL;
        return rv;
    }
    TCREALLOC(jb->cdbs, jb->cdbs, sizeof (jb->cdbs[0]) * (++jb->cdbsnum));
    EJCOLL *jcoll = jb->cdbs + jb->cdbsnum - 1;
    jcoll->cname = tcstrdup(cname);
    jcoll->cnamesz = strlen(cname);
    jcoll->tdb = cdb;
    jcoll->jb = jb;
    jcoll->mmtx = NULL;
    _ejdbcolsetmutex(jcoll);
    *res = jcoll;
    return rv;
}

static bool _createcoldb(const char *colname, EJDB *jb, EJCOLLOPTS *opts, TCTDB **res) {
    assert(jb && jb->metadb);
    if (!JBISVALCOLNAME(colname)) {
        _ejdbsetecode(jb, JBEINVALIDCOLNAME, __FILE__, __LINE__, __func__);
        *res = NULL;
        return false;
    }
    bool rv = true;
    TCTDB *cdb = tctdbnew();
    if (opts) {
        if (opts->cachedrecords > 0) {
            tctdbsetcache(cdb, opts->cachedrecords, 0, 0);
        }
        int bnum = 0;
        uint8_t tflags = 0;
        if (opts->records > 0) {
            bnum = tclmax(opts->records * 2 + 1, TDBDEFBNUM);
        }
        if (opts->large) {
            tflags |= TDBTLARGE;
        }
        if (opts->compressed) {
            tflags |= TDBTDEFLATE;
        }
        tctdbtune(cdb, bnum, 0, 0, tflags);
    }
    const char *mdbpath = jb->metadb->hdb->path;
    assert(mdbpath);
    TCXSTR *cxpath = tcxstrnew2(mdbpath);
    tcxstrcat2(cxpath, "_");
    tcxstrcat2(cxpath, colname);
    rv = tctdbopen(cdb, tcxstrptr(cxpath), jb->metadb->hdb->omode);
    *res = rv ? cdb : NULL;
    tcxstrdel(cxpath);
    return rv;
}

static void _ejdbclear(EJDB *jb) {
    assert(jb);
    jb->cdbs = NULL;
    jb->cdbsnum = 0;
    jb->metadb = NULL;
    jb->mmtx = NULL;
}

/* Check whether a string includes all tokens in another string.*/
static bool _qrycondcheckstrand(const char *vbuf, const TCLIST *tokens) {
    assert(vbuf && tokens);
    for (int i = 0; i < TCLISTNUM(tokens); ++i) {
        const char *token = TCLISTVALPTR(tokens, i);
        int tokensz = TCLISTVALSIZ(tokens, i);
        bool found = false;
        const char *str = vbuf;
        while (true) {
            const char *sp = str;
            while (*str != '\0' && !strchr(", ", *str)) {
                str++;
            }
            if (tokensz == (str - sp) && !strncmp(token, sp, tokensz)) { //Token matched
                found = true;
                break;
            }
            if (*str == '\0') break;
            str++;
        }
        if (!found) {
            return false;
        }
    }
    return true;
}

/* Check whether a string includes at least one tokens in another string.*/
static bool _qrycondcheckstror(const char *vbuf, const TCLIST *tokens) {
    for (int i = 0; i < TCLISTNUM(tokens); ++i) {
        const char *token = TCLISTVALPTR(tokens, i);
        int tokensz = TCLISTVALSIZ(tokens, i);
        bool found = false;
        const char *str = vbuf;
        while (true) {
            const char *sp = str;
            while (*str != '\0' && !strchr(", ", *str)) {
                str++;
            }
            if (tokensz == (str - sp) && !strncmp(token, sp, tokensz)) { //Token matched
                found = true;
                break;
            }
            if (*str == '\0') break;
            str++;
        }
        if (found) {
            return true;
        }
    }
    return false;
}