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
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
|
/*****************************************************************************
Copyright (c) 2009, 2017, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2015, 2017, MariaDB Corporation.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file dict/dict0stats.cc
Code used for calculating and manipulating table statistics.
Created Jan 06, 2010 Vasil Dimov
*******************************************************/
#include "univ.i"
#include "ut0ut.h"
#include "ut0rnd.h"
#include "dyn0buf.h"
#include "row0sel.h"
#include "trx0trx.h"
#include "pars0pars.h"
#include "dict0stats.h"
#include "ha_prototypes.h"
#include "ut0new.h"
#include <mysql_com.h>
#include "btr0btr.h"
#include <algorithm>
#include <map>
#include <vector>
/* Sampling algorithm description @{
The algorithm is controlled by one number - N_SAMPLE_PAGES(index),
let it be A, which is the number of leaf pages to analyze for a given index
for each n-prefix (if the index is on 3 columns, then 3*A leaf pages will be
analyzed).
Let the total number of leaf pages in the table be T.
Level 0 - leaf pages, level H - root.
Definition: N-prefix-boring record is a record on a non-leaf page that equals
the next (to the right, cross page boundaries, skipping the supremum and
infimum) record on the same level when looking at the fist n-prefix columns.
The last (user) record on a level is not boring (it does not match the
non-existent user record to the right). We call the records boring because all
the records on the page below a boring record are equal to that boring record.
We avoid diving below boring records when searching for a leaf page to
estimate the number of distinct records because we know that such a leaf
page will have number of distinct records == 1.
For each n-prefix: start from the root level and full scan subsequent lower
levels until a level that contains at least A*10 distinct records is found.
Lets call this level LA.
As an optimization the search is canceled if it has reached level 1 (never
descend to the level 0 (leaf)) and also if the next level to be scanned
would contain more than A pages. The latter is because the user has asked
to analyze A leaf pages and it does not make sense to scan much more than
A non-leaf pages with the sole purpose of finding a good sample of A leaf
pages.
After finding the appropriate level LA with >A*10 distinct records (or less in
the exceptions described above), divide it into groups of equal records and
pick A such groups. Then pick the last record from each group. For example,
let the level be:
index: 0,1,2,3,4,5,6,7,8,9,10
record: 1,1,1,2,2,7,7,7,7,7,9
There are 4 groups of distinct records and if A=2 random ones are selected,
e.g. 1,1,1 and 7,7,7,7,7, then records with indexes 2 and 9 will be selected.
After selecting A records as described above, dive below them to find A leaf
pages and analyze them, finding the total number of distinct records. The
dive to the leaf level is performed by selecting a non-boring record from
each page and diving below it.
This way, a total of A leaf pages are analyzed for the given n-prefix.
Let the number of different key values found in each leaf page i be Pi (i=1..A).
Let N_DIFF_AVG_LEAF be (P1 + P2 + ... + PA) / A.
Let the number of different key values on level LA be N_DIFF_LA.
Let the total number of records on level LA be TOTAL_LA.
Let R be N_DIFF_LA / TOTAL_LA, we assume this ratio is the same on the
leaf level.
Let the number of leaf pages be N.
Then the total number of different key values on the leaf level is:
N * R * N_DIFF_AVG_LEAF.
See REF01 for the implementation.
The above describes how to calculate the cardinality of an index.
This algorithm is executed for each n-prefix of a multi-column index
where n=1..n_uniq.
@} */
/* names of the tables from the persistent statistics storage */
#define TABLE_STATS_NAME "mysql/innodb_table_stats"
#define TABLE_STATS_NAME_PRINT "mysql.innodb_table_stats"
#define INDEX_STATS_NAME "mysql/innodb_index_stats"
#define INDEX_STATS_NAME_PRINT "mysql.innodb_index_stats"
#ifdef UNIV_STATS_DEBUG
#define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
#else /* UNIV_STATS_DEBUG */
#define DEBUG_PRINTF(fmt, ...) /* noop */
#endif /* UNIV_STATS_DEBUG */
/* Gets the number of leaf pages to sample in persistent stats estimation */
#define N_SAMPLE_PAGES(index) \
static_cast<ib_uint64_t>( \
(index)->table->stats_sample_pages != 0 \
? (index)->table->stats_sample_pages \
: srv_stats_persistent_sample_pages)
/* number of distinct records on a given level that are required to stop
descending to lower levels and fetch N_SAMPLE_PAGES(index) records
from that level */
#define N_DIFF_REQUIRED(index) (N_SAMPLE_PAGES(index) * 10)
/* A dynamic array where we store the boundaries of each distinct group
of keys. For example if a btree level is:
index: 0,1,2,3,4,5,6,7,8,9,10,11,12
data: b,b,b,b,b,b,g,g,j,j,j, x, y
then we would store 5,7,10,11,12 in the array. */
typedef std::vector<ib_uint64_t, ut_allocator<ib_uint64_t> > boundaries_t;
/** Allocator type used for index_map_t. */
typedef ut_allocator<std::pair<const char* const, dict_index_t*> >
index_map_t_allocator;
/** Auxiliary map used for sorting indexes by name in dict_stats_save(). */
typedef std::map<const char*, dict_index_t*, ut_strcmp_functor,
index_map_t_allocator> index_map_t;
/*********************************************************************//**
Checks whether an index should be ignored in stats manipulations:
* stats fetch
* stats recalc
* stats save
@return true if exists and all tables are ok */
UNIV_INLINE
bool
dict_stats_should_ignore_index(
/*===========================*/
const dict_index_t* index) /*!< in: index */
{
return((index->type & DICT_FTS)
|| dict_index_is_corrupted(index)
|| dict_index_is_spatial(index)
|| index->to_be_dropped
|| !index->is_committed());
}
/*********************************************************************//**
Checks whether the persistent statistics storage exists and that all
tables have the proper structure.
@return true if exists and all tables are ok */
static
bool
dict_stats_persistent_storage_check(
/*================================*/
bool caller_has_dict_sys_mutex) /*!< in: true if the caller
owns dict_sys->mutex */
{
/* definition for the table TABLE_STATS_NAME */
dict_col_meta_t table_stats_columns[] = {
{"database_name", DATA_VARMYSQL,
DATA_NOT_NULL, 192},
{"table_name", DATA_VARMYSQL,
DATA_NOT_NULL, 192},
{"last_update", DATA_FIXBINARY,
DATA_NOT_NULL, 4},
{"n_rows", DATA_INT,
DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"clustered_index_size", DATA_INT,
DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"sum_of_other_index_sizes", DATA_INT,
DATA_NOT_NULL | DATA_UNSIGNED, 8}
};
dict_table_schema_t table_stats_schema = {
TABLE_STATS_NAME,
UT_ARR_SIZE(table_stats_columns),
table_stats_columns,
0 /* n_foreign */,
0 /* n_referenced */
};
/* definition for the table INDEX_STATS_NAME */
dict_col_meta_t index_stats_columns[] = {
{"database_name", DATA_VARMYSQL,
DATA_NOT_NULL, 192},
{"table_name", DATA_VARMYSQL,
DATA_NOT_NULL, 192},
{"index_name", DATA_VARMYSQL,
DATA_NOT_NULL, 192},
{"last_update", DATA_FIXBINARY,
DATA_NOT_NULL, 4},
{"stat_name", DATA_VARMYSQL,
DATA_NOT_NULL, 64*3},
{"stat_value", DATA_INT,
DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"sample_size", DATA_INT,
DATA_UNSIGNED, 8},
{"stat_description", DATA_VARMYSQL,
DATA_NOT_NULL, 1024*3}
};
dict_table_schema_t index_stats_schema = {
INDEX_STATS_NAME,
UT_ARR_SIZE(index_stats_columns),
index_stats_columns,
0 /* n_foreign */,
0 /* n_referenced */
};
char errstr[512];
dberr_t ret;
if (!caller_has_dict_sys_mutex) {
mutex_enter(&dict_sys->mutex);
}
ut_ad(mutex_own(&dict_sys->mutex));
/* first check table_stats */
ret = dict_table_schema_check(&table_stats_schema, errstr,
sizeof(errstr));
if (ret == DB_SUCCESS) {
/* if it is ok, then check index_stats */
ret = dict_table_schema_check(&index_stats_schema, errstr,
sizeof(errstr));
}
if (!caller_has_dict_sys_mutex) {
mutex_exit(&dict_sys->mutex);
}
if (ret != DB_SUCCESS && ret != DB_STATS_DO_NOT_EXIST) {
ib::error() << errstr;
return(false);
} else if (ret == DB_STATS_DO_NOT_EXIST) {
return false;
}
/* else */
return(true);
}
/** Executes a given SQL statement using the InnoDB internal SQL parser.
This function will free the pinfo object.
@param[in,out] pinfo pinfo to pass to que_eval_sql() must already
have any literals bound to it
@param[in] sql SQL string to execute
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
static
dberr_t
dict_stats_exec_sql(
pars_info_t* pinfo,
const char* sql,
trx_t* trx)
{
dberr_t err;
err = que_eval_sql(pinfo, sql, FALSE, trx); /* pinfo is freed here */
DBUG_EXECUTE_IF("stats_index_error",
err = DB_STATS_DO_NOT_EXIST;
trx->error_state = DB_STATS_DO_NOT_EXIST;);
return(err);
}
/*********************************************************************//**
Duplicate a table object and its indexes.
This function creates a dummy dict_table_t object and initializes the
following table and index members:
dict_table_t::id (copied)
dict_table_t::heap (newly created)
dict_table_t::name (copied)
dict_table_t::corrupted (copied)
dict_table_t::indexes<> (newly created)
dict_table_t::magic_n
for each entry in dict_table_t::indexes, the following are initialized:
(indexes that have DICT_FTS set in index->type are skipped)
dict_index_t::id (copied)
dict_index_t::name (copied)
dict_index_t::table_name (points to the copied table name)
dict_index_t::table (points to the above semi-initialized object)
dict_index_t::type (copied)
dict_index_t::to_be_dropped (copied)
dict_index_t::online_status (copied)
dict_index_t::n_uniq (copied)
dict_index_t::fields[] (newly created, only first n_uniq, only fields[i].name)
dict_index_t::indexes<> (newly created)
dict_index_t::stat_n_diff_key_vals[] (only allocated, left uninitialized)
dict_index_t::stat_n_sample_sizes[] (only allocated, left uninitialized)
dict_index_t::stat_n_non_null_key_vals[] (only allocated, left uninitialized)
dict_index_t::magic_n
The returned object should be freed with dict_stats_table_clone_free()
when no longer needed.
@return incomplete table object */
static
dict_table_t*
dict_stats_table_clone_create(
/*==========================*/
const dict_table_t* table) /*!< in: table whose stats to copy */
{
size_t heap_size;
dict_index_t* index;
/* Estimate the size needed for the table and all of its indexes */
heap_size = 0;
heap_size += sizeof(dict_table_t);
heap_size += strlen(table->name.m_name) + 1;
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (dict_stats_should_ignore_index(index)) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
ulint n_uniq = dict_index_get_n_unique(index);
heap_size += sizeof(dict_index_t);
heap_size += strlen(index->name) + 1;
heap_size += n_uniq * sizeof(index->fields[0]);
for (ulint i = 0; i < n_uniq; i++) {
heap_size += strlen(index->fields[i].name) + 1;
}
heap_size += n_uniq * sizeof(index->stat_n_diff_key_vals[0]);
heap_size += n_uniq * sizeof(index->stat_n_sample_sizes[0]);
heap_size += n_uniq * sizeof(index->stat_n_non_null_key_vals[0]);
}
/* Allocate the memory and copy the members */
mem_heap_t* heap;
heap = mem_heap_create(heap_size);
dict_table_t* t;
t = (dict_table_t*) mem_heap_alloc(heap, sizeof(*t));
UNIV_MEM_ASSERT_RW_ABORT(&table->id, sizeof(table->id));
t->id = table->id;
t->heap = heap;
t->name.m_name = mem_heap_strdup(heap, table->name.m_name);
t->corrupted = table->corrupted;
/* This private object "t" is not shared with other threads, so
we do not need the stats_latch (thus we pass false below). The
dict_table_stats_lock()/unlock() routines will do nothing. */
dict_table_stats_latch_create(t, false);
UT_LIST_INIT(t->indexes, &dict_index_t::indexes);
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (dict_stats_should_ignore_index(index)) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
dict_index_t* idx;
idx = (dict_index_t*) mem_heap_alloc(heap, sizeof(*idx));
UNIV_MEM_ASSERT_RW_ABORT(&index->id, sizeof(index->id));
idx->id = index->id;
idx->name = mem_heap_strdup(heap, index->name);
idx->table_name = t->name.m_name;
idx->table = t;
idx->type = index->type;
idx->to_be_dropped = 0;
idx->online_status = ONLINE_INDEX_COMPLETE;
idx->set_committed(true);
idx->n_uniq = index->n_uniq;
idx->fields = (dict_field_t*) mem_heap_alloc(
heap, idx->n_uniq * sizeof(idx->fields[0]));
for (ulint i = 0; i < idx->n_uniq; i++) {
idx->fields[i].name = mem_heap_strdup(
heap, index->fields[i].name);
}
/* hook idx into t->indexes */
UT_LIST_ADD_LAST(t->indexes, idx);
idx->stat_n_diff_key_vals = (ib_uint64_t*) mem_heap_alloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_diff_key_vals[0]));
idx->stat_n_sample_sizes = (ib_uint64_t*) mem_heap_alloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_sample_sizes[0]));
idx->stat_n_non_null_key_vals = (ib_uint64_t*) mem_heap_alloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_non_null_key_vals[0]));
ut_d(idx->magic_n = DICT_INDEX_MAGIC_N);
idx->stat_defrag_n_page_split = 0;
idx->stat_defrag_n_pages_freed = 0;
}
ut_d(t->magic_n = DICT_TABLE_MAGIC_N);
return(t);
}
/*********************************************************************//**
Free the resources occupied by an object returned by
dict_stats_table_clone_create(). */
static
void
dict_stats_table_clone_free(
/*========================*/
dict_table_t* t) /*!< in: dummy table object to free */
{
dict_table_stats_latch_destroy(t);
mem_heap_free(t->heap);
}
/*********************************************************************//**
Write all zeros (or 1 where it makes sense) into an index
statistics members. The resulting stats correspond to an empty index.
The caller must own index's table stats latch in X mode
(dict_table_stats_lock(table, RW_X_LATCH)) */
static
void
dict_stats_empty_index(
/*===================*/
dict_index_t* index, /*!< in/out: index */
bool empty_defrag_stats)
/*!< in: whether to empty defrag stats */
{
ut_ad(!(index->type & DICT_FTS));
ut_ad(!dict_index_is_ibuf(index));
ulint n_uniq = index->n_uniq;
for (ulint i = 0; i < n_uniq; i++) {
index->stat_n_diff_key_vals[i] = 0;
index->stat_n_sample_sizes[i] = 1;
index->stat_n_non_null_key_vals[i] = 0;
}
index->stat_index_size = 1;
index->stat_n_leaf_pages = 1;
if (empty_defrag_stats) {
dict_stats_empty_defrag_stats(index);
dict_stats_empty_defrag_summary(index);
}
}
/** Reset the table and index statsistics, corresponding to an empty table.
@param[in,out] table table whose statistics are to be reset
@param[in] empty_defrag_stats whether to empty the defrag statistics
*/
void
dict_stats_empty_table(dict_table_t* table, bool empty_defrag_stats)
{
/* Zero the stats members */
dict_table_stats_lock(table, RW_X_LATCH);
table->stat_n_rows = 0;
table->stat_clustered_index_size = 1;
/* 1 page for each index, not counting the clustered */
table->stat_sum_of_other_index_sizes
= UT_LIST_GET_LEN(table->indexes) - 1;
table->stat_modified_counter = 0;
dict_index_t* index;
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (index->type & DICT_FTS) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
dict_stats_empty_index(index, empty_defrag_stats);
}
table->stat_initialized = TRUE;
dict_table_stats_unlock(table, RW_X_LATCH);
}
/*********************************************************************//**
Check whether index's stats are initialized (assert if they are not). */
static
void
dict_stats_assert_initialized_index(
/*================================*/
const dict_index_t* index) /*!< in: index */
{
UNIV_MEM_ASSERT_RW_ABORT(
index->stat_n_diff_key_vals,
index->n_uniq * sizeof(index->stat_n_diff_key_vals[0]));
UNIV_MEM_ASSERT_RW_ABORT(
index->stat_n_sample_sizes,
index->n_uniq * sizeof(index->stat_n_sample_sizes[0]));
UNIV_MEM_ASSERT_RW_ABORT(
index->stat_n_non_null_key_vals,
index->n_uniq * sizeof(index->stat_n_non_null_key_vals[0]));
UNIV_MEM_ASSERT_RW_ABORT(
&index->stat_index_size,
sizeof(index->stat_index_size));
UNIV_MEM_ASSERT_RW_ABORT(
&index->stat_n_leaf_pages,
sizeof(index->stat_n_leaf_pages));
}
/*********************************************************************//**
Check whether table's stats are initialized (assert if they are not). */
static
void
dict_stats_assert_initialized(
/*==========================*/
const dict_table_t* table) /*!< in: table */
{
ut_a(table->stat_initialized);
UNIV_MEM_ASSERT_RW_ABORT(&table->stats_last_recalc,
sizeof(table->stats_last_recalc));
UNIV_MEM_ASSERT_RW_ABORT(&table->stat_persistent,
sizeof(table->stat_persistent));
UNIV_MEM_ASSERT_RW_ABORT(&table->stats_auto_recalc,
sizeof(table->stats_auto_recalc));
UNIV_MEM_ASSERT_RW_ABORT(&table->stats_sample_pages,
sizeof(table->stats_sample_pages));
UNIV_MEM_ASSERT_RW_ABORT(&table->stat_n_rows,
sizeof(table->stat_n_rows));
UNIV_MEM_ASSERT_RW_ABORT(&table->stat_clustered_index_size,
sizeof(table->stat_clustered_index_size));
UNIV_MEM_ASSERT_RW_ABORT(&table->stat_sum_of_other_index_sizes,
sizeof(table->stat_sum_of_other_index_sizes));
UNIV_MEM_ASSERT_RW_ABORT(&table->stat_modified_counter,
sizeof(table->stat_modified_counter));
UNIV_MEM_ASSERT_RW_ABORT(&table->stats_bg_flag,
sizeof(table->stats_bg_flag));
for (dict_index_t* index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (!dict_stats_should_ignore_index(index)) {
dict_stats_assert_initialized_index(index);
}
}
}
#define INDEX_EQ(i1, i2) \
((i1) != NULL \
&& (i2) != NULL \
&& (i1)->id == (i2)->id \
&& strcmp((i1)->name, (i2)->name) == 0)
/*********************************************************************//**
Copy table and index statistics from one table to another, including index
stats. Extra indexes in src are ignored and extra indexes in dst are
initialized to correspond to an empty index. */
static
void
dict_stats_copy(
/*============*/
dict_table_t* dst, /*!< in/out: destination table */
const dict_table_t* src, /*!< in: source table */
bool reset_ignored_indexes) /*!< in: if true, set ignored indexes
to have the same statistics as if
the table was empty */
{
dst->stats_last_recalc = src->stats_last_recalc;
dst->stat_n_rows = src->stat_n_rows;
dst->stat_clustered_index_size = src->stat_clustered_index_size;
dst->stat_sum_of_other_index_sizes = src->stat_sum_of_other_index_sizes;
dst->stat_modified_counter = src->stat_modified_counter;
dict_index_t* dst_idx;
dict_index_t* src_idx;
for (dst_idx = dict_table_get_first_index(dst),
src_idx = dict_table_get_first_index(src);
dst_idx != NULL;
dst_idx = dict_table_get_next_index(dst_idx),
(src_idx != NULL
&& (src_idx = dict_table_get_next_index(src_idx)))) {
if (dict_stats_should_ignore_index(dst_idx)) {
if (reset_ignored_indexes) {
/* Reset index statistics for all ignored indexes,
unless they are FT indexes (these have no statistics)*/
if (dst_idx->type & DICT_FTS) {
continue;
}
dict_stats_empty_index(dst_idx, true);
} else {
continue;
}
}
ut_ad(!dict_index_is_ibuf(dst_idx));
if (!INDEX_EQ(src_idx, dst_idx)) {
for (src_idx = dict_table_get_first_index(src);
src_idx != NULL;
src_idx = dict_table_get_next_index(src_idx)) {
if (INDEX_EQ(src_idx, dst_idx)) {
break;
}
}
}
if (!INDEX_EQ(src_idx, dst_idx)) {
dict_stats_empty_index(dst_idx, true);
continue;
}
ulint n_copy_el;
if (dst_idx->n_uniq > src_idx->n_uniq) {
n_copy_el = src_idx->n_uniq;
/* Since src is smaller some elements in dst
will remain untouched by the following memmove(),
thus we init all of them here. */
dict_stats_empty_index(dst_idx, true);
} else {
n_copy_el = dst_idx->n_uniq;
}
memmove(dst_idx->stat_n_diff_key_vals,
src_idx->stat_n_diff_key_vals,
n_copy_el * sizeof(dst_idx->stat_n_diff_key_vals[0]));
memmove(dst_idx->stat_n_sample_sizes,
src_idx->stat_n_sample_sizes,
n_copy_el * sizeof(dst_idx->stat_n_sample_sizes[0]));
memmove(dst_idx->stat_n_non_null_key_vals,
src_idx->stat_n_non_null_key_vals,
n_copy_el * sizeof(dst_idx->stat_n_non_null_key_vals[0]));
dst_idx->stat_index_size = src_idx->stat_index_size;
dst_idx->stat_n_leaf_pages = src_idx->stat_n_leaf_pages;
dst_idx->stat_defrag_modified_counter =
src_idx->stat_defrag_modified_counter;
dst_idx->stat_defrag_n_pages_freed =
src_idx->stat_defrag_n_pages_freed;
dst_idx->stat_defrag_n_page_split =
src_idx->stat_defrag_n_page_split;
}
dst->stat_initialized = TRUE;
}
/** Duplicate the stats of a table and its indexes.
This function creates a dummy dict_table_t object and copies the input
table's stats into it. The returned table object is not in the dictionary
cache and cannot be accessed by any other threads. In addition to the
members copied in dict_stats_table_clone_create() this function initializes
the following:
dict_table_t::stat_initialized
dict_table_t::stat_persistent
dict_table_t::stat_n_rows
dict_table_t::stat_clustered_index_size
dict_table_t::stat_sum_of_other_index_sizes
dict_table_t::stat_modified_counter
dict_index_t::stat_n_diff_key_vals[]
dict_index_t::stat_n_sample_sizes[]
dict_index_t::stat_n_non_null_key_vals[]
dict_index_t::stat_index_size
dict_index_t::stat_n_leaf_pages
dict_index_t::stat_defrag_modified_counter
dict_index_t::stat_defrag_n_pages_freed
dict_index_t::stat_defrag_n_page_split
The returned object should be freed with dict_stats_snapshot_free()
when no longer needed.
@param[in] table table whose stats to copy
@return incomplete table object */
static
dict_table_t*
dict_stats_snapshot_create(
dict_table_t* table)
{
mutex_enter(&dict_sys->mutex);
dict_table_stats_lock(table, RW_S_LATCH);
dict_stats_assert_initialized(table);
dict_table_t* t;
t = dict_stats_table_clone_create(table);
dict_stats_copy(t, table, false);
t->stat_persistent = table->stat_persistent;
t->stats_auto_recalc = table->stats_auto_recalc;
t->stats_sample_pages = table->stats_sample_pages;
t->stats_bg_flag = table->stats_bg_flag;
dict_table_stats_unlock(table, RW_S_LATCH);
mutex_exit(&dict_sys->mutex);
return(t);
}
/*********************************************************************//**
Free the resources occupied by an object returned by
dict_stats_snapshot_create(). */
static
void
dict_stats_snapshot_free(
/*=====================*/
dict_table_t* t) /*!< in: dummy table object to free */
{
dict_stats_table_clone_free(t);
}
/*********************************************************************//**
Calculates new estimates for index statistics. This function is
relatively quick and is used to calculate transient statistics that
are not saved on disk. This was the only way to calculate statistics
before the Persistent Statistics feature was introduced.
This function doesn't update the defragmentation related stats.
Only persistent statistics supports defragmentation stats. */
static
void
dict_stats_update_transient_for_index(
/*==================================*/
dict_index_t* index) /*!< in/out: index */
{
if (srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO
&& (srv_force_recovery >= SRV_FORCE_NO_LOG_REDO
|| !dict_index_is_clust(index))) {
/* If we have set a high innodb_force_recovery
level, do not calculate statistics, as a badly
corrupted index can cause a crash in it.
Initialize some bogus index cardinality
statistics, so that the data can be queried in
various means, also via secondary indexes. */
dict_stats_empty_index(index, false);
#if defined UNIV_DEBUG || defined UNIV_IBUF_DEBUG
} else if (ibuf_debug && !dict_index_is_clust(index)) {
dict_stats_empty_index(index, false);
#endif /* UNIV_DEBUG || UNIV_IBUF_DEBUG */
} else {
mtr_t mtr;
ulint size;
mtr_start(&mtr);
mtr_s_lock(dict_index_get_lock(index), &mtr);
size = btr_get_size(index, BTR_TOTAL_SIZE, &mtr);
if (size != ULINT_UNDEFINED) {
index->stat_index_size = size;
size = btr_get_size(
index, BTR_N_LEAF_PAGES, &mtr);
}
mtr_commit(&mtr);
switch (size) {
case ULINT_UNDEFINED:
dict_stats_empty_index(index, false);
return;
case 0:
/* The root node of the tree is a leaf */
size = 1;
}
index->stat_n_leaf_pages = size;
/* Do not continue if table decryption has failed or
table is already marked as corrupted. */
if (index->is_readable()) {
/* We don't handle the return value since it
will be false only when some thread is
dropping the table and we don't have to empty
the statistics of the to be dropped index */
btr_estimate_number_of_different_key_vals(index);
}
}
}
/*********************************************************************//**
Calculates new estimates for table and index statistics. This function
is relatively quick and is used to calculate transient statistics that
are not saved on disk.
This was the only way to calculate statistics before the
Persistent Statistics feature was introduced. */
static
void
dict_stats_update_transient(
/*========================*/
dict_table_t* table) /*!< in/out: table */
{
dict_index_t* index;
ulint sum_of_index_sizes = 0;
/* Find out the sizes of the indexes and how many different values
for the key they approximately have */
index = dict_table_get_first_index(table);
if (dict_table_is_discarded(table)) {
/* Nothing to do. */
dict_stats_empty_table(table, true);
return;
} else if (index == NULL) {
/* Table definition is corrupt */
ib::warn() << "Table " << table->name
<< " has no indexes. Cannot calculate statistics.";
dict_stats_empty_table(table, true);
return;
}
for (; index != NULL; index = dict_table_get_next_index(index)) {
ut_ad(!dict_index_is_ibuf(index));
if (index->type & DICT_FTS || dict_index_is_spatial(index)) {
continue;
}
dict_stats_empty_index(index, false);
if (dict_stats_should_ignore_index(index)) {
continue;
}
/* Do not continue if table decryption has failed or
table is already marked as corrupted. */
if (!index->is_readable()) {
break;
}
dict_stats_update_transient_for_index(index);
sum_of_index_sizes += index->stat_index_size;
}
index = dict_table_get_first_index(table);
table->stat_n_rows = index->stat_n_diff_key_vals[
dict_index_get_n_unique(index) - 1];
table->stat_clustered_index_size = index->stat_index_size;
table->stat_sum_of_other_index_sizes = sum_of_index_sizes
- index->stat_index_size;
table->stats_last_recalc = ut_time();
table->stat_modified_counter = 0;
table->stat_initialized = TRUE;
}
/* @{ Pseudo code about the relation between the following functions
let N = N_SAMPLE_PAGES(index)
dict_stats_analyze_index()
for each n_prefix
search for good enough level:
dict_stats_analyze_index_level() // only called if level has <= N pages
// full scan of the level in one mtr
collect statistics about the given level
if we are not satisfied with the level, search next lower level
we have found a good enough level here
dict_stats_analyze_index_for_n_prefix(that level, stats collected above)
// full scan of the level in one mtr
dive below some records and analyze the leaf page there:
dict_stats_analyze_index_below_cur()
@} */
/*********************************************************************//**
Find the total number and the number of distinct keys on a given level in
an index. Each of the 1..n_uniq prefixes are looked up and the results are
saved in the array n_diff[0] .. n_diff[n_uniq - 1]. The total number of
records on the level is saved in total_recs.
Also, the index of the last record in each group of equal records is saved
in n_diff_boundaries[0..n_uniq - 1], records indexing starts from the leftmost
record on the level and continues cross pages boundaries, counting from 0. */
static
void
dict_stats_analyze_index_level(
/*===========================*/
dict_index_t* index, /*!< in: index */
ulint level, /*!< in: level */
ib_uint64_t* n_diff, /*!< out: array for number of
distinct keys for all prefixes */
ib_uint64_t* total_recs, /*!< out: total number of records */
ib_uint64_t* total_pages, /*!< out: total number of pages */
boundaries_t* n_diff_boundaries,/*!< out: boundaries of the groups
of distinct keys */
mtr_t* mtr) /*!< in/out: mini-transaction */
{
ulint n_uniq;
mem_heap_t* heap;
btr_pcur_t pcur;
const page_t* page;
const rec_t* rec;
const rec_t* prev_rec;
bool prev_rec_is_copied;
byte* prev_rec_buf = NULL;
ulint prev_rec_buf_size = 0;
ulint* rec_offsets;
ulint* prev_rec_offsets;
ulint i;
DEBUG_PRINTF(" %s(table=%s, index=%s, level=" ULINTPF ")\n",
__func__, index->table->name, index->name, level);
ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
MTR_MEMO_SX_LOCK));
n_uniq = dict_index_get_n_unique(index);
/* elements in the n_diff array are 0..n_uniq-1 (inclusive) */
memset(n_diff, 0x0, n_uniq * sizeof(n_diff[0]));
/* Allocate space for the offsets header (the allocation size at
offsets[0] and the REC_OFFS_HEADER_SIZE bytes), and n_fields + 1,
so that this will never be less than the size calculated in
rec_get_offsets_func(). */
i = (REC_OFFS_HEADER_SIZE + 1 + 1) + index->n_fields;
heap = mem_heap_create((2 * sizeof *rec_offsets) * i);
rec_offsets = static_cast<ulint*>(
mem_heap_alloc(heap, i * sizeof *rec_offsets));
prev_rec_offsets = static_cast<ulint*>(
mem_heap_alloc(heap, i * sizeof *prev_rec_offsets));
rec_offs_set_n_alloc(rec_offsets, i);
rec_offs_set_n_alloc(prev_rec_offsets, i);
/* reset the dynamic arrays n_diff_boundaries[0..n_uniq-1] */
if (n_diff_boundaries != NULL) {
for (i = 0; i < n_uniq; i++) {
n_diff_boundaries[i].erase(
n_diff_boundaries[i].begin(),
n_diff_boundaries[i].end());
}
}
/* Position pcur on the leftmost record on the leftmost page
on the desired level. */
btr_pcur_open_at_index_side(
true, index, BTR_SEARCH_TREE_ALREADY_S_LATCHED,
&pcur, true, level, mtr);
btr_pcur_move_to_next_on_page(&pcur);
page = btr_pcur_get_page(&pcur);
/* The page must not be empty, except when
it is the root page (and the whole index is empty). */
ut_ad(btr_pcur_is_on_user_rec(&pcur) || page_is_leaf(page));
ut_ad(btr_pcur_get_rec(&pcur)
== page_rec_get_next_const(page_get_infimum_rec(page)));
/* check that we are indeed on the desired level */
ut_a(btr_page_get_level(page, mtr) == level);
/* there should not be any pages on the left */
ut_a(btr_page_get_prev(page, mtr) == FIL_NULL);
if (REC_INFO_MIN_REC_FLAG & rec_get_info_bits(
btr_pcur_get_rec(&pcur), page_is_comp(page))) {
ut_ad(btr_pcur_is_on_user_rec(&pcur));
if (level == 0) {
/* Skip the 'default row' pseudo-record */
ut_ad(index->is_instant());
btr_pcur_move_to_next_user_rec(&pcur, mtr);
}
} else {
/* The first record on the leftmost page must be
marked as such on each level except the leaf level. */
ut_a(level == 0);
}
prev_rec = NULL;
prev_rec_is_copied = false;
/* no records by default */
*total_recs = 0;
*total_pages = 0;
/* iterate over all user records on this level
and compare each two adjacent ones, even the last on page
X and the fist on page X+1 */
for (;
btr_pcur_is_on_user_rec(&pcur);
btr_pcur_move_to_next_user_rec(&pcur, mtr)) {
bool rec_is_last_on_page;
rec = btr_pcur_get_rec(&pcur);
/* If rec and prev_rec are on different pages, then prev_rec
must have been copied, because we hold latch only on the page
where rec resides. */
if (prev_rec != NULL
&& page_align(rec) != page_align(prev_rec)) {
ut_a(prev_rec_is_copied);
}
rec_is_last_on_page =
page_rec_is_supremum(page_rec_get_next_const(rec));
/* increment the pages counter at the end of each page */
if (rec_is_last_on_page) {
(*total_pages)++;
}
/* Skip delete-marked records on the leaf level. If we
do not skip them, then ANALYZE quickly after DELETE
could count them or not (purge may have already wiped
them away) which brings non-determinism. We skip only
leaf-level delete marks because delete marks on
non-leaf level do not make sense. */
if (level == 0
&& !srv_stats_include_delete_marked
&& rec_get_deleted_flag(
rec,
page_is_comp(btr_pcur_get_page(&pcur)))) {
if (rec_is_last_on_page
&& !prev_rec_is_copied
&& prev_rec != NULL) {
/* copy prev_rec */
prev_rec_offsets = rec_get_offsets(
prev_rec, index, prev_rec_offsets,
true,
n_uniq, &heap);
prev_rec = rec_copy_prefix_to_buf(
prev_rec, index,
rec_offs_n_fields(prev_rec_offsets),
&prev_rec_buf, &prev_rec_buf_size);
prev_rec_is_copied = true;
}
continue;
}
rec_offsets = rec_get_offsets(
rec, index, rec_offsets, !level, n_uniq, &heap);
(*total_recs)++;
if (prev_rec != NULL) {
ulint matched_fields;
prev_rec_offsets = rec_get_offsets(
prev_rec, index, prev_rec_offsets, !level,
n_uniq, &heap);
cmp_rec_rec_with_match(rec,
prev_rec,
rec_offsets,
prev_rec_offsets,
index,
FALSE,
&matched_fields);
for (i = matched_fields; i < n_uniq; i++) {
if (n_diff_boundaries != NULL) {
/* push the index of the previous
record, that is - the last one from
a group of equal keys */
ib_uint64_t idx;
/* the index of the current record
is total_recs - 1, the index of the
previous record is total_recs - 2;
we know that idx is not going to
become negative here because if we
are in this branch then there is a
previous record and thus
total_recs >= 2 */
idx = *total_recs - 2;
n_diff_boundaries[i].push_back(idx);
}
/* increment the number of different keys
for n_prefix=i+1 (e.g. if i=0 then we increment
for n_prefix=1 which is stored in n_diff[0]) */
n_diff[i]++;
}
} else {
/* this is the first non-delete marked record */
for (i = 0; i < n_uniq; i++) {
n_diff[i] = 1;
}
}
if (rec_is_last_on_page) {
/* end of a page has been reached */
/* we need to copy the record instead of assigning
like prev_rec = rec; because when we traverse the
records on this level at some point we will jump from
one page to the next and then rec and prev_rec will
be on different pages and
btr_pcur_move_to_next_user_rec() will release the
latch on the page that prev_rec is on */
prev_rec = rec_copy_prefix_to_buf(
rec, index, rec_offs_n_fields(rec_offsets),
&prev_rec_buf, &prev_rec_buf_size);
prev_rec_is_copied = true;
} else {
/* still on the same page, the next call to
btr_pcur_move_to_next_user_rec() will not jump
on the next page, we can simply assign pointers
instead of copying the records like above */
prev_rec = rec;
prev_rec_is_copied = false;
}
}
/* if *total_pages is left untouched then the above loop was not
entered at all and there is one page in the whole tree which is
empty or the loop was entered but this is level 0, contains one page
and all records are delete-marked */
if (*total_pages == 0) {
ut_ad(level == 0);
ut_ad(*total_recs == 0);
*total_pages = 1;
}
/* if there are records on this level and boundaries
should be saved */
if (*total_recs > 0 && n_diff_boundaries != NULL) {
/* remember the index of the last record on the level as the
last one from the last group of equal keys; this holds for
all possible prefixes */
for (i = 0; i < n_uniq; i++) {
ib_uint64_t idx;
idx = *total_recs - 1;
n_diff_boundaries[i].push_back(idx);
}
}
/* now in n_diff_boundaries[i] there are exactly n_diff[i] integers,
for i=0..n_uniq-1 */
#ifdef UNIV_STATS_DEBUG
for (i = 0; i < n_uniq; i++) {
DEBUG_PRINTF(" %s(): total recs: " UINT64PF
", total pages: " UINT64PF
", n_diff[" ULINTPF "]: " UINT64PF "\n",
__func__, *total_recs,
*total_pages,
i, n_diff[i]);
#if 0
if (n_diff_boundaries != NULL) {
ib_uint64_t j;
DEBUG_PRINTF(" %s(): boundaries[%lu]: ",
__func__, i);
for (j = 0; j < n_diff[i]; j++) {
ib_uint64_t idx;
idx = n_diff_boundaries[i][j];
DEBUG_PRINTF(UINT64PF "=" UINT64PF ", ",
j, idx);
}
DEBUG_PRINTF("\n");
}
#endif
}
#endif /* UNIV_STATS_DEBUG */
/* Release the latch on the last page, because that is not done by
btr_pcur_close(). This function works also for non-leaf pages. */
btr_leaf_page_release(btr_pcur_get_block(&pcur), BTR_SEARCH_LEAF, mtr);
btr_pcur_close(&pcur);
ut_free(prev_rec_buf);
mem_heap_free(heap);
}
/** Scan a page, reading records from left to right and counting the number
of distinct records (looking only at the first n_prefix
columns) and the number of external pages pointed by records from this page.
If scan_method is QUIT_ON_FIRST_NON_BORING then the function
will return as soon as it finds a record that does not match its neighbor
to the right, which means that in the case of QUIT_ON_FIRST_NON_BORING the
returned n_diff can either be 0 (empty page), 1 (the whole page has all keys
equal) or 2 (the function found a non-boring record and returned).
@param[out] out_rec record, or NULL
@param[out] offsets1 rec_get_offsets() working space (must
be big enough)
@param[out] offsets2 rec_get_offsets() working space (must
be big enough)
@param[in] index index of the page
@param[in] page the page to scan
@param[in] n_prefix look at the first n_prefix columns
@param[in] is_leaf whether this is the leaf page
@param[out] n_diff number of distinct records encountered
@param[out] n_external_pages if this is non-NULL then it will be set
to the number of externally stored pages which were encountered
@return offsets1 or offsets2 (the offsets of *out_rec),
or NULL if the page is empty and does not contain user records. */
UNIV_INLINE
ulint*
dict_stats_scan_page(
const rec_t** out_rec,
ulint* offsets1,
ulint* offsets2,
const dict_index_t* index,
const page_t* page,
ulint n_prefix,
bool is_leaf,
ib_uint64_t* n_diff,
ib_uint64_t* n_external_pages)
{
ulint* offsets_rec = offsets1;
ulint* offsets_next_rec = offsets2;
const rec_t* rec;
const rec_t* next_rec;
/* A dummy heap, to be passed to rec_get_offsets().
Because offsets1,offsets2 should be big enough,
this memory heap should never be used. */
mem_heap_t* heap = NULL;
ut_ad(is_leaf == page_is_leaf(page));
const rec_t* (*get_next)(const rec_t*)
= !is_leaf || srv_stats_include_delete_marked
? page_rec_get_next_const
: page_rec_get_next_non_del_marked;
const bool should_count_external_pages = n_external_pages != NULL;
if (should_count_external_pages) {
*n_external_pages = 0;
}
rec = get_next(page_get_infimum_rec(page));
if (page_rec_is_supremum(rec)) {
/* the page is empty or contains only delete-marked records */
*n_diff = 0;
*out_rec = NULL;
return(NULL);
}
offsets_rec = rec_get_offsets(rec, index, offsets_rec, is_leaf,
ULINT_UNDEFINED, &heap);
if (should_count_external_pages) {
*n_external_pages += btr_rec_get_externally_stored_len(
rec, offsets_rec);
}
next_rec = get_next(rec);
*n_diff = 1;
while (!page_rec_is_supremum(next_rec)) {
ulint matched_fields;
offsets_next_rec = rec_get_offsets(next_rec, index,
offsets_next_rec, is_leaf,
ULINT_UNDEFINED,
&heap);
/* check whether rec != next_rec when looking at
the first n_prefix fields */
cmp_rec_rec_with_match(rec, next_rec,
offsets_rec, offsets_next_rec,
index, FALSE, &matched_fields);
if (matched_fields < n_prefix) {
/* rec != next_rec, => rec is non-boring */
(*n_diff)++;
if (!is_leaf) {
break;
}
}
rec = next_rec;
{
/* Assign offsets_rec = offsets_next_rec
so that offsets_rec matches with rec which
was just assigned rec = next_rec above.
Also need to point offsets_next_rec to the
place where offsets_rec was pointing before
because we have just 2 placeholders where
data is actually stored:
offsets1 and offsets2 and we
are using them in circular fashion
(offsets[_next]_rec are just pointers to
those placeholders). */
ulint* offsets_tmp;
offsets_tmp = offsets_rec;
offsets_rec = offsets_next_rec;
offsets_next_rec = offsets_tmp;
}
if (should_count_external_pages) {
*n_external_pages += btr_rec_get_externally_stored_len(
rec, offsets_rec);
}
next_rec = get_next(next_rec);
}
/* offsets1,offsets2 should have been big enough */
ut_a(heap == NULL);
*out_rec = rec;
return(offsets_rec);
}
/** Dive below the current position of a cursor and calculate the number of
distinct records on the leaf page, when looking at the fist n_prefix
columns. Also calculate the number of external pages pointed by records
on the leaf page.
@param[in] cur cursor
@param[in] n_prefix look at the first n_prefix columns
when comparing records
@param[out] n_diff number of distinct records
@param[out] n_external_pages number of external pages
@return number of distinct records on the leaf page */
static
void
dict_stats_analyze_index_below_cur(
const btr_cur_t* cur,
ulint n_prefix,
ib_uint64_t* n_diff,
ib_uint64_t* n_external_pages)
{
dict_index_t* index;
buf_block_t* block;
const page_t* page;
mem_heap_t* heap;
const rec_t* rec;
ulint* offsets1;
ulint* offsets2;
ulint* offsets_rec;
ulint size;
mtr_t mtr;
index = btr_cur_get_index(cur);
/* Allocate offsets for the record and the node pointer, for
node pointer records. In a secondary index, the node pointer
record will consist of all index fields followed by a child
page number.
Allocate space for the offsets header (the allocation size at
offsets[0] and the REC_OFFS_HEADER_SIZE bytes), and n_fields + 1,
so that this will never be less than the size calculated in
rec_get_offsets_func(). */
size = (1 + REC_OFFS_HEADER_SIZE) + 1 + dict_index_get_n_fields(index);
heap = mem_heap_create(size * (sizeof *offsets1 + sizeof *offsets2));
offsets1 = static_cast<ulint*>(mem_heap_alloc(
heap, size * sizeof *offsets1));
offsets2 = static_cast<ulint*>(mem_heap_alloc(
heap, size * sizeof *offsets2));
rec_offs_set_n_alloc(offsets1, size);
rec_offs_set_n_alloc(offsets2, size);
rec = btr_cur_get_rec(cur);
ut_ad(!page_rec_is_leaf(rec));
offsets_rec = rec_get_offsets(rec, index, offsets1, false,
ULINT_UNDEFINED, &heap);
page_id_t page_id(dict_index_get_space(index),
btr_node_ptr_get_child_page_no(
rec, offsets_rec));
const page_size_t page_size(dict_table_page_size(index->table));
/* assume no external pages by default - in case we quit from this
function without analyzing any leaf pages */
*n_external_pages = 0;
mtr_start(&mtr);
/* descend to the leaf level on the B-tree */
for (;;) {
dberr_t err = DB_SUCCESS;
block = buf_page_get_gen(page_id, page_size, RW_S_LATCH,
NULL /* no guessed block */,
BUF_GET, __FILE__, __LINE__, &mtr, &err);
page = buf_block_get_frame(block);
if (page_is_leaf(page)) {
/* leaf level */
break;
}
/* else */
/* search for the first non-boring record on the page */
offsets_rec = dict_stats_scan_page(
&rec, offsets1, offsets2, index, page, n_prefix,
false, n_diff, NULL);
/* pages on level > 0 are not allowed to be empty */
ut_a(offsets_rec != NULL);
/* if page is not empty (offsets_rec != NULL) then n_diff must
be > 0, otherwise there is a bug in dict_stats_scan_page() */
ut_a(*n_diff > 0);
if (*n_diff == 1) {
mtr_commit(&mtr);
/* page has all keys equal and the end of the page
was reached by dict_stats_scan_page(), no need to
descend to the leaf level */
mem_heap_free(heap);
/* can't get an estimate for n_external_pages here
because we do not dive to the leaf level, assume no
external pages (*n_external_pages was assigned to 0
above). */
return;
}
/* else */
/* when we instruct dict_stats_scan_page() to quit on the
first non-boring record it finds, then the returned n_diff
can either be 0 (empty page), 1 (page has all keys equal) or
2 (non-boring record was found) */
ut_a(*n_diff == 2);
/* we have a non-boring record in rec, descend below it */
page_id.set_page_no(
btr_node_ptr_get_child_page_no(rec, offsets_rec));
}
/* make sure we got a leaf page as a result from the above loop */
ut_ad(page_is_leaf(page));
/* scan the leaf page and find the number of distinct keys,
when looking only at the first n_prefix columns; also estimate
the number of externally stored pages pointed by records on this
page */
offsets_rec = dict_stats_scan_page(
&rec, offsets1, offsets2, index, page, n_prefix,
true, n_diff,
n_external_pages);
#if 0
DEBUG_PRINTF(" %s(): n_diff below page_no=%lu: " UINT64PF "\n",
__func__, page_no, n_diff);
#endif
mtr_commit(&mtr);
mem_heap_free(heap);
}
/** Input data that is used to calculate dict_index_t::stat_n_diff_key_vals[]
for each n-columns prefix (n from 1 to n_uniq). */
struct n_diff_data_t {
/** Index of the level on which the descent through the btree
stopped. level 0 is the leaf level. This is >= 1 because we
avoid scanning the leaf level because it may contain too many
pages and doing so is useless when combined with the random dives -
if we are to scan the leaf level, this means a full scan and we can
simply do that instead of fiddling with picking random records higher
in the tree and to dive below them. At the start of the analyzing
we may decide to do full scan of the leaf level, but then this
structure is not used in that code path. */
ulint level;
/** Number of records on the level where the descend through the btree
stopped. When we scan the btree from the root, we stop at some mid
level, choose some records from it and dive below them towards a leaf
page to analyze. */
ib_uint64_t n_recs_on_level;
/** Number of different key values that were found on the mid level. */
ib_uint64_t n_diff_on_level;
/** Number of leaf pages that are analyzed. This is also the same as
the number of records that we pick from the mid level and dive below
them. */
ib_uint64_t n_leaf_pages_to_analyze;
/** Cumulative sum of the number of different key values that were
found on all analyzed pages. */
ib_uint64_t n_diff_all_analyzed_pages;
/** Cumulative sum of the number of external pages (stored outside of
the btree but in the same file segment). */
ib_uint64_t n_external_pages_sum;
};
/** Estimate the number of different key values in an index when looking at
the first n_prefix columns. For a given level in an index select
n_diff_data->n_leaf_pages_to_analyze records from that level and dive below
them to the corresponding leaf pages, then scan those leaf pages and save the
sampling results in n_diff_data->n_diff_all_analyzed_pages.
@param[in] index index
@param[in] n_prefix look at first 'n_prefix' columns when
comparing records
@param[in] boundaries a vector that contains
n_diff_data->n_diff_on_level integers each of which represents the index (on
level 'level', counting from left/smallest to right/biggest from 0) of the
last record from each group of distinct keys
@param[in,out] n_diff_data n_diff_all_analyzed_pages and
n_external_pages_sum in this structure will be set by this function. The
members level, n_diff_on_level and n_leaf_pages_to_analyze must be set by the
caller in advance - they are used by some calculations inside this function
@param[in,out] mtr mini-transaction */
static
void
dict_stats_analyze_index_for_n_prefix(
dict_index_t* index,
ulint n_prefix,
const boundaries_t* boundaries,
n_diff_data_t* n_diff_data,
mtr_t* mtr)
{
btr_pcur_t pcur;
const page_t* page;
ib_uint64_t rec_idx;
ib_uint64_t i;
#if 0
DEBUG_PRINTF(" %s(table=%s, index=%s, level=%lu, n_prefix=%lu,"
" n_diff_on_level=" UINT64PF ")\n",
__func__, index->table->name, index->name, level,
n_prefix, n_diff_data->n_diff_on_level);
#endif
ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
MTR_MEMO_SX_LOCK));
/* Position pcur on the leftmost record on the leftmost page
on the desired level. */
btr_pcur_open_at_index_side(
true, index, BTR_SEARCH_TREE_ALREADY_S_LATCHED,
&pcur, true, n_diff_data->level, mtr);
btr_pcur_move_to_next_on_page(&pcur);
page = btr_pcur_get_page(&pcur);
const rec_t* first_rec = btr_pcur_get_rec(&pcur);
/* We shouldn't be scanning the leaf level. The caller of this function
should have stopped the descend on level 1 or higher. */
ut_ad(n_diff_data->level > 0);
ut_ad(!page_is_leaf(page));
/* The page must not be empty, except when
it is the root page (and the whole index is empty). */
ut_ad(btr_pcur_is_on_user_rec(&pcur));
ut_ad(first_rec == page_rec_get_next_const(page_get_infimum_rec(page)));
/* check that we are indeed on the desired level */
ut_a(btr_page_get_level(page, mtr) == n_diff_data->level);
/* there should not be any pages on the left */
ut_a(btr_page_get_prev(page, mtr) == FIL_NULL);
/* check whether the first record on the leftmost page is marked
as such; we are on a non-leaf level */
ut_a(rec_get_info_bits(first_rec, page_is_comp(page))
& REC_INFO_MIN_REC_FLAG);
const ib_uint64_t last_idx_on_level = boundaries->at(
static_cast<unsigned>(n_diff_data->n_diff_on_level - 1));
rec_idx = 0;
n_diff_data->n_diff_all_analyzed_pages = 0;
n_diff_data->n_external_pages_sum = 0;
for (i = 0; i < n_diff_data->n_leaf_pages_to_analyze; i++) {
/* there are n_diff_on_level elements
in 'boundaries' and we divide those elements
into n_leaf_pages_to_analyze segments, for example:
let n_diff_on_level=100, n_leaf_pages_to_analyze=4, then:
segment i=0: [0, 24]
segment i=1: [25, 49]
segment i=2: [50, 74]
segment i=3: [75, 99] or
let n_diff_on_level=1, n_leaf_pages_to_analyze=1, then:
segment i=0: [0, 0] or
let n_diff_on_level=2, n_leaf_pages_to_analyze=2, then:
segment i=0: [0, 0]
segment i=1: [1, 1] or
let n_diff_on_level=13, n_leaf_pages_to_analyze=7, then:
segment i=0: [0, 0]
segment i=1: [1, 2]
segment i=2: [3, 4]
segment i=3: [5, 6]
segment i=4: [7, 8]
segment i=5: [9, 10]
segment i=6: [11, 12]
then we select a random record from each segment and dive
below it */
const ib_uint64_t n_diff = n_diff_data->n_diff_on_level;
const ib_uint64_t n_pick
= n_diff_data->n_leaf_pages_to_analyze;
const ib_uint64_t left = n_diff * i / n_pick;
const ib_uint64_t right = n_diff * (i + 1) / n_pick - 1;
ut_a(left <= right);
ut_a(right <= last_idx_on_level);
/* we do not pass (left, right) because we do not want to ask
ut_rnd_interval() to work with too big numbers since
ib_uint64_t could be bigger than ulint */
const ulint rnd = ut_rnd_interval(
0, static_cast<ulint>(right - left));
const ib_uint64_t dive_below_idx
= boundaries->at(static_cast<unsigned>(left + rnd));
#if 0
DEBUG_PRINTF(" %s(): dive below record with index="
UINT64PF "\n", __func__, dive_below_idx);
#endif
/* seek to the record with index dive_below_idx */
while (rec_idx < dive_below_idx
&& btr_pcur_is_on_user_rec(&pcur)) {
btr_pcur_move_to_next_user_rec(&pcur, mtr);
rec_idx++;
}
/* if the level has finished before the record we are
searching for, this means that the B-tree has changed in
the meantime, quit our sampling and use whatever stats
we have collected so far */
if (rec_idx < dive_below_idx) {
ut_ad(!btr_pcur_is_on_user_rec(&pcur));
break;
}
/* it could be that the tree has changed in such a way that
the record under dive_below_idx is the supremum record, in
this case rec_idx == dive_below_idx and pcur is positioned
on the supremum, we do not want to dive below it */
if (!btr_pcur_is_on_user_rec(&pcur)) {
break;
}
ut_a(rec_idx == dive_below_idx);
ib_uint64_t n_diff_on_leaf_page;
ib_uint64_t n_external_pages;
dict_stats_analyze_index_below_cur(btr_pcur_get_btr_cur(&pcur),
n_prefix,
&n_diff_on_leaf_page,
&n_external_pages);
/* We adjust n_diff_on_leaf_page here to avoid counting
one value twice - once as the last on some page and once
as the first on another page. Consider the following example:
Leaf level:
page: (2,2,2,2,3,3)
... many pages like (3,3,3,3,3,3) ...
page: (3,3,3,3,5,5)
... many pages like (5,5,5,5,5,5) ...
page: (5,5,5,5,8,8)
page: (8,8,8,8,9,9)
our algo would (correctly) get an estimate that there are
2 distinct records per page (average). Having 4 pages below
non-boring records, it would (wrongly) estimate the number
of distinct records to 8. */
if (n_diff_on_leaf_page > 0) {
n_diff_on_leaf_page--;
}
n_diff_data->n_diff_all_analyzed_pages += n_diff_on_leaf_page;
n_diff_data->n_external_pages_sum += n_external_pages;
}
btr_pcur_close(&pcur);
}
/** Set dict_index_t::stat_n_diff_key_vals[] and stat_n_sample_sizes[].
@param[in] n_diff_data input data to use to derive the results
@param[in,out] index index whose stat_n_diff_key_vals[] to set */
UNIV_INLINE
void
dict_stats_index_set_n_diff(
const n_diff_data_t* n_diff_data,
dict_index_t* index)
{
for (ulint n_prefix = dict_index_get_n_unique(index);
n_prefix >= 1;
n_prefix--) {
/* n_diff_all_analyzed_pages can be 0 here if
all the leaf pages sampled contained only
delete-marked records. In this case we should assign
0 to index->stat_n_diff_key_vals[n_prefix - 1], which
the formula below does. */
const n_diff_data_t* data = &n_diff_data[n_prefix - 1];
ut_ad(data->n_leaf_pages_to_analyze > 0);
ut_ad(data->n_recs_on_level > 0);
ib_uint64_t n_ordinary_leaf_pages;
if (data->level == 1) {
/* If we know the number of records on level 1, then
this number is the same as the number of pages on
level 0 (leaf). */
n_ordinary_leaf_pages = data->n_recs_on_level;
} else {
/* If we analyzed D ordinary leaf pages and found E
external pages in total linked from those D ordinary
leaf pages, then this means that the ratio
ordinary/external is D/E. Then the ratio ordinary/total
is D / (D + E). Knowing that the total number of pages
is T (including ordinary and external) then we estimate
that the total number of ordinary leaf pages is
T * D / (D + E). */
n_ordinary_leaf_pages
= index->stat_n_leaf_pages
* data->n_leaf_pages_to_analyze
/ (data->n_leaf_pages_to_analyze
+ data->n_external_pages_sum);
}
/* See REF01 for an explanation of the algorithm */
index->stat_n_diff_key_vals[n_prefix - 1]
= n_ordinary_leaf_pages
* data->n_diff_on_level
/ data->n_recs_on_level
* data->n_diff_all_analyzed_pages
/ data->n_leaf_pages_to_analyze;
index->stat_n_sample_sizes[n_prefix - 1]
= data->n_leaf_pages_to_analyze;
DEBUG_PRINTF(" %s(): n_diff=" UINT64PF
" for n_prefix=" ULINTPF
" (" ULINTPF
" * " UINT64PF " / " UINT64PF
" * " UINT64PF " / " UINT64PF ")\n",
__func__,
index->stat_n_diff_key_vals[n_prefix - 1],
n_prefix,
index->stat_n_leaf_pages,
data->n_diff_on_level,
data->n_recs_on_level,
data->n_diff_all_analyzed_pages,
data->n_leaf_pages_to_analyze);
}
}
/*********************************************************************//**
Calculates new statistics for a given index and saves them to the index
members stat_n_diff_key_vals[], stat_n_sample_sizes[], stat_index_size and
stat_n_leaf_pages. This function could be slow. */
static
void
dict_stats_analyze_index(
/*=====================*/
dict_index_t* index) /*!< in/out: index to analyze */
{
ulint root_level;
ulint level;
bool level_is_analyzed;
ulint n_uniq;
ulint n_prefix;
ib_uint64_t total_recs;
ib_uint64_t total_pages;
mtr_t mtr;
ulint size;
DBUG_ENTER("dict_stats_analyze_index");
DBUG_PRINT("info", ("index: %s, online status: %d", index->name(),
dict_index_get_online_status(index)));
/* Disable update statistic for Rtree */
if (dict_index_is_spatial(index)) {
DBUG_VOID_RETURN;
}
DEBUG_PRINTF(" %s(index=%s)\n", __func__, index->name());
dict_stats_empty_index(index, false);
mtr_start(&mtr);
mtr_s_lock(dict_index_get_lock(index), &mtr);
size = btr_get_size(index, BTR_TOTAL_SIZE, &mtr);
if (size != ULINT_UNDEFINED) {
index->stat_index_size = size;
size = btr_get_size(index, BTR_N_LEAF_PAGES, &mtr);
}
/* Release the X locks on the root page taken by btr_get_size() */
mtr_commit(&mtr);
switch (size) {
case ULINT_UNDEFINED:
dict_stats_assert_initialized_index(index);
DBUG_VOID_RETURN;
case 0:
/* The root node of the tree is a leaf */
size = 1;
}
index->stat_n_leaf_pages = size;
mtr_start(&mtr);
mtr_sx_lock(dict_index_get_lock(index), &mtr);
root_level = btr_height_get(index, &mtr);
n_uniq = dict_index_get_n_unique(index);
/* If the tree has just one level (and one page) or if the user
has requested to sample too many pages then do full scan.
For each n-column prefix (for n=1..n_uniq) N_SAMPLE_PAGES(index)
will be sampled, so in total N_SAMPLE_PAGES(index) * n_uniq leaf
pages will be sampled. If that number is bigger than the total
number of leaf pages then do full scan of the leaf level instead
since it will be faster and will give better results. */
if (root_level == 0
|| N_SAMPLE_PAGES(index) * n_uniq > index->stat_n_leaf_pages) {
if (root_level == 0) {
DEBUG_PRINTF(" %s(): just one page,"
" doing full scan\n", __func__);
} else {
DEBUG_PRINTF(" %s(): too many pages requested for"
" sampling, doing full scan\n", __func__);
}
/* do full scan of level 0; save results directly
into the index */
dict_stats_analyze_index_level(index,
0 /* leaf level */,
index->stat_n_diff_key_vals,
&total_recs,
&total_pages,
NULL /* boundaries not needed */,
&mtr);
for (ulint i = 0; i < n_uniq; i++) {
index->stat_n_sample_sizes[i] = total_pages;
}
mtr_commit(&mtr);
dict_stats_assert_initialized_index(index);
DBUG_VOID_RETURN;
}
/* For each level that is being scanned in the btree, this contains the
number of different key values for all possible n-column prefixes. */
ib_uint64_t* n_diff_on_level = UT_NEW_ARRAY(
ib_uint64_t, n_uniq, mem_key_dict_stats_n_diff_on_level);
/* For each level that is being scanned in the btree, this contains the
index of the last record from each group of equal records (when
comparing only the first n columns, n=1..n_uniq). */
boundaries_t* n_diff_boundaries = UT_NEW_ARRAY_NOKEY(boundaries_t,
n_uniq);
/* For each n-column prefix this array contains the input data that is
used to calculate dict_index_t::stat_n_diff_key_vals[]. */
n_diff_data_t* n_diff_data = UT_NEW_ARRAY_NOKEY(n_diff_data_t, n_uniq);
/* total_recs is also used to estimate the number of pages on one
level below, so at the start we have 1 page (the root) */
total_recs = 1;
/* Here we use the following optimization:
If we find that level L is the first one (searching from the
root) that contains at least D distinct keys when looking at
the first n_prefix columns, then:
if we look at the first n_prefix-1 columns then the first
level that contains D distinct keys will be either L or a
lower one.
So if we find that the first level containing D distinct
keys (on n_prefix columns) is L, we continue from L when
searching for D distinct keys on n_prefix-1 columns. */
level = root_level;
level_is_analyzed = false;
for (n_prefix = n_uniq; n_prefix >= 1; n_prefix--) {
DEBUG_PRINTF(" %s(): searching level with >=%llu "
"distinct records, n_prefix=" ULINTPF "\n",
__func__, N_DIFF_REQUIRED(index), n_prefix);
/* Commit the mtr to release the tree S lock to allow
other threads to do some work too. */
mtr_commit(&mtr);
mtr_start(&mtr);
mtr_sx_lock(dict_index_get_lock(index), &mtr);
if (root_level != btr_height_get(index, &mtr)) {
/* Just quit if the tree has changed beyond
recognition here. The old stats from previous
runs will remain in the values that we have
not calculated yet. Initially when the index
object is created the stats members are given
some sensible values so leaving them untouched
here even the first time will not cause us to
read uninitialized memory later. */
break;
}
/* check whether we should pick the current level;
we pick level 1 even if it does not have enough
distinct records because we do not want to scan the
leaf level because it may contain too many records */
if (level_is_analyzed
&& (n_diff_on_level[n_prefix - 1] >= N_DIFF_REQUIRED(index)
|| level == 1)) {
goto found_level;
}
/* search for a level that contains enough distinct records */
if (level_is_analyzed && level > 1) {
/* if this does not hold we should be on
"found_level" instead of here */
ut_ad(n_diff_on_level[n_prefix - 1]
< N_DIFF_REQUIRED(index));
level--;
level_is_analyzed = false;
}
/* descend into the tree, searching for "good enough" level */
for (;;) {
/* make sure we do not scan the leaf level
accidentally, it may contain too many pages */
ut_ad(level > 0);
/* scanning the same level twice is an optimization
bug */
ut_ad(!level_is_analyzed);
/* Do not scan if this would read too many pages.
Here we use the following fact:
the number of pages on level L equals the number
of records on level L+1, thus we deduce that the
following call would scan total_recs pages, because
total_recs is left from the previous iteration when
we scanned one level upper or we have not scanned any
levels yet in which case total_recs is 1. */
if (total_recs > N_SAMPLE_PAGES(index)) {
/* if the above cond is true then we are
not at the root level since on the root
level total_recs == 1 (set before we
enter the n-prefix loop) and cannot
be > N_SAMPLE_PAGES(index) */
ut_a(level != root_level);
/* step one level back and be satisfied with
whatever it contains */
level++;
level_is_analyzed = true;
break;
}
dict_stats_analyze_index_level(index,
level,
n_diff_on_level,
&total_recs,
&total_pages,
n_diff_boundaries,
&mtr);
level_is_analyzed = true;
if (level == 1
|| n_diff_on_level[n_prefix - 1]
>= N_DIFF_REQUIRED(index)) {
/* we have reached the last level we could scan
or we found a good level with many distinct
records */
break;
}
level--;
level_is_analyzed = false;
}
found_level:
DEBUG_PRINTF(" %s(): found level " ULINTPF
" that has " UINT64PF
" distinct records for n_prefix=" ULINTPF "\n",
__func__, level, n_diff_on_level[n_prefix - 1],
n_prefix);
/* here we are either on level 1 or the level that we are on
contains >= N_DIFF_REQUIRED distinct keys or we did not scan
deeper levels because they would contain too many pages */
ut_ad(level > 0);
ut_ad(level_is_analyzed);
/* if any of these is 0 then there is exactly one page in the
B-tree and it is empty and we should have done full scan and
should not be here */
ut_ad(total_recs > 0);
ut_ad(n_diff_on_level[n_prefix - 1] > 0);
ut_ad(N_SAMPLE_PAGES(index) > 0);
n_diff_data_t* data = &n_diff_data[n_prefix - 1];
data->level = level;
data->n_recs_on_level = total_recs;
data->n_diff_on_level = n_diff_on_level[n_prefix - 1];
data->n_leaf_pages_to_analyze = std::min(
N_SAMPLE_PAGES(index),
n_diff_on_level[n_prefix - 1]);
/* pick some records from this level and dive below them for
the given n_prefix */
dict_stats_analyze_index_for_n_prefix(
index, n_prefix, &n_diff_boundaries[n_prefix - 1],
data, &mtr);
}
mtr_commit(&mtr);
UT_DELETE_ARRAY(n_diff_boundaries);
UT_DELETE_ARRAY(n_diff_on_level);
/* n_prefix == 0 means that the above loop did not end up prematurely
due to tree being changed and so n_diff_data[] is set up. */
if (n_prefix == 0) {
dict_stats_index_set_n_diff(n_diff_data, index);
}
UT_DELETE_ARRAY(n_diff_data);
dict_stats_assert_initialized_index(index);
DBUG_VOID_RETURN;
}
/*********************************************************************//**
Calculates new estimates for table and index statistics. This function
is relatively slow and is used to calculate persistent statistics that
will be saved on disk.
@return DB_SUCCESS or error code */
static
dberr_t
dict_stats_update_persistent(
/*=========================*/
dict_table_t* table) /*!< in/out: table */
{
dict_index_t* index;
DEBUG_PRINTF("%s(table=%s)\n", __func__, table->name);
dict_table_stats_lock(table, RW_X_LATCH);
/* analyze the clustered index first */
index = dict_table_get_first_index(table);
if (index == NULL
|| dict_index_is_corrupted(index)
|| (index->type | DICT_UNIQUE) != (DICT_CLUSTERED | DICT_UNIQUE)) {
/* Table definition is corrupt */
dict_table_stats_unlock(table, RW_X_LATCH);
dict_stats_empty_table(table, true);
return(DB_CORRUPTION);
}
ut_ad(!dict_index_is_ibuf(index));
dict_stats_analyze_index(index);
ulint n_unique = dict_index_get_n_unique(index);
table->stat_n_rows = index->stat_n_diff_key_vals[n_unique - 1];
table->stat_clustered_index_size = index->stat_index_size;
/* analyze other indexes from the table, if any */
table->stat_sum_of_other_index_sizes = 0;
for (index = dict_table_get_next_index(index);
index != NULL;
index = dict_table_get_next_index(index)) {
ut_ad(!dict_index_is_ibuf(index));
if (index->type & DICT_FTS || dict_index_is_spatial(index)) {
continue;
}
dict_stats_empty_index(index, false);
if (dict_stats_should_ignore_index(index)) {
continue;
}
if (!(table->stats_bg_flag & BG_STAT_SHOULD_QUIT)) {
dict_stats_analyze_index(index);
}
table->stat_sum_of_other_index_sizes
+= index->stat_index_size;
}
table->stats_last_recalc = ut_time();
table->stat_modified_counter = 0;
table->stat_initialized = TRUE;
dict_stats_assert_initialized(table);
dict_table_stats_unlock(table, RW_X_LATCH);
return(DB_SUCCESS);
}
#include "mysql_com.h"
/** Save an individual index's statistic into the persistent statistics
storage.
@param[in] index index to be updated
@param[in] last_update timestamp of the stat
@param[in] stat_name name of the stat
@param[in] stat_value value of the stat
@param[in] sample_size n pages sampled or NULL
@param[in] stat_description description of the stat
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
dberr_t
dict_stats_save_index_stat(
dict_index_t* index,
lint last_update,
const char* stat_name,
ib_uint64_t stat_value,
ib_uint64_t* sample_size,
const char* stat_description,
trx_t* trx)
{
dberr_t ret;
pars_info_t* pinfo;
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
ut_ad(trx->persistent_stats || trx->in_mysql_trx_list);
dict_fs2utf8(index->table->name.m_name, db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db_utf8);
pars_info_add_str_literal(pinfo, "table_name", table_utf8);
pars_info_add_str_literal(pinfo, "index_name", index->name);
UNIV_MEM_ASSERT_RW_ABORT(&last_update, 4);
pars_info_add_int4_literal(pinfo, "last_update", last_update);
UNIV_MEM_ASSERT_RW_ABORT(stat_name, strlen(stat_name));
pars_info_add_str_literal(pinfo, "stat_name", stat_name);
UNIV_MEM_ASSERT_RW_ABORT(&stat_value, 8);
pars_info_add_ull_literal(pinfo, "stat_value", stat_value);
if (sample_size != NULL) {
UNIV_MEM_ASSERT_RW_ABORT(sample_size, 8);
pars_info_add_ull_literal(pinfo, "sample_size", *sample_size);
} else {
pars_info_add_literal(pinfo, "sample_size", NULL,
UNIV_SQL_NULL, DATA_FIXBINARY, 0);
}
UNIV_MEM_ASSERT_RW_ABORT(stat_description, strlen(stat_description));
pars_info_add_str_literal(pinfo, "stat_description",
stat_description);
mutex_enter(&dict_sys->mutex);
ret = dict_stats_exec_sql(
pinfo,
"PROCEDURE INDEX_STATS_SAVE () IS\n"
"BEGIN\n"
"DELETE FROM \"" INDEX_STATS_NAME "\"\n"
"WHERE\n"
"database_name = :database_name AND\n"
"table_name = :table_name AND\n"
"index_name = :index_name AND\n"
"stat_name = :stat_name;\n"
"INSERT INTO \"" INDEX_STATS_NAME "\"\n"
"VALUES\n"
"(\n"
":database_name,\n"
":table_name,\n"
":index_name,\n"
":last_update,\n"
":stat_name,\n"
":stat_value,\n"
":sample_size,\n"
":stat_description\n"
");\n"
"END;", trx);
mutex_exit(&dict_sys->mutex);
if (ret != DB_SUCCESS) {
if (innodb_index_stats_not_found == false &&
index->stats_error_printed == false) {
ib::error() << "Cannot save index statistics for table "
<< index->table->name
<< ", index " << index->name
<< ", stat name \"" << stat_name << "\": "
<< ut_strerr(ret);
index->stats_error_printed = true;
}
}
return(ret);
}
/** Report an error if updating table statistics failed because
.ibd file is missing, table decryption failed or table is corrupted.
@param[in,out] table Table
@param[in] defragment true if statistics is for defragment
@retval DB_DECRYPTION_FAILED if decryption of the table failed
@retval DB_TABLESPACE_DELETED if .ibd file is missing
@retval DB_CORRUPTION if table is marked as corrupted */
dberr_t
dict_stats_report_error(dict_table_t* table, bool defragment)
{
dberr_t err;
FilSpace space(table->space);
const char* df = defragment ? " defragment" : "";
if (!space()) {
ib::warn() << "Cannot save" << df << " statistics for table "
<< table->name
<< " because the .ibd file is missing. "
<< TROUBLESHOOTING_MSG;
err = DB_TABLESPACE_DELETED;
} else {
ib::warn() << "Cannot save" << df << " statistics for table "
<< table->name
<< " because file " << space()->chain.start->name
<< (table->corrupted
? " is corrupted."
: " cannot be decrypted.");
err = table->corrupted ? DB_CORRUPTION : DB_DECRYPTION_FAILED;
}
dict_stats_empty_table(table, defragment);
return err;
}
/** Save the table's statistics into the persistent statistics storage.
@param[in] table_orig table whose stats to save
@param[in,out] trx transaction
@param[in] only_for_index if this is non-NULL, then stats for indexes
that are not equal to it will not be saved, if NULL, then all indexes' stats
are saved
@return DB_SUCCESS or error code */
static
dberr_t
dict_stats_save(
dict_table_t* table_orig,
trx_t* trx,
const index_id_t* only_for_index = NULL)
{
pars_info_t* pinfo;
lint now;
dberr_t ret;
dict_table_t* table;
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
ut_ad(trx->persistent_stats || trx->in_mysql_trx_list);
if (table_orig->is_readable()) {
} else {
return (dict_stats_report_error(table_orig));
}
table = dict_stats_snapshot_create(table_orig);
dict_fs2utf8(table->name.m_name, db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
/* MySQL's timestamp is 4 byte, so we use
pars_info_add_int4_literal() which takes a lint arg, so "now" is
lint */
now = (lint) ut_time();
pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db_utf8);
pars_info_add_str_literal(pinfo, "table_name", table_utf8);
pars_info_add_int4_literal(pinfo, "last_update", now);
pars_info_add_ull_literal(pinfo, "n_rows", table->stat_n_rows);
pars_info_add_ull_literal(pinfo, "clustered_index_size",
table->stat_clustered_index_size);
pars_info_add_ull_literal(pinfo, "sum_of_other_index_sizes",
table->stat_sum_of_other_index_sizes);
mutex_enter(&dict_sys->mutex);
ret = dict_stats_exec_sql(
pinfo,
"PROCEDURE TABLE_STATS_SAVE () IS\n"
"BEGIN\n"
"DELETE FROM \"" TABLE_STATS_NAME "\"\n"
"WHERE\n"
"database_name = :database_name AND\n"
"table_name = :table_name;\n"
"INSERT INTO \"" TABLE_STATS_NAME "\"\n"
"VALUES\n"
"(\n"
":database_name,\n"
":table_name,\n"
":last_update,\n"
":n_rows,\n"
":clustered_index_size,\n"
":sum_of_other_index_sizes\n"
");\n"
"END;", trx);
mutex_exit(&dict_sys->mutex);
index_map_t indexes(
(ut_strcmp_functor()),
index_map_t_allocator(mem_key_dict_stats_index_map_t));
if (ret != DB_SUCCESS) {
goto end;
}
/* Below we do all the modifications in innodb_index_stats in a single
transaction for performance reasons. Modifying more than one row in a
single transaction may deadlock with other transactions if they
lock the rows in different order. Other transaction could be for
example when we DROP a table and do
DELETE FROM innodb_index_stats WHERE database_name = '...'
AND table_name = '...'; which will affect more than one row. To
prevent deadlocks we always lock the rows in the same order - the
order of the PK, which is (database_name, table_name, index_name,
stat_name). This is why below we sort the indexes by name and then
for each index, do the mods ordered by stat_name. */
for (dict_index_t* index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
indexes[index->name] = index;
}
for (index_map_t::const_iterator it = indexes.begin();
it != indexes.end(); ++it) {
dict_index_t* index = it->second;
if (only_for_index != NULL && index->id != *only_for_index) {
continue;
}
if (dict_stats_should_ignore_index(index)) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
for (unsigned i = 0; i < index->n_uniq; i++) {
char stat_name[16];
char stat_description[1024];
snprintf(stat_name, sizeof(stat_name),
"n_diff_pfx%02u", i + 1);
/* craft a string that contains the column names */
snprintf(stat_description, sizeof(stat_description),
"%s", index->fields[0].name());
for (unsigned j = 1; j <= i; j++) {
size_t len;
len = strlen(stat_description);
snprintf(stat_description + len,
sizeof(stat_description) - len,
",%s", index->fields[j].name());
}
ret = dict_stats_save_index_stat(
index, now, stat_name,
index->stat_n_diff_key_vals[i],
&index->stat_n_sample_sizes[i],
stat_description, trx);
if (ret != DB_SUCCESS) {
goto end;
}
}
ret = dict_stats_save_index_stat(index, now, "n_leaf_pages",
index->stat_n_leaf_pages,
NULL,
"Number of leaf pages "
"in the index", trx);
if (ret != DB_SUCCESS) {
goto end;
}
ret = dict_stats_save_index_stat(index, now, "size",
index->stat_index_size,
NULL,
"Number of pages "
"in the index", trx);
if (ret != DB_SUCCESS) {
goto end;
}
}
if (ret != DB_SUCCESS) {
end:
ib::error() << "Cannot save table statistics for table "
<< table->name << ": " << ut_strerr(ret);
}
dict_stats_snapshot_free(table);
return(ret);
}
/*********************************************************************//**
Called for the row that is selected by
SELECT ... FROM mysql.innodb_table_stats WHERE table='...'
The second argument is a pointer to the table and the fetched stats are
written to it.
@return non-NULL dummy */
static
ibool
dict_stats_fetch_table_stats_step(
/*==============================*/
void* node_void, /*!< in: select node */
void* table_void) /*!< out: table */
{
sel_node_t* node = (sel_node_t*) node_void;
dict_table_t* table = (dict_table_t*) table_void;
que_common_t* cnode;
int i;
/* this should loop exactly 3 times - for
n_rows,clustered_index_size,sum_of_other_index_sizes */
for (cnode = static_cast<que_common_t*>(node->select_list), i = 0;
cnode != NULL;
cnode = static_cast<que_common_t*>(que_node_get_next(cnode)),
i++) {
const byte* data;
dfield_t* dfield = que_node_get_val(cnode);
dtype_t* type = dfield_get_type(dfield);
ulint len = dfield_get_len(dfield);
data = static_cast<const byte*>(dfield_get_data(dfield));
switch (i) {
case 0: /* mysql.innodb_table_stats.n_rows */
ut_a(dtype_get_mtype(type) == DATA_INT);
ut_a(len == 8);
table->stat_n_rows = mach_read_from_8(data);
break;
case 1: /* mysql.innodb_table_stats.clustered_index_size */
ut_a(dtype_get_mtype(type) == DATA_INT);
ut_a(len == 8);
table->stat_clustered_index_size
= (ulint) mach_read_from_8(data);
break;
case 2: /* mysql.innodb_table_stats.sum_of_other_index_sizes */
ut_a(dtype_get_mtype(type) == DATA_INT);
ut_a(len == 8);
table->stat_sum_of_other_index_sizes
= (ulint) mach_read_from_8(data);
break;
default:
/* someone changed SELECT
n_rows,clustered_index_size,sum_of_other_index_sizes
to select more columns from innodb_table_stats without
adjusting here */
ut_error;
}
}
/* if i < 3 this means someone changed the
SELECT n_rows,clustered_index_size,sum_of_other_index_sizes
to select less columns from innodb_table_stats without adjusting here;
if i > 3 we would have ut_error'ed earlier */
ut_a(i == 3 /*n_rows,clustered_index_size,sum_of_other_index_sizes*/);
/* XXX this is not used but returning non-NULL is necessary */
return(TRUE);
}
/** Aux struct used to pass a table and a boolean to
dict_stats_fetch_index_stats_step(). */
struct index_fetch_t {
dict_table_t* table; /*!< table whose indexes are to be modified */
bool stats_were_modified; /*!< will be set to true if at
least one index stats were modified */
};
/*********************************************************************//**
Called for the rows that are selected by
SELECT ... FROM mysql.innodb_index_stats WHERE table='...'
The second argument is a pointer to the table and the fetched stats are
written to its indexes.
Let a table has N indexes and each index has Ui unique columns for i=1..N,
then mysql.innodb_index_stats will have SUM(Ui) i=1..N rows for that table.
So this function will be called SUM(Ui) times where SUM(Ui) is of magnitude
N*AVG(Ui). In each call it searches for the currently fetched index into
table->indexes linearly, assuming this list is not sorted. Thus, overall,
fetching all indexes' stats from mysql.innodb_index_stats is O(N^2) where N
is the number of indexes.
This can be improved if we sort table->indexes in a temporary area just once
and then search in that sorted list. Then the complexity will be O(N*log(N)).
We assume a table will not have more than 100 indexes, so we go with the
simpler N^2 algorithm.
@return non-NULL dummy */
static
ibool
dict_stats_fetch_index_stats_step(
/*==============================*/
void* node_void, /*!< in: select node */
void* arg_void) /*!< out: table + a flag that tells if we
modified anything */
{
sel_node_t* node = (sel_node_t*) node_void;
index_fetch_t* arg = (index_fetch_t*) arg_void;
dict_table_t* table = arg->table;
dict_index_t* index = NULL;
que_common_t* cnode;
const char* stat_name = NULL;
ulint stat_name_len = ULINT_UNDEFINED;
ib_uint64_t stat_value = UINT64_UNDEFINED;
ib_uint64_t sample_size = UINT64_UNDEFINED;
int i;
/* this should loop exactly 4 times - for the columns that
were selected: index_name,stat_name,stat_value,sample_size */
for (cnode = static_cast<que_common_t*>(node->select_list), i = 0;
cnode != NULL;
cnode = static_cast<que_common_t*>(que_node_get_next(cnode)),
i++) {
const byte* data;
dfield_t* dfield = que_node_get_val(cnode);
dtype_t* type = dfield_get_type(dfield);
ulint len = dfield_get_len(dfield);
data = static_cast<const byte*>(dfield_get_data(dfield));
switch (i) {
case 0: /* mysql.innodb_index_stats.index_name */
ut_a(dtype_get_mtype(type) == DATA_VARMYSQL);
/* search for index in table's indexes whose name
matches data; the fetched index name is in data,
has no terminating '\0' and has length len */
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (index->is_committed()
&& strlen(index->name) == len
&& memcmp(index->name, data, len) == 0) {
/* the corresponding index was found */
break;
}
}
/* if index is NULL here this means that
mysql.innodb_index_stats contains more rows than the
number of indexes in the table; this is ok, we just
return ignoring those extra rows; in other words
dict_stats_fetch_index_stats_step() has been called
for a row from index_stats with unknown index_name
column */
if (index == NULL) {
return(TRUE);
}
break;
case 1: /* mysql.innodb_index_stats.stat_name */
ut_a(dtype_get_mtype(type) == DATA_VARMYSQL);
ut_a(index != NULL);
stat_name = (const char*) data;
stat_name_len = len;
break;
case 2: /* mysql.innodb_index_stats.stat_value */
ut_a(dtype_get_mtype(type) == DATA_INT);
ut_a(len == 8);
ut_a(index != NULL);
ut_a(stat_name != NULL);
ut_a(stat_name_len != ULINT_UNDEFINED);
stat_value = mach_read_from_8(data);
break;
case 3: /* mysql.innodb_index_stats.sample_size */
ut_a(dtype_get_mtype(type) == DATA_INT);
ut_a(len == 8 || len == UNIV_SQL_NULL);
ut_a(index != NULL);
ut_a(stat_name != NULL);
ut_a(stat_name_len != ULINT_UNDEFINED);
ut_a(stat_value != UINT64_UNDEFINED);
if (len == UNIV_SQL_NULL) {
break;
}
/* else */
sample_size = mach_read_from_8(data);
break;
default:
/* someone changed
SELECT index_name,stat_name,stat_value,sample_size
to select more columns from innodb_index_stats without
adjusting here */
ut_error;
}
}
/* if i < 4 this means someone changed the
SELECT index_name,stat_name,stat_value,sample_size
to select less columns from innodb_index_stats without adjusting here;
if i > 4 we would have ut_error'ed earlier */
ut_a(i == 4 /* index_name,stat_name,stat_value,sample_size */);
ut_a(index != NULL);
ut_a(stat_name != NULL);
ut_a(stat_name_len != ULINT_UNDEFINED);
ut_a(stat_value != UINT64_UNDEFINED);
/* sample_size could be UINT64_UNDEFINED here, if it is NULL */
#define PFX "n_diff_pfx"
#define PFX_LEN 10
if (stat_name_len == 4 /* strlen("size") */
&& strncasecmp("size", stat_name, stat_name_len) == 0) {
index->stat_index_size = (ulint) stat_value;
arg->stats_were_modified = true;
} else if (stat_name_len == 12 /* strlen("n_leaf_pages") */
&& strncasecmp("n_leaf_pages", stat_name, stat_name_len)
== 0) {
index->stat_n_leaf_pages = (ulint) stat_value;
arg->stats_were_modified = true;
} else if (stat_name_len == 12 /* strlen("n_page_split") */
&& strncasecmp("n_page_split", stat_name, stat_name_len)
== 0) {
index->stat_defrag_n_page_split = (ulint) stat_value;
arg->stats_were_modified = true;
} else if (stat_name_len == 13 /* strlen("n_pages_freed") */
&& strncasecmp("n_pages_freed", stat_name, stat_name_len)
== 0) {
index->stat_defrag_n_pages_freed = (ulint) stat_value;
arg->stats_were_modified = true;
} else if (stat_name_len > PFX_LEN /* e.g. stat_name=="n_diff_pfx01" */
&& strncasecmp(PFX, stat_name, PFX_LEN) == 0) {
const char* num_ptr;
unsigned long n_pfx;
/* point num_ptr into "1" from "n_diff_pfx12..." */
num_ptr = stat_name + PFX_LEN;
/* stat_name should have exactly 2 chars appended to PFX
and they should be digits */
if (stat_name_len != PFX_LEN + 2
|| num_ptr[0] < '0' || num_ptr[0] > '9'
|| num_ptr[1] < '0' || num_ptr[1] > '9') {
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
dict_fs2utf8(table->name.m_name,
db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
ib::info out;
out << "Ignoring strange row from "
<< INDEX_STATS_NAME_PRINT << " WHERE"
" database_name = '" << db_utf8
<< "' AND table_name = '" << table_utf8
<< "' AND index_name = '" << index->name()
<< "' AND stat_name = '";
out.write(stat_name, stat_name_len);
out << "'; because stat_name is malformed";
return(TRUE);
}
/* else */
/* extract 12 from "n_diff_pfx12..." into n_pfx
note that stat_name does not have a terminating '\0' */
n_pfx = (num_ptr[0] - '0') * 10 + (num_ptr[1] - '0');
ulint n_uniq = index->n_uniq;
if (n_pfx == 0 || n_pfx > n_uniq) {
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
dict_fs2utf8(table->name.m_name,
db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
ib::info out;
out << "Ignoring strange row from "
<< INDEX_STATS_NAME_PRINT << " WHERE"
" database_name = '" << db_utf8
<< "' AND table_name = '" << table_utf8
<< "' AND index_name = '" << index->name()
<< "' AND stat_name = '";
out.write(stat_name, stat_name_len);
out << "'; because stat_name is out of range, the index"
" has " << n_uniq << " unique columns";
return(TRUE);
}
/* else */
index->stat_n_diff_key_vals[n_pfx - 1] = stat_value;
if (sample_size != UINT64_UNDEFINED) {
index->stat_n_sample_sizes[n_pfx - 1] = sample_size;
} else {
/* hmm, strange... the user must have UPDATEd the
table manually and SET sample_size = NULL */
index->stat_n_sample_sizes[n_pfx - 1] = 0;
}
index->stat_n_non_null_key_vals[n_pfx - 1] = 0;
arg->stats_were_modified = true;
} else {
/* silently ignore rows with unknown stat_name, the
user may have developed her own stats */
}
/* XXX this is not used but returning non-NULL is necessary */
return(TRUE);
}
/*********************************************************************//**
Read table's statistics from the persistent statistics storage.
@return DB_SUCCESS or error code */
static
dberr_t
dict_stats_fetch_from_ps(
/*=====================*/
dict_table_t* table) /*!< in/out: table */
{
index_fetch_t index_fetch_arg;
trx_t* trx;
pars_info_t* pinfo;
dberr_t ret;
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
ut_ad(!mutex_own(&dict_sys->mutex));
/* Initialize all stats to dummy values before fetching because if
the persistent storage contains incomplete stats (e.g. missing stats
for some index) then we would end up with (partially) uninitialized
stats. */
dict_stats_empty_table(table, true);
trx = trx_allocate_for_background();
/* Use 'read-uncommitted' so that the SELECTs we execute
do not get blocked in case some user has locked the rows we
are SELECTing */
trx->isolation_level = TRX_ISO_READ_UNCOMMITTED;
if (srv_read_only_mode) {
trx_start_internal_read_only(trx);
} else {
trx_start_internal(trx);
}
dict_fs2utf8(table->name.m_name, db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db_utf8);
pars_info_add_str_literal(pinfo, "table_name", table_utf8);
pars_info_bind_function(pinfo,
"fetch_table_stats_step",
dict_stats_fetch_table_stats_step,
table);
index_fetch_arg.table = table;
index_fetch_arg.stats_were_modified = false;
pars_info_bind_function(pinfo,
"fetch_index_stats_step",
dict_stats_fetch_index_stats_step,
&index_fetch_arg);
ret = que_eval_sql(pinfo,
"PROCEDURE FETCH_STATS () IS\n"
"found INT;\n"
"DECLARE FUNCTION fetch_table_stats_step;\n"
"DECLARE FUNCTION fetch_index_stats_step;\n"
"DECLARE CURSOR table_stats_cur IS\n"
" SELECT\n"
/* if you change the selected fields, be
sure to adjust
dict_stats_fetch_table_stats_step() */
" n_rows,\n"
" clustered_index_size,\n"
" sum_of_other_index_sizes\n"
" FROM \"" TABLE_STATS_NAME "\"\n"
" WHERE\n"
" database_name = :database_name AND\n"
" table_name = :table_name;\n"
"DECLARE CURSOR index_stats_cur IS\n"
" SELECT\n"
/* if you change the selected fields, be
sure to adjust
dict_stats_fetch_index_stats_step() */
" index_name,\n"
" stat_name,\n"
" stat_value,\n"
" sample_size\n"
" FROM \"" INDEX_STATS_NAME "\"\n"
" WHERE\n"
" database_name = :database_name AND\n"
" table_name = :table_name;\n"
"BEGIN\n"
"OPEN table_stats_cur;\n"
"FETCH table_stats_cur INTO\n"
" fetch_table_stats_step();\n"
"IF (SQL % NOTFOUND) THEN\n"
" CLOSE table_stats_cur;\n"
" RETURN;\n"
"END IF;\n"
"CLOSE table_stats_cur;\n"
"OPEN index_stats_cur;\n"
"found := 1;\n"
"WHILE found = 1 LOOP\n"
" FETCH index_stats_cur INTO\n"
" fetch_index_stats_step();\n"
" IF (SQL % NOTFOUND) THEN\n"
" found := 0;\n"
" END IF;\n"
"END LOOP;\n"
"CLOSE index_stats_cur;\n"
"END;",
TRUE, trx);
/* pinfo is freed by que_eval_sql() */
trx_commit_for_mysql(trx);
trx_free_for_background(trx);
if (!index_fetch_arg.stats_were_modified) {
return(DB_STATS_DO_NOT_EXIST);
}
return(ret);
}
/*********************************************************************//**
Clear defragmentation stats modified counter for all indices in table. */
static
void
dict_stats_empty_defrag_modified_counter(
dict_table_t* table) /*!< in: table */
{
dict_index_t* index;
ut_a(table);
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
index->stat_defrag_modified_counter = 0;
}
}
/** Calculate index statistics.
@param[in,out] index index tree
@param[in,out] trx transaction (for persistent statistics)
@return DB_SUCCESS or error code */
UNIV_INTERN
dberr_t
dict_stats_update_for_index(dict_index_t* index, trx_t* trx)
{
DBUG_ENTER("dict_stats_update_for_index");
ut_ad(!mutex_own(&dict_sys->mutex));
if (dict_stats_is_persistent_enabled(index->table)) {
if (dict_stats_persistent_storage_check(false)) {
dict_table_stats_lock(index->table, RW_X_LATCH);
dict_stats_analyze_index(index);
dict_table_stats_unlock(index->table, RW_X_LATCH);
DBUG_RETURN(dict_stats_save(index->table, trx,
&index->id));
}
/* else */
if (innodb_index_stats_not_found == false &&
index->stats_error_printed == false) {
/* Fall back to transient stats since the persistent
storage is not present or is corrupted */
ib::info() << "Recalculation of persistent statistics"
" requested for table " << index->table->name
<< " index " << index->name
<< " but the required"
" persistent statistics storage is not present or is"
" corrupted. Using transient stats instead.";
index->stats_error_printed = false;
}
}
dict_table_stats_lock(index->table, RW_X_LATCH);
dict_stats_update_transient_for_index(index);
dict_table_stats_unlock(index->table, RW_X_LATCH);
DBUG_RETURN(DB_SUCCESS);
}
/** Calculate new estimates for table and index statistics.
@param[in,out] table table
@param[in] stats_upd_option how to update statistics
@param[in,out] trx transaction
@return DB_* error code or DB_SUCCESS */
UNIV_INTERN
dberr_t
dict_stats_update(
dict_table_t* table,
dict_stats_upd_option_t stats_upd_option,
trx_t* trx)
{
ut_ad(!mutex_own(&dict_sys->mutex));
if (!table->is_readable()) {
return (dict_stats_report_error(table));
} else if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) {
/* If we have set a high innodb_force_recovery level, do
not calculate statistics, as a badly corrupted index can
cause a crash in it. */
dict_stats_empty_table(table, false);
return(DB_SUCCESS);
}
switch (stats_upd_option) {
case DICT_STATS_RECALC_PERSISTENT:
if (srv_read_only_mode) {
goto transient;
}
/* Persistent recalculation requested, called from
1) ANALYZE TABLE, or
2) the auto recalculation background thread, or
3) open table if stats do not exist on disk and auto recalc
is enabled */
/* InnoDB internal tables (e.g. SYS_TABLES) cannot have
persistent stats enabled */
ut_a(strchr(table->name.m_name, '/') != NULL);
/* check if the persistent statistics storage exists
before calling the potentially slow function
dict_stats_update_persistent(); that is a
prerequisite for dict_stats_save() succeeding */
if (dict_stats_persistent_storage_check(false)) {
dberr_t err;
err = dict_stats_update_persistent(table);
if (err != DB_SUCCESS) {
return(err);
}
err = dict_stats_save(table, trx);
return(err);
}
/* Fall back to transient stats since the persistent
storage is not present or is corrupted */
if (innodb_table_stats_not_found == false &&
table->stats_error_printed == false) {
ib::warn() << "Recalculation of persistent statistics"
" requested for table "
<< table->name
<< " but the required persistent"
" statistics storage is not present or is corrupted."
" Using transient stats instead.";
table->stats_error_printed = true;
}
goto transient;
case DICT_STATS_RECALC_TRANSIENT:
goto transient;
case DICT_STATS_EMPTY_TABLE:
dict_stats_empty_table(table, true);
/* If table is using persistent stats,
then save the stats on disk */
if (dict_stats_is_persistent_enabled(table)) {
if (dict_stats_persistent_storage_check(false)) {
return(dict_stats_save(table, trx));
}
return(DB_STATS_DO_NOT_EXIST);
}
return(DB_SUCCESS);
case DICT_STATS_FETCH_ONLY_IF_NOT_IN_MEMORY:
/* fetch requested, either fetch from persistent statistics
storage or use the old method */
if (table->stat_initialized) {
return(DB_SUCCESS);
}
/* InnoDB internal tables (e.g. SYS_TABLES) cannot have
persistent stats enabled */
ut_a(strchr(table->name.m_name, '/') != NULL);
if (!dict_stats_persistent_storage_check(false)) {
/* persistent statistics storage does not exist
or is corrupted, calculate the transient stats */
if (innodb_table_stats_not_found == false &&
table->stats_error_printed == false) {
ib::error() << "Fetch of persistent statistics"
" requested for table "
<< table->name
<< " but the required system tables "
<< TABLE_STATS_NAME_PRINT
<< " and " << INDEX_STATS_NAME_PRINT
<< " are not present or have unexpected"
" structure. Using transient stats instead.";
table->stats_error_printed = true;
}
goto transient;
}
dict_table_t* t;
/* Create a dummy table object with the same name and
indexes, suitable for fetching the stats into it. */
t = dict_stats_table_clone_create(table);
dberr_t err = dict_stats_fetch_from_ps(t);
t->stats_last_recalc = table->stats_last_recalc;
t->stat_modified_counter = 0;
dict_stats_empty_defrag_modified_counter(t);
switch (err) {
case DB_SUCCESS:
dict_table_stats_lock(table, RW_X_LATCH);
/* Pass reset_ignored_indexes=true as parameter
to dict_stats_copy. This will cause statictics
for corrupted indexes to be set to empty values */
dict_stats_copy(table, t, true);
dict_stats_assert_initialized(table);
dict_table_stats_unlock(table, RW_X_LATCH);
dict_stats_table_clone_free(t);
return(DB_SUCCESS);
case DB_STATS_DO_NOT_EXIST:
dict_stats_table_clone_free(t);
if (srv_read_only_mode) {
goto transient;
}
if (dict_stats_auto_recalc_is_enabled(table)) {
return dict_stats_update(
table, DICT_STATS_RECALC_PERSISTENT,
trx);
}
ib::info() << "Trying to use table " << table->name
<< " which has persistent statistics enabled,"
" but auto recalculation turned off and the"
" statistics do not exist in "
TABLE_STATS_NAME_PRINT
" and " INDEX_STATS_NAME_PRINT
". Please either run \"ANALYZE TABLE "
<< table->name << ";\" manually or enable the"
" auto recalculation with \"ALTER TABLE "
<< table->name << " STATS_AUTO_RECALC=1;\"."
" InnoDB will now use transient statistics for "
<< table->name << ".";
goto transient;
default:
dict_stats_table_clone_free(t);
if (innodb_table_stats_not_found == false &&
table->stats_error_printed == false) {
ib::error() << "Error fetching persistent statistics"
" for table "
<< table->name
<< " from " TABLE_STATS_NAME_PRINT " and "
INDEX_STATS_NAME_PRINT ": " << ut_strerr(err)
<< ". Using transient stats method instead.";
}
goto transient;
}
/* no "default:" in order to produce a compilation warning
about unhandled enumeration value */
}
transient:
dict_table_stats_lock(table, RW_X_LATCH);
dict_stats_update_transient(table);
dict_table_stats_unlock(table, RW_X_LATCH);
return(DB_SUCCESS);
}
/** Remove the persistent statistics for an index.
@param[in] db_and_table schema and table name, e.g., 'db/table'
@param[in] iname index name
@param[out] errstr error message (when not returning DB_SUCCESS)
@param[in] errstr_sz sizeof errstr
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
dberr_t
dict_stats_drop_index(
const char* db_and_table,
const char* iname,
char* errstr,
size_t errstr_sz,
trx_t* trx)
{
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
pars_info_t* pinfo;
dberr_t ret;
ut_ad(!mutex_own(&dict_sys->mutex));
/* skip indexes whose table names do not contain a database name
e.g. if we are dropping an index from SYS_TABLES */
if (strchr(db_and_table, '/') == NULL) {
return(DB_SUCCESS);
}
if (!dict_stats_persistent_storage_check(false)) {
/* Statistics tables do not exist. */
return(DB_SUCCESS);
}
dict_fs2utf8(db_and_table, db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db_utf8);
pars_info_add_str_literal(pinfo, "table_name", table_utf8);
pars_info_add_str_literal(pinfo, "index_name", iname);
mutex_enter(&dict_sys->mutex);
ret = dict_stats_exec_sql(
pinfo,
"PROCEDURE DROP_INDEX_STATS () IS\n"
"BEGIN\n"
"DELETE FROM \"" INDEX_STATS_NAME "\" WHERE\n"
"database_name = :database_name AND\n"
"table_name = :table_name AND\n"
"index_name = :index_name;\n"
"END;\n", trx);
mutex_exit(&dict_sys->mutex);
switch (ret) {
case DB_STATS_DO_NOT_EXIST:
case DB_SUCCESS:
return(DB_SUCCESS);
case DB_QUE_THR_SUSPENDED:
ret = DB_LOCK_WAIT;
/* fall through */
default:
snprintf(errstr, errstr_sz,
"Unable to delete statistics for index %s"
" from %s%s: %s. They can be deleted later using"
" DELETE FROM %s WHERE"
" database_name = '%s' AND"
" table_name = '%s' AND"
" index_name = '%s';",
iname,
INDEX_STATS_NAME_PRINT,
(ret == DB_LOCK_WAIT_TIMEOUT
? " because the rows are locked"
: ""),
ut_strerr(ret),
INDEX_STATS_NAME_PRINT,
db_utf8,
table_utf8,
iname);
ut_print_timestamp(stderr);
fprintf(stderr, " InnoDB: %s\n", errstr);
}
return(ret);
}
/** Delete table statistics.
@param[in] db schema name
@param[in] t table name
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
UNIV_INLINE
dberr_t
dict_stats_delete_from_table_stats(const char* db, const char* t, trx_t* trx)
{
pars_info_t* pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db);
pars_info_add_str_literal(pinfo, "table_name", t);
return dict_stats_exec_sql(
pinfo,
"PROCEDURE DELETE_FROM_TABLE_STATS () IS\n"
"BEGIN\n"
"DELETE FROM \"" TABLE_STATS_NAME "\" WHERE\n"
"database_name = :database_name AND\n"
"table_name = :table_name;\n"
"END;\n", trx);
}
/** Delete index statistics.
@param[in] db schema name
@param[in] t table name
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
UNIV_INLINE
dberr_t
dict_stats_delete_from_index_stats(const char* db, const char* t, trx_t* trx)
{
pars_info_t* pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "database_name", db);
pars_info_add_str_literal(pinfo, "table_name", t);
return dict_stats_exec_sql(
pinfo,
"PROCEDURE DELETE_FROM_INDEX_STATS () IS\n"
"BEGIN\n"
"DELETE FROM \"" INDEX_STATS_NAME "\" WHERE\n"
"database_name = :database_name AND\n"
"table_name = :table_name;\n"
"END;\n", trx);
}
/** Remove the persistent statistics for a table and all of its indexes.
@param[in] db_and_table schema and table name, e.g., 'db/table'
@param[out] errstr error message (when not returning DB_SUCCESS)
@param[in] errstr_sz sizeof errstr
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
dberr_t
dict_stats_drop_table(
const char* db_and_table,
char* errstr,
size_t errstr_sz,
trx_t* trx)
{
char db_utf8[MAX_DB_UTF8_LEN];
char table_utf8[MAX_TABLE_UTF8_LEN];
dberr_t ret;
/* skip tables that do not contain a database name
e.g. if we are dropping SYS_TABLES */
if (strchr(db_and_table, '/') == NULL) {
return(DB_SUCCESS);
}
/* skip innodb_table_stats and innodb_index_stats themselves */
if (strcmp(db_and_table, TABLE_STATS_NAME) == 0
|| strcmp(db_and_table, INDEX_STATS_NAME) == 0) {
return(DB_SUCCESS);
}
if (!dict_stats_persistent_storage_check(true)) {
/* Statistics tables do not exist. */
return(DB_SUCCESS);
}
dict_fs2utf8(db_and_table, db_utf8, sizeof(db_utf8),
table_utf8, sizeof(table_utf8));
ret = dict_stats_delete_from_table_stats(db_utf8, table_utf8, trx);
if (ret == DB_SUCCESS) {
ret = dict_stats_delete_from_index_stats(
db_utf8, table_utf8, trx);
}
switch (ret) {
case DB_SUCCESS:
case DB_STATS_DO_NOT_EXIST:
return(DB_SUCCESS);
case DB_QUE_THR_SUSPENDED:
ret = DB_LOCK_WAIT;
/* fall through */
default:
snprintf(errstr, errstr_sz,
"Unable to delete statistics for table %s.%s: %s. "
"They can be deleted later using "
" DELETE FROM %s WHERE"
" database_name = '%s' AND"
" table_name = '%s';"
" DELETE FROM %s WHERE"
" database_name = '%s' AND"
" table_name = '%s';",
db_utf8, table_utf8,
ut_strerr(ret),
INDEX_STATS_NAME_PRINT,
db_utf8, table_utf8,
TABLE_STATS_NAME_PRINT,
db_utf8, table_utf8);
}
return(ret);
}
/** Rename table statistics.
@param[in] old_dbname_utf8 old schema name
@param[in] old_tablename_utf8 old table name
@param[in] new_dbname_utf8 new schema name
@param[in] new_tablename_utf8 new schema name
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
UNIV_INLINE
dberr_t
dict_stats_rename_in_table_stats(
const char* old_dbname_utf8,
const char* old_tablename_utf8,
const char* new_dbname_utf8,
const char* new_tablename_utf8,
trx_t* trx)
{
pars_info_t* pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "old_dbname_utf8", old_dbname_utf8);
pars_info_add_str_literal(pinfo, "old_tablename_utf8", old_tablename_utf8);
pars_info_add_str_literal(pinfo, "new_dbname_utf8", new_dbname_utf8);
pars_info_add_str_literal(pinfo, "new_tablename_utf8", new_tablename_utf8);
return dict_stats_exec_sql(
pinfo,
"PROCEDURE RENAME_TABLE_IN_TABLE_STATS () IS\n"
"BEGIN\n"
"UPDATE \"" TABLE_STATS_NAME "\" SET\n"
"database_name = :new_dbname_utf8,\n"
"table_name = :new_tablename_utf8\n"
"WHERE\n"
"database_name = :old_dbname_utf8 AND\n"
"table_name = :old_tablename_utf8;\n"
"END;\n", trx);
}
/** Rename index statistics.
@param[in] old_dbname_utf8 old schema name
@param[in] old_tablename_utf8 old table name
@param[in] new_dbname_utf8 new schema name
@param[in] new_tablename_utf8 new schema name
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
UNIV_INLINE
dberr_t
dict_stats_rename_in_index_stats(
const char* old_dbname_utf8,
const char* old_tablename_utf8,
const char* new_dbname_utf8,
const char* new_tablename_utf8,
trx_t* trx)
{
pars_info_t* pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "old_dbname_utf8", old_dbname_utf8);
pars_info_add_str_literal(pinfo, "old_tablename_utf8", old_tablename_utf8);
pars_info_add_str_literal(pinfo, "new_dbname_utf8", new_dbname_utf8);
pars_info_add_str_literal(pinfo, "new_tablename_utf8", new_tablename_utf8);
return dict_stats_exec_sql(
pinfo,
"PROCEDURE RENAME_TABLE_IN_INDEX_STATS () IS\n"
"BEGIN\n"
"UPDATE \"" INDEX_STATS_NAME "\" SET\n"
"database_name = :new_dbname_utf8,\n"
"table_name = :new_tablename_utf8\n"
"WHERE\n"
"database_name = :old_dbname_utf8 AND\n"
"table_name = :old_tablename_utf8;\n"
"END;\n", trx);
}
/** Rename a table in the InnoDB persistent statistics storage.
@param[in] old_name old schema and table name, e.g., 'db/table'
@param[in] new_name new schema and table name, e.g., 'db/table'
@param[out] errstr error message (when not returning DB_SUCCESS)
@param[in] errstr_sz sizeof errstr
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
dberr_t
dict_stats_rename_table(
const char* old_name,
const char* new_name,
char* errstr,
size_t errstr_sz,
trx_t* trx)
{
char old_db_utf8[MAX_DB_UTF8_LEN];
char new_db_utf8[MAX_DB_UTF8_LEN];
char old_table_utf8[MAX_TABLE_UTF8_LEN];
char new_table_utf8[MAX_TABLE_UTF8_LEN];
dberr_t ret;
/* skip innodb_table_stats and innodb_index_stats themselves */
if (strcmp(old_name, TABLE_STATS_NAME) == 0
|| strcmp(old_name, INDEX_STATS_NAME) == 0
|| strcmp(new_name, TABLE_STATS_NAME) == 0
|| strcmp(new_name, INDEX_STATS_NAME) == 0) {
return(DB_SUCCESS);
}
if (!dict_stats_persistent_storage_check(false)) {
/* Statistics tables do not exist. */
return(DB_SUCCESS);
}
dict_fs2utf8(old_name, old_db_utf8, sizeof(old_db_utf8),
old_table_utf8, sizeof(old_table_utf8));
dict_fs2utf8(new_name, new_db_utf8, sizeof(new_db_utf8),
new_table_utf8, sizeof(new_table_utf8));
ulint n_attempts = 0;
do {
trx_savept_t savept = trx_savept_take(trx);
mutex_enter(&dict_sys->mutex);
ret = dict_stats_rename_in_table_stats(
old_db_utf8, old_table_utf8,
new_db_utf8, new_table_utf8, trx);
mutex_exit(&dict_sys->mutex);
switch (ret) {
case DB_DUPLICATE_KEY:
trx_rollback_to_savepoint(trx, &savept);
mutex_enter(&dict_sys->mutex);
dict_stats_delete_from_table_stats(
new_db_utf8, new_table_utf8, trx);
mutex_exit(&dict_sys->mutex);
/* fall through */
case DB_DEADLOCK:
case DB_LOCK_WAIT_TIMEOUT:
os_thread_sleep(200000 /* 0.2 sec */);
continue;
case DB_STATS_DO_NOT_EXIST:
ret = DB_SUCCESS;
break;
default:
break;
}
break;
} while (++n_attempts < 5);
const char* table_name = TABLE_STATS_NAME_PRINT;
if (ret != DB_SUCCESS) {
goto err_exit;
}
table_name = INDEX_STATS_NAME_PRINT;
n_attempts = 0;
do {
trx_savept_t savept = trx_savept_take(trx);
mutex_enter(&dict_sys->mutex);
ret = dict_stats_rename_in_index_stats(
old_db_utf8, old_table_utf8,
new_db_utf8, new_table_utf8, trx);
mutex_exit(&dict_sys->mutex);
switch (ret) {
case DB_DUPLICATE_KEY:
trx_rollback_to_savepoint(trx, &savept);
mutex_enter(&dict_sys->mutex);
dict_stats_delete_from_index_stats(
new_db_utf8, new_table_utf8, trx);
mutex_exit(&dict_sys->mutex);
/* fall through */
case DB_DEADLOCK:
case DB_LOCK_WAIT_TIMEOUT:
os_thread_sleep(200000 /* 0.2 sec */);
continue;
case DB_STATS_DO_NOT_EXIST:
ret = DB_SUCCESS;
break;
default:
break;
}
break;
} while (++n_attempts < 5);
if (ret != DB_SUCCESS) {
err_exit:
snprintf(errstr, errstr_sz,
"Unable to rename statistics from"
" %s.%s to %s.%s in %s: %s."
" They can be renamed later using"
" UPDATE %s SET"
" database_name = '%s',"
" table_name = '%s'"
" WHERE"
" database_name = '%s' AND"
" table_name = '%s';",
old_db_utf8, old_table_utf8,
new_db_utf8, new_table_utf8,
table_name,
ut_strerr(ret),
table_name,
new_db_utf8, new_table_utf8,
old_db_utf8, old_table_utf8);
}
return(ret);
}
/*********************************************************************//**
Renames an index in InnoDB persistent stats storage.
This function creates its own transaction and commits it.
@return DB_SUCCESS or error code. DB_STATS_DO_NOT_EXIST will be returned
if the persistent stats do not exist. */
dberr_t
dict_stats_rename_index(
/*====================*/
const dict_table_t* table, /*!< in: table whose index
is renamed */
const char* old_index_name, /*!< in: old index name */
const char* new_index_name) /*!< in: new index name */
{
rw_lock_x_lock(dict_operation_lock);
mutex_enter(&dict_sys->mutex);
if (!dict_stats_persistent_storage_check(true)) {
mutex_exit(&dict_sys->mutex);
rw_lock_x_unlock(dict_operation_lock);
return(DB_STATS_DO_NOT_EXIST);
}
char dbname_utf8[MAX_DB_UTF8_LEN];
char tablename_utf8[MAX_TABLE_UTF8_LEN];
dict_fs2utf8(table->name.m_name, dbname_utf8, sizeof(dbname_utf8),
tablename_utf8, sizeof(tablename_utf8));
pars_info_t* pinfo;
pinfo = pars_info_create();
pars_info_add_str_literal(pinfo, "dbname_utf8", dbname_utf8);
pars_info_add_str_literal(pinfo, "tablename_utf8", tablename_utf8);
pars_info_add_str_literal(pinfo, "new_index_name", new_index_name);
pars_info_add_str_literal(pinfo, "old_index_name", old_index_name);
dberr_t ret;
ret = dict_stats_exec_sql(
pinfo,
"PROCEDURE RENAME_INDEX_IN_INDEX_STATS () IS\n"
"BEGIN\n"
"UPDATE \"" INDEX_STATS_NAME "\" SET\n"
"index_name = :new_index_name\n"
"WHERE\n"
"database_name = :dbname_utf8 AND\n"
"table_name = :tablename_utf8 AND\n"
"index_name = :old_index_name;\n"
"END;\n", NULL);
mutex_exit(&dict_sys->mutex);
rw_lock_x_unlock(dict_operation_lock);
return(ret);
}
/* tests @{ */
#ifdef UNIV_ENABLE_UNIT_TEST_DICT_STATS
/* The following unit tests test some of the functions in this file
individually, such testing cannot be performed by the mysql-test framework
via SQL. */
/* test_dict_table_schema_check() @{ */
void
test_dict_table_schema_check()
{
/*
CREATE TABLE tcheck (
c01 VARCHAR(123),
c02 INT,
c03 INT NOT NULL,
c04 INT UNSIGNED,
c05 BIGINT,
c06 BIGINT UNSIGNED NOT NULL,
c07 TIMESTAMP
) ENGINE=INNODB;
*/
/* definition for the table 'test/tcheck' */
dict_col_meta_t columns[] = {
{"c01", DATA_VARCHAR, 0, 123},
{"c02", DATA_INT, 0, 4},
{"c03", DATA_INT, DATA_NOT_NULL, 4},
{"c04", DATA_INT, DATA_UNSIGNED, 4},
{"c05", DATA_INT, 0, 8},
{"c06", DATA_INT, DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"c07", DATA_INT, 0, 4},
{"c_extra", DATA_INT, 0, 4}
};
dict_table_schema_t schema = {
"test/tcheck",
0 /* will be set individually for each test below */,
columns
};
char errstr[512];
snprintf(errstr, sizeof(errstr), "Table not found");
/* prevent any data dictionary modifications while we are checking
the tables' structure */
mutex_enter(&dict_sys->mutex);
/* check that a valid table is reported as valid */
schema.n_cols = 7;
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
== DB_SUCCESS) {
printf("OK: test.tcheck ok\n");
} else {
printf("ERROR: %s\n", errstr);
printf("ERROR: test.tcheck not present or corrupted\n");
goto test_dict_table_schema_check_end;
}
/* check columns with wrong length */
schema.columns[1].len = 8;
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
!= DB_SUCCESS) {
printf("OK: test.tcheck.c02 has different length and is"
" reported as corrupted\n");
} else {
printf("OK: test.tcheck.c02 has different length but is"
" reported as ok\n");
goto test_dict_table_schema_check_end;
}
schema.columns[1].len = 4;
/* request that c02 is NOT NULL while actually it does not have
this flag set */
schema.columns[1].prtype_mask |= DATA_NOT_NULL;
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
!= DB_SUCCESS) {
printf("OK: test.tcheck.c02 does not have NOT NULL while"
" it should and is reported as corrupted\n");
} else {
printf("ERROR: test.tcheck.c02 does not have NOT NULL while"
" it should and is not reported as corrupted\n");
goto test_dict_table_schema_check_end;
}
schema.columns[1].prtype_mask &= ~DATA_NOT_NULL;
/* check a table that contains some extra columns */
schema.n_cols = 6;
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
== DB_SUCCESS) {
printf("ERROR: test.tcheck has more columns but is not"
" reported as corrupted\n");
goto test_dict_table_schema_check_end;
} else {
printf("OK: test.tcheck has more columns and is"
" reported as corrupted\n");
}
/* check a table that has some columns missing */
schema.n_cols = 8;
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
!= DB_SUCCESS) {
printf("OK: test.tcheck has missing columns and is"
" reported as corrupted\n");
} else {
printf("ERROR: test.tcheck has missing columns but is"
" reported as ok\n");
goto test_dict_table_schema_check_end;
}
/* check non-existent table */
schema.table_name = "test/tcheck_nonexistent";
if (dict_table_schema_check(&schema, errstr, sizeof(errstr))
!= DB_SUCCESS) {
printf("OK: test.tcheck_nonexistent is not present\n");
} else {
printf("ERROR: test.tcheck_nonexistent is present!?\n");
goto test_dict_table_schema_check_end;
}
test_dict_table_schema_check_end:
mutex_exit(&dict_sys->mutex);
}
/* @} */
/* save/fetch aux macros @{ */
#define TEST_DATABASE_NAME "foobardb"
#define TEST_TABLE_NAME "test_dict_stats"
#define TEST_N_ROWS 111
#define TEST_CLUSTERED_INDEX_SIZE 222
#define TEST_SUM_OF_OTHER_INDEX_SIZES 333
#define TEST_IDX1_NAME "tidx1"
#define TEST_IDX1_COL1_NAME "tidx1_col1"
#define TEST_IDX1_INDEX_SIZE 123
#define TEST_IDX1_N_LEAF_PAGES 234
#define TEST_IDX1_N_DIFF1 50
#define TEST_IDX1_N_DIFF1_SAMPLE_SIZE 500
#define TEST_IDX2_NAME "tidx2"
#define TEST_IDX2_COL1_NAME "tidx2_col1"
#define TEST_IDX2_COL2_NAME "tidx2_col2"
#define TEST_IDX2_COL3_NAME "tidx2_col3"
#define TEST_IDX2_COL4_NAME "tidx2_col4"
#define TEST_IDX2_INDEX_SIZE 321
#define TEST_IDX2_N_LEAF_PAGES 432
#define TEST_IDX2_N_DIFF1 60
#define TEST_IDX2_N_DIFF1_SAMPLE_SIZE 600
#define TEST_IDX2_N_DIFF2 61
#define TEST_IDX2_N_DIFF2_SAMPLE_SIZE 610
#define TEST_IDX2_N_DIFF3 62
#define TEST_IDX2_N_DIFF3_SAMPLE_SIZE 620
#define TEST_IDX2_N_DIFF4 63
#define TEST_IDX2_N_DIFF4_SAMPLE_SIZE 630
/* @} */
/* test_dict_stats_save() @{ */
void
test_dict_stats_save()
{
dict_table_t table;
dict_index_t index1;
dict_field_t index1_fields[1];
ib_uint64_t index1_stat_n_diff_key_vals[1];
ib_uint64_t index1_stat_n_sample_sizes[1];
dict_index_t index2;
dict_field_t index2_fields[4];
ib_uint64_t index2_stat_n_diff_key_vals[4];
ib_uint64_t index2_stat_n_sample_sizes[4];
dberr_t ret;
/* craft a dummy dict_table_t */
table.name.m_name = (char*) (TEST_DATABASE_NAME "/" TEST_TABLE_NAME);
table.stat_n_rows = TEST_N_ROWS;
table.stat_clustered_index_size = TEST_CLUSTERED_INDEX_SIZE;
table.stat_sum_of_other_index_sizes = TEST_SUM_OF_OTHER_INDEX_SIZES;
UT_LIST_INIT(table.indexes, &dict_index_t::indexes);
UT_LIST_ADD_LAST(table.indexes, &index1);
UT_LIST_ADD_LAST(table.indexes, &index2);
ut_d(table.magic_n = DICT_TABLE_MAGIC_N);
ut_d(index1.magic_n = DICT_INDEX_MAGIC_N);
index1.name = TEST_IDX1_NAME;
index1.table = &table;
index1.cached = 1;
index1.n_uniq = 1;
index1.fields = index1_fields;
index1.stat_n_diff_key_vals = index1_stat_n_diff_key_vals;
index1.stat_n_sample_sizes = index1_stat_n_sample_sizes;
index1.stat_index_size = TEST_IDX1_INDEX_SIZE;
index1.stat_n_leaf_pages = TEST_IDX1_N_LEAF_PAGES;
index1_fields[0].name = TEST_IDX1_COL1_NAME;
index1_stat_n_diff_key_vals[0] = TEST_IDX1_N_DIFF1;
index1_stat_n_sample_sizes[0] = TEST_IDX1_N_DIFF1_SAMPLE_SIZE;
ut_d(index2.magic_n = DICT_INDEX_MAGIC_N);
index2.name = TEST_IDX2_NAME;
index2.table = &table;
index2.cached = 1;
index2.n_uniq = 4;
index2.fields = index2_fields;
index2.stat_n_diff_key_vals = index2_stat_n_diff_key_vals;
index2.stat_n_sample_sizes = index2_stat_n_sample_sizes;
index2.stat_index_size = TEST_IDX2_INDEX_SIZE;
index2.stat_n_leaf_pages = TEST_IDX2_N_LEAF_PAGES;
index2_fields[0].name = TEST_IDX2_COL1_NAME;
index2_fields[1].name = TEST_IDX2_COL2_NAME;
index2_fields[2].name = TEST_IDX2_COL3_NAME;
index2_fields[3].name = TEST_IDX2_COL4_NAME;
index2_stat_n_diff_key_vals[0] = TEST_IDX2_N_DIFF1;
index2_stat_n_diff_key_vals[1] = TEST_IDX2_N_DIFF2;
index2_stat_n_diff_key_vals[2] = TEST_IDX2_N_DIFF3;
index2_stat_n_diff_key_vals[3] = TEST_IDX2_N_DIFF4;
index2_stat_n_sample_sizes[0] = TEST_IDX2_N_DIFF1_SAMPLE_SIZE;
index2_stat_n_sample_sizes[1] = TEST_IDX2_N_DIFF2_SAMPLE_SIZE;
index2_stat_n_sample_sizes[2] = TEST_IDX2_N_DIFF3_SAMPLE_SIZE;
index2_stat_n_sample_sizes[3] = TEST_IDX2_N_DIFF4_SAMPLE_SIZE;
ret = dict_stats_save(&table, NULL);
ut_a(ret == DB_SUCCESS);
printf("\nOK: stats saved successfully, now go ahead and read"
" what's inside %s and %s:\n\n",
TABLE_STATS_NAME_PRINT,
INDEX_STATS_NAME_PRINT);
printf("SELECT COUNT(*) = 1 AS table_stats_saved_successfully\n"
"FROM %s\n"
"WHERE\n"
"database_name = '%s' AND\n"
"table_name = '%s' AND\n"
"n_rows = %d AND\n"
"clustered_index_size = %d AND\n"
"sum_of_other_index_sizes = %d;\n"
"\n",
TABLE_STATS_NAME_PRINT,
TEST_DATABASE_NAME,
TEST_TABLE_NAME,
TEST_N_ROWS,
TEST_CLUSTERED_INDEX_SIZE,
TEST_SUM_OF_OTHER_INDEX_SIZES);
printf("SELECT COUNT(*) = 3 AS tidx1_stats_saved_successfully\n"
"FROM %s\n"
"WHERE\n"
"database_name = '%s' AND\n"
"table_name = '%s' AND\n"
"index_name = '%s' AND\n"
"(\n"
" (stat_name = 'size' AND stat_value = %d AND"
" sample_size IS NULL) OR\n"
" (stat_name = 'n_leaf_pages' AND stat_value = %d AND"
" sample_size IS NULL) OR\n"
" (stat_name = 'n_diff_pfx01' AND stat_value = %d AND"
" sample_size = '%d' AND stat_description = '%s')\n"
");\n"
"\n",
INDEX_STATS_NAME_PRINT,
TEST_DATABASE_NAME,
TEST_TABLE_NAME,
TEST_IDX1_NAME,
TEST_IDX1_INDEX_SIZE,
TEST_IDX1_N_LEAF_PAGES,
TEST_IDX1_N_DIFF1,
TEST_IDX1_N_DIFF1_SAMPLE_SIZE,
TEST_IDX1_COL1_NAME);
printf("SELECT COUNT(*) = 6 AS tidx2_stats_saved_successfully\n"
"FROM %s\n"
"WHERE\n"
"database_name = '%s' AND\n"
"table_name = '%s' AND\n"
"index_name = '%s' AND\n"
"(\n"
" (stat_name = 'size' AND stat_value = %d AND"
" sample_size IS NULL) OR\n"
" (stat_name = 'n_leaf_pages' AND stat_value = %d AND"
" sample_size IS NULL) OR\n"
" (stat_name = 'n_diff_pfx01' AND stat_value = %d AND"
" sample_size = '%d' AND stat_description = '%s') OR\n"
" (stat_name = 'n_diff_pfx02' AND stat_value = %d AND"
" sample_size = '%d' AND stat_description = '%s,%s') OR\n"
" (stat_name = 'n_diff_pfx03' AND stat_value = %d AND"
" sample_size = '%d' AND stat_description = '%s,%s,%s') OR\n"
" (stat_name = 'n_diff_pfx04' AND stat_value = %d AND"
" sample_size = '%d' AND stat_description = '%s,%s,%s,%s')\n"
");\n"
"\n",
INDEX_STATS_NAME_PRINT,
TEST_DATABASE_NAME,
TEST_TABLE_NAME,
TEST_IDX2_NAME,
TEST_IDX2_INDEX_SIZE,
TEST_IDX2_N_LEAF_PAGES,
TEST_IDX2_N_DIFF1,
TEST_IDX2_N_DIFF1_SAMPLE_SIZE, TEST_IDX2_COL1_NAME,
TEST_IDX2_N_DIFF2,
TEST_IDX2_N_DIFF2_SAMPLE_SIZE,
TEST_IDX2_COL1_NAME, TEST_IDX2_COL2_NAME,
TEST_IDX2_N_DIFF3,
TEST_IDX2_N_DIFF3_SAMPLE_SIZE,
TEST_IDX2_COL1_NAME, TEST_IDX2_COL2_NAME, TEST_IDX2_COL3_NAME,
TEST_IDX2_N_DIFF4,
TEST_IDX2_N_DIFF4_SAMPLE_SIZE,
TEST_IDX2_COL1_NAME, TEST_IDX2_COL2_NAME, TEST_IDX2_COL3_NAME,
TEST_IDX2_COL4_NAME);
}
/* @} */
/* test_dict_stats_fetch_from_ps() @{ */
void
test_dict_stats_fetch_from_ps()
{
dict_table_t table;
dict_index_t index1;
ib_uint64_t index1_stat_n_diff_key_vals[1];
ib_uint64_t index1_stat_n_sample_sizes[1];
dict_index_t index2;
ib_uint64_t index2_stat_n_diff_key_vals[4];
ib_uint64_t index2_stat_n_sample_sizes[4];
dberr_t ret;
/* craft a dummy dict_table_t */
table.name.m_name = (char*) (TEST_DATABASE_NAME "/" TEST_TABLE_NAME);
UT_LIST_INIT(table.indexes, &dict_index_t::indexes);
UT_LIST_ADD_LAST(table.indexes, &index1);
UT_LIST_ADD_LAST(table.indexes, &index2);
ut_d(table.magic_n = DICT_TABLE_MAGIC_N);
index1.name = TEST_IDX1_NAME;
ut_d(index1.magic_n = DICT_INDEX_MAGIC_N);
index1.cached = 1;
index1.n_uniq = 1;
index1.stat_n_diff_key_vals = index1_stat_n_diff_key_vals;
index1.stat_n_sample_sizes = index1_stat_n_sample_sizes;
index2.name = TEST_IDX2_NAME;
ut_d(index2.magic_n = DICT_INDEX_MAGIC_N);
index2.cached = 1;
index2.n_uniq = 4;
index2.stat_n_diff_key_vals = index2_stat_n_diff_key_vals;
index2.stat_n_sample_sizes = index2_stat_n_sample_sizes;
ret = dict_stats_fetch_from_ps(&table);
ut_a(ret == DB_SUCCESS);
ut_a(table.stat_n_rows == TEST_N_ROWS);
ut_a(table.stat_clustered_index_size == TEST_CLUSTERED_INDEX_SIZE);
ut_a(table.stat_sum_of_other_index_sizes
== TEST_SUM_OF_OTHER_INDEX_SIZES);
ut_a(index1.stat_index_size == TEST_IDX1_INDEX_SIZE);
ut_a(index1.stat_n_leaf_pages == TEST_IDX1_N_LEAF_PAGES);
ut_a(index1_stat_n_diff_key_vals[0] == TEST_IDX1_N_DIFF1);
ut_a(index1_stat_n_sample_sizes[0] == TEST_IDX1_N_DIFF1_SAMPLE_SIZE);
ut_a(index2.stat_index_size == TEST_IDX2_INDEX_SIZE);
ut_a(index2.stat_n_leaf_pages == TEST_IDX2_N_LEAF_PAGES);
ut_a(index2_stat_n_diff_key_vals[0] == TEST_IDX2_N_DIFF1);
ut_a(index2_stat_n_sample_sizes[0] == TEST_IDX2_N_DIFF1_SAMPLE_SIZE);
ut_a(index2_stat_n_diff_key_vals[1] == TEST_IDX2_N_DIFF2);
ut_a(index2_stat_n_sample_sizes[1] == TEST_IDX2_N_DIFF2_SAMPLE_SIZE);
ut_a(index2_stat_n_diff_key_vals[2] == TEST_IDX2_N_DIFF3);
ut_a(index2_stat_n_sample_sizes[2] == TEST_IDX2_N_DIFF3_SAMPLE_SIZE);
ut_a(index2_stat_n_diff_key_vals[3] == TEST_IDX2_N_DIFF4);
ut_a(index2_stat_n_sample_sizes[3] == TEST_IDX2_N_DIFF4_SAMPLE_SIZE);
printf("OK: fetch successful\n");
}
/* @} */
/* test_dict_stats_all() @{ */
void
test_dict_stats_all()
{
test_dict_table_schema_check();
test_dict_stats_save();
test_dict_stats_fetch_from_ps();
}
/* @} */
#endif /* UNIV_ENABLE_UNIT_TEST_DICT_STATS */
/* @} */
|