summaryrefslogtreecommitdiff
path: root/sql/sql_parse.cc
blob: b5d93e6fd99dcb897ba37cc865e1d25ab5bc5464 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
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
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
/* Copyright (c) 2000, 2017, Oracle and/or its affiliates.
   Copyright (c) 2008, 2023, MariaDB

   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 St, Fifth Floor, Boston, MA  02110-1335  USA */

#define MYSQL_LEX 1
#include "mariadb.h"
#include "sql_priv.h"
#include "sql_parse.h"        // sql_kill, *_precheck, *_prepare
#include "lock.h"             // try_transactional_lock,
                              // check_transactional_lock,
                              // set_handler_table_locks,
                              // lock_global_read_lock,
                              // make_global_read_lock_block_commit
#include "sql_base.h"         // open_tables, open_and_lock_tables,
                              // lock_tables, unique_table,
                              // close_thread_tables, is_temporary_table
                              // table_cache.h
#include "sql_cache.h"        // QUERY_CACHE_FLAGS_SIZE, query_cache_*
#include "sql_show.h"         // mysqld_list_*, mysqld_show_*,
                              // calc_sum_of_all_status
#include "mysqld.h"
#include "sql_locale.h"                         // my_locale_en_US
#include "log.h"                                // flush_error_log
#include "sql_view.h"         // mysql_create_view, mysql_drop_view
#include "sql_delete.h"       // mysql_delete
#include "sql_insert.h"       // mysql_insert
#include "sql_update.h"       // mysql_update, mysql_multi_update
#include "sql_partition.h"    // struct partition_info
#include "sql_db.h"           // mysql_change_db, mysql_create_db,
                              // mysql_rm_db, mysql_upgrade_db,
                              // mysql_alter_db,
                              // check_db_dir_existence,
                              // my_dbopt_cleanup
#include "sql_table.h"        // mysql_alter_table,
                              // mysql_backup_table,
                              // mysql_restore_table
#include "sql_reload.h"       // reload_acl_and_cache
#include "sql_admin.h"        // mysql_assign_to_keycache
#include "sql_connect.h"      // decrease_user_connections,
                              // check_mqh,
                              // reset_mqh
#include "sql_rename.h"       // mysql_rename_tables
#include "hostname.h"         // hostname_cache_refresh
#include "sql_test.h"         // mysql_print_status
#include "sql_select.h"       // handle_select, mysql_select,
                              // mysql_explain_union
#include "sql_load.h"         // mysql_load
#include "sql_servers.h"      // create_servers, alter_servers,
                              // drop_servers, servers_reload
#include "sql_handler.h"      // mysql_ha_open, mysql_ha_close,
                              // mysql_ha_read
#include "sql_binlog.h"       // mysql_client_binlog_statement
#include "sql_do.h"           // mysql_do
#include "sql_help.h"         // mysqld_help
#include "rpl_constants.h"    // Incident, INCIDENT_LOST_EVENTS
#include "log_event.h"
#include "sql_repl.h"
#include "rpl_filter.h"
#include "repl_failsafe.h"
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>
#include "rpl_mi.h"

#include "sql_digest.h"

#include "sp_head.h"
#include "sp.h"
#include "sp_cache.h"
#include "events.h"
#include "sql_trigger.h"
#include "transaction.h"
#include "sql_alter.h"
#include "sql_audit.h"
#include "sql_prepare.h"
#include "sql_cte.h"
#include "debug_sync.h"
#include "probes_mysql.h"
#include "set_var.h"
#include "sql_bootstrap.h"
#include "sql_sequence.h"
#include "opt_trace.h"
#include "mysql/psi/mysql_sp.h"

#include "my_json_writer.h" 

#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")

#ifdef WITH_ARIA_STORAGE_ENGINE
#include "../storage/maria/ha_maria.h"
#endif

#include "wsrep.h"
#include "wsrep_mysqld.h"
#ifdef WITH_WSREP
#include "wsrep_thd.h"
#include "wsrep_trans_observer.h" /* wsrep transaction hooks */

static bool wsrep_mysql_parse(THD *thd, char *rawbuf, uint length,
                              Parser_state *parser_state);

#endif /* WITH_WSREP */
/**
  @defgroup Runtime_Environment Runtime Environment
  @{
*/

static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
static void sql_kill(THD *thd, my_thread_id id, killed_state state, killed_type type);
static void sql_kill_user(THD *thd, LEX_USER *user, killed_state state);
static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables);
static bool execute_show_status(THD *, TABLE_LIST *);
static bool check_rename_table(THD *, TABLE_LIST *, TABLE_LIST *);
static bool generate_incident_event(THD *thd);
static int  show_create_db(THD *thd, LEX *lex);
static bool alter_routine(THD *thd, LEX *lex);
static bool drop_routine(THD *thd, LEX *lex);

const LEX_CSTRING any_db= {STRING_WITH_LEN("*any*")};

const LEX_CSTRING command_name[257]={
  { STRING_WITH_LEN("Sleep") },           //0
  { STRING_WITH_LEN("Quit") },            //1
  { STRING_WITH_LEN("Init DB") },         //2
  { STRING_WITH_LEN("Query") },           //3
  { STRING_WITH_LEN("Field List") },      //4
  { STRING_WITH_LEN("Create DB") },       //5
  { STRING_WITH_LEN("Drop DB") },         //6
  { STRING_WITH_LEN("Refresh") },         //7
  { STRING_WITH_LEN("Shutdown") },        //8
  { STRING_WITH_LEN("Statistics") },      //9
  { STRING_WITH_LEN("Processlist") },     //10
  { STRING_WITH_LEN("Connect") },         //11
  { STRING_WITH_LEN("Kill") },            //12
  { STRING_WITH_LEN("Debug") },           //13
  { STRING_WITH_LEN("Ping") },            //14
  { STRING_WITH_LEN("Time") },            //15
  { STRING_WITH_LEN("Delayed insert") },  //16
  { STRING_WITH_LEN("Change user") },     //17
  { STRING_WITH_LEN("Binlog Dump") },     //18
  { STRING_WITH_LEN("Table Dump") },      //19
  { STRING_WITH_LEN("Connect Out") },     //20
  { STRING_WITH_LEN("Register Slave") },  //21
  { STRING_WITH_LEN("Prepare") },         //22
  { STRING_WITH_LEN("Execute") },         //23
  { STRING_WITH_LEN("Long Data") },       //24
  { STRING_WITH_LEN("Close stmt") },      //25
  { STRING_WITH_LEN("Reset stmt") },      //26
  { STRING_WITH_LEN("Set option") },      //27
  { STRING_WITH_LEN("Fetch") },           //28
  { STRING_WITH_LEN("Daemon") },          //29
  { STRING_WITH_LEN("Unimpl get tid") },  //30
  { STRING_WITH_LEN("Reset connection") },//31
  { 0, 0 }, //32
  { 0, 0 }, //33
  { 0, 0 }, //34
  { 0, 0 }, //35
  { 0, 0 }, //36
  { 0, 0 }, //37
  { 0, 0 }, //38
  { 0, 0 }, //39
  { 0, 0 }, //40
  { 0, 0 }, //41
  { 0, 0 }, //42
  { 0, 0 }, //43
  { 0, 0 }, //44
  { 0, 0 }, //45
  { 0, 0 }, //46
  { 0, 0 }, //47
  { 0, 0 }, //48
  { 0, 0 }, //49
  { 0, 0 }, //50
  { 0, 0 }, //51
  { 0, 0 }, //52
  { 0, 0 }, //53
  { 0, 0 }, //54
  { 0, 0 }, //55
  { 0, 0 }, //56
  { 0, 0 }, //57
  { 0, 0 }, //58
  { 0, 0 }, //59
  { 0, 0 }, //60
  { 0, 0 }, //61
  { 0, 0 }, //62
  { 0, 0 }, //63
  { 0, 0 }, //64
  { 0, 0 }, //65
  { 0, 0 }, //66
  { 0, 0 }, //67
  { 0, 0 }, //68
  { 0, 0 }, //69
  { 0, 0 }, //70
  { 0, 0 }, //71
  { 0, 0 }, //72
  { 0, 0 }, //73
  { 0, 0 }, //74
  { 0, 0 }, //75
  { 0, 0 }, //76
  { 0, 0 }, //77
  { 0, 0 }, //78
  { 0, 0 }, //79
  { 0, 0 }, //80
  { 0, 0 }, //81
  { 0, 0 }, //82
  { 0, 0 }, //83
  { 0, 0 }, //84
  { 0, 0 }, //85
  { 0, 0 }, //86
  { 0, 0 }, //87
  { 0, 0 }, //88
  { 0, 0 }, //89
  { 0, 0 }, //90
  { 0, 0 }, //91
  { 0, 0 }, //92
  { 0, 0 }, //93
  { 0, 0 }, //94
  { 0, 0 }, //95
  { 0, 0 }, //96
  { 0, 0 }, //97
  { 0, 0 }, //98
  { 0, 0 }, //99
  { 0, 0 }, //100
  { 0, 0 }, //101
  { 0, 0 }, //102
  { 0, 0 }, //103
  { 0, 0 }, //104
  { 0, 0 }, //105
  { 0, 0 }, //106
  { 0, 0 }, //107
  { 0, 0 }, //108
  { 0, 0 }, //109
  { 0, 0 }, //110
  { 0, 0 }, //111
  { 0, 0 }, //112
  { 0, 0 }, //113
  { 0, 0 }, //114
  { 0, 0 }, //115
  { 0, 0 }, //116
  { 0, 0 }, //117
  { 0, 0 }, //118
  { 0, 0 }, //119
  { 0, 0 }, //120
  { 0, 0 }, //121
  { 0, 0 }, //122
  { 0, 0 }, //123
  { 0, 0 }, //124
  { 0, 0 }, //125
  { 0, 0 }, //126
  { 0, 0 }, //127
  { 0, 0 }, //128
  { 0, 0 }, //129
  { 0, 0 }, //130
  { 0, 0 }, //131
  { 0, 0 }, //132
  { 0, 0 }, //133
  { 0, 0 }, //134
  { 0, 0 }, //135
  { 0, 0 }, //136
  { 0, 0 }, //137
  { 0, 0 }, //138
  { 0, 0 }, //139
  { 0, 0 }, //140
  { 0, 0 }, //141
  { 0, 0 }, //142
  { 0, 0 }, //143
  { 0, 0 }, //144
  { 0, 0 }, //145
  { 0, 0 }, //146
  { 0, 0 }, //147
  { 0, 0 }, //148
  { 0, 0 }, //149
  { 0, 0 }, //150
  { 0, 0 }, //151
  { 0, 0 }, //152
  { 0, 0 }, //153
  { 0, 0 }, //154
  { 0, 0 }, //155
  { 0, 0 }, //156
  { 0, 0 }, //157
  { 0, 0 }, //158
  { 0, 0 }, //159
  { 0, 0 }, //160
  { 0, 0 }, //161
  { 0, 0 }, //162
  { 0, 0 }, //163
  { 0, 0 }, //164
  { 0, 0 }, //165
  { 0, 0 }, //166
  { 0, 0 }, //167
  { 0, 0 }, //168
  { 0, 0 }, //169
  { 0, 0 }, //170
  { 0, 0 }, //171
  { 0, 0 }, //172
  { 0, 0 }, //173
  { 0, 0 }, //174
  { 0, 0 }, //175
  { 0, 0 }, //176
  { 0, 0 }, //177
  { 0, 0 }, //178
  { 0, 0 }, //179
  { 0, 0 }, //180
  { 0, 0 }, //181
  { 0, 0 }, //182
  { 0, 0 }, //183
  { 0, 0 }, //184
  { 0, 0 }, //185
  { 0, 0 }, //186
  { 0, 0 }, //187
  { 0, 0 }, //188
  { 0, 0 }, //189
  { 0, 0 }, //190
  { 0, 0 }, //191
  { 0, 0 }, //192
  { 0, 0 }, //193
  { 0, 0 }, //194
  { 0, 0 }, //195
  { 0, 0 }, //196
  { 0, 0 }, //197
  { 0, 0 }, //198
  { 0, 0 }, //199
  { 0, 0 }, //200
  { 0, 0 }, //201
  { 0, 0 }, //202
  { 0, 0 }, //203
  { 0, 0 }, //204
  { 0, 0 }, //205
  { 0, 0 }, //206
  { 0, 0 }, //207
  { 0, 0 }, //208
  { 0, 0 }, //209
  { 0, 0 }, //210
  { 0, 0 }, //211
  { 0, 0 }, //212
  { 0, 0 }, //213
  { 0, 0 }, //214
  { 0, 0 }, //215
  { 0, 0 }, //216
  { 0, 0 }, //217
  { 0, 0 }, //218
  { 0, 0 }, //219
  { 0, 0 }, //220
  { 0, 0 }, //221
  { 0, 0 }, //222
  { 0, 0 }, //223
  { 0, 0 }, //224
  { 0, 0 }, //225
  { 0, 0 }, //226
  { 0, 0 }, //227
  { 0, 0 }, //228
  { 0, 0 }, //229
  { 0, 0 }, //230
  { 0, 0 }, //231
  { 0, 0 }, //232
  { 0, 0 }, //233
  { 0, 0 }, //234
  { 0, 0 }, //235
  { 0, 0 }, //236
  { 0, 0 }, //237
  { 0, 0 }, //238
  { 0, 0 }, //239
  { 0, 0 }, //240
  { 0, 0 }, //241
  { 0, 0 }, //242
  { 0, 0 }, //243
  { 0, 0 }, //244
  { 0, 0 }, //245
  { 0, 0 }, //246
  { 0, 0 }, //247
  { 0, 0 }, //248
  { 0, 0 }, //249
  { STRING_WITH_LEN("Bulk_execute") }, //250
  { STRING_WITH_LEN("Slave_worker") }, //251
  { STRING_WITH_LEN("Slave_IO") }, //252
  { STRING_WITH_LEN("Slave_SQL") }, //253
  { 0, 0},
  { STRING_WITH_LEN("Error") }  // Last command number 255
};

#ifdef HAVE_REPLICATION
/**
  Returns true if all tables should be ignored.
*/
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
  Rpl_filter *rpl_filter= thd->system_thread_info.rpl_sql_info->rpl_filter;
  return rpl_filter->is_on() && tables && !thd->spcont &&
         !rpl_filter->tables_ok(thd->db.str, tables);
}
#endif


static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
{
  for (TABLE_LIST *table= tables; table; table= table->next_global)
  {
    DBUG_ASSERT(table->db.str && table->table_name.str);
    if (table->updating && !thd->find_tmp_table_share(table))
      return 1;
  }
  return 0;
}


/*
  Check whether the statement implicitly commits an active transaction.

  @param thd    Thread handle.
  @param mask   Bitmask used for the SQL command match.

  @return 0     No implicit commit
  @return 1     Do a commit
*/
bool stmt_causes_implicit_commit(THD *thd, uint mask)
{
  LEX *lex= thd->lex;
  bool skip= FALSE;
  DBUG_ENTER("stmt_causes_implicit_commit");

  if (!(sql_command_flags[lex->sql_command] & mask))
    DBUG_RETURN(FALSE);

  switch (lex->sql_command) {
  case SQLCOM_ALTER_TABLE:
  case SQLCOM_ALTER_SEQUENCE:
    /* If ALTER TABLE of non-temporary table, do implicit commit */
    skip= (lex->tmp_table());
    break;
  case SQLCOM_DROP_TABLE:
  case SQLCOM_DROP_SEQUENCE:
  case SQLCOM_CREATE_TABLE:
  case SQLCOM_CREATE_SEQUENCE:
    /*
      If CREATE TABLE of non-temporary table and the table is not part
      if a BEGIN GTID ... COMMIT group, do a implicit commit.
      This ensures that CREATE ... SELECT will in the same GTID group on the
      master and slave.
    */
    skip= (lex->tmp_table() ||
           (thd->variables.option_bits & OPTION_GTID_BEGIN));
    break;
  case SQLCOM_SET_OPTION:
    skip= lex->autocommit ? FALSE : TRUE;
    break;
  default:
    break;
  }

  DBUG_RETURN(!skip);
}


/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.

  sql_command is actually set to SQLCOM_END sometimes
  so we need the +1 to include it in the array.

  See COMMAND_FLAG_xxx for different type of commands
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
*/

uint sql_command_flags[SQLCOM_END+1];
uint server_command_flags[COM_END+1];

void init_update_queries(void)
{
  /* Initialize the server command flags array. */
  memset(server_command_flags, 0, sizeof(server_command_flags));

  server_command_flags[COM_STATISTICS]= CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_PING]=       CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;

  server_command_flags[COM_QUIT]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_PROCESS_INFO]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_PROCESS_KILL]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SHUTDOWN]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SLEEP]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_TIME]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_INIT_DB]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_END]= CF_SKIP_WSREP_CHECK;
  for (uint i= COM_MDB_GAP_BEG; i <= COM_MDB_GAP_END; i++)
  {
    server_command_flags[i]= CF_SKIP_WSREP_CHECK;
  }

  /*
    COM_QUERY, COM_SET_OPTION and COM_STMT_XXX are allowed to pass the early
    COM_xxx filter, they're checked later in mysql_execute_command().
  */
  server_command_flags[COM_QUERY]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SET_OPTION]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_PREPARE]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_EXECUTE]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_FETCH]=   CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_CLOSE]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_RESET]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_EXECUTE]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_SEND_LONG_DATA]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_REGISTER_SLAVE]= CF_SKIP_WSREP_CHECK;

  /* Initialize the sql command flags array. */
  memset(sql_command_flags, 0, sizeof(sql_command_flags));

  /*
    In general, DDL statements do not generate row events and do not go
    through a cache before being written to the binary log. However, the
    CREATE TABLE...SELECT is an exception because it may generate row
    events. For that reason,  the SQLCOM_CREATE_TABLE  which represents
    a CREATE TABLE, including the CREATE TABLE...SELECT, has the
    CF_CAN_GENERATE_ROW_EVENTS flag. The distinction between a regular
    CREATE TABLE and the CREATE TABLE...SELECT is made in other parts of
    the code, in particular in the Query_log_event's constructor.
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_SCHEMA_CHANGE;
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]=  (CF_CHANGES_DATA |
                                            CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS |
                                            CF_SCHEMA_CHANGE);
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS |
                                            CF_ADMIN_COMMAND | CF_REPORT_PROGRESS;
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
                                            CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS |
                                            CF_INSERTS_DATA | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_ALTER_SEQUENCE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
                                            CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE |
                                            CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
                                            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE;
  sql_command_flags[SQLCOM_DROP_SEQUENCE]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE;
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS | CF_REPORT_PROGRESS |
                                            CF_INSERTS_DATA;
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
  sql_command_flags[SQLCOM_CREATE_PACKAGE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_PACKAGE_BODY]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE_BODY]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB]=       CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS |
                                            CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_VIEW]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_EVENT]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_EVENT]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;

  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_UPDATES_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE;
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_UPDATES_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE;
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE |
                                            CF_PS_ARRAY_BINDING_OPTIMIZED;
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA;
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_DELETES_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE;
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_DELETES_DATA;
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE |
                                            CF_PS_ARRAY_BINDING_OPTIMIZED;
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA;
  sql_command_flags[SQLCOM_SELECT]=         CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED;
  // (1) so that subquery is traced when doing "SET @var = (subquery)"
  /*
    @todo SQLCOM_SET_OPTION should have CF_CAN_GENERATE_ROW_EVENTS
    set, because it may invoke a stored function that generates row
    events. /Sven
  */
  sql_command_flags[SQLCOM_SET_OPTION]=     CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE; // (1)
  // (1) so that subquery is traced when doing "DO @var := (subquery)"
  sql_command_flags[SQLCOM_DO]=             CF_REEXECUTION_FRAGILE |
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE; // (1)

  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS_PACKAGE]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS_PACKAGE_BODY]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_TRIGGERS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_EVENTS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_GENERIC]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_BINLOGS]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_AUTHORS]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PRIVILEGES]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_WARNS]=       CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
  sql_command_flags[SQLCOM_SHOW_ERRORS]=      CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_EXPLAIN]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ANALYZE]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_GRANTS]=      CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_USER]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOG_STAT]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_PACKAGE]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_PACKAGE_BODY]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_PROC_CODE]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_FUNC_CODE]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PACKAGE_BODY_CODE]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILES]=    CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILE]=     CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_BINLOG_BASE64_EVENT]= CF_STATUS_COMMAND | CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE);
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE);


  sql_command_flags[SQLCOM_CREATE_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_RENAME_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_USER]=         CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_ALTER_USER]=        CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_ROLE]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_GRANT]=             CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_GRANT_ROLE]=        CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_REVOKE]=            CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_REVOKE_ROLE]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_OPTIMIZE]=          CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_CREATE_FUNCTION]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;

  /*
    The following is used to preserver CF_ROW_COUNT during the
    a CALL or EXECUTE statement, so the value generated by the
    last called (or executed) statement is preserved.
    See mysql_execute_command() for how CF_ROW_COUNT is used.
  */
  /*
    (1): without it, in "CALL some_proc((subq))", subquery would not be
    traced.
  */
  sql_command_flags[SQLCOM_CALL]=      CF_REEXECUTION_FRAGILE |
                                       CF_CAN_GENERATE_ROW_EVENTS |
                                       CF_OPTIMIZER_TRACE; // (1)
  sql_command_flags[SQLCOM_EXECUTE]=   CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_EXECUTE_IMMEDIATE]= CF_CAN_GENERATE_ROW_EVENTS;
  sql_command_flags[SQLCOM_COMPOUND]=  CF_CAN_GENERATE_ROW_EVENTS;

  /*
    We don't want to change to statement based replication for these commands
  */
  sql_command_flags[SQLCOM_ROLLBACK]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate ALTER TABLE for temp tables in row format */
  sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate TRUNCATE for temp tables in row format */
  sql_command_flags[SQLCOM_TRUNCATE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate DROP for temp tables in row format */
  sql_command_flags[SQLCOM_DROP_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate CREATE/DROP INDEX for temp tables in row format */
  sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  sql_command_flags[SQLCOM_DROP_INDEX]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* One can change replication mode with SET */
  sql_command_flags[SQLCOM_SET_OPTION]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;

  /*
    The following admin table operations are allowed
    on log tables.
  */
  sql_command_flags[SQLCOM_REPAIR]=    CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_ANALYZE]=   CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_CHECK]=     CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_CHECKSUM]=  CF_REPORT_PROGRESS;

  sql_command_flags[SQLCOM_CREATE_USER]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_USER]|=        CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_USER]|=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_RENAME_USER]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_ROLE]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_ROLE]|=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_REVOKE]|=            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_REVOKE_ALL]=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_REVOKE_ROLE]|=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_GRANT]|=             CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_GRANT_ROLE]|=        CF_AUTO_COMMIT_TRANS;

  sql_command_flags[SQLCOM_FLUSH]=              CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_RESET]=              CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_SERVER]=      CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_SERVER]=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_SERVER]=        CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_BACKUP]=             CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_BACKUP_LOCK]=        CF_AUTO_COMMIT_TRANS;

  /*
    The following statements can deal with temporary tables,
    so temporary tables should be pre-opened for those statements to
    simplify privilege checking.

    There are other statements that deal with temporary tables and open
    them, but which are not listed here. The thing is that the order of
    pre-opening temporary tables for those statements is somewhat custom.

    Note that SQLCOM_RENAME_TABLE should not be in this list!
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CREATE_INDEX]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=     CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_TRUNCATE]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_LOAD]|=            CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DROP_INDEX]|=      CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_UPDATE]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_UPDATE_MULTI]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_INSERT_SELECT]|=   CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DELETE]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DELETE_MULTI]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_REPLACE_SELECT]|=  CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_SELECT]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_SET_OPTION]|=      CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DO]|=              CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_HA_OPEN]|=         CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CALL]|=            CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CHECKSUM]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ANALYZE]|=         CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CHECK]|=           CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_OPTIMIZE]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_REPAIR]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_PRELOAD_KEYS]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_PREOPEN_TMP_TABLES;

  /*
    DDL statements that should start with closing opened handlers.

    We use this flag only for statements for which open HANDLERs
    have to be closed before temporary tables are pre-opened.
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=    CF_HA_CLOSE;
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]|= CF_HA_CLOSE;
  sql_command_flags[SQLCOM_DROP_TABLE]|=      CF_HA_CLOSE;
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|=   CF_HA_CLOSE;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=     CF_HA_CLOSE;
  sql_command_flags[SQLCOM_TRUNCATE]|=        CF_HA_CLOSE;
  sql_command_flags[SQLCOM_REPAIR]|=          CF_HA_CLOSE;
  sql_command_flags[SQLCOM_OPTIMIZE]|=        CF_HA_CLOSE;
  sql_command_flags[SQLCOM_ANALYZE]|=         CF_HA_CLOSE;
  sql_command_flags[SQLCOM_CHECK]|=           CF_HA_CLOSE;
  sql_command_flags[SQLCOM_CREATE_INDEX]|=    CF_HA_CLOSE;
  sql_command_flags[SQLCOM_DROP_INDEX]|=      CF_HA_CLOSE;
  sql_command_flags[SQLCOM_PRELOAD_KEYS]|=    CF_HA_CLOSE;
  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|=  CF_HA_CLOSE;

  /*
    Mark statements that always are disallowed in read-only
    transactions. Note that according to the SQL standard,
    even temporary table DDL should be disallowed.
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]|=  CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_TABLE]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|=    CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_RENAME_TABLE]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_INDEX]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_INDEX]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_DB]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_DB]|=          CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_PACKAGE]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_PACKAGE_BODY]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE_BODY]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_VIEW]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_VIEW]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_TRIGGER]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_EVENT]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_EVENT]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_EVENT]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_USER]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_USER]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_RENAME_USER]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_USER]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_SERVER]|=    CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_SERVER]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_SERVER]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_FUNCTION]|=  CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]|=CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]|=    CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]|=  CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_TRUNCATE]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REPAIR]|=           CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_OPTIMIZE]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_GRANT]|=            CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REVOKE]|=           CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REVOKE_ALL]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS;
#ifdef WITH_WSREP
  /*
    Statements for which some errors are ignored when
    wsrep_ignore_apply_errors = WSREP_IGNORE_ERRORS_ON_RECONCILING_DDL
  */
  sql_command_flags[SQLCOM_DROP_DB]|=          CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_DROP_TABLE]|=       CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_DROP_INDEX]|=       CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=      CF_WSREP_MAY_IGNORE_ERRORS;
#endif /* WITH_WSREP */
}

bool sqlcom_can_generate_row_events(const THD *thd)
{
  return (sql_command_flags[thd->lex->sql_command] &
          CF_CAN_GENERATE_ROW_EVENTS);
}
 
bool is_update_query(enum enum_sql_command command)
{
  DBUG_ASSERT(command <= SQLCOM_END);
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
}

/**
  Check if a sql command is allowed to write to log tables.
  @param command The SQL command
  @return true if writing is allowed
*/
bool is_log_table_write_query(enum enum_sql_command command)
{
  DBUG_ASSERT(command <= SQLCOM_END);
  return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0;
}

void execute_init_command(THD *thd, LEX_STRING *init_command,
                          mysql_rwlock_t *var_lock)
{
  Vio* save_vio;
  ulonglong save_client_capabilities;

  mysql_rwlock_rdlock(var_lock);
  if (!init_command->length)
  {
    mysql_rwlock_unlock(var_lock);
    return;
  }

  /*
    copy the value under a lock, and release the lock.
    init_command has to be executed without a lock held,
    as it may try to change itself
  */
  size_t len= init_command->length;
  char *buf= thd->strmake(init_command->str, len);
  mysql_rwlock_unlock(var_lock);

  THD_STAGE_INFO(thd, stage_execution_of_init_command);
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
  /*
    We don't need return result of execution to client side.
    To forbid this we should set thd->net.vio to 0.
  */
  save_vio= thd->net.vio;
  thd->net.vio= 0;
  thd->clear_error(1);
  dispatch_command(COM_QUERY, thd, buf, (uint)len);
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;

}


static char *fgets_fn(char *buffer, size_t size, fgets_input_t input, int *error)
{
  MYSQL_FILE *in= static_cast<MYSQL_FILE*> (input);
  char *line= mysql_file_fgets(buffer, (int)size, in);
  if (unlikely(error))
    *error= (line == NULL) ? ferror(in->m_file) : 0;
  return line;
}


int bootstrap(MYSQL_FILE *file)
{
  int bootstrap_error= 0;
  DBUG_ENTER("handle_bootstrap");

  THD *thd= new THD(next_thread_id());
  char *buffer= new char[MAX_BOOTSTRAP_QUERY_SIZE];
#ifdef WITH_WSREP
  thd->variables.wsrep_on= 0;
#endif
  thd->bootstrap=1;
  my_net_init(&thd->net,(st_vio*) 0, thd, MYF(0));
  thd->max_client_packet_length= thd->net.max_packet;
  thd->security_ctx->master_access= ALL_KNOWN_ACL;

#ifndef EMBEDDED_LIBRARY
  mysql_thread_set_psi_id(thd->thread_id);
#else
  thd->mysql= 0;
#endif

  /* The following must be called before DBUG_ENTER */
  thd->thread_stack= (char*) &thd;
  thd->store_globals();

  thd->security_ctx->user= (char*) my_strdup(key_memory_MPVIO_EXT_auth_info,
                                             "boot", MYF(MY_WME));
  thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]=
    thd->security_ctx->priv_role[0]= 0;
  /*
    Make the "client" handle multiple results. This is necessary
    to enable stored procedures with SELECTs and Dynamic SQL
    in init-file.
  */
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;

  thd->init_for_queries();

  for ( ; ; )
  {
    buffer[0]= 0;
    int rc, length;
    char *query;
    int error= 0;

    rc= read_bootstrap_query(buffer, &length, file, fgets_fn, 0, &error);

    if (rc == READ_BOOTSTRAP_EOF)
      break;
    /*
      Check for bootstrap file errors. SQL syntax errors will be
      caught below.
    */
    if (rc != READ_BOOTSTRAP_SUCCESS)
    {
      /*
        mysql_parse() may have set a successful error status for the previous
        query. We must clear the error status to report the bootstrap error.
      */
      thd->get_stmt_da()->reset_diagnostics_area();

      /* Get the nearest query text for reference. */
      char *err_ptr= buffer + (length <= MAX_BOOTSTRAP_ERROR_LEN ?
                                        0 : (length - MAX_BOOTSTRAP_ERROR_LEN));
      switch (rc)
      {
      case READ_BOOTSTRAP_ERROR:
        my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error, return code (%d). "
                        "Nearest query: '%s'", MYF(0), error, err_ptr);
        break;

      case READ_BOOTSTRAP_QUERY_SIZE:
        my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error. Query size "
                        "exceeded %d bytes near '%s'.", MYF(0),
                        MAX_BOOTSTRAP_QUERY_SIZE, err_ptr);
        break;

      default:
        DBUG_ASSERT(false);
        break;
      }

      thd->protocol->end_statement();
      bootstrap_error= 1;
      break;
    }

    query= (char *) thd->memdup_w_gap(buffer, length + 1,
                                      thd->db.length + 1 +
                                      QUERY_CACHE_DB_LENGTH_SIZE +
                                      QUERY_CACHE_FLAGS_SIZE);
    size_t db_len= 0;
    memcpy(query + length + 1, (char *) &db_len, sizeof(size_t));
    thd->set_query_and_id(query, length, thd->charset(), next_query_id());
    int2store(query + length + 1, 0);           // No db in bootstrap
    DBUG_PRINT("query",("%-.4096s",thd->query()));
#if defined(ENABLED_PROFILING)
    thd->profiling.start_new_query();
    thd->profiling.set_query_source(thd->query(), length);
#endif

    thd->set_time();
    Parser_state parser_state;
    if (parser_state.init(thd, thd->query(), length))
    {
      thd->protocol->end_statement();
      bootstrap_error= 1;
      break;
    }

    mysql_parse(thd, thd->query(), length, &parser_state);

    bootstrap_error= thd->is_error();
    thd->protocol->end_statement();

#if defined(ENABLED_PROFILING)
    thd->profiling.finish_current_query();
#endif
    delete_explain_query(thd->lex);

    if (unlikely(bootstrap_error))
      break;

    thd->reset_kill_query();  /* Ensure that killed_errmsg is released */
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
    thd->lex->restore_set_statement_var();
  }
  delete thd;
  delete[] buffer;
  DBUG_RETURN(bootstrap_error);
}


/* This works because items are allocated on THD::mem_root */

void free_items(Item *item)
{
  Item *next;
  DBUG_ENTER("free_items");
  for (; item ; item=next)
  {
    next=item->next;
    item->delete_self();
  }
  DBUG_VOID_RETURN;
}

/**
   This works because items are allocated on THD::mem_root.
   @note The function also handles null pointers (empty list).
*/
void cleanup_items(Item *item)
{
  DBUG_ENTER("cleanup_items");  
  for (; item ; item=item->next)
    item->cleanup();
  DBUG_VOID_RETURN;
}

#ifdef WITH_WSREP
static bool wsrep_tables_accessible_when_detached(const TABLE_LIST *tables)
{
  for (const TABLE_LIST *table= tables; table; table= table->next_global)
  {
    LEX_CSTRING db= table->db, tn= table->table_name;
    if (get_table_category(&db, &tn)  < TABLE_CATEGORY_INFORMATION)
      return false;
  }
  return tables != NULL;
}

static bool wsrep_command_no_result(char command)
{
  return (command == COM_STMT_FETCH            ||
          command == COM_STMT_SEND_LONG_DATA   ||
          command == COM_STMT_CLOSE);
}
#endif /* WITH_WSREP */
#ifndef EMBEDDED_LIBRARY
static enum enum_server_command fetch_command(THD *thd, char *packet)
{
  enum enum_server_command
    command= (enum enum_server_command) (uchar) packet[0];
  DBUG_ENTER("fetch_command");

  if (command >= COM_END ||
      (command >= COM_MDB_GAP_BEG && command <= COM_MDB_GAP_END))
    command= COM_END;				// Wrong command

  DBUG_PRINT("info",("Command on %s = %d (%s)",
                     vio_description(thd->net.vio), command,
                     command_name[command].str));
  DBUG_RETURN(command);
}

/**
  Read one command from connection and execute it (query or simple command).
  This function is to be used by different schedulers (one-thread-per-connection,
  pool-of-threads)

  For profiling to work, it must never be called recursively.

  @param thd - client connection context

  @param blocking - wait for command to finish.
                    if false (nonblocking), then the function might
                    return when command is "half-finished", with
                    DISPATCH_COMMAND_WOULDBLOCK.
                    Currenly, this can *only* happen when using
                    threadpool. The command will resume, after all outstanding
                    async operations (i.e group commit) finish.
                    Threadpool scheduler takes care of "resume".

  @retval
    DISPATCH_COMMAND_SUCCESS - success
  @retval
    DISPATCH_COMMAND_CLOSE_CONNECTION  request of THD shutdown
          (s. dispatch_command() description)
  @retval
    DISPATCH_COMMAND_WOULDBLOCK - need to wait for asynchronous operations
                                  to finish. Only returned if parameter
                                  'blocking' is false.
*/

dispatch_command_return do_command(THD *thd, bool blocking)
{
  dispatch_command_return return_value;
  char *packet= 0;
  ulong packet_length;
  NET *net= &thd->net;
  enum enum_server_command command;
  DBUG_ENTER("do_command");

#ifdef WITH_WSREP
  DBUG_ASSERT(!thd->async_state.pending_ops() ||
              (WSREP(thd) &&
               thd->wsrep_trx().state() == wsrep::transaction::s_aborted));
#else
  DBUG_ASSERT(!thd->async_state.pending_ops());
#endif

  if (thd->async_state.m_state == thd_async_state::enum_async_state::RESUMED)
  {
    /*
     Resuming previously suspended command.
     Restore the state
    */
    command = thd->async_state.m_command;
    packet = thd->async_state.m_packet.str;
    packet_length = (ulong)thd->async_state.m_packet.length;
    goto resume;
  }

  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
  thd->lex->current_select= 0;

  /*
    This thread will do a blocking read from the client which
    will be interrupted when the next command is received from
    the client, the connection is closed or "net_wait_timeout"
    number of seconds has passed.
  */
  if (!thd->skip_wait_timeout)
    my_net_set_read_timeout(net, thd->get_net_wait_timeout());

  /* Errors and diagnostics are cleared once here before query */
  thd->clear_error(1);

  net_new_transaction(net);

  /* Save for user statistics */
  thd->start_bytes_received= thd->status_var.bytes_received;

  /*
    Synchronization point for testing of KILL_CONNECTION.
    This sync point can wait here, to simulate slow code execution
    between the last test of thd->killed and blocking in read().

    The goal of this test is to verify that a connection does not
    hang, if it is killed at this point of execution.
    (Bug#37780 - main.kill fails randomly)

    Note that the sync point wait itself will be terminated by a
    kill. In this case it consumes a condition broadcast, but does
    not change anything else. The consumed broadcast should not
    matter here, because the read/recv() below doesn't use it.
  */
  DEBUG_SYNC(thd, "before_do_command_net_read");

  packet_length= my_net_read_packet(net, 1);

  if (unlikely(packet_length == packet_error))
  {
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));

    /* Instrument this broken statement as "statement/com/error" */
    thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                                 com_statement_info[COM_END].
                                                 m_key);


    /* Check if we can continue without closing the connection */

    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
    thd->protocol->end_statement();

    /* Mark the statement completed. */
    MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
    thd->m_statement_psi= NULL;
    thd->m_digest= NULL;

    if (net->error != 3)
    {
      return_value= DISPATCH_COMMAND_CLOSE_CONNECTION;     // We have to close it.
      goto out;
    }

    net->error= 0;
    return_value= DISPATCH_COMMAND_SUCCESS;
    goto out;
  }

  packet= (char*) net->read_pos;
  /*
    'packet_length' contains length of data, as it was stored in packet
    header. In case of malformed header, my_net_read returns zero.
    If packet_length is not zero, my_net_read ensures that the returned
    number of bytes was actually read from network.
    There is also an extra safety measure in my_net_read:
    it sets packet[packet_length]= 0, but only for non-zero packets.
  */
  if (packet_length == 0)                       /* safety */
  {
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
  }
  /* Do not rely on my_net_read, extra safety against programming errors. */
  packet[packet_length]= '\0';                  /* safety */


  command= fetch_command(thd, packet);

#ifdef WITH_WSREP
  DEBUG_SYNC(thd, "wsrep_before_before_command");
  /*
    If this command does not return a result, then we
    instruct wsrep_before_command() to skip result handling.
    This causes BF aborted transaction to roll back but keep
    the error state until next command which is able to return
    a result to the client.
  */
  if (unlikely(wsrep_service_started) &&
      wsrep_before_command(thd, wsrep_command_no_result(command)))
  {
    /*
      Aborted by background rollbacker thread.
      Handle error here and jump straight to out.
      Notice that thd->store_globals() is called
      in wsrep_before_command().
    */
    WSREP_LOG_THD(thd, "enter found BF aborted");
    DBUG_ASSERT(!thd->mdl_context.has_locks());
    DBUG_ASSERT(!thd->get_stmt_da()->is_set());
    /* We let COM_QUIT and COM_STMT_CLOSE to execute even if wsrep aborted. */
    if (command == COM_STMT_EXECUTE)
    {
      WSREP_DEBUG("PS BF aborted at do_command");
      thd->wsrep_delayed_BF_abort= true;
    }
    if (command != COM_STMT_CLOSE   &&
	command != COM_STMT_EXECUTE &&
        command != COM_QUIT)
    {
      my_error(ER_LOCK_DEADLOCK, MYF(0));
      WSREP_DEBUG("Deadlock error for: %s", thd->query());
      thd->reset_killed();
      thd->mysys_var->abort     = 0;
      thd->wsrep_retry_counter  = 0;

      /* Instrument this broken statement as "statement/com/error" */
      thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                                 com_statement_info[COM_END].
                                                 m_key);

      thd->protocol->end_statement();

      /* Mark the statement completed. */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
      thd->m_digest= NULL;
      return_value= DISPATCH_COMMAND_SUCCESS;

      wsrep_after_command_before_result(thd);
      goto out;
    }
  }

  if (WSREP(thd))
  {
    /*
     * bail out if DB snapshot has not been installed. We however,
     * allow queries "SET" and "SHOW", they are trapped later in execute_command
     */
    if (!(thd->wsrep_applier) &&
        (!wsrep_ready_get() || wsrep_reject_queries != WSREP_REJECT_NONE) &&
        (server_command_flags[command] & CF_SKIP_WSREP_CHECK) == 0)
    {
      my_message(ER_UNKNOWN_COM_ERROR,
                 "WSREP has not yet prepared node for application use", MYF(0));
      thd->protocol->end_statement();

      /* Performance Schema Interface instrumentation end. */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
      thd->m_digest= NULL;

      return_value= DISPATCH_COMMAND_SUCCESS;
      wsrep_after_command_before_result(thd);
      goto out;
    }
  }
#endif /* WITH_WSREP */
  /* Restore read timeout value */
  my_net_set_read_timeout(net, thd->variables.net_read_timeout);

  DBUG_ASSERT(packet_length);
  DBUG_ASSERT(!thd->apc_target.is_enabled());

resume:
  return_value= dispatch_command(command, thd, packet+1,
                                 (uint) (packet_length-1), blocking);
  if (return_value == DISPATCH_COMMAND_WOULDBLOCK)
  {
    /* Save current state, and resume later.*/
    thd->async_state.m_command= command;
    thd->async_state.m_packet={packet,packet_length};
    DBUG_RETURN(return_value);
  }

  DBUG_ASSERT(!thd->apc_target.is_enabled());

out:
  thd->lex->restore_set_statement_var();
  /* The statement instrumentation must be closed in all cases. */
  DBUG_ASSERT(thd->m_digest == NULL);
  DBUG_ASSERT(thd->m_statement_psi == NULL);
#ifdef WITH_WSREP
  if (packet_length != packet_error)
  {
    /* there was a command to process, and before_command() has been called */
    if (unlikely(wsrep_service_started))
      wsrep_after_command_after_result(thd);
  }

  if (thd->wsrep_delayed_BF_abort)
  {
      my_error(ER_LOCK_DEADLOCK, MYF(0));
      WSREP_DEBUG("Deadlock error for PS query: %s", thd->query());
      thd->reset_killed();
      thd->mysys_var->abort     = 0;
      thd->wsrep_retry_counter  = 0;

      thd->wsrep_delayed_BF_abort= false;
  }
#endif /* WITH_WSREP */
  DBUG_RETURN(return_value);
}
#endif  /* EMBEDDED_LIBRARY */

/**
  @brief Determine if an attempt to update a non-temporary table while the
    read-only option was enabled has been made.

  This is a helper function to mysql_execute_command.

  @note SQLCOM_MULTI_UPDATE is an exception and dealt with elsewhere.

  @see mysql_execute_command
  @returns Status code
    @retval TRUE The statement should be denied.
    @retval FALSE The statement isn't updating any relevant tables.
*/

static bool deny_updates_if_read_only_option(THD *thd, TABLE_LIST *all_tables)
{
  DBUG_ENTER("deny_updates_if_read_only_option");

  if (!opt_readonly)
    DBUG_RETURN(FALSE);

  LEX *lex= thd->lex;

  /* Super user is allowed to do changes */
  if ((thd->security_ctx->master_access & PRIV_IGNORE_READ_ONLY) != NO_ACL)
    DBUG_RETURN(FALSE);

  /* Check if command doesn't update anything */
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
    DBUG_RETURN(FALSE);

  /* Multi update is an exception and is dealt with later. */
  if (lex->sql_command == SQLCOM_UPDATE_MULTI)
    DBUG_RETURN(FALSE);

  /*
    a table-to-be-created is not in the temp table list yet,
    so CREATE TABLE needs a special treatment
  */
  if (lex->sql_command == SQLCOM_CREATE_TABLE)
    DBUG_RETURN(!lex->tmp_table());

  /*
    a table-to-be-dropped might not exist (DROP TEMPORARY TABLE IF EXISTS),
    cannot use the temp table list either.
  */
  if (lex->sql_command == SQLCOM_DROP_TABLE && lex->tmp_table())
    DBUG_RETURN(FALSE);

  /* Check if we created, dropped, or renamed a database */
  if ((sql_command_flags[lex->sql_command] & CF_DB_CHANGE))
    DBUG_RETURN(TRUE);

  if (some_non_temp_table_to_be_updated(thd, all_tables))
    DBUG_RETURN(TRUE);

  /* Assuming that only temporary tables are modified. */
  DBUG_RETURN(FALSE);
}

#ifdef WITH_WSREP
static void wsrep_copy_query(THD *thd)
{
  thd->wsrep_retry_command   = thd->get_command();
  thd->wsrep_retry_query_len = thd->query_length();
  if (thd->wsrep_retry_query) {
      my_free(thd->wsrep_retry_query);
  }
  thd->wsrep_retry_query = (char *)my_malloc(PSI_INSTRUMENT_ME,
                                 thd->wsrep_retry_query_len + 1, MYF(0));
  strncpy(thd->wsrep_retry_query, thd->query(), thd->wsrep_retry_query_len);
  thd->wsrep_retry_query[thd->wsrep_retry_query_len] = '\0';
}
#endif /* WITH_WSREP */



#if defined(WITH_ARIA_STORAGE_ENGINE)
class Silence_all_errors : public Internal_error_handler
{
  char m_message[MYSQL_ERRMSG_SIZE];
  int error;
public:
  Silence_all_errors():error(0) {}
  virtual ~Silence_all_errors() {}

  virtual bool handle_condition(THD *thd,
                                uint sql_errno,
                                const char* sql_state,
                                Sql_condition::enum_warning_level *level,
                                const char* msg,
                                Sql_condition ** cond_hdl)
  {
    error= sql_errno;
    *cond_hdl= NULL;
    strmake_buf(m_message, msg);
    return true;                              // Error handled
  }
};
#endif


/**
  Perform one connection-level (COM_XXXX) command.

  @param command         type of command to perform
  @param thd             connection handle
  @param packet          data for the command, packet is always null-terminated
  @param packet_length   length of packet + 1 (to show that data is
                         null-terminated) except for COM_SLEEP, where it
                         can be zero.
  @param blocking        if false (nonblocking), then the function might
                         return when command is "half-finished", with
                         DISPATCH_COMMAND_WOULDBLOCK.
                         Currenly, this can *only* happen when using threadpool.
                         The current command will resume, after all outstanding
                         async operations (i.e group commit) finish.
                         Threadpool scheduler takes care of "resume".

  @todo
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer

  @retval
    0   ok
  @retval
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
dispatch_command_return dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length, bool blocking)
{
  NET *net= &thd->net;
  bool error= 0;
  bool do_end_of_statement= true;
  DBUG_ENTER("dispatch_command");
  DBUG_PRINT("info", ("command: %d %s", command,
                      (command_name[command].str != 0 ?
                       command_name[command].str :
                       "<?>")));
  bool drop_more_results= 0;

  if (thd->async_state.m_state == thd_async_state::enum_async_state::RESUMED)
  {
    thd->async_state.m_state = thd_async_state::enum_async_state::NONE;
    goto resume;
  }

  /* keep it withing 1 byte */
  compile_time_assert(COM_END == 255);

#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query();
#endif
  MYSQL_COMMAND_START(thd->thread_id, command,
                      &thd->security_ctx->priv_user[0],
                      (char *) thd->security_ctx->host_or_ip);
  
  DBUG_EXECUTE_IF("crash_dispatch_command_before",
                  { DBUG_PRINT("crash_dispatch_command_before", ("now"));
                    DBUG_SUICIDE(); });

  /* Performance Schema Interface instrumentation, begin */
  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                               com_statement_info[command].
                                               m_key);
  /*
    We should always call reset_for_next_command() before a query.
    mysql_parse() will do this for queries. Ensure it's also done
    for other commands.
  */
  if (command != COM_QUERY)
    thd->reset_for_next_command();
  thd->set_command(command);

  thd->enable_slow_log= true;
  thd->query_plan_flags= QPLAN_INIT;
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
  thd->reset_kill_query();

  DEBUG_SYNC(thd,"dispatch_command_before_set_time");

  thd->set_time();
  if (!(server_command_flags[command] & CF_SKIP_QUERY_ID))
    thd->set_query_id(next_query_id());
  else
  {
    /*
      ping, get statistics or similar stateless command.
      No reason to increase query id here.
    */
    thd->set_query_id(get_query_id());
  }
#ifdef WITH_WSREP
  if (WSREP(thd) && thd->wsrep_next_trx_id() == WSREP_UNDEFINED_TRX_ID)
  {
    thd->set_wsrep_next_trx_id(thd->query_id);
    WSREP_DEBUG("assigned new next trx id: %" PRIu64, thd->wsrep_next_trx_id());
  }
#endif /* WITH_WSREP */

  if (!(server_command_flags[command] & CF_SKIP_QUESTIONS))
    statistic_increment(thd->status_var.questions, &LOCK_status);

  /* Copy data for user stats */
  if ((thd->userstat_running= opt_userstat_running))
  {
    thd->start_cpu_time= my_getcputime();
    memcpy(&thd->org_status_var, &thd->status_var, sizeof(thd->status_var));
    thd->select_commands= thd->update_commands= thd->other_commands= 0;
  }

  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;

  if (unlikely(thd->security_ctx->password_expired &&
               command != COM_QUERY &&
               command != COM_PING &&
               command != COM_QUIT &&
               command != COM_STMT_PREPARE &&
               command != COM_STMT_EXECUTE &&
               command != COM_STMT_CLOSE))
  {
    my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
    goto dispatch_end;
  }

  switch (command) {
  case COM_INIT_DB:
  {
    LEX_CSTRING tmp;
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
    if (unlikely(thd->copy_with_error(system_charset_info, (LEX_STRING*) &tmp,
                                      thd->charset(), packet, packet_length)))
      break;
    if (!mysql_change_db(thd, &tmp, FALSE))
    {
      general_log_write(thd, command, thd->db.str, thd->db.length);
      my_ok(thd);
    }
    break;
  }
#ifdef HAVE_REPLICATION
  case COM_REGISTER_SLAVE:
  {
    status_var_increment(thd->status_var.com_register_slave);
    if (!thd->register_slave((uchar*) packet, packet_length))
      my_ok(thd);
    break;
  }
#endif
  case COM_RESET_CONNECTION:
  {
    thd->status_var.com_other++;
#ifdef WITH_WSREP
    if (unlikely(wsrep_service_started))
    {
      wsrep_after_command_ignore_result(thd);
      wsrep_close(thd);
    }
#endif /* WITH_WSREP */
    thd->change_user();
    thd->clear_error();                         // if errors from rollback
#ifdef WITH_WSREP
    if (unlikely(wsrep_service_started))
    {
      wsrep_open(thd);
      wsrep_before_command(thd);
    }
#endif /* WITH_WSREP */
    /* Restore original charset from client authentication packet.*/
    if(thd->org_charset)
      thd->update_charset(thd->org_charset,thd->org_charset,thd->org_charset);
    my_ok(thd, 0, 0, 0);
    break;
  }
  case COM_CHANGE_USER:
  {
    int auth_rc;
    status_var_increment(thd->status_var.com_other);

#ifdef WITH_WSREP
    if (unlikely(wsrep_service_started))
    {
      wsrep_after_command_ignore_result(thd);
      wsrep_close(thd);
    }
#endif /* WITH_WSREP */
    thd->change_user();
#ifdef WITH_WSREP
    if (unlikely(wsrep_service_started))
    {
      wsrep_open(thd);
      wsrep_before_command(thd);
    }
#endif /* WITH_WSREP */
    thd->clear_error();                         // if errors from rollback

    /* acl_authenticate() takes the data from net->read_pos */
    net->read_pos= (uchar*)packet;

    LEX_CSTRING save_db= thd->db;
    USER_CONN *save_user_connect= thd->user_connect;
    Security_context save_security_ctx= *thd->security_ctx;
    CHARSET_INFO *save_character_set_client=
      thd->variables.character_set_client;
    CHARSET_INFO *save_collation_connection=
      thd->variables.collation_connection;
    CHARSET_INFO *save_character_set_results=
      thd->variables.character_set_results;

    /* Ensure we don't free security_ctx->user in case we have to revert */
    thd->security_ctx->user= 0;
    thd->user_connect= 0;

    /*
      to limit COM_CHANGE_USER ability to brute-force passwords,
      we only allow three unsuccessful COM_CHANGE_USER per connection.
    */
    if (thd->failed_com_change_user >= 3)
    {
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd,ER_UNKNOWN_COM_ERROR),
                 MYF(0));
      auth_rc= 1;
    }
    else
      auth_rc= acl_authenticate(thd, packet_length);

    mysql_audit_notify_connection_change_user(thd, &save_security_ctx);
    if (auth_rc)
    {
      /* Free user if allocated by acl_authenticate */
      my_free(const_cast<char*>(thd->security_ctx->user));
      *thd->security_ctx= save_security_ctx;
      if (thd->user_connect)
	decrease_user_connections(thd->user_connect);
      thd->user_connect= save_user_connect;
      thd->reset_db(&save_db);
      thd->update_charset(save_character_set_client, save_collation_connection,
                          save_character_set_results);
      thd->failed_com_change_user++;
      my_sleep(1000000);
    }
    else
    {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
      /* we've authenticated new user */
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
      my_free((char*) save_db.str);
      my_free(const_cast<char*>(save_security_ctx.user));
    }
    break;
  }
  case COM_STMT_BULK_EXECUTE:
  {
    mysqld_stmt_bulk_execute(thd, packet, packet_length);
#ifdef WITH_WSREP
    if (WSREP(thd))
    {
        (void)wsrep_after_statement(thd);
    }
#endif /* WITH_WSREP */
    break;
  }
  case COM_STMT_EXECUTE:
  {
    mysqld_stmt_execute(thd, packet, packet_length);
#ifdef WITH_WSREP
    if (WSREP(thd))
    {
        (void)wsrep_after_statement(thd);
    }
#endif /* WITH_WSREP */
    break;
  }
  case COM_STMT_FETCH:
  {
    mysqld_stmt_fetch(thd, packet, packet_length);
    break;
  }
  case COM_STMT_SEND_LONG_DATA:
  {
    mysql_stmt_get_longdata(thd, packet, packet_length);
    break;
  }
  case COM_STMT_PREPARE:
  {
    mysqld_stmt_prepare(thd, packet, packet_length);
    break;
  }
  case COM_STMT_CLOSE:
  {
    mysqld_stmt_close(thd, packet);
    break;
  }
  case COM_STMT_RESET:
  {
    mysqld_stmt_reset(thd, packet);
    break;
  }
  case COM_QUERY:
  {
    DBUG_ASSERT(thd->m_digest == NULL);
    thd->m_digest= & thd->m_digest_state;
    thd->m_digest->reset(thd->m_token_array, max_digest_length);

    if (unlikely(alloc_query(thd, packet, packet_length)))
      break;					// fatal error is set
    MYSQL_QUERY_START(thd->query(), thd->thread_id,
                      thd->get_db(),
                      &thd->security_ctx->priv_user[0],
                      (char *) thd->security_ctx->host_or_ip);
    char *packet_end= thd->query() + thd->query_length();
    general_log_write(thd, command, thd->query(), thd->query_length());
    DBUG_PRINT("query",("%-.4096s",thd->query()));
#if defined(ENABLED_PROFILING)
    thd->profiling.set_query_source(thd->query(), thd->query_length());
#endif
    MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(),
                             thd->query_length());

    Parser_state parser_state;
    if (unlikely(parser_state.init(thd, thd->query(), thd->query_length())))
      break;

#ifdef WITH_WSREP
    if (WSREP(thd))
    {
      if (wsrep_mysql_parse(thd, thd->query(), thd->query_length(),
                            &parser_state))
      {
        WSREP_DEBUG("Deadlock error for: %s", thd->query());
        mysql_mutex_lock(&thd->LOCK_thd_data);
        thd->reset_kill_query();
        thd->wsrep_retry_counter  = 0;
        mysql_mutex_unlock(&thd->LOCK_thd_data);
        goto dispatch_end;
      }
    }
    else
#endif /* WITH_WSREP */
      mysql_parse(thd, thd->query(), thd->query_length(), &parser_state);

    while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) &&
           ! thd->is_error())
    {
      /*
        Multiple queries exist, execute them individually
      */
      char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon;

      /* Finalize server status flags after executing a statement. */
      thd->update_server_status();
      thd->protocol->end_statement();
      query_cache_end_of_result(thd);

      mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
                          thd->get_stmt_da()->is_error()
                            ? thd->get_stmt_da()->sql_errno()
                            : 0,
                          command_name[command].str);

      ulong length= (ulong)(packet_end - beginning_of_next_stmt);

      log_slow_statement(thd);
      DBUG_ASSERT(!thd->apc_target.is_enabled());

      /* Remove garbage at start of query */
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
      {
        beginning_of_next_stmt++;
        length--;
      }

      /* PSI end */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
      thd->m_digest= NULL;

      /* DTRACE end */
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

#if defined(ENABLED_PROFILING)
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

      /* DTRACE begin */
      MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
                        thd->get_db(),
                        &thd->security_ctx->priv_user[0],
                        (char *) thd->security_ctx->host_or_ip);

      /* PSI begin */
      thd->m_digest= & thd->m_digest_state;

      thd->m_statement_psi= MYSQL_START_STATEMENT(&thd->m_statement_state,
                                                  com_statement_info[command].m_key,
                                                  thd->db.str, thd->db.length,
                                                  thd->charset(), NULL);
      THD_STAGE_INFO(thd, stage_starting);
      MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, beginning_of_next_stmt,
                               length);

      thd->set_query_and_id(beginning_of_next_stmt, length,
                            thd->charset(), next_query_id());

      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);

      if (!WSREP(thd))
        thd->set_time(); /* Reset the query start time. */

      parser_state.reset(beginning_of_next_stmt, length);

#ifdef WITH_WSREP
      if (WSREP(thd))
      {
        if (wsrep_mysql_parse(thd, beginning_of_next_stmt,
                              length, &parser_state))
        {
          WSREP_DEBUG("Deadlock error for: %s", thd->query());
          mysql_mutex_lock(&thd->LOCK_thd_data);
          thd->reset_kill_query();
          thd->wsrep_retry_counter  = 0;
          mysql_mutex_unlock(&thd->LOCK_thd_data);

          goto dispatch_end;
        }
      }
      else
#endif /* WITH_WSREP */
      mysql_parse(thd, beginning_of_next_stmt, length, &parser_state);

    }

    DBUG_PRINT("info",("query ready"));
    break;
  }
  case COM_FIELD_LIST:				// This isn't actually needed
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
    break;
#else
  {
    char *fields, *packet_end= packet + packet_length, *arg_end;
    /* Locked closure of all tables */
    TABLE_LIST table_list;
    LEX_STRING table_name;
    LEX_CSTRING db;
    /*
      SHOW statements should not add the used tables to the list of tables
      used in a transaction.
    */
    MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();

    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
    if (thd->copy_db_to(&db))
      break;
    /*
      We have name + wildcard in packet, separated by endzero
      (The packet is guaranteed to end with an end zero)
    */
    arg_end= strend(packet);
    uint arg_length= (uint)(arg_end - packet);

    /* Check given table name length. */
    if (packet_length - arg_length > NAME_LEN + 1 || arg_length > SAFE_NAME_LEN)
    {
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
                 MYF(0));
      break;
    }
    thd->convert_string(&table_name, system_charset_info,
			packet, arg_length, thd->charset());
    if (check_table_name(table_name.str, table_name.length, FALSE))
    {
      /* this is OK due to convert_string() null-terminating the string */
      my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
      break;
    }
    packet= arg_end + 1;

    lex_start(thd);
    /* Must be before we init the table list. */
    if (lower_case_table_names)
    {
      table_name.length= my_casedn_str(files_charset_info, table_name.str);
      db.length= my_casedn_str(files_charset_info, (char*) db.str);
    }
    table_list.init_one_table(&db, (LEX_CSTRING*) &table_name, 0, TL_READ);
    /*
      Init TABLE_LIST members necessary when the undelrying
      table is view.
    */
    table_list.select_lex= thd->lex->first_select_lex();
    thd->lex->
      first_select_lex()->table_list.link_in_list(&table_list,
                                                  &table_list.next_local);
    thd->lex->add_to_query_tables(&table_list);

    if (is_infoschema_db(&table_list.db))
    {
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, &table_list.alias);
      if (schema_table)
        table_list.schema_table= schema_table;
    }

    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
      break;
    thd->set_query(fields, query_length);
    general_log_print(thd, command, "%s %s", table_list.table_name.str,
                      fields);

    if (thd->open_temporary_tables(&table_list))
      break;

    if (check_table_access(thd, SELECT_ACL, &table_list,
                           TRUE, UINT_MAX, FALSE))
      break;
    /*
      Turn on an optimization relevant if the underlying table
      is a view: do not fill derived tables.
    */
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;

    mysqld_list_fields(thd,&table_list,fields);
    thd->lex->unit.cleanup();
    /* No need to rollback statement transaction, it's not started. */
    DBUG_ASSERT(thd->transaction->stmt.is_empty());
    close_thread_tables(thd);
    thd->mdl_context.rollback_to_savepoint(mdl_savepoint);

    if (thd->transaction_rollback_request)
    {
      /*
        Transaction rollback was requested since MDL deadlock was
        discovered while trying to open tables. Rollback transaction
        in all storage engines including binary log and release all
        locks.
      */
      trans_rollback_implicit(thd);
      thd->release_transactional_locks();
    }

    thd->cleanup_after_query();
    break;
  }
#endif
  case COM_QUIT:
    /* Note: We don't calculate statistics for this command */

    /* Ensure that quit works even if max_mem_used is set */
    thd->variables.max_mem_used= LONGLONG_MAX;
    general_log_print(thd, command, NullS);
    net->error=0;				// Don't give 'abort' message
    thd->get_stmt_da()->disable_status();       // Don't send anything back
    error=TRUE;					// End server
    break;
#ifndef EMBEDDED_LIBRARY
  case COM_BINLOG_DUMP:
    {
      ulong pos;
      ushort flags;
      uint32 slave_server_id;

      status_var_increment(thd->status_var.com_other);

      thd->query_plan_flags|= QPLAN_ADMIN;
      if (check_global_access(thd, PRIV_COM_BINLOG_DUMP))
	break;

      /* TODO: The following has to be changed to an 8 byte integer */
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
      thd->variables.server_id=0; /* avoid suicide */
      if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
	kill_zombie_dump_threads(slave_server_id);
      thd->variables.server_id = slave_server_id;

      const char *name= packet + 10;
      size_t nlen= strlen(name);

      general_log_print(thd, command, "Log: '%s'  Pos: %lu", name, pos);
      if (nlen < FN_REFLEN)
        mysql_binlog_send(thd, thd->strmake(name, nlen), (my_off_t)pos, flags);
      thd->unregister_slave(); // todo: can be extraneous
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
      error = TRUE;
      break;
    }
#endif
  case COM_REFRESH:
  {
    int not_used;

    /*
      Initialize thd->lex since it's used in many base functions, such as
      open_tables(). Otherwise, it remains unitialized and may cause crash
      during execution of COM_REFRESH.
    */
    lex_start(thd);
    
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
    ulonglong options= (ulonglong) (uchar) packet[0];
    if (trans_commit_implicit(thd))
      break;
    thd->release_transactional_locks();
    if (check_global_access(thd,RELOAD_ACL))
      break;
    general_log_print(thd, command, NullS);
#ifndef DBUG_OFF
    bool debug_simulate= FALSE;
    DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
    if (debug_simulate)
    {
      /* This code doesn't work under FTWRL */
      DBUG_ASSERT(! (options & REFRESH_READ_LOCK));
      /*
        Simulate a reload without a attached thread session.
        Provides a environment similar to that of when the
        server receives a SIGHUP signal and reloads caches
        and flushes tables.
      */
      bool res;
      set_current_thd(0);
      res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
                                NULL, &not_used);
      set_current_thd(thd);
      if (res)
        break;
    }
    else
#endif
    {
      thd->lex->relay_log_connection_name= empty_clex_str;
      if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
        break;
    }
    if (trans_commit_implicit(thd))
      break;
    close_thread_tables(thd);
    thd->release_transactional_locks();
    my_ok(thd);
    break;
  }
#ifndef EMBEDDED_LIBRARY
  case COM_SHUTDOWN:
  {
    status_var_increment(thd->status_var.com_other);
    if (check_global_access(thd,SHUTDOWN_ACL))
      break; /* purecov: inspected */
    /*
      If the client is < 4.1.3, it is going to send us no argument; then
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
    */
    enum mysql_enum_shutdown_level level;
    level= (enum mysql_enum_shutdown_level) (uchar) packet[0];
    thd->lex->is_shutdown_wait_for_slaves= false;  // "deferred" cleanup
    if (level == SHUTDOWN_DEFAULT)
      level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
    else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
      break;
    }
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
    general_log_print(thd, command, NullS);
    my_eof(thd);
    kill_mysql(thd);
    error=TRUE;
    break;
  }
#endif
  case COM_STATISTICS:
  {
    STATUS_VAR *current_global_status_var;      // Big; Don't allocate on stack
    ulong uptime;
    ulonglong queries_per_second1000;
    char buff[250];
    uint buff_len= sizeof(buff);

    if (!(current_global_status_var= (STATUS_VAR*)
          thd->alloc(sizeof(STATUS_VAR))))
      break;
    general_log_print(thd, command, NullS);
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
    *current_global_status_var= global_status_var;
    calc_sum_of_all_status(current_global_status_var);
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
      queries_per_second1000= thd->query_id * 1000 / uptime;
#ifndef EMBEDDED_LIBRARY
    size_t length=
#endif
    my_snprintf(buff, buff_len - 1,
                        "Uptime: %lu  Threads: %u  Questions: %lu  "
                        "Slow queries: %lu  Opens: %lu  "
                        "Open tables: %u  Queries per second avg: %u.%03u",
                        uptime, THD_count::value(), (ulong) thd->query_id,
                        current_global_status_var->long_query_count,
                        current_global_status_var->opened_tables,
                        tc_records(),
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
    my_ok(thd, 0, 0, buff);
#else
    (void) my_net_write(net, (uchar*) buff, length);
    (void) net_flush(net);
    thd->get_stmt_da()->disable_status();
#endif
    break;
  }
  case COM_PING:
    status_var_increment(thd->status_var.com_other);
    my_ok(thd);				// Tell client we are alive
    break;
  case COM_PROCESS_INFO:
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PRIV_COM_PROCESS_INFO))
      break;
    general_log_print(thd, command, NullS);
    mysqld_list_processes(thd,
                     thd->security_ctx->master_access & PRIV_COM_PROCESS_INFO ?
                     NullS : thd->security_ctx->priv_user, 0);
    break;
  case COM_PROCESS_KILL:
  {
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
    ulong id=(ulong) uint4korr(packet);
    sql_kill(thd, id, KILL_CONNECTION_HARD, KILL_TYPE_ID);
    break;
  }
  case COM_SET_OPTION:
  {
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
      my_eof(thd);
      break;
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
      my_eof(thd);
      break;
    default:
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
                 MYF(0));
      break;
    }
    break;
  }
  case COM_DEBUG:
    status_var_increment(thd->status_var.com_other);
    if (check_global_access(thd, PRIV_DEBUG))
      break;					/* purecov: inspected */
    mysql_print_status();
    general_log_print(thd, command, NullS);
    my_eof(thd);
    break;

  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
  case COM_END:
  case COM_UNIMPLEMENTED:
  default:
    my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
               MYF(0));
    break;
  }

dispatch_end:
  /*
   For the threadpool i.e if non-blocking call, if not all async operations
   are finished, return without cleanup. The cleanup will be done on
   later, when command execution is resumed.
  */
  if (!blocking && !error && thd->async_state.pending_ops())
  {
    DBUG_RETURN(DISPATCH_COMMAND_WOULDBLOCK);
  }

resume:

#ifdef WITH_WSREP
  /*
    Next test should really be WSREP(thd), but that causes a failure when doing
    'set WSREP_ON=0'
  */
  if (unlikely(wsrep_service_started))
  {
    if (thd->killed == KILL_QUERY)
    {
      WSREP_DEBUG("THD is killed at dispatch_end");
    }
    wsrep_after_command_before_result(thd);
    if (wsrep_current_error(thd) && !wsrep_command_no_result(command))
    {
      /* todo: Pass wsrep client state current error to override */
      wsrep_override_error(thd, wsrep_current_error(thd),
                           wsrep_current_error_status(thd));
      WSREP_LOG_THD(thd, "leave");
    }
    if (WSREP(thd))
    {
      /*
        MDEV-10812
        In the case of COM_QUIT/COM_STMT_CLOSE thread status should be disabled.
      */
      DBUG_ASSERT((command != COM_QUIT && command != COM_STMT_CLOSE)
                  || thd->get_stmt_da()->is_disabled());
      DBUG_ASSERT(thd->wsrep_trx().state() != wsrep::transaction::s_replaying);
      /* wsrep BF abort in query exec phase */
      mysql_mutex_lock(&thd->LOCK_thd_kill);
      do_end_of_statement= thd_is_connection_alive(thd);
      mysql_mutex_unlock(&thd->LOCK_thd_kill);
    }
  }
#endif /* WITH_WSREP */


  if (do_end_of_statement)
  {
    DBUG_ASSERT(thd->derived_tables == NULL &&
               (thd->open_tables == NULL ||
               (thd->locked_tables_mode == LTM_LOCK_TABLES)));

    thd_proc_info(thd, "Updating status");
    /* Finalize server status flags after executing a command. */
    thd->update_server_status();
    thd->protocol->end_statement();
    query_cache_end_of_result(thd);
  }
  if (drop_more_results)
    thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;

  if (likely(!thd->is_error() && !thd->killed_errno()))
    mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);

  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
                      thd->get_stmt_da()->is_error() ?
                      thd->get_stmt_da()->sql_errno() : 0,
                      command_name[command].str);

  thd->update_all_stats();

  /*
    Write to slow query log only those statements that received via the text
    protocol except the EXECUTE statement. The reason we do that way is
    that for statements received via binary protocol and for the EXECUTE
    statement, the slow statements have been already written to slow query log
    inside the method Prepared_statement::execute().
  */
  if(command == COM_QUERY &&
     thd->lex->sql_command != SQLCOM_EXECUTE)
    log_slow_statement(thd);
  else
    delete_explain_query(thd->lex);

  THD_STAGE_INFO(thd, stage_cleaning_up);
  thd->reset_query();

  /* Performance Schema Interface instrumentation, end */
  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
  thd->set_examined_row_count(0);                   // For processlist
  thd->set_command(COM_SLEEP);

  thd->m_statement_psi= NULL;
  thd->m_digest= NULL;

  thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory

  thd->reset_kill_query();  /* Ensure that killed_errmsg is released */
  /*
    LEX::m_sql_cmd can point to Sql_cmd allocated on thd->mem_root.
    Unlink it now, before freeing the root.
  */
  thd->lex->m_sql_cmd= NULL;
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));

#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif
  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
  {
    int res __attribute__((unused));
    res= (int) thd->is_error();
    if (command == COM_QUERY)
    {
      MYSQL_QUERY_DONE(res);
    }
    MYSQL_COMMAND_DONE(res);
  }
  DEBUG_SYNC(thd,"dispatch_command_end");

  /* Check that some variables are reset properly */
  DBUG_ASSERT(thd->abort_on_warning == 0);
  thd->lex->restore_set_statement_var();
  DBUG_RETURN(error?DISPATCH_COMMAND_CLOSE_CONNECTION: DISPATCH_COMMAND_SUCCESS);
}

static bool slow_filter_masked(THD *thd, ulonglong mask)
{
  return thd->variables.log_slow_filter && !(thd->variables.log_slow_filter & mask);
}

/*
  Log query to slow queries, if it passes filtering

  @note
    This function must call delete_explain_query().
*/

void log_slow_statement(THD *thd)
{
  DBUG_ENTER("log_slow_statement");

  /*
    The following should never be true with our current code base,
    but better to keep this here so we don't accidently try to log a
    statement in a trigger or stored function
  */
  if (unlikely(thd->in_sub_stmt))
    goto end;                           // Don't set time for sub stmt
  /*
    Skip both long_query_count increment and logging if the current
    statement forces slow log suppression (e.g. an SP statement).

    Note, we don't check for global_system_variables.sql_log_slow here.
    According to the manual, the "Slow_queries" status variable does not require
    sql_log_slow to be ON. So even if sql_log_slow is OFF, we still need to
    continue and increment long_query_count (and skip only logging, see below):
  */
  if (!thd->enable_slow_log)
    goto end; // E.g. SP statement

  DBUG_EXECUTE_IF("simulate_slow_query", {
                  if (thd->get_command() == COM_QUERY ||
                      thd->get_command() == COM_STMT_EXECUTE)
                    thd->server_status|= SERVER_QUERY_WAS_SLOW;
                  });

  if ((thd->server_status &
       (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
      !(thd->query_plan_flags & QPLAN_STATUS) &&
      (thd->variables.log_slow_filter & QPLAN_NOT_USING_INDEX))
  {
    thd->query_plan_flags|= QPLAN_NOT_USING_INDEX;
    /* We are always logging no index queries if enabled in filter */
    thd->server_status|= SERVER_QUERY_WAS_SLOW;
  }

  if ((thd->server_status & SERVER_QUERY_WAS_SLOW) &&
      thd->get_examined_row_count() >= thd->variables.min_examined_row_limit)
  {
    thd->status_var.long_query_count++;

    /*
      until log_slow_disabled_statements=admin is removed, it
      duplicates slow_log_filter=admin
    */
    if ((thd->query_plan_flags & QPLAN_ADMIN) &&
        (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_ADMIN))
      goto end;

    if (!global_system_variables.sql_log_slow || !thd->variables.sql_log_slow)
      goto end;

    /*
      If rate limiting of slow log writes is enabled, decide whether to log
      this query to the log or not.
    */ 
    if (thd->variables.log_slow_rate_limit > 1 &&
        (global_query_id % thd->variables.log_slow_rate_limit) != 0)
      goto end;

    /*
      Follow the slow log filter configuration:
      skip logging if the current statement matches the filter.
    */
    if (slow_filter_masked(thd, thd->query_plan_flags))
      goto end;

    THD_STAGE_INFO(thd, stage_logging_slow_query);
    slow_log_print(thd, thd->query(), thd->query_length(), 
                   thd->utime_after_query);
  }

end:
  delete_explain_query(thd->lex);
  DBUG_VOID_RETURN;
}


/**
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.

    This function is used in the parser to convert a SHOW or DESCRIBE
    table_name command to a SELECT from INFORMATION_SCHEMA.
    It prepares a SELECT_LEX and a TABLE_LIST object to represent the
    given command as a SELECT parse tree.

  @param thd              thread handle
  @param lex              current lex
  @param table_ident      table alias if it's used
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
                          created

  @note
    Due to the way this function works with memory and LEX it cannot
    be used outside the parser (parse tree transformations outside
    the parser break PS and SP).

  @retval
    0                 success
  @retval
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
  SELECT_LEX *schema_select_lex= NULL;
  DBUG_ENTER("prepare_schema_table");

  switch (schema_table_idx) {
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
    DBUG_RETURN(1);
#else
    break;
#endif

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_CHECK_CONSTRAINTS:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
  case SCH_EVENTS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
    DBUG_RETURN(1);
#else
    {
      if (lex->first_select_lex()->db.str == NULL &&
          lex->copy_db_to(&lex->first_select_lex()->db))
      {
        DBUG_RETURN(1);
      }
      schema_select_lex= new (thd->mem_root) SELECT_LEX();
      schema_select_lex->table_list.first= NULL;
      if (lower_case_table_names == 1)
        lex->first_select_lex()->db.str=
          thd->strdup(lex->first_select_lex()->db.str);
      schema_select_lex->db= lex->first_select_lex()->db;
      /*
        check_db_name() may change db.str if lower_case_table_names == 1,
        but that's ok as the db is allocted above in this case.
      */
      if (check_db_name((LEX_STRING*) &lex->first_select_lex()->db))
      {
        my_error(ER_WRONG_DB_NAME, MYF(0), lex->first_select_lex()->db.str);
        DBUG_RETURN(1);
      }
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND,
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
    DBUG_RETURN(1);
#else
  {
    DBUG_ASSERT(table_ident);
    TABLE_LIST **query_tables_last= lex->query_tables_last;
    schema_select_lex= new (thd->mem_root) SELECT_LEX();
    /* 'parent_lex' is used in init_query() so it must be before it. */
    schema_select_lex->parent_lex= lex;
    schema_select_lex->init_query();
    schema_select_lex->select_number= 0;
    if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ,
                                              MDL_SHARED_READ))
      DBUG_RETURN(1);
    lex->query_tables_last= query_tables_last;
    break;
#endif
  }
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
#if defined(ENABLED_PROFILING)
    thd->profiling.discard_current_query();
#endif
    break;
  default:
    break;
  }
  if (schema_select_lex)
    schema_select_lex->set_master_unit(&lex->unit);
  SELECT_LEX *select_lex= lex->current_select;
  if (make_schema_select(thd, select_lex, get_schema_table(schema_table_idx)))
    DBUG_RETURN(1);

  select_lex->table_list.first->schema_select_lex= schema_select_lex;
  DBUG_RETURN(0);
}


/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.

    Sets the following THD variables:
  - query
  - query_length

  @retval
    FALSE ok
  @retval
    TRUE  error;  In this case thd->fatal_error is set
*/

bool alloc_query(THD *thd, const char *packet, size_t packet_length)
{
  char *query;
  /* Remove garbage at start and end of query */
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
  {
    packet++;
    packet_length--;
  }
  const char *pos= packet + packet_length;     // Point at end null
  while (packet_length > 0 &&
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
  {
    pos--;
    packet_length--;
  }
  /* We must allocate some extra memory for query cache 

    The query buffer layout is:
       buffer :==
            <statement>   The input statement(s)
            '\0'          Terminating null char  (1 byte)
            <length>      Length of following current database name (size_t)
            <db_name>     Name of current database
            <flags>       Flags struct
  */
  if (! (query= (char*) thd->memdup_w_gap(packet,
                                          packet_length,
                                          1 + thd->db.length +
                                          QUERY_CACHE_DB_LENGTH_SIZE +
                                          QUERY_CACHE_FLAGS_SIZE)))
      return TRUE;
  query[packet_length]= '\0';
  /*
    Space to hold the name of the current database is allocated.  We
    also store this length, in case current database is changed during
    execution.  We might need to reallocate the 'query' buffer
  */
  int2store(query + packet_length + 1, thd->db.length);
    
  thd->set_query(query, packet_length);

  /* Reclaim some memory */
  thd->packet.shrink(thd->variables.net_buffer_length);
  thd->convert_buffer.shrink(thd->variables.net_buffer_length);

  return FALSE;
}


bool sp_process_definer(THD *thd)
{
  DBUG_ENTER("sp_process_definer");

  LEX *lex= thd->lex;

  /*
    If the definer is not specified, this means that CREATE-statement missed
    DEFINER-clause. DEFINER-clause can be missed in two cases:

      - The user submitted a statement w/o the clause. This is a normal
        case, we should assign CURRENT_USER as definer.

      - Our slave received an updated from the master, that does not
        replicate definer for stored rountines. We should also assign
        CURRENT_USER as definer here, but also we should mark this routine
        as NON-SUID. This is essential for the sake of backward
        compatibility.

        The problem is the slave thread is running under "special" user (@),
        that actually does not exist. In the older versions we do not fail
        execution of a stored routine if its definer does not exist and
        continue the execution under the authorization of the invoker
        (BUG#13198). And now if we try to switch to slave-current-user (@),
        we will fail.

        Actually, this leads to the inconsistent state of master and
        slave (different definers, different SUID behaviour), but it seems,
        this is the best we can do.
  */

  if (!lex->definer)
  {
    Query_arena original_arena;
    Query_arena *ps_arena= thd->activate_stmt_arena_if_needed(&original_arena);

    lex->definer= create_default_definer(thd, false);

    if (ps_arena)
      thd->restore_active_arena(ps_arena, &original_arena);

    /* Error has been already reported. */
    if (lex->definer == NULL)
      DBUG_RETURN(TRUE);

    if (thd->slave_thread && lex->sphead)
      lex->sphead->set_suid(SP_IS_NOT_SUID);
  }
  else
  {
    LEX_USER *d= get_current_user(thd, lex->definer);
    if (!d)
      DBUG_RETURN(TRUE);
    if (d->user.str == public_name.str)
    {
      my_error(ER_INVALID_ROLE, MYF(0), lex->definer->user.str);
      DBUG_RETURN(TRUE);
    }
    thd->change_item_tree((Item**)&lex->definer, (Item*)d);

    /*
      If the specified definer differs from the current user or role, we
      should check that the current user has SUPER privilege (in order
      to create a stored routine under another user one must have
      SUPER privilege).
    */
    bool curuser= !strcmp(d->user.str, thd->security_ctx->priv_user);
    bool currole= !curuser && !strcmp(d->user.str, thd->security_ctx->priv_role);
    bool curuserhost= curuser && d->host.str &&
                  !my_strcasecmp(system_charset_info, d->host.str,
                                 thd->security_ctx->priv_host);
    if (!curuserhost && !currole &&
        check_global_access(thd, PRIV_DEFINER_CLAUSE, false))
      DBUG_RETURN(TRUE);
  }

  /* Check that the specified definer exists. Emit a warning if not. */

#ifndef NO_EMBEDDED_ACCESS_CHECKS
  if (!is_acl_user(lex->definer->host.str, lex->definer->user.str))
  {
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                        ER_NO_SUCH_USER, ER_THD(thd, ER_NO_SUCH_USER),
                        lex->definer->user.str, lex->definer->host.str);
  }
#endif /* NO_EMBEDDED_ACCESS_CHECKS */

  DBUG_RETURN(FALSE);
}


/**
  Auxiliary call that opens and locks tables for LOCK TABLES statement
  and initializes the list of locked tables.

  @param thd     Thread context.
  @param tables  List of tables to be locked.

  @return FALSE in case of success, TRUE in case of error.
*/

static bool __attribute__ ((noinline))
lock_tables_open_and_lock_tables(THD *thd, TABLE_LIST *tables)
{
  Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
  MDL_deadlock_and_lock_abort_error_handler deadlock_handler;
  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
  uint counter;
  TABLE_LIST *table;

  thd->in_lock_tables= 1;

retry:

  if (open_tables(thd, &tables, &counter, 0, &lock_tables_prelocking_strategy))
    goto err;

  for (table= tables; table; table= table->next_global)
  {
    if (!table->placeholder())
    {
      if (table->table->s->tmp_table)
      {
        /*
          We allow to change temporary tables even if they were locked for read
          by LOCK TABLES. To avoid a discrepancy between lock acquired at LOCK
          TABLES time and by the statement which is later executed under LOCK
          TABLES we ensure that for temporary tables we always request a write
          lock (such discrepancy can cause problems for the storage engine).
          We don't set TABLE_LIST::lock_type in this case as this might result
          in extra warnings from THD::decide_logging_format() even though
          binary logging is totally irrelevant for LOCK TABLES.
        */
        table->table->reginfo.lock_type= TL_WRITE;
      }
      else if (table->mdl_request.type == MDL_SHARED_READ &&
               ! table->prelocking_placeholder &&
               table->table->file->lock_count() == 0)
      {
        enum enum_mdl_type lock_type;
        /*
          In case when LOCK TABLE ... READ LOCAL was issued for table with
          storage engine which doesn't support READ LOCAL option and doesn't
          use THR_LOCK locks we need to upgrade weak SR metadata lock acquired
          in open_tables() to stronger SRO metadata lock.
          This is not needed for tables used through stored routines or
          triggers as we always acquire SRO (or even stronger SNRW) metadata
          lock for them.
        */
        deadlock_handler.init();
        thd->push_internal_handler(&deadlock_handler);

        lock_type= table->table->mdl_ticket->get_type() == MDL_SHARED_WRITE ?
                   MDL_SHARED_NO_READ_WRITE : MDL_SHARED_READ_ONLY;

        bool result= thd->mdl_context.upgrade_shared_lock(
                                        table->table->mdl_ticket,
                                        lock_type,
                                        thd->variables.lock_wait_timeout);

        thd->pop_internal_handler();

        if (deadlock_handler.need_reopen())
        {
          /*
            Deadlock occurred during upgrade of metadata lock.
            Let us restart acquring and opening tables for LOCK TABLES.
          */
          close_tables_for_reopen(thd, &tables, mdl_savepoint);
          if (thd->open_temporary_tables(tables))
            goto err;
          goto retry;
        }

        if (result)
          goto err;
      }
    }
    /*
       Check privileges of view tables here, after views were opened.
       Either definer or invoker has to have PRIV_LOCK_TABLES to be able
       to lock view and its tables. For mysqldump (that locks views
       before dumping their structures) compatibility we allow locking
       views that select from I_S or P_S tables, but downrade the lock
       to TL_READ
     */
    if (table->belong_to_view &&
        check_single_table_access(thd, PRIV_LOCK_TABLES, table, 1))
    {
      if (table->grant.m_internal.m_schema_access)
        table->lock_type= TL_READ;
      else
      {
        bool error= true;
        if (Security_context *sctx= table->security_ctx)
        {
          table->security_ctx= 0;
          error= check_single_table_access(thd, PRIV_LOCK_TABLES, table, 1);
          table->security_ctx= sctx;
        }
        if (error)
        {
          my_error(ER_VIEW_INVALID, MYF(0), table->belong_to_view->view_db.str,
                   table->belong_to_view->view_name.str);
          goto err;
        }
      }
    }
  }

  if (lock_tables(thd, tables, counter, 0) ||
      thd->locked_tables_list.init_locked_tables(thd))
    goto err;

  thd->in_lock_tables= 0;

  return FALSE;

err:
  thd->in_lock_tables= 0;

  trans_rollback_stmt(thd);
  /*
    Need to end the current transaction, so the storage engine (InnoDB)
    can free its locks if LOCK TABLES locked some tables before finding
    that it can't lock a table in its list
  */
  trans_rollback(thd);
  /* Close tables and release metadata locks. */
  close_thread_tables(thd);
  DBUG_ASSERT(!thd->locked_tables_mode);
  thd->release_transactional_locks();
  return TRUE;
}


static bool do_execute_sp(THD *thd, sp_head *sp)
{
  /* bits that should be cleared in thd->server_status */
  uint bits_to_be_cleared= 0;
  ulonglong affected_rows;
  if (sp->m_flags & sp_head::MULTI_RESULTS)
  {
    if (!(thd->client_capabilities & CLIENT_MULTI_RESULTS))
    {
      /* The client does not support multiple result sets being sent back */
      my_error(ER_SP_BADSELECT, MYF(0), ErrConvDQName(sp).ptr());
      return 1;
    }
  }
  /*
    If SERVER_MORE_RESULTS_EXISTS is not set,
    then remember that it should be cleared
  */
  bits_to_be_cleared= (~thd->server_status &
                       SERVER_MORE_RESULTS_EXISTS);
  thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
  ha_rows select_limit= thd->variables.select_limit;
  thd->variables.select_limit= HA_POS_ERROR;

  /*
    Reset current_select as it may point to random data as a
    result of previous parsing.
  */
  thd->lex->current_select= NULL;
  thd->lex->in_sum_func= 0;                     // For Item_field::fix_fields()

  /*
    We never write CALL statements into binlog:
     - If the mode is non-prelocked, each statement will be logged
       separately.
     - If the mode is prelocked, the invoking statement will care
       about writing into binlog.
    So just execute the statement.
  */
  int res= sp->execute_procedure(thd, &thd->lex->value_list);

  thd->variables.select_limit= select_limit;
  thd->server_status&= ~bits_to_be_cleared;

  if (res)
  {
    DBUG_ASSERT(thd->is_error() || thd->killed);
    return 1;  		// Substatement should already have sent error
  }

  affected_rows= thd->affected_rows; // Affected rows for all sub statements
  thd->affected_rows= 0;             // Reset total, as my_ok() adds to it
  my_ok(thd, affected_rows);
  return 0;
}


static int __attribute__ ((noinline))
mysql_create_routine(THD *thd, LEX *lex)
{
  DBUG_ASSERT(lex->sphead != 0);
  DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
  /*
    Verify that the database name is allowed, optionally
    lowercase it.
  */
  if (check_db_name((LEX_STRING*) &lex->sphead->m_db))
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str);
    return true;
  }

  if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str,
                   NULL, NULL, 0, 0))
    return true;

  /* Checking the drop permissions if CREATE OR REPLACE is used */
  if (lex->create_info.or_replace())
  {
    if (check_routine_access(thd, ALTER_PROC_ACL, &lex->sphead->m_db,
                             &lex->sphead->m_name,
                             Sp_handler::handler(lex->sql_command), 0))
      return true;
  }

  const LEX_CSTRING *name= lex->sphead->name();
#ifdef HAVE_DLOPEN
  if (lex->sphead->m_handler->type() == SP_TYPE_FUNCTION)
  {
    udf_func *udf = find_udf(name->str, name->length);

    if (udf)
    {
      my_error(ER_UDF_EXISTS, MYF(0), name->str);
      return true;
    }
  }
#endif

  if (sp_process_definer(thd))
    return true;

  WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

  if (!lex->sphead->m_handler->sp_create_routine(thd, lex->sphead))
  {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
    /* only add privileges if really neccessary */

    Security_context security_context;
    bool restore_backup_context= false;
    Security_context *backup= NULL;
    LEX_USER *definer= thd->lex->definer;
    /*
      We're going to issue an implicit GRANT statement so we close all
      open tables. We have to keep metadata locks as this ensures that
      this statement is atomic against concurent FLUSH TABLES WITH READ
      LOCK. Deadlocks which can arise due to fact that this implicit
      statement takes metadata locks should be detected by a deadlock
      detector in MDL subsystem and reported as errors.

      TODO: Long-term we should either ensure that implicit GRANT statement
            is written into binary log as a separate statement or make both
            creation of routine and implicit GRANT parts of one fully atomic
            statement.
      */
    if (trans_commit_stmt(thd))
      goto wsrep_error_label;
    close_thread_tables(thd);
    /*
      Check if the definer exists on slave,
      then use definer privilege to insert routine privileges to mysql.procs_priv.

      For current user of SQL thread has GLOBAL_ACL privilege,
      which doesn't any check routine privileges,
      so no routine privilege record  will insert into mysql.procs_priv.
    */
    if (thd->slave_thread && is_acl_user(definer->host.str, definer->user.str))
    {
      security_context.change_security_context(thd, &thd->lex->definer->user,
                                               &thd->lex->definer->host,
                                               &thd->lex->sphead->m_db,
                                               &backup);
      restore_backup_context= true;
    }

    if (sp_automatic_privileges && !opt_noacl &&
        check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
                             &lex->sphead->m_db, name,
                             Sp_handler::handler(lex->sql_command), 1))
    {
      if (sp_grant_privileges(thd, lex->sphead->m_db.str, name->str,
                              Sp_handler::handler(lex->sql_command)))
        push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
                     ER_PROC_AUTO_GRANT_FAIL, ER_THD(thd, ER_PROC_AUTO_GRANT_FAIL));
      thd->clear_error();
    }

    /*
      Restore current user with GLOBAL_ACL privilege of SQL thread
    */
    if (restore_backup_context)
    {
      DBUG_ASSERT(thd->slave_thread == 1);
      thd->security_ctx->restore_security_context(thd, backup);
    }

#endif
    return false;
  }
  (void) trans_commit_stmt(thd);

#if !defined(NO_EMBEDDED_ACCESS_CHECKS) || defined(WITH_WSREP)
wsrep_error_label:
#endif
  return true;
}


/**
  Prepare for CREATE DATABASE, ALTER DATABASE, DROP DATABASE.

  @param thd         - current THD
  @param want_access - access needed
  @param dbname      - the database name

  @retval false      - Ok to proceed with CREATE/ALTER/DROP
  @retval true       - not OK to proceed (error, or filtered)

  Note, on slave this function returns true if the database
  is in the ignore filter. The caller must distinguish this case
  from other cases: bad database error, no access error.
  This can be done by testing thd->is_error().
*/
static bool prepare_db_action(THD *thd, privilege_t want_access,
                              LEX_CSTRING *dbname)
{
  if (check_db_name((LEX_STRING*)dbname))
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), dbname->str);
    return true;
  }
  /*
    If in a slave thread :
    - CREATE DATABASE DB was certainly not preceded by USE DB.
    - ALTER DATABASE DB may not be preceded by USE DB.
    - DROP DATABASE DB may not be preceded by USE DB.
    For that reason, db_ok() in sql/slave.cc did not check the
    do_db/ignore_db. And as this query involves no tables, tables_ok()
    was not called. So we have to check rules again here.
  */
#ifdef HAVE_REPLICATION
  if (thd->slave_thread)
  {
    Rpl_filter *rpl_filter;
    rpl_filter= thd->system_thread_info.rpl_sql_info->rpl_filter;
    if (!rpl_filter->db_ok(dbname->str) ||
        !rpl_filter->db_ok_with_wild_table(dbname->str))
    {
      my_message(ER_SLAVE_IGNORED_TABLE,
                 ER_THD(thd, ER_SLAVE_IGNORED_TABLE), MYF(0));
      return true;
    }
  }
#endif
  return check_access(thd, want_access, dbname->str, NULL, NULL, 1, 0);
}


bool Sql_cmd_call::execute(THD *thd)
{
  TABLE_LIST *all_tables= thd->lex->query_tables;
  sp_head *sp;
  /*
    This will cache all SP and SF and open and lock all tables
    required for execution.
  */
  if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                         UINT_MAX, FALSE) ||
      open_and_lock_tables(thd, all_tables, TRUE, 0))
   return true;

  /*
    By this moment all needed SPs should be in cache so no need to look
    into DB.
  */
  if (!(sp= m_handler->sp_find_routine(thd, m_name, true)))
  {
    /*
      If the routine is not found, let's still check EXECUTE_ACL to decide
      whether to return "Access denied" or "Routine does not exist".
    */
    if (check_routine_access(thd, EXECUTE_ACL, &m_name->m_db,
                             &m_name->m_name,
                             &sp_handler_procedure,
                             false))
      return true;
    /*
      sp_find_routine can have issued an ER_SP_RECURSION_LIMIT error.
      Send message ER_SP_DOES_NOT_EXIST only if procedure is not found in
      cache.
    */
    if (!sp_cache_lookup(&thd->sp_proc_cache, m_name))
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
               ErrConvDQName(m_name).ptr());
    return true;
  }
  else
  {
    if (sp->check_execute_access(thd))
      return true;
    /*
      Check that the stored procedure doesn't contain Dynamic SQL
      and doesn't return result sets: such stored procedures can't
      be called from a function or trigger.
    */
    if (thd->in_sub_stmt)
    {
      const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ?
                          "trigger" : "function");
      if (sp->is_not_allowed_in_function(where))
        return true;
    }

    if (do_execute_sp(thd, sp))
      return true;

    /*
      Disable slow log for the above call(), if calls are disabled.
      Instead we will log the executed statements to the slow log.
    */
    if (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_CALL)
      thd->enable_slow_log= 0;
  }
  return false;
}


/**
  Check whether the SQL statement being processed is prepended by
  SET STATEMENT clause and handle variables assignment if it is.

  @param thd  thread handle
  @param lex  current lex

  @return false in case of success, true in case of error.
*/

bool run_set_statement_if_requested(THD *thd, LEX *lex)
{
  if (!lex->stmt_var_list.is_empty() && !thd->slave_thread)
  {
    Query_arena backup;
    DBUG_PRINT("info", ("SET STATEMENT %d vars", lex->stmt_var_list.elements));

    lex->old_var_list.empty();
    List_iterator_fast<set_var_base> it(lex->stmt_var_list);
    set_var_base *var;

    if (lex->set_arena_for_set_stmt(&backup))
      return true;

    MEM_ROOT *mem_root= thd->mem_root;
    while ((var= it++))
    {
      DBUG_ASSERT(var->is_system());
      set_var *o= NULL, *v= (set_var*)var;
      if (!v->var->is_set_stmt_ok())
      {
        my_error(ER_SET_STATEMENT_NOT_SUPPORTED, MYF(0), v->var->name.str);
        lex->reset_arena_for_set_stmt(&backup);
        lex->old_var_list.empty();
        lex->free_arena_for_set_stmt();
        return true;
      }
      if (v->var->session_is_default(thd))
        o= new set_var(thd,v->type, v->var, &v->base, NULL);
      else
      {
        switch (v->var->option.var_type & GET_TYPE_MASK)
        {
          case GET_BIT:
          case GET_BOOL:
          case GET_INT:
          case GET_LONG:
          case GET_LL:
          {
            bool null_value;
            longlong val= v->var->val_int(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_int(thd, val)));
          }
          break;
          case GET_UINT:
          case GET_ULONG:
          case GET_ULL:
          {
            bool null_value;
            ulonglong val= v->var->val_int(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_uint(thd, val)));
          }
          break;
          case GET_DOUBLE:
          {
            bool null_value;
            double val= v->var->val_real(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_float(thd, val, 1)));
          }
          break;
          default:
          case GET_NO_ARG:
          case GET_DISABLED:
            DBUG_ASSERT(0);
            /* fall through */
          case 0:
          case GET_FLAGSET:
          case GET_ENUM:
          case GET_SET:
          case GET_STR:
          case GET_STR_ALLOC:
          {
            char buff[STRING_BUFFER_USUAL_SIZE];
            String tmp(buff, sizeof(buff), v->var->charset(thd)),*val;
            val= v->var->val_str(&tmp, thd, v->type, &v->base);
            if (val)
            {
              Item_string *str=
		new (mem_root) Item_string(thd, v->var->charset(thd),
                                           val->ptr(), val->length());
              o= new set_var(thd, v->type, v->var, &v->base, str);
            }
            else
              o= new set_var(thd, v->type, v->var, &v->base,
                             new (mem_root) Item_null(thd));
          }
          break;
        }
      }
      DBUG_ASSERT(o);
      lex->old_var_list.push_back(o, thd->mem_root);
    }
    lex->reset_arena_for_set_stmt(&backup);

    if (lex->old_var_list.is_empty())
      lex->free_arena_for_set_stmt();

    if (thd->is_error() ||
        sql_set_variables(thd, &lex->stmt_var_list, false))
    {
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS, MYF(0), "SET");
      lex->restore_set_statement_var();
      return true;
    }
    /*
      The value of last_insert_id is remembered in THD to be written to binlog
      when it's used *the first time* in the statement. But SET STATEMENT
      must read the old value of last_insert_id to be able to restore it at
      the end. This should not count at "reading of last_insert_id" and
      should not remember last_insert_id for binlog. That is, it should clear
      stmt_depends_on_first_successful_insert_id_in_prev_stmt flag.
    */
    if (!thd->in_sub_stmt)
    {
      thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
    }
  }
  return false;
}


/**
  Execute command saved in thd and lex->sql_command.

  @param thd                       Thread handle

  @todo
    - Invalidate the table in the query cache if something changed
    after unlocking when changes become visible.
    TODO: this is workaround. right way will be move invalidating in
    the unlock procedure.
    - TODO: use check_change_password()

  @retval
    FALSE       OK
  @retval
    TRUE        Error
*/

int
mysql_execute_command(THD *thd, bool is_called_from_prepared_stmt)
{
  int res= 0;
  int  up_result= 0;
  LEX  *lex= thd->lex;
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
  SELECT_LEX *select_lex= lex->first_select_lex();
  /* first table of first SELECT_LEX */
  TABLE_LIST *first_table= select_lex->table_list.first;
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
  SELECT_LEX_UNIT *unit= &lex->unit;
#ifdef HAVE_REPLICATION
  /* have table map for update for multi-update statement (BUG#37051) */
  bool have_table_map_for_update= FALSE;
  /* */
  Rpl_filter *rpl_filter;
#endif
  DBUG_ENTER("mysql_execute_command");

  // check that we correctly marked first table for data insertion
  DBUG_ASSERT(!(sql_command_flags[lex->sql_command] & CF_INSERTS_DATA) ||
              first_table->for_insert_data);

  if (thd->security_ctx->password_expired &&
      lex->sql_command != SQLCOM_SET_OPTION &&
      lex->sql_command != SQLCOM_PREPARE &&
      lex->sql_command != SQLCOM_EXECUTE &&
      lex->sql_command != SQLCOM_DEALLOCATE_PREPARE)
  {
    my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
    DBUG_RETURN(1);
  }

  DBUG_ASSERT(thd->transaction->stmt.is_empty() || thd->in_sub_stmt);
  /*
    Each statement or replication event which might produce deadlock
    should handle transaction rollback on its own. So by the start of
    the next statement transaction rollback request should be fulfilled
    already.
  */
  DBUG_ASSERT(! thd->transaction_rollback_request || thd->in_sub_stmt);
  /*
    In many cases first table of main SELECT_LEX have special meaning =>
    check that it is first table in global list and relink it first in 
    queries_tables list if it is necessary (we need such relinking only
    for queries with subqueries in select list, in this case tables of
    subqueries will go to global list first)

    all_tables will differ from first_table only if most upper SELECT_LEX
    do not contain tables.

    Because of above in place where should be at least one table in most
    outer SELECT_LEX we have following check:
    DBUG_ASSERT(first_table == all_tables);
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
  */
  lex->first_lists_tables_same();
  lex->fix_first_select_number();
  /* should be assigned after making first tables same */
  all_tables= lex->query_tables;
  /* set context for commands which do not use setup_tables */
  select_lex->
    context.resolve_in_table_list_only(select_lex->
                                       table_list.first);

  /*
    Remember last commmand executed, so that we can use it in functions called by
    dispatch_command()
  */
  thd->last_sql_command= lex->sql_command;

  /*
    Reset warning count for each query that uses tables
    A better approach would be to reset this for any commands
    that is not a SHOW command or a select that only access local
    variables, but for now this is probably good enough.
  */
  if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0)
    thd->get_stmt_da()->set_warning_info_read_only(TRUE);
  else
  {
    thd->get_stmt_da()->set_warning_info_read_only(FALSE);
    if (all_tables)
      thd->get_stmt_da()->opt_clear_warning_info(thd->query_id);
  }

#ifdef HAVE_REPLICATION
  if (unlikely(thd->slave_thread))
  {
    if (lex->sql_command == SQLCOM_DROP_TRIGGER)
    {
      /*
        When dropping a trigger, we need to load its table name
        before checking slave filter rules.
      */
      add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables);
      
      if (!all_tables)
      {
        /*
          If table name cannot be loaded,
          it means the trigger does not exists possibly because
          CREATE TRIGGER was previously skipped for this trigger
          according to slave filtering rules.
          Returning success without producing any errors in this case.
        */
        if (!thd->lex->create_info.if_exists() &&
            !(thd->variables.option_bits & OPTION_IF_EXISTS))
          DBUG_RETURN(0);
        /*
          DROP TRIGGER IF NOT EXISTS will return without an error later
          after possibly writing the query to a binlog
        */
      }
      else // force searching in slave.cc:tables_ok()
        all_tables->updating= 1;
    }

    /*
      For fix of BUG#37051, the master stores the table map for update
      in the Query_log_event, and the value is assigned to
      thd->variables.table_map_for_update before executing the update
      query.

      If thd->variables.table_map_for_update is set, then we are
      replicating from a new master, we can use this value to apply
      filter rules without opening all the tables. However If
      thd->variables.table_map_for_update is not set, then we are
      replicating from an old master, so we just skip this and
      continue with the old method. And of course, the bug would still
      exist for old masters.
    */
    if (lex->sql_command == SQLCOM_UPDATE_MULTI &&
        thd->table_map_for_update)
    {
      have_table_map_for_update= TRUE;
      table_map table_map_for_update= thd->table_map_for_update;
      uint nr= 0;
      TABLE_LIST *table;
      for (table=all_tables; table; table=table->next_global, nr++)
      {
        if (table_map_for_update & ((table_map)1 << nr))
          table->updating= TRUE;
        else
          table->updating= FALSE;
      }

      if (all_tables_not_ok(thd, all_tables))
      {
        /* we warn the slave SQL thread */
        my_message(ER_SLAVE_IGNORED_TABLE, ER_THD(thd, ER_SLAVE_IGNORED_TABLE),
                   MYF(0));
      }
    }
    
    /*
      Check if statment should be skipped because of slave filtering
      rules

      Exceptions are:
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
      - SET: we always execute it (Not that many SET commands exists in
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
        have stale files on slave caused by exclusion of one tmp table).
    */
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
	!((lex->sql_command == SQLCOM_DROP_TABLE ||
           lex->sql_command == SQLCOM_DROP_SEQUENCE) &&
          lex->tmp_table() && lex->if_exists()) &&
        all_tables_not_ok(thd, all_tables))
    {
      /* we warn the slave SQL thread */
      my_message(ER_SLAVE_IGNORED_TABLE, ER_THD(thd, ER_SLAVE_IGNORED_TABLE),
                 MYF(0));
      DBUG_RETURN(0);
    }
    /* 
       Execute deferred events first
    */
    if (slave_execute_deferred_events(thd))
      DBUG_RETURN(-1);
  }
  else
  {
#endif /* HAVE_REPLICATION */
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
    if (deny_updates_if_read_only_option(thd, all_tables))
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
  Opt_trace_start ots(thd);

  /* store old value of binlog format */
  enum_binlog_format orig_binlog_format,orig_current_stmt_binlog_format;

  thd->get_binlog_format(&orig_binlog_format,
                         &orig_current_stmt_binlog_format);
#ifdef WITH_WSREP
  if (WSREP(thd))
  {
    /*
      change LOCK TABLE WRITE to transaction
    */
    if (lex->sql_command== SQLCOM_LOCK_TABLES && wsrep_convert_LOCK_to_trx)
    {
      for (TABLE_LIST *table= all_tables; table; table= table->next_global)
      {
	if (table->lock_type >= TL_FIRST_WRITE)
        {
	  lex->sql_command= SQLCOM_BEGIN;
	  thd->wsrep_converted_lock_session= true;
	  break;
	}
      }
    }
    if (lex->sql_command== SQLCOM_UNLOCK_TABLES &&
	thd->wsrep_converted_lock_session)
    {
      thd->wsrep_converted_lock_session= false;
      lex->sql_command= SQLCOM_COMMIT;
      lex->tx_release= TVL_NO;
    }

    /*
     * Bail out if DB snapshot has not been installed. We however,
     * allow SET and SHOW queries and reads from information schema
     * and dirty reads (if configured)
     */
    if (!(thd->wsrep_applier) &&
        !(wsrep_ready_get() && wsrep_reject_queries == WSREP_REJECT_NONE)  &&
        !(thd->variables.wsrep_dirty_reads &&
          (sql_command_flags[lex->sql_command] & CF_CHANGES_DATA) == 0)    &&
        !wsrep_tables_accessible_when_detached(all_tables)                 &&
        lex->sql_command != SQLCOM_SET_OPTION                              &&
        lex->sql_command != SQLCOM_CHANGE_DB                               &&
        !(lex->sql_command == SQLCOM_SELECT && !all_tables)                &&
        !wsrep_is_show_query(lex->sql_command))
    {
      my_message(ER_UNKNOWN_COM_ERROR,
                 "WSREP has not yet prepared node for application use", MYF(0));
      goto error;
    }
  }
#endif /* WITH_WSREP */
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
  thd->progress.report_to_client= MY_TEST(sql_command_flags[lex->sql_command] &
                                          CF_REPORT_PROGRESS);

  DBUG_ASSERT(thd->transaction->stmt.modified_non_trans_table == FALSE);

  /*
    Assign system variables with values specified by the clause
    SET STATEMENT var1=value1 [, var2=value2, ...] FOR <statement>
    if they are any.
  */
  if (run_set_statement_if_requested(thd, lex))
    goto error;

  /* After SET STATEMENT is done, we can initialize the Optimizer Trace: */
  ots.init(thd, all_tables, lex->sql_command, &lex->var_list, thd->query(),
           thd->query_length(), thd->variables.character_set_client);

  if (thd->lex->mi.connection_name.str == NULL)
      thd->lex->mi.connection_name= thd->variables.default_master_connection;

  /*
    Force statement logging for DDL commands to allow us to update
    privilege, system or statistic tables directly without the updates
    getting logged.
  */
  if (!(sql_command_flags[lex->sql_command] &
        (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT |
         CF_STATUS_COMMAND)))
    thd->set_binlog_format_stmt();

  /*
    End a active transaction so that this command will have it's
    own transaction and will also sync the binary log. If a DDL is
    not run in it's own transaction it may simply never appear on
    the slave in case the outside transaction rolls back.
  */
  if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_BEGIN))
  {
    /*
      Note that this should never happen inside of stored functions
      or triggers as all such statements prohibited there.
    */
    DBUG_ASSERT(! thd->in_sub_stmt);
    /* Statement transaction still should not be started. */
    DBUG_ASSERT(thd->transaction->stmt.is_empty());
    if (!(thd->variables.option_bits & OPTION_GTID_BEGIN))
    {
      /* Commit the normal transaction if one is active. */
      bool commit_failed= trans_commit_implicit(thd);
      /* Release metadata locks acquired in this transaction. */
      thd->release_transactional_locks();
      if (commit_failed)
      {
        WSREP_DEBUG("implicit commit failed, MDL released: %lld",
                    (longlong) thd->thread_id);
        goto error;
      }
    }
    thd->transaction->stmt.mark_trans_did_ddl();
#ifdef WITH_WSREP
    /* Clean up the previous transaction on implicit commit */
    if (WSREP_NNULL(thd) && wsrep_thd_is_local(thd) &&
        wsrep_after_statement(thd))
    {
      goto error;
    }
#endif /* WITH_WSREP */
  }

#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION)
    DEBUG_SYNC(thd,"before_execute_sql_command");
#endif

  /*
    Check if we are in a read-only transaction and we're trying to
    execute a statement which should always be disallowed in such cases.

    Note that this check is done after any implicit commits.
  */
  if (thd->tx_read_only &&
      (sql_command_flags[lex->sql_command] & CF_DISALLOW_IN_RO_TRANS))
  {
    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
    goto error;
  }

  /*
    Close tables open by HANDLERs before executing DDL statement
    which is going to affect those tables.

    This should happen before temporary tables are pre-opened as
    otherwise we will get errors about attempt to re-open tables
    if table to be changed is open through HANDLER.

    Note that even although this is done before any privilege
    checks there is no security problem here as closing open
    HANDLER doesn't require any privileges anyway.
  */
  if (sql_command_flags[lex->sql_command] & CF_HA_CLOSE)
    mysql_ha_rm_tables(thd, all_tables);

  /*
    Pre-open temporary tables to simplify privilege checking
    for statements which need this.
  */
  if (sql_command_flags[lex->sql_command] & CF_PREOPEN_TMP_TABLES)
  {
    if (thd->open_temporary_tables(all_tables))
      goto error;
  }

  if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
    thd->query_plan_flags|= QPLAN_STATUS;
  if (sql_command_flags[lex->sql_command] & CF_ADMIN_COMMAND)
    thd->query_plan_flags|= QPLAN_ADMIN;

  /* Start timeouts */
  thd->set_query_timer();

#ifdef WITH_WSREP
  /* Check wsrep_mode rules before command execution. */
  if (WSREP_NNULL(thd) &&
      wsrep_thd_is_local(thd) && !wsrep_check_mode_before_cmd_execute(thd))
    goto error;

  /*
    Always start a new transaction for a wsrep THD unless the
    current command is DDL or explicit BEGIN. This will guarantee that
    the THD is BF abortable even if it does not generate any
    changes and takes only read locks. If the statement does not
    start a multi STMT transaction, the wsrep_transaction is
    committed as empty at the end of this function.

    Transaction is started for BEGIN in trans_begin(), for DDL the
    implicit commit took care of committing previous transaction
    above and a new transaction should not be started.

    Do not start transaction for stored procedures, it will be handled
    internally in SP processing.
  */
  if (WSREP_NNULL(thd)                    &&
      wsrep_thd_is_local(thd)             &&
      lex->sql_command != SQLCOM_BEGIN    &&
      lex->sql_command != SQLCOM_CALL     &&
      lex->sql_command != SQLCOM_EXECUTE  &&
      lex->sql_command != SQLCOM_EXECUTE_IMMEDIATE &&
      !(sql_command_flags[lex->sql_command] & CF_AUTO_COMMIT_TRANS))
  {
    wsrep_start_trx_if_not_started(thd);
  }
#endif /* WITH_WSREP */

  switch (lex->sql_command) {

  case SQLCOM_SHOW_EVENTS:
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
  case SQLCOM_SHOW_STATUS:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    execute_show_status(thd, all_tables);

    break;
  }
  case SQLCOM_SHOW_EXPLAIN:
  case SQLCOM_SHOW_ANALYZE:
  {
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PRIV_STMT_SHOW_EXPLAIN))
      break;

    /*
      The select should use only one table, it's the SHOW EXPLAIN pseudo-table
    */
    if (lex->sroutines.records || lex->query_tables->next_global)
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }

    Item **it= lex->value_list.head_ref();
    if (!(*it)->basic_const_item() ||
        (*it)->fix_fields_if_needed_for_scalar(lex->thd, it))
    {
      my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
		 MYF(0));
      goto error;
    }
  }
    /* fall through */
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
  case SQLCOM_SHOW_STATUS_PACKAGE:
  case SQLCOM_SHOW_STATUS_PACKAGE_BODY:
  case SQLCOM_SHOW_DATABASES:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_TRIGGERS:
  case SQLCOM_SHOW_TABLE_STATUS:
  case SQLCOM_SHOW_OPEN_TABLES:
  case SQLCOM_SHOW_GENERIC:
  case SQLCOM_SHOW_PLUGINS:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_SHOW_KEYS:
  case SQLCOM_SHOW_VARIABLES:
  case SQLCOM_SHOW_CHARSETS:
  case SQLCOM_SHOW_COLLATIONS:
  case SQLCOM_SHOW_STORAGE_ENGINES:
  case SQLCOM_SHOW_PROFILE:
  case SQLCOM_SELECT:
  {
#ifdef WITH_WSREP
    if (lex->sql_command == SQLCOM_SELECT)
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_READ);
    }
    else
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
# ifdef ENABLED_PROFILING
      if (lex->sql_command == SQLCOM_SHOW_PROFILE)
        thd->profiling.discard_current_query();
# endif
    }
#endif /* WITH_WSREP */

    thd->status_var.last_query_cost= 0.0;

    /*
      lex->exchange != NULL implies SELECT .. INTO OUTFILE and this
      requires FILE_ACL access.
    */
    privilege_t privileges_requested= lex->exchange ? SELECT_ACL | FILE_ACL :
                                                      SELECT_ACL;

    if (all_tables)
      res= check_table_access(thd,
                              privileges_requested,
                              all_tables, FALSE, UINT_MAX, FALSE);
    else
      res= check_access(thd, privileges_requested, any_db.str, NULL,NULL,0,0);

    if (!res)
      res= execute_sqlcom_select(thd, all_tables);

    break;
  }
  case SQLCOM_EXECUTE_IMMEDIATE:
  {
    mysql_sql_stmt_execute_immediate(thd);
    break;
  }
  case SQLCOM_PREPARE:
  {
    mysql_sql_stmt_prepare(thd);
    break;
  }
  case SQLCOM_EXECUTE:
  {
    mysql_sql_stmt_execute(thd);
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
    mysql_sql_stmt_close(thd);
    break;
  }
  case SQLCOM_DO:
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
        || open_and_lock_tables(thd, all_tables, TRUE, 0))
      goto error;

    res= mysql_do(thd, *lex->insert_list);
    break;

  case SQLCOM_EMPTY_QUERY:
    my_ok(thd);
    break;

  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

#ifndef EMBEDDED_LIBRARY
  case SQLCOM_PURGE:
  {
    if (check_global_access(thd, PRIV_STMT_PURGE_BINLOG))
      goto error;
    /* PURGE MASTER LOGS TO 'file' */
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
  case SQLCOM_PURGE_BEFORE:
  {
    Item *it;

    if (check_global_access(thd, PRIV_STMT_PURGE_BINLOG))
      goto error;
    /* PURGE MASTER LOGS BEFORE 'data' */
    it= (Item *)lex->value_list.head();
    if (it->fix_fields_if_needed_for_scalar(lex->thd, &it))
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
      goto error;
    }
    it= new (thd->mem_root) Item_func_unix_timestamp(thd, it);
    it->fix_fields(thd, &it);
    res = purge_master_logs_before_date(thd, (ulong)it->val_int());
    break;
  }
#endif
  case SQLCOM_SHOW_WARNS:
  {
    res= mysqld_show_warnings(thd, (ulong)
			      ((1L << (uint) Sql_condition::WARN_LEVEL_NOTE) |
			       (1L << (uint) Sql_condition::WARN_LEVEL_WARN) |
			       (1L << (uint) Sql_condition::WARN_LEVEL_ERROR)
			       ));
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
    res= mysqld_show_warnings(thd, (ulong)
			      (1L << (uint) Sql_condition::WARN_LEVEL_ERROR));
    break;
  }
  case SQLCOM_SHOW_PROFILES:
  {
#if defined(ENABLED_PROFILING)
    thd->profiling.discard_current_query();
    res= thd->profiling.show_profiles();
    if (res)
      goto error;
#else
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
    goto error;
#endif
    break;
  }

#ifdef HAVE_REPLICATION
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
    if (check_global_access(thd, PRIV_STMT_SHOW_SLAVE_HOSTS))
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
  case SQLCOM_SHOW_RELAYLOG_EVENTS:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    if (check_global_access(thd, PRIV_STMT_SHOW_RELAYLOG_EVENTS))
      goto error;
    res = mysql_show_binlog_events(thd);
    break;
  }
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    if (check_global_access(thd, PRIV_STMT_SHOW_BINLOG_EVENTS))
      goto error;
    res = mysql_show_binlog_events(thd);
    break;
  }
#endif

  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_access(thd, INDEX_ACL, first_table->db.str,
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
      goto error;
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
    break;
  }
  case SQLCOM_PRELOAD_KEYS:
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_access(thd, INDEX_ACL, first_table->db.str,
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
      goto error;
    res = mysql_preload_keys(thd, first_table);
    break;
  }
#ifdef HAVE_REPLICATION
  case SQLCOM_CHANGE_MASTER:
  {
    LEX_MASTER_INFO *lex_mi= &thd->lex->mi;
    Master_info *mi;
    bool new_master= 0;
    bool master_info_added;

    if (check_global_access(thd, PRIV_STMT_CHANGE_MASTER))
      goto error;
    /*
      In this code it's ok to use LOCK_active_mi as we are adding new things
      into master_info_index
    */
    mysql_mutex_lock(&LOCK_active_mi);
    if (!master_info_index)
    {
      mysql_mutex_unlock(&LOCK_active_mi);
      my_error(ER_SERVER_SHUTDOWN, MYF(0));
      goto error;
    }

    mi= master_info_index->get_master_info(&lex_mi->connection_name,
                                           Sql_condition::WARN_LEVEL_NOTE);

    if (mi == NULL)
    {
      /* New replication created */
      mi= new Master_info(&lex_mi->connection_name, relay_log_recovery); 
      if (unlikely(!mi || mi->error()))
      {
        delete mi;
        res= 1;
        mysql_mutex_unlock(&LOCK_active_mi);
        break;
      }
      new_master= 1;
    }

    res= change_master(thd, mi, &master_info_added);
    if (res && new_master)
    {
      /*
        If the new master was added by change_master(), remove it as it didn't
        work (this will free mi as well).

        If new master was not added, we still need to free mi.
      */
      if (master_info_added)
        master_info_index->remove_master_info(mi, 1);
      else
        delete mi;
    }
    else
    {
      mi->rpl_filter= get_or_create_rpl_filter(lex_mi->connection_name.str,
                                               lex_mi->connection_name.length);
    }

    mysql_mutex_unlock(&LOCK_active_mi);
    break;
  }

  case SQLCOM_SHOW_BINLOG_STAT:
  {
    /* Accept one of two privileges */
    if (check_global_access(thd, PRIV_STMT_SHOW_BINLOG_STATUS))
      goto error;
    res = show_binlog_info(thd);
    break;
  }

#endif /* HAVE_REPLICATION */
  case SQLCOM_SHOW_ENGINE_STATUS:
    {
      if (check_global_access(thd, PRIV_STMT_SHOW_ENGINE_STATUS))
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
      break;
    }
  case SQLCOM_SHOW_ENGINE_MUTEX:
    {
      if (check_global_access(thd, PRIV_STMT_SHOW_ENGINE_MUTEX))
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
      break;
    }
  case SQLCOM_DROP_INDEX:
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
    /* fall through */
  case SQLCOM_CREATE_INDEX:
  /*
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
    TABLE with proper arguments.

    In the future ALTER TABLE will notice that the request is to
    only add indexes and create these one by one for the existing
    table without having to do a full rebuild.
  */
  {
    /* Prepare stack copies to be re-execution safe */
    Table_specification_st create_info;
    Alter_info alter_info(lex->alter_info, thd->mem_root);

    if (unlikely(thd->is_fatal_error)) /* out of memory creating alter_info */
      goto error;

    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
      goto error; /* purecov: inspected */

    create_info.init();
    create_info.db_type= 0;
    create_info.row_type= ROW_TYPE_NOT_USED;
    create_info.alter_info= &alter_info;

    WSREP_TO_ISOLATION_BEGIN(first_table->db.str, first_table->table_name.str, NULL);

    Recreate_info recreate_info;
    res= mysql_alter_table(thd, &first_table->db, &first_table->table_name,
                           &create_info, first_table,
                           &recreate_info, &alter_info,
                           0, (ORDER*) 0, 0, lex->if_exists());
    break;
  }
#ifdef HAVE_REPLICATION
  case SQLCOM_SLAVE_START:
  {
    LEX_MASTER_INFO* lex_mi= &thd->lex->mi;
    Master_info *mi;
    int load_error;

    load_error= rpl_load_gtid_slave_state(thd);

    /*
      We don't need to ensure that only one user is using master_info
      as start_slave is protected against simultaneous usage
    */
    if (unlikely((mi= get_master_info(&lex_mi->connection_name,
                                      Sql_condition::WARN_LEVEL_ERROR))))
    {
      if (load_error)
      {
        /*
          We cannot start a slave using GTID if we cannot load the
          GTID position from the mysql.gtid_slave_pos table. But we
          can allow non-GTID replication (useful eg. during upgrade).
        */
        if (mi->using_gtid != Master_info::USE_GTID_NO)
        {
          mi->release();
          break;
        }
        else
          thd->clear_error();
      }
      if (!start_slave(thd, mi, 1 /* net report*/))
        my_ok(thd);
      mi->release();
    }
    break;
  }
  case SQLCOM_SLAVE_STOP:
  {
    LEX_MASTER_INFO *lex_mi;
    Master_info *mi;
    /*
      If the client thread has locked tables, a deadlock is possible.
      Assume that
      - the client thread does LOCK TABLE t READ.
      - then the master updates t.
      - then the SQL slave thread wants to update t,
        so it waits for the client thread because t is locked by it.
    - then the client thread does SLAVE STOP.
      SLAVE STOP waits for the SQL slave thread to terminate its
      update t, which waits for the client thread because t is locked by it.
      To prevent that, refuse SLAVE STOP if the
      client thread has locked tables
    */
    if (thd->locked_tables_mode ||
        thd->in_active_multi_stmt_transaction() ||
        thd->global_read_lock.is_acquired())
    {
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER_THD(thd, ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
      goto error;
    }

    lex_mi= &thd->lex->mi;
    if ((mi= get_master_info(&lex_mi->connection_name,
                             Sql_condition::WARN_LEVEL_ERROR)))
    {
      if (stop_slave(thd, mi, 1/* net report*/))
        res= 1;
      mi->release();
      if (rpl_parallel_resize_pool_if_no_slaves())
        res= 1;
      if (!res)
        my_ok(thd);
    }
    break;
  }
  case SQLCOM_SLAVE_ALL_START:
  {
    mysql_mutex_lock(&LOCK_active_mi);
    if (master_info_index && !master_info_index->start_all_slaves(thd))
      my_ok(thd);
    mysql_mutex_unlock(&LOCK_active_mi);
    break;
  }
  case SQLCOM_SLAVE_ALL_STOP:
  {
    if (thd->locked_tables_mode ||
        thd->in_active_multi_stmt_transaction() ||
        thd->global_read_lock.is_acquired())
    {
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
                 ER_THD(thd, ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
      goto error;
    }
    mysql_mutex_lock(&LOCK_active_mi);
    if (master_info_index && !master_info_index->stop_all_slaves(thd))
      my_ok(thd);      
    mysql_mutex_unlock(&LOCK_active_mi);
    break;
  }
#endif /* HAVE_REPLICATION */
  case SQLCOM_RENAME_TABLE:
  {
    if (check_rename_table(thd, first_table, all_tables))
      goto error;

    WSREP_TO_ISOLATION_BEGIN(0, 0, first_table);

    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

    if (mysql_rename_tables(thd, first_table, 0, lex->if_exists()))
      goto error;
    break;
  }
#ifndef EMBEDDED_LIBRARY
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
    goto error;
#else
    {
      if (check_global_access(thd, PRIV_STMT_SHOW_BINARY_LOGS))
	goto error;
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
      res = show_binlogs(thd);
      break;
    }
#endif
#endif /* EMBEDDED_LIBRARY */
  case SQLCOM_SHOW_CREATE:
  {
     DBUG_ASSERT(first_table == all_tables && first_table != 0);
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
               MYF(0)); /* purecov: inspected */
    goto error;
#else
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);

     /*
        Access check:
        SHOW CREATE TABLE require any privileges on the table level (ie
        effecting all columns in the table).
        SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table
        level.
        NOTE: SHOW_VIEW ACL is checked when the view is created.
      */

      DBUG_PRINT("debug", ("lex->only_view: %d, table: %s.%s",
                           lex->table_type == TABLE_TYPE_VIEW,
                           first_table->db.str, first_table->table_name.str));
      res= mysqld_show_create(thd, first_table);
      break;
#endif
  }
  case SQLCOM_CHECKSUM:
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_READ);

    if (check_table_access(thd, SELECT_ACL, all_tables,
                           FALSE, UINT_MAX, FALSE))
      goto error; /* purecov: inspected */

    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
    break;
  }
  case SQLCOM_UPDATE:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);
    ha_rows found= 0, updated= 0;
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);

    if (update_precheck(thd, all_tables))
      break;

    /*
      UPDATE IGNORE can be unsafe. We therefore use row based
      logging if mixed or row based logging is available.
      TODO: Check if the order of the output of the select statement is
      deterministic. Waiting for BUG#42415
    */
    if (lex->ignore)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_UPDATE_IGNORE);

    DBUG_ASSERT(select_lex->limit_params.offset_limit == 0);
    unit->set_limit(select_lex);
    MYSQL_UPDATE_START(thd->query());
    res= up_result= mysql_update(thd, all_tables,
                                  select_lex->item_list,
                                  lex->value_list,
                                  select_lex->where,
                                  select_lex->order_list.elements,
                                  select_lex->order_list.first,
                                  unit->lim.get_select_limit(),
                                  lex->ignore, &found, &updated);
    MYSQL_UPDATE_DONE(res, found, updated);
    /* mysql_update return 2 if we need to switch to multi-update */
    if (up_result != 2)
      break;
    if (thd->lex->period_conditions.is_set())
    {
      DBUG_ASSERT(0); // Should never happen
      goto error;
    }
  }
  /* fall through */
  case SQLCOM_UPDATE_MULTI:
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* if we switched from normal update, rights are checked */
    if (up_result != 2)
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);
      if ((res= multi_update_precheck(thd, all_tables)))
        break;
    }
    else
      res= 0;

    unit->set_limit(select_lex);
    /*
      We can not use mysql_explain_union() because of parameters of
      mysql_select in mysql_multi_update so just set the option if needed
    */
    if (thd->lex->describe)
    {
      select_lex->set_explain_type(FALSE);
      select_lex->options|= SELECT_DESCRIBE;
    }

    res= mysql_multi_update_prepare(thd);

#ifdef HAVE_REPLICATION
    /* Check slave filtering rules */
    if (unlikely(thd->slave_thread && !have_table_map_for_update))
    {
      if (all_tables_not_ok(thd, all_tables))
      {
        if (res!= 0)
        {
          res= 0;             /* don't care of prev failure  */
          thd->clear_error(); /* filters are of highest prior */
        }
        /* we warn the slave SQL thread */
        my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
        break;
      }
      if (res)
        break;
    }
    else
    {
#endif /* HAVE_REPLICATION */
      if (res)
        break;
      if (opt_readonly &&
	  !(thd->security_ctx->master_access & PRIV_IGNORE_READ_ONLY) &&
	  some_non_temp_table_to_be_updated(thd, all_tables))
      {
	my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
	break;
      }
#ifdef HAVE_REPLICATION
    }  /* unlikely */
#endif
    {
      multi_update *result_obj;
      MYSQL_MULTI_UPDATE_START(thd->query());
      res= mysql_multi_update(thd, all_tables,
                              &select_lex->item_list,
                              &lex->value_list,
                              select_lex->where,
                              select_lex->options,
                              lex->duplicates,
                              lex->ignore,
                              unit,
                              select_lex,
                              &result_obj);
      if (result_obj)
      {
        MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(),
                                result_obj->num_updated());
        res= FALSE; /* Ignore errors here */
        delete result_obj;
      }
      else
      {
        MYSQL_MULTI_UPDATE_DONE(1, 0, 0);
      }
    }
    break;
  }
  case SQLCOM_REPLACE:
    if ((res= generate_incident_event(thd)))
      break;
    /* fall through */
  case SQLCOM_INSERT:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);
    select_result *sel_result= NULL;
    DBUG_ASSERT(first_table == all_tables && first_table != 0);

    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);

    /*
      Since INSERT DELAYED doesn't support temporary tables, we could
      not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE.
      Open them here instead.
    */
    if (first_table->lock_type != TL_WRITE_DELAYED)
    {
      res= (thd->open_temporary_tables(all_tables)) ? TRUE : FALSE;
      if (res)
        break;
    }

    if ((res= insert_precheck(thd, all_tables)))
      break;

    MYSQL_INSERT_START(thd->query());
    Protocol* save_protocol=NULL;

    if (lex->has_returning())
    {
      status_var_increment(thd->status_var.feature_insert_returning);

      /* This is INSERT ... RETURNING. It will return output to the client */
      if (thd->lex->analyze_stmt)
      {
        /*
          Actually, it is ANALYZE .. INSERT .. RETURNING. We need to produce
          output and then discard it.
        */
        sel_result= new (thd->mem_root) select_send_analyze(thd);
        save_protocol= thd->protocol;
        thd->protocol= new Protocol_discard(thd);
      }
      else
      {
        if (!(sel_result= new (thd->mem_root) select_send(thd)))
          goto error;
      }
    }

    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
                      lex->update_list, lex->value_list,
                      lex->duplicates, lex->ignore, sel_result);
    if (save_protocol)
    {
      delete thd->protocol;
      thd->protocol= save_protocol;
    }
    if (!res && thd->lex->analyze_stmt)
      res= thd->lex->explain->send_explain(thd);
    delete sel_result;
    MYSQL_INSERT_DONE(res, (ulong) thd->get_row_count_func());
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
    if (first_table->view && !first_table->contain_auto_increment)
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;

#ifdef ENABLED_DEBUG_SYNC
    DBUG_EXECUTE_IF("after_mysql_insert",
                    {
                      const char act1[]= "now wait_for signal.continue";
                      const char act2[]= "now signal signal.continued";
                      DBUG_ASSERT(debug_sync_service);
                      DBUG_ASSERT(!debug_sync_set_action(thd,
                                                         STRING_WITH_LEN(act1)));
                      DBUG_ASSERT(!debug_sync_set_action(thd,
                                                         STRING_WITH_LEN(act2)));
                    };);
    DEBUG_SYNC(thd, "after_mysql_insert");
#endif
    break;
  }
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);
    select_insert *sel_result;
    select_result *result= NULL;
    bool explain= MY_TEST(lex->describe);
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);

    if ((res= insert_precheck(thd, all_tables)))
      break;
#ifdef WITH_WSREP
    if (WSREP(thd) && thd->wsrep_consistency_check == CONSISTENCY_CHECK_DECLARED)
    {
      thd->wsrep_consistency_check = CONSISTENCY_CHECK_RUNNING;
      WSREP_TO_ISOLATION_BEGIN(first_table->db.str, first_table->table_name.str, NULL);
    }
#endif /* WITH_WSREP */

    /*
      INSERT...SELECT...ON DUPLICATE KEY UPDATE/REPLACE SELECT/
      INSERT...IGNORE...SELECT can be unsafe, unless ORDER BY PRIMARY KEY
      clause is used in SELECT statement. We therefore use row based
      logging if mixed or row based logging is available.
      TODO: Check if the order of the output of the select statement is
      deterministic. Waiting for BUG#42415
    */
    if (lex->sql_command == SQLCOM_INSERT_SELECT &&
        lex->duplicates == DUP_UPDATE)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE);

    if (lex->sql_command == SQLCOM_INSERT_SELECT && lex->ignore)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT);

    if (lex->sql_command == SQLCOM_REPLACE_SELECT)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_REPLACE_SELECT);

    /* Fix lock for first table */
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;

    /* Don't unlock tables until command is written to binary log */
    select_lex->options|= SELECT_NO_UNLOCK;

    unit->set_limit(select_lex);

    if (!(res=open_and_lock_tables(thd, all_tables, TRUE, 0)))
    {
      MYSQL_INSERT_SELECT_START(thd->query());
      /*
        Only the INSERT table should be merged. Other will be handled by
        select.
      */

      Protocol* save_protocol=NULL;

      if (lex->has_returning())
      {
        status_var_increment(thd->status_var.feature_insert_returning);

        /* This is INSERT ... RETURNING. It will return output to the client */
        if (thd->lex->analyze_stmt)
        {
          /*
            Actually, it is ANALYZE .. INSERT .. RETURNING. We need to produce
            output and then discard it.
          */
          result= new (thd->mem_root) select_send_analyze(thd);
          save_protocol= thd->protocol;
          thd->protocol= new Protocol_discard(thd);
        }
        else
        {
          if (!(result= new (thd->mem_root) select_send(thd)))
            goto error;
        }
      }

      /* Skip first table, which is the table we are inserting in */
      TABLE_LIST *second_table= first_table->next_local;
      /*
        This is a hack: this leaves select_lex->table_list in an inconsistent
        state as 'elements' does not contain number of elements in the list.
        Moreover, if second_table == NULL then 'next' becomes invalid.
        TODO: fix it by removing the front element (restoring of it should
        be done properly as well)
      */
      select_lex->table_list.first= second_table;
      select_lex->context.table_list=
        select_lex->context.first_name_resolution_table= second_table;
      res= mysql_insert_select_prepare(thd, result);
      if (!res &&
          (sel_result= new (thd->mem_root)
                       select_insert(thd, first_table,
                                    first_table->table,
                                    &lex->field_list,
                                    &lex->update_list,
                                    &lex->value_list,
                                    lex->duplicates,
                                    lex->ignore,
                                    result)))
      {
        if (lex->analyze_stmt)
          ((select_result_interceptor*)sel_result)->disable_my_ok_calls();

        if (explain)
          res= mysql_explain_union(thd, &thd->lex->unit, sel_result);
        else
          res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
        /*
          Invalidate the table in the query cache if something changed
          after unlocking when changes become visible.
          TODO: this is workaround. right way will be move invalidating in
          the unlock procedure.
        */
        if (!res && first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
            thd->lock)
        {
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
          query_cache_invalidate3(thd, first_table, 1);
          first_table->next_local= save_table;
        }
        if (explain)
        {
          /*
            sel_result needs to be cleaned up properly.
            INSERT... SELECT statement will call either send_eof() or
            abort_result_set(). EXPLAIN doesn't call either, so we need
            to cleanup manually.
          */
          sel_result->abort_result_set();
        }
        delete sel_result;
      }
      else if (res < 0)
      {
        /*
          Insert should be ignored but we have to log the query in statement
          format in the binary log
        */
        res= thd->binlog_current_query_unfiltered();
      }
      delete result;
      if (save_protocol)
      {
        delete thd->protocol;
        thd->protocol= save_protocol;
      }
      if (!res && (explain || lex->analyze_stmt))
        res= thd->lex->explain->send_explain(thd);

      /* revert changes for SP */
      MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->get_row_count_func());
      select_lex->table_list.first= first_table;
    }
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
    if (first_table->view && !first_table->contain_auto_increment)
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;

    break;
  }
  case SQLCOM_DELETE:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);
    select_result *sel_result= NULL;
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);

    if ((res= delete_precheck(thd, all_tables)))
      break;
    DBUG_ASSERT(select_lex->limit_params.offset_limit == 0);
    unit->set_limit(select_lex);

    MYSQL_DELETE_START(thd->query());
    Protocol *save_protocol= NULL;

    if (lex->has_returning())
    {
      /* This is DELETE ... RETURNING.  It will return output to the client */
      if (thd->lex->analyze_stmt)
      {
        /* 
          Actually, it is ANALYZE .. DELETE .. RETURNING. We need to produce
          output and then discard it.
        */
        sel_result= new (thd->mem_root) select_send_analyze(thd);
        save_protocol= thd->protocol;
        thd->protocol= new Protocol_discard(thd);
      }
      else
      {
        if (!lex->result && !(sel_result= new (thd->mem_root) select_send(thd)))
          goto error;
      }
    }

    res = mysql_delete(thd, all_tables, 
                       select_lex->where, &select_lex->order_list,
                       unit->lim.get_select_limit(), select_lex->options,
                       lex->result ? lex->result : sel_result);

    if (save_protocol)
    {
      delete thd->protocol;
      thd->protocol= save_protocol;
    }

    if (thd->lex->analyze_stmt || thd->lex->describe)
    {
      if (!res)
        res= thd->lex->explain->send_explain(thd);
    }

    delete sel_result;
    MYSQL_DELETE_DONE(res, (ulong) thd->get_row_count_func());
    break;
  }
  case SQLCOM_DELETE_MULTI:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
    multi_delete *result;
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);

    if ((res= multi_delete_precheck(thd, all_tables)))
      break;

    /* condition will be TRUE on SP re-excuting */
    if (select_lex->item_list.elements != 0)
      select_lex->item_list.empty();
    if (add_item_to_list(thd, new (thd->mem_root) Item_null(thd)))
      goto error;

    THD_STAGE_INFO(thd, stage_init);
    if ((res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
      break;

    MYSQL_MULTI_DELETE_START(thd->query());
    if (unlikely(res= mysql_multi_delete_prepare(thd)))
    {
      MYSQL_MULTI_DELETE_DONE(1, 0);
      goto error;
    }

    if (likely(!thd->is_fatal_error))
    {
      result= new (thd->mem_root) multi_delete(thd, aux_tables,
                                               lex->table_count_update);
      if (likely(result))
      {
        if (unlikely(select_lex->vers_setup_conds(thd, aux_tables)))
          goto multi_delete_error;
        res= mysql_select(thd,
                          select_lex->get_table_list(),
                          select_lex->item_list,
                          select_lex->where,
                          0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
                          (ORDER *)NULL,
                          (select_lex->options | thd->variables.option_bits |
                          SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                          OPTION_SETUP_TABLES_DONE) & ~OPTION_BUFFER_RESULT,
                          result, unit, select_lex);
        res|= (int)(thd->is_error());

        MYSQL_MULTI_DELETE_DONE(res, result->num_deleted());
        if (res)
          result->abort_result_set(); /* for both DELETE and EXPLAIN DELETE */
        else
        {
          if (lex->describe || lex->analyze_stmt)
            res= thd->lex->explain->send_explain(thd);
        }
      multi_delete_error:
        delete result;
      }
    }
    else
    {
      res= TRUE;                                // Error
      MYSQL_MULTI_DELETE_DONE(1, 0);
    }
    break;
  }
  case SQLCOM_DROP_SEQUENCE:
  case SQLCOM_DROP_TABLE:
  {
    int result;
    DBUG_ASSERT(first_table == all_tables && first_table != 0);

    thd->open_options|= HA_OPEN_FOR_REPAIR;
    result= thd->open_temporary_tables(all_tables);
    thd->open_options&= ~HA_OPEN_FOR_REPAIR;
    if (result)
      goto error;
    if (!lex->tmp_table())
    {
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
	goto error;				/* purecov: inspected */
    }
    else
    {
      if (thd->transaction->xid_state.check_has_uncommitted_xa())
        goto error;
      status_var_decrement(thd->status_var.com_stat[lex->sql_command]);
      status_var_increment(thd->status_var.com_drop_tmp_table);

      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
      thd->variables.option_bits|= OPTION_BINLOG_THIS_TRX;
    }
    /*
      If we are a slave, we should add IF EXISTS if the query executed
      on the master without an error. This will help a slave to
      recover from multi-table DROP TABLE that was aborted in the
      middle.
    */
    if ((thd->slave_thread && !thd->slave_expected_error &&
         slave_ddl_exec_mode_options == SLAVE_EXEC_MODE_IDEMPOTENT) ||
        thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

#ifdef WITH_WSREP
    if (WSREP(thd))
    {
      for (TABLE_LIST *table= all_tables; table; table= table->next_global)
      {
        if (!lex->tmp_table() &&
           (!thd->is_current_stmt_binlog_format_row() ||
	    !is_temporary_table(table)))
        {
          WSREP_TO_ISOLATION_BEGIN(NULL, NULL, all_tables);
          break;
        }
      }
    }
#endif /* WITH_WSREP */

    /* DDL and binlog write order are protected by metadata locks. */
    res= mysql_rm_table(thd, first_table, lex->if_exists(), lex->tmp_table(),
                        lex->table_type == TABLE_TYPE_SEQUENCE, 0);

    /*
      When dropping temporary tables if @@session_track_state_change is ON
      then send the boolean tracker in the OK packet
    */
    if(!res && (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
      thd->session_tracker.state_change.mark_as_changed(thd);
    }
    break;
  }
  case SQLCOM_SHOW_PROCESSLIST:
    if (!thd->security_ctx->priv_user[0] &&
        check_global_access(thd, PRIV_STMT_SHOW_PROCESSLIST))
      break;
    mysqld_list_processes(thd,
                (thd->security_ctx->master_access & PRIV_STMT_SHOW_PROCESSLIST ?
                 NullS :
                 thd->security_ctx->priv_user),
                lex->verbose);
    break;
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
  case SQLCOM_SHOW_ENGINE_LOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
               MYF(0));	/* purecov: inspected */
    goto error;
#else
    {
      if (check_access(thd, FILE_ACL, any_db.str, NULL, NULL, 0, 0))
	goto error;
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
      break;
    }
#endif
  case SQLCOM_CHANGE_DB:
  {
    if (!mysql_change_db(thd, &select_lex->db, FALSE))
      my_ok(thd);

    break;
  }

  case SQLCOM_LOAD:
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    privilege_t privilege= (lex->duplicates == DUP_REPLACE ?
                            INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                           (lex->local_file ? NO_ACL : FILE_ACL);

    if (lex->local_file)
    {
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
          !opt_local_infile)
      {
        my_message(ER_LOAD_INFILE_CAPABILITY_DISABLED, 
                   ER_THD(thd, ER_LOAD_INFILE_CAPABILITY_DISABLED), MYF(0));
        goto error;
      }
    }

    if (check_one_table_access(thd, privilege, all_tables))
      goto error;

    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
                    lex->update_list, lex->value_list, lex->duplicates,
                    lex->ignore, (bool) lex->local_file);
    break;
  }

  case SQLCOM_SET_OPTION:
  {
    List<set_var_base> *lex_var_list= &lex->var_list;

    if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
         || open_and_lock_tables(thd, all_tables, TRUE, 0)))
      goto error;
    if (likely(!(res= sql_set_variables(thd, lex_var_list, true))))
    {
      if (likely(!thd->is_error()))
        my_ok(thd);
    }
    else
    {
      /*
        We encountered some sort of error, but no message was sent.
        Send something semi-generic here since we don't know which
        assignment in the list caused the error.
      */
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
      goto error;
    }

    break;
  }

  case SQLCOM_UNLOCK_TABLES:
    /*
      It is critical for mysqldump --single-transaction --master-data that
      UNLOCK TABLES does not implicitely commit a connection which has only
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
      false, mysqldump will not work.
    */
    if (thd->variables.option_bits & OPTION_TABLE_LOCK)
    {
      res= trans_commit_implicit(thd);
      if (thd->locked_tables_list.unlock_locked_tables(thd))
        res= 1;
      thd->release_transactional_locks();
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
      thd->reset_binlog_for_next_statement();
    }
    if (thd->global_read_lock.is_acquired() &&
        thd->current_backup_stage == BACKUP_FINISHED)
      thd->global_read_lock.unlock_global_read_lock(thd);
    if (res)
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_LOCK_TABLES:
    /* We must end the transaction first, regardless of anything */
    res= trans_commit_implicit(thd);
    if (thd->locked_tables_list.unlock_locked_tables(thd))
      res= 1;
    /* Release transactional metadata locks. */
    thd->release_transactional_locks();
    if (res)
      goto error;

#ifdef WITH_WSREP
    /* Clean up the previous transaction on implicit commit. */
    if (wsrep_on(thd) && !wsrep_not_committed(thd) && wsrep_after_statement(thd))
      goto error;
#endif

    /* We can't have any kind of table locks while backup is active */
    if (thd->current_backup_stage != BACKUP_FINISHED)
    {
      my_error(ER_BACKUP_LOCK_IS_ACTIVE, MYF(0));
      goto error;
    }

    /* Should not lock tables while BACKUP LOCK is active */
    if (thd->mdl_backup_lock)
    {
      my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
      goto error;
    }

    /*
      Here we have to pre-open temporary tables for LOCK TABLES.

      CF_PREOPEN_TMP_TABLES is not set for this SQL statement simply
      because LOCK TABLES calls close_thread_tables() as a first thing
      (it's called from unlock_locked_tables() above). So even if
      CF_PREOPEN_TMP_TABLES was set and the tables would be pre-opened
      in a usual way, they would have been closed.
    */
    if (thd->open_temporary_tables(all_tables))
      goto error;

    if (lock_tables_precheck(thd, all_tables))
      goto error;

    thd->variables.option_bits|= OPTION_TABLE_LOCK;

    res= lock_tables_open_and_lock_tables(thd, all_tables);

    if (res)
    {
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
    }
    else
    {
#ifdef HAVE_QUERY_CACHE
      if (thd->variables.query_cache_wlock_invalidate)
	query_cache.invalidate_locked_for_write(thd, first_table);
#endif /*HAVE_QUERY_CACHE*/
      my_ok(thd);
    }
    break;
  case SQLCOM_BACKUP:
    if (check_global_access(thd, RELOAD_ACL))
      goto error;
    if (!(res= run_backup_stage(thd, lex->backup_stage)))
      my_ok(thd);
    break;
  case SQLCOM_BACKUP_LOCK:
    if (check_global_access(thd, RELOAD_ACL))
      goto error;
    /* first table is set for lock. For unlock the list is empty */
    if (first_table)
      res= backup_lock(thd, first_table);
    else
      backup_unlock(thd);
    if (!res)
      my_ok(thd);
    break;
  case SQLCOM_CREATE_DB:
  {
    if (prepare_db_action(thd, lex->create_info.or_replace() ?
                          (CREATE_ACL | DROP_ACL) : CREATE_ACL,
                          &lex->name))
      break;

    if ((res= lex->create_info.resolve_to_charset_collation_context(thd,
                                 thd->charset_collation_context_create_db())))
      break;

    WSREP_TO_ISOLATION_BEGIN(lex->name.str, NULL, NULL);

    res= mysql_create_db(thd, &lex->name,
                         lex->create_info, &lex->create_info);
    break;
  }
  case SQLCOM_DROP_DB:
  {
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

    if (prepare_db_action(thd, DROP_ACL, &lex->name))
      break;

    WSREP_TO_ISOLATION_BEGIN(lex->name.str, NULL, NULL);

    res= mysql_rm_db(thd, &lex->name, lex->if_exists());
    break;
  }
  case SQLCOM_ALTER_DB_UPGRADE:
  {
    LEX_CSTRING *db= &lex->name;
#ifdef HAVE_REPLICATION
    if (thd->slave_thread)
    {
      rpl_filter= thd->system_thread_info.rpl_sql_info->rpl_filter;
      if (!rpl_filter->db_ok(db->str) ||
          !rpl_filter->db_ok_with_wild_table(db->str))
      {
        res= 1;
        my_message(ER_SLAVE_IGNORED_TABLE, ER_THD(thd, ER_SLAVE_IGNORED_TABLE), MYF(0));
        break;
      }
    }
#endif
    if (check_db_name((LEX_STRING*) db))
    {
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
      break;
    }
    if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, DROP_ACL, db->str, NULL, NULL, 1, 0) ||
        check_access(thd, CREATE_ACL, db->str, NULL, NULL, 1, 0))
    {
      res= 1;
      break;
    }

    WSREP_TO_ISOLATION_BEGIN(db->str, NULL, NULL);

    res= mysql_upgrade_db(thd, db);
    if (!res)
      my_ok(thd);
    break;
  }
  case SQLCOM_ALTER_DB:
  {
    LEX_CSTRING *db= &lex->name;
    if (prepare_db_action(thd, ALTER_ACL, db))
      break;

    if ((res= lex->create_info.resolve_to_charset_collation_context(thd,
                     thd->charset_collation_context_alter_db(lex->name.str))))
      break;

    WSREP_TO_ISOLATION_BEGIN(db->str, NULL, NULL);

    res= mysql_alter_db(thd, db, &lex->create_info);
    break;
  }
  case SQLCOM_SHOW_CREATE_DB:
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    res= show_create_db(thd, lex);
    break;
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
  #ifdef HAVE_EVENT_SCHEDULER
  do
  {
    DBUG_ASSERT(lex->event_parse_data);
    if (lex->table_or_sp_used())
    {
      my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), "CREATE/ALTER EVENT");
      break;
    }

    res= sp_process_definer(thd);
    if (res)
      break;

    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
    {
      res= Events::create_event(thd, lex->event_parse_data);
      break;
    }
    case SQLCOM_ALTER_EVENT:
      res= Events::update_event(thd, lex->event_parse_data,
                                lex->spname ? &lex->spname->m_db : NULL,
                                lex->spname ? &lex->spname->m_name : NULL);
      break;
    default:
      DBUG_ASSERT(0);
    }
    DBUG_PRINT("info",("DDL error code=%d", res));
    if (!res)
      my_ok(thd);

  } while (0);
  /* Don't do it, if we are inside a SP */
  if (!thd->spcont && !is_called_from_prepared_stmt)
  {
    sp_head::destroy(lex->sphead);
    lex->sphead= NULL;
  }
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
  case SQLCOM_SHOW_CREATE_EVENT:
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    res= Events::show_create_event(thd, &lex->spname->m_db,
                                   &lex->spname->m_name);
    break;
  case SQLCOM_DROP_EVENT:
    if (!(res= Events::drop_event(thd,
                                  &lex->spname->m_db, &lex->spname->m_name,
                                  lex->if_exists())))
      my_ok(thd);
    break;
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
  {
    if (check_access(thd, lex->create_info.or_replace() ?
                          (INSERT_ACL | DELETE_ACL) : INSERT_ACL,
                     "mysql", NULL, NULL, 1, 0))
      break;
#ifdef HAVE_DLOPEN
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    if (!(res = mysql_create_function(thd, &lex->udf)))
      my_ok(thd);
#else
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
    res= TRUE;
#endif
    break;
  }
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  case SQLCOM_CREATE_USER:
  case SQLCOM_CREATE_ROLE:
  {
    if (check_access(thd, lex->create_info.or_replace() ?
                          INSERT_ACL | DELETE_ACL : INSERT_ACL,
                     "mysql", NULL, NULL, 1, 1) &&
        check_global_access(thd,CREATE_USER_ACL))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    /* Conditionally writes to binlog */
    if (!(res= mysql_create_user(thd, lex->users_list,
                                 lex->sql_command == SQLCOM_CREATE_ROLE)))
      my_ok(thd);
    break;
  }
  case SQLCOM_DROP_USER:
  case SQLCOM_DROP_ROLE:
  {
    if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) &&
        check_global_access(thd,CREATE_USER_ACL))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    /* Conditionally writes to binlog */
    if (!(res= mysql_drop_user(thd, lex->users_list,
                               lex->sql_command == SQLCOM_DROP_ROLE)))
      my_ok(thd);
    break;
  }
  case SQLCOM_ALTER_USER:
  case SQLCOM_RENAME_USER:
  {
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
        check_global_access(thd,CREATE_USER_ACL))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    /* Conditionally writes to binlog */
    if (lex->sql_command == SQLCOM_ALTER_USER)
      res= mysql_alter_user(thd, lex->users_list);
    else
      res= mysql_rename_user(thd, lex->users_list);
    if (!res)
      my_ok(thd);
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
        check_global_access(thd,CREATE_USER_ACL))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    /* Conditionally writes to binlog */
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
      my_ok(thd);
    break;
  }

  case SQLCOM_REVOKE_ROLE:
  case SQLCOM_GRANT_ROLE:
  {
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    if (!(res= mysql_grant_role(thd, lex->users_list,
                                lex->sql_command != SQLCOM_GRANT_ROLE)))
      my_ok(thd);
    break;
  }
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
  case SQLCOM_RESET:
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
    */
    lex->no_write_to_binlog= 1;
    /* fall through */
  case SQLCOM_FLUSH:
  {
    int write_to_binlog;
    if (check_global_access(thd,RELOAD_ACL))
      goto error;

    if (first_table && lex->type & (REFRESH_READ_LOCK|REFRESH_FOR_EXPORT))
    {
      /* Check table-level privileges. */
      if (check_table_access(thd, PRIV_LOCK_TABLES, all_tables,
                             FALSE, UINT_MAX, FALSE))
        goto error;

      if (flush_tables_with_read_lock(thd, all_tables))
        goto error;

      my_ok(thd);
      break;
    }

#ifdef WITH_WSREP
    if (lex->type & (
    REFRESH_GRANT                           |
    REFRESH_HOSTS                           |
#ifdef HAVE_OPENSSL
    REFRESH_DES_KEY_FILE                    |
#endif
    /*
      Write all flush log statements except
      FLUSH LOGS
      FLUSH BINARY LOGS
      Check reload_acl_and_cache for why.
    */
    REFRESH_RELAY_LOG                       |
    REFRESH_SLOW_LOG                        |
    REFRESH_GENERAL_LOG                     |
    REFRESH_ENGINE_LOG                      |
    REFRESH_ERROR_LOG                       |
#ifdef HAVE_QUERY_CACHE
    REFRESH_QUERY_CACHE_FREE                |
#endif /* HAVE_QUERY_CACHE */
    REFRESH_STATUS                          |
    REFRESH_USER_RESOURCES))
    {
      WSREP_TO_ISOLATION_BEGIN_WRTCHK(WSREP_MYSQL_DB, NULL, NULL);
    }
#endif /* WITH_WSREP*/

#ifdef HAVE_REPLICATION
    if (lex->type & REFRESH_READ_LOCK)
    {
      /*
        We need to pause any parallel replication slave workers during FLUSH
        TABLES WITH READ LOCK. Otherwise we might cause a deadlock, as
        worker threads eun run in arbitrary order but need to commit in a
        specific given order.
      */
      if (rpl_pause_for_ftwrl(thd))
        goto error;
    }
#endif
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
    {
#ifdef WITH_WSREP
      if ((lex->type & REFRESH_TABLES) && !(lex->type & (REFRESH_FOR_EXPORT|REFRESH_READ_LOCK)))
      {
        /*
          This is done after reload_acl_and_cache is because
          LOCK TABLES is not replicated in galera, the upgrade of which
          is checked in reload_acl_and_cache.
          Hence, done after/if we are able to upgrade locks.
        */
        if (first_table)
        {
          WSREP_TO_ISOLATION_BEGIN_WRTCHK(NULL, NULL, first_table);
        }
        else
        {
          WSREP_TO_ISOLATION_BEGIN_WRTCHK(WSREP_MYSQL_DB, NULL, NULL);
        }
      }
#endif /* WITH_WSREP */
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */

      if (write_to_binlog > 0)  // we should write
      { 
        if (!lex->no_write_to_binlog)
          res= write_bin_log(thd, FALSE, thd->query(), thd->query_length());
      } else if (write_to_binlog < 0) 
      {
        /* 
           We should not write, but rather report error because 
           reload_acl_and_cache binlog interactions failed 
         */
        res= 1;
      }

      if (!res)
        my_ok(thd);
    } 
    else
      res= 1;                                   // reload_acl_and_cache failed
#ifdef HAVE_REPLICATION
    if (lex->type & REFRESH_READ_LOCK)
      rpl_unpause_after_ftwrl(thd);
#endif
    
    break;
  }
  case SQLCOM_KILL:
  {
    if (lex->table_or_sp_used())
    {
      my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), "KILL");
      break;
    }

    if (lex->kill_type == KILL_TYPE_ID || lex->kill_type == KILL_TYPE_QUERY)
    {
      Item *it= (Item *)lex->value_list.head();
      if (it->fix_fields_if_needed_for_scalar(lex->thd, &it))
      {
        my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
                   MYF(0));
        goto error;
      }
      sql_kill(thd, (my_thread_id) it->val_int(), lex->kill_signal, lex->kill_type);
    }
    else
      sql_kill_user(thd, get_current_user(thd, lex->users_list.head()),
                    lex->kill_signal);
    break;
  }
  case SQLCOM_SHUTDOWN:
#ifndef EMBEDDED_LIBRARY
    DBUG_EXECUTE_IF("crash_shutdown", DBUG_SUICIDE(););
    if (check_global_access(thd,SHUTDOWN_ACL))
      goto error;
    kill_mysql(thd);
    my_ok(thd);
#else
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
#endif
    break;

#ifndef NO_EMBEDDED_ACCESS_CHECKS
  case SQLCOM_SHOW_CREATE_USER:
  {
    LEX_USER *grant_user= lex->grant_user;
    if (!grant_user)
      goto error;

    res = mysql_show_create_user(thd, grant_user);
    break;
  }
  case SQLCOM_SHOW_GRANTS:
  {
    LEX_USER *grant_user= lex->grant_user;
    if (!grant_user)
      goto error;

    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    res = mysql_show_grants(thd, grant_user);
    break;
  }
#endif
  case SQLCOM_HA_OPEN:
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))
      goto error;
    /* Close temporary tables which were pre-opened for privilege checking. */
    close_thread_tables(thd);
    all_tables->table= NULL;
    res= mysql_ha_open(thd, first_table, 0);
    break;
  case SQLCOM_HA_CLOSE:
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
    break;
  case SQLCOM_HA_READ:
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /*
      There is no need to check for table permissions here, because
      if a user has no permissions to read a table, he won't be
      able to open it (with SQLCOM_HA_OPEN) in the first place.
    */
    unit->set_limit(select_lex);

    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
                       unit->lim.get_select_limit(),
                       unit->lim.get_offset_limit());
    break;

  case SQLCOM_BEGIN:
    DBUG_PRINT("info", ("Executing SQLCOM_BEGIN  thd: %p", thd));
    if (trans_begin(thd, lex->start_transaction_opt))
    {
      thd->release_transactional_locks();
      WSREP_DEBUG("BEGIN failed, MDL released: %lld",
                  (longlong) thd->thread_id);
      WSREP_DEBUG("stmt_da, sql_errno: %d", (thd->get_stmt_da()->is_error()) ? thd->get_stmt_da()->sql_errno() : 0);
      goto error;
    }
    my_ok(thd);
    break;
  case SQLCOM_COMMIT:
  {
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
    bool commit_failed= trans_commit(thd);
    thd->release_transactional_locks();
    if (commit_failed)
    {
      WSREP_DEBUG("COMMIT failed, MDL released: %lld",
                  (longlong) thd->thread_id);
      goto error;
    }
    /* Begin transaction with the same isolation level. */
    if (tx_chain)
    {
      if (trans_begin(thd))
        goto error;
    }
    else
    {
      /* Reset the isolation level and access mode if no chaining transaction.*/
      trans_reset_one_shot_chistics(thd);
    }
    /* Disconnect the current client connection. */
    if (tx_release)
    {
      thd->set_killed(KILL_CONNECTION);
      thd->print_aborted_warning(3, "RELEASE");
    }
    my_ok(thd);
    break;
  }
  case SQLCOM_ROLLBACK:
  {
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
    bool rollback_failed= trans_rollback(thd);
    thd->release_transactional_locks();

    if (rollback_failed)
    {
      WSREP_DEBUG("rollback failed, MDL released: %lld",
                  (longlong) thd->thread_id);
      goto error;
    }
    /* Begin transaction with the same isolation level. */
    if (tx_chain)
    {
#ifdef WITH_WSREP
      /* If there are pending changes after rollback we should clear them */
      if (wsrep_on(thd) && wsrep_has_changes(thd))
        wsrep_after_statement(thd);
#endif
      if (trans_begin(thd))
        goto error;
    }
    else
    {
      /* Reset the isolation level and access mode if no chaining transaction.*/
      trans_reset_one_shot_chistics(thd);
    }
    /* Disconnect the current client connection. */
    if (tx_release)
      thd->set_killed(KILL_CONNECTION);
    my_ok(thd);
   break;
  }
  case SQLCOM_RELEASE_SAVEPOINT:
    if (trans_release_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
    if (trans_rollback_to_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_SAVEPOINT:
    if (trans_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
  case SQLCOM_CREATE_PACKAGE:
  case SQLCOM_CREATE_PACKAGE_BODY:
  {
    if (mysql_create_routine(thd, lex))
      goto error;
    my_ok(thd);
    break; /* break super switch */
  } /* end case group bracket */
  case SQLCOM_COMPOUND:
  {
    sp_head *sp= lex->sphead;
    DBUG_ASSERT(all_tables == 0);
    DBUG_ASSERT(thd->in_sub_stmt == 0);
    sp->m_sql_mode= thd->variables.sql_mode;
    sp->m_sp_share= MYSQL_GET_SP_SHARE(sp->m_handler->type(),
                                       sp->m_db.str, static_cast<uint>(sp->m_db.length),
                                       sp->m_name.str, static_cast<uint>(sp->m_name.length));
    if (do_execute_sp(thd, lex->sphead))
      goto error;
    break;
  }

  case SQLCOM_ALTER_PROCEDURE:
  case SQLCOM_ALTER_FUNCTION:
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
    if (alter_routine(thd, lex))
      goto error;
    break;
  case SQLCOM_DROP_PROCEDURE:
  case SQLCOM_DROP_FUNCTION:
  case SQLCOM_DROP_PACKAGE:
  case SQLCOM_DROP_PACKAGE_BODY:
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
    if (drop_routine(thd, lex))
      goto error;
    break;
  case SQLCOM_SHOW_CREATE_PROC:
  case SQLCOM_SHOW_CREATE_FUNC:
  case SQLCOM_SHOW_CREATE_PACKAGE:
  case SQLCOM_SHOW_CREATE_PACKAGE_BODY:
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
      const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
      if (sph->sp_show_create_routine(thd, lex->spname))
        goto error;
      break;
    }
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
  case SQLCOM_SHOW_PACKAGE_BODY_CODE:
    {
#ifndef DBUG_OFF
      Database_qualified_name pkgname(&null_clex_str, &null_clex_str);
      sp_head *sp;
      const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
      if (sph->sp_resolve_package_routine(thd, thd->lex->sphead,
                                          lex->spname, &sph, &pkgname))
        return true;
      if (sph->sp_cache_routine(thd, lex->spname, false, &sp))
        goto error;
      if (!sp || sp->show_routine_code(thd))
      {
        /* We don't distinguish between errors for now */
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 sph->type_str(), lex->spname->m_name.str);
        goto error;
      }
      break;
#else
      my_error(ER_FEATURE_DISABLED, MYF(0),
               "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
      goto error;
#endif // ifndef DBUG_OFF
    }
  case SQLCOM_SHOW_CREATE_TRIGGER:
    {
      if (check_ident_length(&lex->spname->m_name))
        goto error;

      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
      if (show_create_trigger(thd, lex->spname))
        goto error; /* Error has been already logged. */

      break;
    }
  case SQLCOM_CREATE_VIEW:
    {
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
        as specified through the thd->lex->create_view->mode flag.
      */
      res= mysql_create_view(thd, first_table, thd->lex->create_view->mode);
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
        goto error;

      WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

      if (thd->variables.option_bits & OPTION_IF_EXISTS)
        lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

      /* Conditionally writes to binlog. */
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
      break;
    }
  case SQLCOM_CREATE_TRIGGER:
  {
    /* Conditionally writes to binlog. */
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

    /* Conditionally writes to binlog. */
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
  case SQLCOM_XA_START:
#ifdef WITH_WSREP
    if (WSREP_ON)
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "XA transactions with Galera replication");
      break;
    }
#endif /* WITH_WSREP */
    if (trans_xa_start(thd))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_XA_END:
    if (trans_xa_end(thd))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_XA_PREPARE:
    if (trans_xa_prepare(thd))
      goto error;
    my_ok(thd);
    break;
  case SQLCOM_XA_COMMIT:
  {
    bool commit_failed= trans_xa_commit(thd);
    if (commit_failed)
    {
      WSREP_DEBUG("XA commit failed, MDL released: %lld",
                  (longlong) thd->thread_id);
      goto error;
    }
    /*
      We've just done a commit, reset transaction
      isolation level and access mode to the session default.
    */
    trans_reset_one_shot_chistics(thd);
    my_ok(thd);
    break;
  }
  case SQLCOM_XA_ROLLBACK:
  {
    bool rollback_failed= trans_xa_rollback(thd);
    if (rollback_failed)
    {
      WSREP_DEBUG("XA rollback failed, MDL released: %lld",
                  (longlong) thd->thread_id);
      goto error;
    }
    /*
      We've just done a rollback, reset transaction
      isolation level and access mode to the session default.
    */
    trans_reset_one_shot_chistics(thd);
    my_ok(thd);
    break;
  }
  case SQLCOM_XA_RECOVER:
    res= mysql_xa_recover(thd);
    break;
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
      my_ok(thd);
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment,
                                       &thd->lex->ident)))
      my_ok(thd);
    break;
  case SQLCOM_BINLOG_BASE64_EVENT:
  {
#ifndef EMBEDDED_LIBRARY
    mysql_client_binlog_statement(thd);
#else /* EMBEDDED_LIBRARY */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded");
#endif /* EMBEDDED_LIBRARY */
    break;
  }
  case SQLCOM_CREATE_SERVER:
  {
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));

    if (check_global_access(thd, PRIV_STMT_CREATE_SERVER))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    res= create_server(thd, &lex->server_options);
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));

    if (check_global_access(thd, PRIV_STMT_ALTER_SERVER))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    if (unlikely((error= alter_server(thd, &lex->server_options))))
    {
      DBUG_PRINT("info", ("problem altering server <%s>",
                          lex->server_options.server_name.str));
      my_error(error, MYF(0), lex->server_options.server_name.str);
      break;
    }
    my_ok(thd, 1);
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));

    if (check_global_access(thd, PRIV_STMT_DROP_SERVER))
      break;

    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

    if ((err_code= drop_server(thd, &lex->server_options)))
    {
      if (! lex->if_exists() && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
      {
        DBUG_PRINT("info", ("problem dropping server %s",
                            lex->server_options.server_name.str));
        my_error(err_code, MYF(0), lex->server_options.server_name.str);
      }
      else
      {
        my_ok(thd, 0);
      }
      break;
    }
    my_ok(thd, 1);
    break;
  }
  case SQLCOM_ANALYZE:
  case SQLCOM_CHECK:
  case SQLCOM_OPTIMIZE:
  case SQLCOM_REPAIR:
  case SQLCOM_TRUNCATE:
  case SQLCOM_CREATE_TABLE:
  case SQLCOM_CREATE_SEQUENCE:
  case SQLCOM_ALTER_TABLE:
      DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* fall through */
  case SQLCOM_ALTER_SEQUENCE:
  case SQLCOM_SHOW_SLAVE_STAT:
  case SQLCOM_SIGNAL:
  case SQLCOM_RESIGNAL:
  case SQLCOM_GET_DIAGNOSTICS:
  case SQLCOM_CALL:
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
    DBUG_ASSERT(lex->m_sql_cmd != NULL);
    res= lex->m_sql_cmd->execute(thd);
    DBUG_PRINT("result", ("res: %d  killed: %d  is_error(): %d",
                          res, thd->killed, thd->is_error()));
    break;
  default:

#ifndef EMBEDDED_LIBRARY
    DBUG_ASSERT(0);                             /* Impossible */
#endif
    my_ok(thd);
    break;
  }
  THD_STAGE_INFO(thd, stage_query_end);
  thd->update_stats();

  goto finish;

error:
#ifdef WITH_WSREP
wsrep_error_label:
#endif
  res= true;

finish:

  thd->reset_query_timer();
  DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() ||
               thd->in_multi_stmt_transaction_mode());

  lex->unit.cleanup();

  /* close/reopen tables that were marked to need reopen under LOCK TABLES */
  if (unlikely(thd->locked_tables_list.some_table_marked_for_reopen) &&
      !thd->lex->requires_prelocking())
    thd->locked_tables_list.reopen_tables(thd, true);

  if (! thd->in_sub_stmt)
  {
    if (thd->killed != NOT_KILLED)
    {
      /* report error issued during command execution */
      if (thd->killed_errno())
      {
        /* If we already sent 'ok', we can ignore any kill query statements */
        if (! thd->get_stmt_da()->is_set())
          thd->send_kill_message();
      }
      thd->reset_kill_query();
    }
    if (unlikely(thd->is_error()) ||
        (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR))
    {
      THD_STAGE_INFO(thd, stage_rollback);
      trans_rollback_stmt(thd);
    }
    else
    {
      /* If commit fails, we should be able to reset the OK status. */
      THD_STAGE_INFO(thd, stage_commit);
      thd->get_stmt_da()->set_overwrite_status(true);
      trans_commit_stmt(thd);
      thd->get_stmt_da()->set_overwrite_status(false);
    }
  }

  /* Free tables. Set stage 'closing tables' */
  close_thread_tables_for_query(thd);

#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt)
    DEBUG_SYNC(thd, "execute_command_after_close_tables");
#endif
  if (!(sql_command_flags[lex->sql_command] &
        (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT |
         CF_STATUS_COMMAND)))
    thd->set_binlog_format(orig_binlog_format,
                           orig_current_stmt_binlog_format);

  if (! thd->in_sub_stmt && thd->transaction_rollback_request)
  {
    /*
      We are not in sub-statement and transaction rollback was requested by
      one of storage engines (e.g. due to deadlock). Rollback transaction in
      all storage engines including binary log.
    */
    THD_STAGE_INFO(thd, stage_rollback_implicit);
    trans_rollback_implicit(thd);
    thd->release_transactional_locks();
  }
  else if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
  {
    /* No transaction control allowed in sub-statements. */
    DBUG_ASSERT(! thd->in_sub_stmt);
    if (!(thd->variables.option_bits & OPTION_GTID_BEGIN))
    {
      THD_STAGE_INFO(thd, stage_commit_implicit);
      /* If commit fails, we should be able to reset the OK status. */
      thd->get_stmt_da()->set_overwrite_status(true);
      /* Commit the normal transaction if one is active. */
      trans_commit_implicit(thd);
      thd->get_stmt_da()->set_overwrite_status(false);
      thd->release_transactional_locks();
    }
  }
  else if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode())
  {
    /*
      - If inside a multi-statement transaction,
      defer the release of metadata locks until the current
      transaction is either committed or rolled back. This prevents
      other statements from modifying the table for the entire
      duration of this transaction.  This provides commit ordering
      and guarantees serializability across multiple transactions.
      - If in autocommit mode, or outside a transactional context,
      automatically release metadata locks of the current statement.
    */
    thd->release_transactional_locks();
  }
  else if (! thd->in_sub_stmt)
  {
    thd->mdl_context.release_statement_locks();
  }

  THD_STAGE_INFO(thd, stage_starting_cleanup);

  TRANSACT_TRACKER(add_trx_state_from_thd(thd));

#ifdef WITH_WSREP
  thd->wsrep_consistency_check= NO_CONSISTENCY_CHECK;

  if (wsrep_thd_is_toi(thd) || wsrep_thd_is_in_rsu(thd))
  {
    WSREP_DEBUG("mysql_execute_command for %s", wsrep_thd_query(thd));
    THD_STAGE_INFO(thd, stage_waiting_isolation);
    wsrep_to_isolation_end(thd);
  }

  /*
    Force release of transactional locks if not in active MST and wsrep is on.
  */
  if (WSREP(thd) &&
      ! thd->in_sub_stmt &&
      ! thd->in_active_multi_stmt_transaction() &&
      thd->mdl_context.has_transactional_locks())
  {
    WSREP_DEBUG("Forcing release of transactional locks for thd: %lld",
                (longlong) thd->thread_id);
    thd->release_transactional_locks();
  }

  /*
    Current command did not start multi STMT transaction and the command
    did not cause commit to happen (e.g. read only). Commit the wsrep
    transaction as empty.
  */
  if (!thd->in_active_multi_stmt_transaction() &&
      !thd->in_sub_stmt &&
      thd->wsrep_trx().active() &&
      thd->wsrep_trx().state() == wsrep::transaction::s_executing)
  {
    wsrep_commit_empty(thd, true);
  }

  /* assume PA safety for next transaction */
  thd->wsrep_PA_safe= true;
#endif /* WITH_WSREP */

  DBUG_RETURN(res || thd->is_error());
 }

static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
{
  LEX	*lex= thd->lex;
  select_result *result=lex->result;
  bool res;
  /* assign global limit variable if limit is not given */
  {
    SELECT_LEX *param= lex->unit.global_parameters();
    if (!param->limit_params.explicit_limit)
      param->limit_params.select_limit=
        new (thd->mem_root) Item_int(thd,
                                     (ulonglong) thd->variables.select_limit);
  }

  if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
  {
    if (lex->describe)
    {
      /*
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
        for SELECT ... INTO OUTFILE: a user application should be able
        to prepend EXPLAIN to any query and receive output for it,
        even if the query itself redirects the output.
      */
      if (unlikely(!(result= new (thd->mem_root) select_send(thd))))
        return 1;                               /* purecov: inspected */
      thd->send_explain_fields(result, lex->describe, lex->analyze_stmt);
        
      /*
        This will call optimize() for all parts of query. The query plan is
        printed out below.
      */
      res= mysql_explain_union(thd, &lex->unit, result);
      
      /* Print EXPLAIN only if we don't have an error */
      if (likely(!res))
      {
        /* 
          Do like the original select_describe did: remove OFFSET from the
          top-level LIMIT
        */
        result->remove_offset_limit();
        if (lex->explain_json)
        {
          lex->explain->print_explain_json(result, lex->analyze_stmt,
                                           false /* is_show_cmd */);
        }
        else
        {
          lex->explain->print_explain(result, thd->lex->describe,
                                      thd->lex->analyze_stmt);
          if (lex->describe & DESCRIBE_EXTENDED)
          {
            char buff[1024];
            String str(buff,(uint32) sizeof(buff), system_charset_info);
            str.length(0);
            /*
              The warnings system requires input in utf8, @see
              mysqld_show_warnings().
            */
            lex->unit.print(&str, QT_EXPLAIN_EXTENDED);
            push_warning(thd, Sql_condition::WARN_LEVEL_NOTE,
                         ER_YES, str.c_ptr_safe());
          }
        }
      }

      if (res)
        result->abort_result_set();
      else
        result->send_eof();
      delete result;
    }
    else
    {
      Protocol *save_protocol= NULL;
      if (lex->analyze_stmt)
      {
        if (result && result->result_interceptor())
          result->result_interceptor()->disable_my_ok_calls();
        else 
        {
          DBUG_ASSERT(thd->protocol);
          result= new (thd->mem_root) select_send_analyze(thd);
          save_protocol= thd->protocol;
          thd->protocol= new Protocol_discard(thd);
        }
      }
      else
      {
        if (!result && !(result= new (thd->mem_root) select_send(thd)))
          return 1;                               /* purecov: inspected */
      }
      query_cache_store_query(thd, all_tables);
      res= handle_select(thd, lex, result, 0);
      if (result != lex->result)
        delete result;

      if (lex->analyze_stmt)
      {
        if (save_protocol)
        {
          delete thd->protocol;
          thd->protocol= save_protocol;
        }
        if (!res)
          res= thd->lex->explain->send_explain(thd);
      }
    }
  }
  /* Count number of empty select queries */
  if (!thd->get_sent_row_count() && !res)
    status_var_increment(thd->status_var.empty_queries);
  else
    status_var_add(thd->status_var.rows_sent, thd->get_sent_row_count());

  return res;
}


/**
   SHOW STATUS

   Notes: This is noinline as we don't want to have system_status_var (> 3K)
   to be on the stack of mysql_execute_command()
*/

static bool __attribute__ ((noinline))
execute_show_status(THD *thd, TABLE_LIST *all_tables)
{
  bool res;
  system_status_var old_status_var= thd->status_var;
  thd->initial_status_var= &old_status_var;
  WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
  if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                UINT_MAX, FALSE)))
    res= execute_sqlcom_select(thd, all_tables);

  thd->initial_status_var= NULL;
  /* Don't log SHOW STATUS commands to slow query log */
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
                         SERVER_QUERY_NO_GOOD_INDEX_USED);
  /*
    restore status variables, as we don't want 'show status' to cause
    changes
  */
  mysql_mutex_lock(&LOCK_status);
  add_diff_to_status(&global_status_var, &thd->status_var,
                     &old_status_var);
  memcpy(&thd->status_var, &old_status_var,
         offsetof(STATUS_VAR, last_cleared_system_status_var));
  mysql_mutex_unlock(&LOCK_status);
  return res;
#ifdef WITH_WSREP
wsrep_error_label: /* see WSREP_SYNC_WAIT() macro above */
  return true;
#endif /* WITH_WSREP */
}


/*
  Find out if a table is a temporary table

  A table is a temporary table if it's a temporary table or
  there has been before a temporary table that has been renamed
  to the current name.

  Some examples:
  A->B          B is a temporary table if and only if A is a temp.
  A->B, B->C    Second B is temp if A is temp
  A->B, A->C    Second A can't be temp as if A was temp then B is temp
                and Second A can only be a normal table. C is also not temp
*/

static TABLE *find_temporary_table_for_rename(THD *thd,
                                              TABLE_LIST *first_table,
                                              TABLE_LIST *cur_table)
{
  TABLE_LIST *table;
  TABLE *res= 0;
  bool found= 0;
  DBUG_ENTER("find_temporary_table_for_rename");

  /* Find last instance when cur_table is in TO part */
  for (table= first_table;
       table != cur_table;
       table= table->next_local->next_local)
  {
    TABLE_LIST *next= table->next_local;

    if (!strcmp(table->get_db_name(),   cur_table->get_db_name()) &&
        !strcmp(table->get_table_name(), cur_table->get_table_name()))
    {
      /* Table was moved away, can't be same as 'table' */
      found= 1;
      res= 0;                      // Table can't be a temporary table
    }
    if (!strcmp(next->get_db_name(),    cur_table->get_db_name()) &&
        !strcmp(next->get_table_name(), cur_table->get_table_name()))
    {
      /*
        Table has matching name with new name of this table. cur_table should
        have same temporary type as this table.
      */
      found= 1;
      res= table->table;
    }
  }
  if (!found)
    res= thd->find_temporary_table(table, THD::TMP_TABLE_ANY);
  DBUG_RETURN(res);
}


static bool __attribute__ ((noinline))
check_rename_table(THD *thd, TABLE_LIST *first_table,
                   TABLE_LIST *all_tables)
{
  DBUG_ASSERT(first_table == all_tables && first_table != 0);
  TABLE_LIST *table;
  for (table= first_table; table; table= table->next_local->next_local)
  {
    if (check_access(thd, ALTER_ACL | DROP_ACL, table->db.str,
                     &table->grant.privilege,
                     &table->grant.m_internal,
                     0, 0) ||
        check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db.str,
                     &table->next_local->grant.privilege,
                     &table->next_local->grant.m_internal,
                     0, 0))
      return 1;

    /* check if these are referring to temporary tables */
    table->table= find_temporary_table_for_rename(thd, first_table, table);
    table->next_local->table= table->table;

    TABLE_LIST old_list, new_list;
    /*
      we do not need initialize old_list and new_list because we will
      copy table[0] and table->next[0] there
    */
    old_list= table[0];
    new_list= table->next_local[0];

    if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
       (!test_all_bits(table->next_local->grant.privilege,
                       INSERT_ACL | CREATE_ACL) &&
        check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
                    FALSE)))
      return 1;
  }

  return 0;
}

/*
  Generate an incident log event before writing the real event
  to the binary log.  We put this event is before the statement
  since that makes it simpler to check that the statement was
  not executed on the slave (since incidents usually stop the
  slave).

  Observe that any row events that are generated will be generated before.

  This is only for testing purposes and will not be present in a release build.
*/

#ifndef DBUG_OFF
static bool __attribute__ ((noinline)) generate_incident_event(THD *thd)
{
  if (mysql_bin_log.is_open())
  {

    Incident incident= INCIDENT_NONE;
    DBUG_PRINT("debug", ("Just before generate_incident()"));
    DBUG_EXECUTE_IF("incident_database_resync_on_replace",
                    incident= INCIDENT_LOST_EVENTS;);
    if (incident)
    {
      Incident_log_event ev(thd, incident);
      (void) mysql_bin_log.write(&ev);        /* error is ignored */
      if (mysql_bin_log.rotate_and_purge(true))
        return 1;
    }
    DBUG_PRINT("debug", ("Just after generate_incident()"));
  }
  return 0;
}
#else
static bool generate_incident_event(THD *thd)
{
  return 0;
}
#endif


static int __attribute__ ((noinline))
show_create_db(THD *thd, LEX *lex)
{
  char db_name_buff[NAME_LEN+1];
  LEX_CSTRING db_name;
  DBUG_EXECUTE_IF("4x_server_emul",
                  my_error(ER_UNKNOWN_ERROR, MYF(0)); return 1;);

  db_name.str= db_name_buff;
  db_name.length= lex->name.length;
  strmov(db_name_buff, lex->name.str);

  if (check_db_name((LEX_STRING*) &db_name))
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), db_name.str);
    return 1;
  }
  return mysqld_show_create_db(thd, &db_name, &lex->name, lex->create_info);
}


/**
   Called on SQLCOM_ALTER_PROCEDURE and SQLCOM_ALTER_FUNCTION
*/

static bool __attribute__ ((noinline))
alter_routine(THD *thd, LEX *lex)
{
  int sp_result;
  const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
  if (check_routine_access(thd, ALTER_PROC_ACL, &lex->spname->m_db,
                           &lex->spname->m_name, sph, 0))
    return 1;
  /*
    Note that if you implement the capability of ALTER FUNCTION to
    alter the body of the function, this command should be made to
    follow the restrictions that log-bin-trust-function-creators=0
    already puts on CREATE FUNCTION.
  */
  /* Conditionally writes to binlog */
  sp_result= sph->sp_update_routine(thd, lex->spname, &lex->sp_chistics);
  switch (sp_result) {
  case SP_OK:
    my_ok(thd);
    return 0;
  case SP_KEY_NOT_FOUND:
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  default:
    my_error(ER_SP_CANT_ALTER, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  }
  return 0;                                     /* purecov: deadcode */
}


static bool __attribute__ ((noinline))
drop_routine(THD *thd, LEX *lex)
{
  int sp_result;
#ifdef HAVE_DLOPEN
  if (lex->sql_command == SQLCOM_DROP_FUNCTION &&
      ! lex->spname->m_explicit_name)
  {
    /* DROP FUNCTION <non qualified name> */
    enum drop_udf_result rc= mysql_drop_function(thd, &lex->spname->m_name);
    switch (rc) {
    case UDF_DEL_RESULT_DELETED:
      my_ok(thd);
      return 0;
    case UDF_DEL_RESULT_ERROR:
      return 1;
    case UDF_DEL_RESULT_ABSENT:
      goto absent;
    }

    DBUG_ASSERT("wrong return code" == 0);
absent:
    // If there was no current database, so it cannot be SP
    if (!lex->spname->m_db.str)
    {
      if (lex->if_exists())
      {
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                            ER_SP_DOES_NOT_EXIST,
                            ER_THD(thd, ER_SP_DOES_NOT_EXIST),
                            "FUNCTION (UDF)", lex->spname->m_name.str);
        my_ok(thd);
        return 0;
      }
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
               "FUNCTION (UDF)", lex->spname->m_name.str);
      return 1;
    }
    /* Fall trough to test for a stored function */
  }
#endif /* HAVE_DLOPEN */

  const Sp_handler *sph= Sp_handler::handler(lex->sql_command);

  if (check_routine_access(thd, ALTER_PROC_ACL, &lex->spname->m_db,
                           &lex->spname->m_name,
                           Sp_handler::handler(lex->sql_command), 0))
    return 1;

  WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

  /* Conditionally writes to binlog */
  sp_result= sph->sp_drop_routine(thd, lex->spname);

#ifndef NO_EMBEDDED_ACCESS_CHECKS
  /*
    We're going to issue an implicit REVOKE statement so we close all
    open tables. We have to keep metadata locks as this ensures that
    this statement is atomic against concurent FLUSH TABLES WITH READ
    LOCK. Deadlocks which can arise due to fact that this implicit
    statement takes metadata locks should be detected by a deadlock
    detector in MDL subsystem and reported as errors.

    TODO: Long-term we should either ensure that implicit REVOKE statement
    is written into binary log as a separate statement or make both
    dropping of routine and implicit REVOKE parts of one fully atomic
    statement.
  */
  if (trans_commit_stmt(thd))
    sp_result= SP_INTERNAL_ERROR;
  close_thread_tables(thd);

  if (sp_result != SP_KEY_NOT_FOUND &&
      sp_automatic_privileges && !opt_noacl &&
      sp_revoke_privileges(thd, lex->spname->m_db.str, lex->spname->m_name.str,
                           Sp_handler::handler(lex->sql_command)))
  {
    push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
                 ER_PROC_AUTO_REVOKE_FAIL,
                 ER_THD(thd, ER_PROC_AUTO_REVOKE_FAIL));
    /* If this happens, an error should have been reported. */
    return 1;
  }
#endif /* NO_EMBEDDED_ACCESS_CHECKS */

  switch (sp_result) {
  case SP_OK:
    my_ok(thd);
    return 0;
  case SP_KEY_NOT_FOUND:
    int res;
    if (lex->if_exists())
    {
      res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                          ER_SP_DOES_NOT_EXIST,
                          ER_THD(thd, ER_SP_DOES_NOT_EXIST),
                          sph->type_str(),
                          ErrConvDQName(lex->spname).ptr());
      if (res)
        return 1;
      my_ok(thd);
      return 0;
    }
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  default:
    my_error(ER_SP_DROP_FAILED, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  }

#ifdef WITH_WSREP
wsrep_error_label:
  return 1;
#endif
}

/**
  @brief Compare requested privileges with the privileges acquired from the
    User- and Db-tables.
  @param thd          Thread handler
  @param want_access  The requested access privileges.
  @param db           A pointer to the Db name.
  @param[out] save_priv A pointer to the granted privileges will be stored.
  @param grant_internal_info A pointer to the internal grant cache.
  @param dont_check_global_grants True if no global grants are checked.
  @param no_error     True if no errors should be sent to the client.

  'save_priv' is used to save the User-table (global) and Db-table grants for
  the supplied db name. Note that we don't store db level grants if the global
  grants is enough to satisfy the request AND the global grants contains a
  SELECT grant.

  For internal databases (INFORMATION_SCHEMA, PERFORMANCE_SCHEMA),
  additional rules apply, see ACL_internal_schema_access.

  @see check_grant

  @return Status of denial of access by exclusive ACLs.
    @retval FALSE Access can't exclusively be denied by Db- and User-table
      access unless Column- and Table-grants are checked too.
    @retval TRUE Access denied.
*/

bool
check_access(THD *thd, privilege_t want_access,
             const char *db, privilege_t *save_priv,
             GRANT_INTERNAL_INFO *grant_internal_info,
             bool dont_check_global_grants, bool no_errors)
{
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  if (save_priv)
    *save_priv= GLOBAL_ACLS;
  return false;
#else
  Security_context *sctx= thd->security_ctx;
  privilege_t db_access(NO_ACL);

  /*
    GRANT command:
    In case of database level grant the database name may be a pattern,
    in case of table|column level grant the database name can not be a pattern.
    We use 'dont_check_global_grants' as a flag to determine
    if it's database level grant command
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
  bool  db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
  privilege_t dummy(NO_ACL);
  DBUG_ENTER("check_access");
  DBUG_PRINT("enter",("db: %s  want_access: %llx  master_access: %llx",
                      db ? db : "",
                      (longlong) want_access,
                      (longlong) sctx->master_access));

  if (save_priv)
    *save_priv= NO_ACL;
  else
  {
    save_priv= &dummy;
    dummy= NO_ACL;
  }

  /* check access may be called twice in a row. Don't change to same stage */
  if (thd->proc_info != stage_checking_permissions.m_name)
    THD_STAGE_INFO(thd, stage_checking_permissions);
  if (unlikely((!db || !db[0]) && !thd->db.str && !dont_check_global_grants))
  {
    DBUG_RETURN(FALSE); // CTE reference or an error later
  }

  if (likely((db != NULL) && (db != any_db.str)))
  {
    /*
      Check if this is reserved database, like information schema or
      performance schema
    */
    const ACL_internal_schema_access *access;
    access= get_cached_schema_access(grant_internal_info, db);
    if (access)
    {
      switch (access->check(want_access, save_priv))
      {
      case ACL_INTERNAL_ACCESS_GRANTED:
        /*
          All the privileges requested have been granted internally.
          [out] *save_privileges= Internal privileges.
        */
        DBUG_RETURN(FALSE);
      case ACL_INTERNAL_ACCESS_DENIED:
        if (! no_errors)
        {
          status_var_increment(thd->status_var.access_denied_errors);
          my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
                   sctx->priv_user, sctx->priv_host, db);
        }
        DBUG_RETURN(TRUE);
      case ACL_INTERNAL_ACCESS_CHECK_GRANT:
        /*
          Only some of the privilege requested have been granted internally,
          proceed with the remaining bits of the request (want_access).
        */
        want_access&= ~(*save_priv);
        break;
      }
    }
  }

  if ((sctx->master_access & want_access) == want_access)
  {
    /*
      1. If we don't have a global SELECT privilege, we have to get the
      database specific access rights to be able to handle queries of type
      UPDATE t1 SET a=1 WHERE b > 0
      2. Change db access if it isn't current db which is being addressed
    */
    if (!(sctx->master_access & SELECT_ACL))
    {
      if (db && (!thd->db.str || db_is_pattern || strcmp(db, thd->db.str)))
      {
        db_access= acl_get_all3(sctx, db, db_is_pattern);
      }
      else
      {
        /* get access for current db */
        db_access= sctx->db_access;
      }
      /*
        The effective privileges are the union of the global privileges
        and the intersection of db- and host-privileges,
        plus the internal privileges.
      */
      *save_priv|= sctx->master_access | db_access;
    }
    else
      *save_priv|= sctx->master_access;
    DBUG_RETURN(FALSE);
  }
  if (unlikely(((want_access & ~sctx->master_access) & ~DB_ACLS) ||
               (! db && dont_check_global_grants)))
  {						// We can never grant this
    DBUG_PRINT("error",("No possible access"));
    if (!no_errors)
    {
      status_var_increment(thd->status_var.access_denied_errors);
      my_error(access_denied_error_code(thd->password), MYF(0),
               sctx->priv_user,
               sctx->priv_host,
               (thd->password ?
                ER_THD(thd, ER_YES) :
                ER_THD(thd, ER_NO)));                    /* purecov: tested */
    }
    DBUG_RETURN(TRUE);				/* purecov: tested */
  }

  if (unlikely(db == any_db.str))
  {
    /*
      Access granted; Allow select on *any* db.
      [out] *save_privileges= 0
    */
    DBUG_RETURN(FALSE);
  }

  if (db && (!thd->db.str || db_is_pattern || strcmp(db, thd->db.str)))
    db_access= acl_get_all3(sctx, db, db_is_pattern);
  else
    db_access= sctx->db_access;
  DBUG_PRINT("info",("db_access: %llx  want_access: %llx",
                     (longlong) db_access, (longlong) want_access));

  /*
    Save the union of User-table and the intersection between Db-table and
    Host-table privileges, with the already saved internal privileges.
  */
  db_access= (db_access | sctx->master_access);
  *save_priv|= db_access;

  /*
    We need to investigate column- and table access if all requested privileges
    belongs to the bit set of .
  */
  bool need_table_or_column_check=
    (want_access & (TABLE_ACLS | PROC_ACLS | db_access)) == want_access;

  /*
    Grant access if the requested access is in the intersection of
    host- and db-privileges (as retrieved from the acl cache),
    also grant access if all the requested privileges are in the union of
    TABLES_ACLS and PROC_ACLS; see check_grant.
  */
  if ( (db_access & want_access) == want_access ||
      (!dont_check_global_grants &&
       need_table_or_column_check))
  {
    /*
       Ok; but need to check table- and column privileges.
       [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
    */
    DBUG_RETURN(FALSE);
  }

  /*
    Access is denied;
    [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
  */
  DBUG_PRINT("error",("Access denied"));
  if (!no_errors)
  {
    status_var_increment(thd->status_var.access_denied_errors);
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
             sctx->priv_user, sctx->priv_host,
             (db ? db : (thd->db.str ?
                         thd->db.str :
                         "unknown")));
  }
  DBUG_RETURN(TRUE);
#endif // NO_EMBEDDED_ACCESS_CHECKS
}


#ifndef NO_EMBEDDED_ACCESS_CHECKS
/**
  Check grants for commands which work only with one table.

  @param thd                    Thread handler
  @param privilege              requested privilege
  @param tables                 global table list of query
  @param no_errors              FALSE/TRUE - report/don't report error to
                            the client (using my_error() call).

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
*/

bool check_single_table_access(THD *thd, privilege_t privilege,
                               TABLE_LIST *tables, bool no_errors)
{
  if (tables->derived)
    return 0;

  Switch_to_definer_security_ctx backup_sctx(thd, tables);

  const char *db_name;
  if ((tables->view || tables->field_translation) && !tables->schema_table)
    db_name= tables->view_db.str;
  else
    db_name= tables->db.str;

  if (check_access(thd, privilege, db_name, &tables->grant.privilege,
                   &tables->grant.m_internal, 0, no_errors))
    return 1;

  /* Show only 1 table for check_grant */
  if (!(tables->belong_to_view &&
       (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
      check_grant(thd, privilege, tables, FALSE, 1, no_errors))
    return 1;

  return 0;
}

/**
  Check grants for commands which work only with one table and all other
  tables belonging to subselects or implicitly opened tables.

  @param thd			Thread handler
  @param privilege		requested privilege
  @param all_tables		global table list of query

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
*/

bool check_one_table_access(THD *thd, privilege_t privilege,
                            TABLE_LIST *all_tables)
{
  if (check_single_table_access (thd,privilege,all_tables, FALSE))
    return 1;

  /* Check rights on tables of subselects and implictly opened tables */
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
  if ((subselects_tables= all_tables->next_global))
  {
    /*
      Access rights asked for the first table of a view should be the same
      as for the view
    */
    if (view && subselects_tables->belong_to_view == view)
    {
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
        (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
                            UINT_MAX, FALSE)))
      return 1;
  }
  return 0;
}


static bool check_show_access(THD *thd, TABLE_LIST *table)
{
  /*
    This is a SHOW command using an INFORMATION_SCHEMA table.
    check_access() has not been called for 'table',
    and SELECT is currently always granted on the I_S, so we automatically
    grant SELECT on table here, to bypass a call to check_access().
    Note that not calling check_access(table) is an optimization,
    which needs to be revisited if the INFORMATION_SCHEMA does
    not always automatically grant SELECT but use the grant tables.
    See Bug#38837 need a way to disable information_schema for security
  */
  table->grant.privilege= SELECT_ACL;

  switch (get_schema_table_idx(table->schema_table)) {
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
      check_global_access(thd, SHOW_DB_ACL);

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
  case SCH_EVENTS:
  {
    const char *dst_db_name= table->schema_select_lex->db.str;

    DBUG_ASSERT(dst_db_name);

    if (check_access(thd, SELECT_ACL, dst_db_name,
                     &thd->col_access, NULL, FALSE, FALSE))
      return TRUE;

    if (!thd->col_access && check_grant_db(thd, dst_db_name))
    {
      status_var_increment(thd->status_var.access_denied_errors);
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               dst_db_name);
      return TRUE;
    }

    return FALSE;
  }

  case SCH_COLUMNS:
  case SCH_STATISTICS:
  {
    TABLE_LIST *dst_table;
    dst_table= table->schema_select_lex->table_list.first;

    DBUG_ASSERT(dst_table);

    /*
      Open temporary tables to be able to detect them during privilege check.
    */
    if (thd->open_temporary_tables(dst_table))
      return TRUE;

    if (check_access(thd, SELECT_ACL, dst_table->db.str,
                     &dst_table->grant.privilege,
                     &dst_table->grant.m_internal,
                     FALSE, FALSE))
          return TRUE; /* Access denied */

    /*
      Check_grant will grant access if there is any column privileges on
      all of the tables thanks to the fourth parameter (bool show_table).
    */
    if (check_grant(thd, SELECT_ACL, dst_table, TRUE, 1, FALSE))
      return TRUE; /* Access denied */

    close_thread_tables(thd);
    dst_table->table= NULL;

    /* Access granted */
    return FALSE;
  }
  default:
    break;
  }

  return FALSE;
}



/**
  @brief Check if the requested privileges exists in either User-, Host- or
    Db-tables.
  @param thd          Thread context
  @param requirements Privileges requested
  @param tables       List of tables to be compared against
  @param any_combination_of_privileges_will_do TRUE if any privileges on any
    column combination is enough.
  @param number       Only the first 'number' tables in the linked list are
                      relevant.
  @param no_errors    Don't report error to the client (using my_error() call).

  The suppled table list contains cached privileges. This functions calls the
  help functions check_access and check_grant to verify the first three steps
  in the privileges check queue:
  1. Global privileges
  2. OR (db privileges AND host privileges)
  3. OR table privileges
  4. OR column privileges (not checked by this function!)
  5. OR routine privileges (not checked by this function!)

  @see check_access
  @see check_grant

  @note This functions assumes that table list used and
  thd->lex->query_tables_own_last value correspond to each other
  (the latter should be either 0 or point to next_global member
  of one of elements of this table list).

  @return
    @retval FALSE OK
    @retval TRUE  Access denied; But column or routine privileges might need to
      be checked also.
*/

bool
check_table_access(THD *thd, privilege_t requirements, TABLE_LIST *tables,
                   bool any_combination_of_privileges_will_do,
                   uint number, bool no_errors)
{
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
  uint i= 0;
  /*
    The check that first_not_own_table is not reached is for the case when
    the given table list refers to the list for prelocking (contains tables
    of other queries). For simple queries first_not_own_table is 0.
  */
  for (; i < number && tables != first_not_own_table && tables;
       tables= tables->next_global, i++)
  {
    TABLE_LIST *const table_ref= tables->correspondent_table ?
      tables->correspondent_table : tables;
    Switch_to_definer_security_ctx backup_ctx(thd, table_ref);

    privilege_t want_access(requirements);

    /*
       Register access for view underlying table.
       Remove SHOW_VIEW_ACL, because it will be checked during making view
     */
    table_ref->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);

    if (table_ref->schema_table_reformed)
    {
      if (check_show_access(thd, table_ref))
        return 1;
      continue;
    }

    DBUG_PRINT("info", ("derived: %d  view: %d", table_ref->derived != 0,
                        table_ref->view != 0));

    if (table_ref->is_anonymous_derived_table())
      continue;

    if (table_ref->sequence)
    {
      /* We want to have either SELECT or INSERT rights to sequences depending
         on how they are accessed
      */
      want_access= ((table_ref->lock_type >= TL_FIRST_WRITE) ?
                    INSERT_ACL : SELECT_ACL);
    }

    if (check_access(thd, want_access,
                     table_ref->get_db_name(),
                     &table_ref->grant.privilege,
                     &table_ref->grant.m_internal,
                     0, no_errors))
      return 1;
  }
  return check_grant(thd,requirements,org_tables,
                     any_combination_of_privileges_will_do,
                     number, no_errors);
}


bool
check_routine_access(THD *thd, privilege_t want_access, const LEX_CSTRING *db,
                     const LEX_CSTRING *name,
                     const Sp_handler *sph, bool no_errors)
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
  tables->db= *db;
  tables->table_name= tables->alias= *name;
  
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access) under the assumption that it's common to
    give persons global right to execute all stored SP (but not
    necessary to create them).
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as long as this code path is not abused to create routines.
    The assert enforce that.
  */
  DBUG_ASSERT((want_access & CREATE_PROC_ACL) == NO_ACL);
  if ((thd->security_ctx->master_access & want_access) == want_access)
    tables->grant.privilege= want_access;
  else if (check_access(thd, want_access, db->str,
                        &tables->grant.privilege,
                        &tables->grant.m_internal,
                        0, no_errors))
    return TRUE;
  
  return check_grant_routine(thd, want_access, tables, sph, no_errors);
}


/**
  Check if the routine has any of the routine privileges.

  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name

  @retval
    0            ok
  @retval
    1            error
*/

bool check_some_routine_access(THD *thd, const char *db, const char *name,
                               const Sp_handler *sph)
{
  privilege_t save_priv(NO_ACL);
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access)
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as it only opens SHOW_PROC_ACLS.
  */
  if (thd->security_ctx->master_access & SHOW_PROC_ACLS)
    return FALSE;
  if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, NULL, 0, 1) ||
      (save_priv & SHOW_PROC_ACLS))
    return FALSE;
  return check_routine_level_acl(thd, db, name, sph);
}


/*
  Check if the given table has any of the asked privileges

  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for

  @retval
    0  ok
  @retval
    1  error
*/

bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table)
{
  DBUG_ENTER("check_some_access");

  for (ulonglong bit= 1; bit < (ulonglong) want_access ; bit<<= 1)
  {
    if (bit & want_access)
    {
      privilege_t access= ALL_KNOWN_ACL & bit;
      if (!check_access(thd, access, table->db.str,
                        &table->grant.privilege,
                        &table->grant.m_internal,
                        0, 1) &&
           !check_grant(thd, access, table, FALSE, 1, TRUE))
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

#endif /*NO_EMBEDDED_ACCESS_CHECKS*/


/**
  check for global access and give descriptive error message if it fails.

  @param thd			Thread handler
  @param want_access		Use should have any of these global rights

  @warning
    Starting from 10.5.2 only one bit is allowed in want_access.
    Access denied error is returned if want_access has multiple bits set.

  @retval
    0	ok
  @retval
    1	Access denied.  In this case an error is sent to the client
*/

bool check_global_access(THD *thd, privilege_t want_access, bool no_errors)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  char command[128];
  if (thd->security_ctx->master_access & want_access)
    return 0;
  if (unlikely(!no_errors))
  {
    get_privilege_desc(command, sizeof(command), want_access);
    my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
  }
  status_var_increment(thd->status_var.access_denied_errors);
  return 1;
#else
  return 0;
#endif
}


/**
  Checks foreign key's parent table access.

  @param thd	       [in]	Thread handler
  @param create_info   [in]     Create information (like MAX_ROWS, ENGINE or
                                temporary table flag)
  @param alter_info    [in]     Initial list of columns and indexes for the
                                table to be created
  @param create_db     [in]     Database of the created table

  @retval
   false  ok.
  @retval
   true	  error or access denied. Error is sent to client in this case.
*/
bool check_fk_parent_table_access(THD *thd,
                                  HA_CREATE_INFO *create_info,
                                  Alter_info *alter_info,
                                  const char* create_db)
{
  Key *key;
  List_iterator<Key> key_iterator(alter_info->key_list);

  while ((key= key_iterator++))
  {
    if (key->type == Key::FOREIGN_KEY)
    {
      TABLE_LIST parent_table;
      Foreign_key *fk_key= (Foreign_key *)key;
      LEX_CSTRING db_name;
      LEX_CSTRING table_name= { fk_key->ref_table.str,
                               fk_key->ref_table.length };
      const privilege_t privileges(COL_DML_ACLS | REFERENCES_ACL);

      // Check if tablename is valid or not.
      DBUG_ASSERT(table_name.str != NULL);
      if (check_table_name(table_name.str, table_name.length, false))
      {
        my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
        return true;
      }

      if (fk_key->ref_db.str)
      {
        if (!(db_name.str= (char *) thd->memdup(fk_key->ref_db.str,
                                                fk_key->ref_db.length+1)))
          return true;
        db_name.length= fk_key->ref_db.length;

        // Check if database name is valid or not.
        if (check_db_name((LEX_STRING*) &db_name))
        {
          my_error(ER_WRONG_DB_NAME, MYF(0), db_name.str);
          return true;
        }
      }
      else
      {
        if (!thd->db.str)
        {
          DBUG_ASSERT(create_db);
          db_name.length= strlen(create_db);
          if (!(db_name.str= (char *) thd->memdup(create_db,
                                                  db_name.length+1)))
            return true;

          if (check_db_name((LEX_STRING*) &db_name))
          {
            my_error(ER_WRONG_DB_NAME, MYF(0), db_name.str);
            return true;
          }
        }
        else
        {
          if (thd->lex->copy_db_to(&db_name))
            return true;
        }
      }

      // if lower_case_table_names is set then convert tablename to lower case.
      if (lower_case_table_names)
      {
        char *name;
        table_name.str= name= (char *) thd->memdup(fk_key->ref_table.str,
                                                   fk_key->ref_table.length+1);
        table_name.length= my_casedn_str(files_charset_info, name);
        db_name.length= my_casedn_str(files_charset_info, (char*) db_name.str);
      }

      parent_table.init_one_table(&db_name, &table_name, 0, TL_IGNORE);

      /*
       Check if user has any of the "privileges" at table level on
       "parent_table".
       Having privilege on any of the parent_table column is not
       enough so checking whether user has any of the "privileges"
       at table level only here.
      */
      if (check_some_access(thd, privileges, &parent_table) ||
          parent_table.grant.want_privilege)
      {
        my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
                "REFERENCES",
                thd->security_ctx->priv_user,
                thd->security_ctx->host_or_ip,
                db_name.str, table_name.str);
        return true;
      }
    }
  }

  return false;
}


/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/


#ifndef DBUG_OFF
long max_stack_used;
#endif

/**
  @note
  Note: The 'buf' parameter is necessary, even if it is unused here.
  - fix_fields functions has a "dummy" buffer large enough for the
    corresponding exec. (Thus we only have to check in fix_fields.)
  - Passing to check_stack_overrun() prevents the compiler from removing it.
*/

bool
#if defined __GNUC__ && !defined __clang__
/*
  Do not optimize the function in order to preserve a stack variable creation.
  Otherwise, the variable pointed as "buf" can be removed due to a missing
  usage.
 */
__attribute__((optimize("-O0")))
#endif
check_stack_overrun(THD *thd, long margin, uchar *buf __attribute__((unused)))
{
  long stack_used;
  DBUG_ASSERT(thd == current_thd);
  if ((stack_used= available_stack_size(thd->thread_stack, &stack_used)) >=
      (long) (my_thread_stack_size - margin))
  {
    thd->is_fatal_error= 1;
    /*
      Do not use stack for the message buffer to ensure correct
      behaviour in cases we have close to no stack left.
    */
    char* ebuff= new char[MYSQL_ERRMSG_SIZE];
    if (ebuff) {
      my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER_THD(thd, ER_STACK_OVERRUN_NEED_MORE),
                  stack_used, my_thread_stack_size, margin);
      my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATAL));
      delete [] ebuff;
    }
    return 1;
  }
#ifndef DBUG_OFF
  max_stack_used= MY_MAX(max_stack_used, stack_used);
#endif
  return 0;
}


#define MY_YACC_INIT 1000			// Start with big alloc
#define MY_YACC_MAX  32000			// Because of 'short'

bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, size_t *yystacksize)
{
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
  size_t old_info=0;
  DBUG_ASSERT(state);
  if ( *yystacksize >= MY_YACC_MAX)
    return 1;
  if (!state->yacc_yyvs)
    old_info= *yystacksize;
  *yystacksize= set_zone((int)(*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
  if (!(state->yacc_yyvs= (uchar*)
        my_realloc(key_memory_bison_stack, state->yacc_yyvs,
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
        my_realloc(key_memory_bison_stack, state->yacc_yyss,
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
    return 1;
  if (old_info)
  {
    /*
      Only copy the old stack on the first call to my_yyoverflow(),
      when replacing a static stack (YYINITDEPTH) by a dynamic stack.
      For subsequent calls, my_realloc already did preserve the old stack.
    */
    memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
    memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
  }
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
  return 0;
}


/**
  Reset the part of THD responsible for the state of command
  processing.

  @param do_clear_error  Set if we should clear errors

  This needs to be called before execution of every statement
  (prepared or conventional).  It is not called by substatements of
  routines.

  @todo Call it after we use THD for queries, not before.
*/

void THD::reset_for_next_command(bool do_clear_error)
{
  DBUG_ENTER("THD::reset_for_next_command");
  DBUG_ASSERT(!spcont); /* not for substatements of routines */
  DBUG_ASSERT(!in_sub_stmt);
  /*
    Table maps should have been reset after previous statement except in the
    case where we have locked tables
  */
  DBUG_ASSERT(binlog_table_maps == 0 ||
              locked_tables_mode == LTM_LOCK_TABLES);

  if (likely(do_clear_error))
  {
    clear_error(1);
    /*
      The following variable can't be reset in clear_error() as
      clear_error() is called during auto_repair of table
    */
    error_printed_to_log= 0;
  }
  free_list= 0;
  /*
    We also assign stmt_lex in lex_start(), but during bootstrap this
    code is executed first.
  */
  DBUG_ASSERT(lex == &main_lex);
  main_lex.stmt_lex= &main_lex; main_lex.current_select_number= 0;
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
  auto_inc_intervals_in_cur_stmt_for_binlog.empty();
  stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;

#ifdef WITH_WSREP
  /*
    Autoinc variables should be adjusted only for locally executed
    transactions. Appliers and replayers are either processing ROW
    events or get autoinc variable values from Query_log_event and
    mysql slave may be processing STATEMENT format events, but he should
    use autoinc values passed in binlog events, not the values forced by
    the cluster.
  */
  if (WSREP_NNULL(this) && wsrep_thd_is_local(this) &&
      !slave_thread && wsrep_auto_increment_control)
  {
    variables.auto_increment_offset=
      global_system_variables.auto_increment_offset;
    variables.auto_increment_increment=
      global_system_variables.auto_increment_increment;
  }
#endif /* WITH_WSREP */

  used= 0;
  is_fatal_error= 0;
  variables.option_bits&= ~OPTION_BINLOG_THIS_STMT;

  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
  server_status&= ~SERVER_STATUS_CLEAR_SET;
  /*
    If in autocommit mode and not in a transaction, reset
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_BINLOG_THIS_TRX to not get warnings
    in ha_rollback_trans() about some tables couldn't be rolled back.
  */
  if (!in_multi_stmt_transaction_mode())
  {
    variables.option_bits&= ~OPTION_BINLOG_THIS_TRX;
    transaction->all.reset();
  }
  DBUG_ASSERT(security_ctx== &main_security_ctx);

  if (opt_bin_log)
    reset_dynamic(&user_var_events);
  DBUG_ASSERT(user_var_events_alloc == &main_mem_root);
  enable_slow_log= true;
  get_stmt_da()->reset_for_next_command();
  m_sent_row_count= m_examined_row_count= 0;
  accessed_rows_and_keys= 0;

  reset_slow_query_state();

  reset_current_stmt_binlog_format_row();
  binlog_unsafe_warning_flags= 0;

  save_prep_leaf_list= false;

#ifdef WITH_WSREP
#if !defined(DBUG_OFF)
  if (mysql_bin_log.is_open())
#endif
#endif
    DBUG_PRINT("debug",
               ("is_current_stmt_binlog_format_row(): %d",
                 is_current_stmt_binlog_format_row()));

  DBUG_VOID_RETURN;
}


/**
  Used to allocate a new SELECT_LEX object on the current thd mem_root and
  link it into the relevant lists.

  This function is always followed by mysql_init_select.

  @see mysql_init_select

  @retval TRUE An error occurred
  @retval FALSE The new SELECT_LEX was successfully allocated.
*/

bool
mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *select_lex)
{
  THD *thd= lex->thd;
  bool new_select= select_lex == NULL;
  int old_nest_level= lex->current_select->nest_level;
  DBUG_ENTER("mysql_new_select");

  if (new_select)
  {
    if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
      DBUG_RETURN(1);
    select_lex->select_number= ++thd->lex->stmt_lex->current_select_number;
    select_lex->parent_lex= lex; /* Used in init_query. */
    select_lex->init_query();
    select_lex->init_select();
  }
  select_lex->nest_level_base= &thd->lex->unit;
  if (move_down)
  {
    lex->nest_level++;
    if (select_lex->set_nest_level(old_nest_level + 1))
      DBUG_RETURN(1);
    SELECT_LEX_UNIT *unit;
    /* first select_lex of subselect or derived table */
    if (!(unit= lex->alloc_unit()))
      DBUG_RETURN(1);

    unit->include_down(lex->current_select);
    unit->return_to= lex->current_select;
    select_lex->include_down(unit);
    /*
      By default we assume that it is usual subselect and we have outer name
      resolution context, if no we will assign it to 0 later
    */
    select_lex->context.outer_context= &select_lex->outer_select()->context;
  }
  else
  {
    bool const outer_most= (lex->current_select->master_unit() == &lex->unit);
    if (outer_most && lex->result)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "INTO");
      DBUG_RETURN(TRUE);
    }

    /*
      This type of query is not possible in the grammar:
        SELECT 1 FROM t1 PROCEDURE ANALYSE() UNION ... ;

      But this type of query is still possible:
        (SELECT 1 FROM t1 PROCEDURE ANALYSE()) UNION ... ;
      and it's not easy to disallow this grammatically,
      because there can be any parenthesis nest level:
        (((SELECT 1 FROM t1 PROCEDURE ANALYSE()))) UNION ... ;
    */
    if (lex->proc_list.elements!=0)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "UNION",
               "SELECT ... PROCEDURE ANALYSE()");
      DBUG_RETURN(TRUE);
    }

    SELECT_LEX_NODE *save_slave= select_lex->slave;
    select_lex->include_neighbour(lex->current_select);
    select_lex->slave= save_slave;
    SELECT_LEX_UNIT *unit= select_lex->master_unit();
    if (select_lex->set_nest_level(old_nest_level))
      DBUG_RETURN(1);
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
      DBUG_RETURN(1);
    select_lex->context.outer_context= 
                unit->first_select()->context.outer_context;
  }

  if (new_select)
    select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
  lex->current_select= select_lex;
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
  DBUG_RETURN(0);
}

/**
  Create a select to return the same output as 'SELECT @@var_name'.

  Used for SHOW COUNT(*) [ WARNINGS | ERROR].

  This will crash with a core dump if the variable doesn't exists.

  @param var_name		Variable name
*/

void create_select_for_variable(THD *thd, LEX_CSTRING *var_name)
{
  LEX *lex;
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
  DBUG_ENTER("create_select_for_variable");

  lex= thd->lex;
  lex->init_select();
  lex->sql_command= SQLCOM_SELECT;
  /*
    We set the name of Item to @@session.var_name because that then is used
    as the column name in the output.
  */
  if ((var= get_system_var(thd, OPT_SESSION, var_name, &null_clex_str)))
  {
    end= strxmov(buff, "@@session.", var_name->str, NullS);
    var->set_name(thd, buff, (uint)(end-buff), system_charset_info);
    add_item_to_list(thd, var);
  }
  DBUG_VOID_RETURN;
}


void mysql_init_multi_delete(LEX *lex)
{
  lex->sql_command=  SQLCOM_DELETE_MULTI;
  lex->init_select();
  lex->first_select_lex()->limit_params.clear();
  lex->unit.lim.clear();
  lex->first_select_lex()->table_list.
    save_and_clear(&lex->auxiliary_table_list);
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
}

#ifdef WITH_WSREP
static void wsrep_prepare_for_autocommit_retry(THD* thd,
                                               char* rawbuf,
                                               uint length,
                                               Parser_state* parser_state)
{
  thd->clear_error();
  close_thread_tables(thd);
  thd->wsrep_retry_counter++;            // grow
  wsrep_copy_query(thd);
  thd->set_time();
  parser_state->reset(rawbuf, length);

  /* PSI end */
  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
  thd->m_statement_psi= NULL;
  thd->m_digest= NULL;

  /* DTRACE end */
  if (MYSQL_QUERY_DONE_ENABLED())
  {
    MYSQL_QUERY_DONE(thd->is_error());
  }

  /* SHOW PROFILE end */
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif

  /* SHOW PROFILE begin */
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query("continuing");
  thd->profiling.set_query_source(rawbuf, length);
#endif

  /* DTRACE begin */
  MYSQL_QUERY_START(rawbuf, thd->thread_id,
                    thd->get_db(),
                    &thd->security_ctx->priv_user[0],
                    (char *) thd->security_ctx->host_or_ip);

  /* Performance Schema Interface instrumentation, begin */
  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                               com_statement_info[thd->get_command()].m_key);
  MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(),
                           thd->query_length());
 
  DBUG_ASSERT(thd->wsrep_trx().active() == false);
  thd->wsrep_cs().reset_error();
  thd->set_query_id(next_query_id());
}

static bool wsrep_mysql_parse(THD *thd, char *rawbuf, uint length,
                              Parser_state *parser_state)
{
  bool is_autocommit=
    !thd->in_multi_stmt_transaction_mode()                  &&
    !thd->wsrep_applier;
  bool retry_autocommit;
  do
  {
    retry_autocommit= false;
    mysql_parse(thd, rawbuf, length, parser_state);

    /*
      Convert all ER_QUERY_INTERRUPTED errors to ER_LOCK_DEADLOCK
      if the transaction was BF aborted. This can happen when the
      transaction is being BF aborted via thd->awake() while it is
      still executing.

      Note that this must be done before wsrep_after_statement() call
      since it clears the transaction for autocommit queries.
     */
    if (((thd->get_stmt_da()->is_error() &&
          thd->get_stmt_da()->sql_errno() == ER_QUERY_INTERRUPTED) ||
         !thd->get_stmt_da()->is_set()) &&
        thd->wsrep_trx().bf_aborted())
    {
      WSREP_DEBUG("overriding error: %d with DEADLOCK",
                  (thd->get_stmt_da()->is_error()) ?
                   thd->get_stmt_da()->sql_errno() : 0);

      thd->reset_kill_query();
      wsrep_override_error(thd, ER_LOCK_DEADLOCK);
    }

#ifdef ENABLED_DEBUG_SYNC
    /* we need the test otherwise we get stuck in the "SET DEBUG_SYNC" itself */
    if (thd->lex->sql_command != SQLCOM_SET_OPTION)
      DEBUG_SYNC(thd, "wsrep_after_statement_enter");
#endif

    if (wsrep_after_statement(thd) &&
        is_autocommit              &&
        thd_is_connection_alive(thd))
    {
      thd->reset_for_next_command();
      thd->reset_kill_query();
      if (is_autocommit                           &&
          thd->lex->sql_command != SQLCOM_SELECT  &&
          thd->wsrep_retry_counter < thd->variables.wsrep_retry_autocommit)
      {
#ifdef ENABLED_DEBUG_SYNC
	DBUG_EXECUTE_IF("sync.wsrep_retry_autocommit",
                    {
                      const char act[]=
                        "now "
                        "SIGNAL wsrep_retry_autocommit_reached "
                        "WAIT_FOR wsrep_retry_autocommit_continue";
                      DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act)));
                    });
#endif
        WSREP_DEBUG("wsrep retrying AC query: %lu  %s",
                    thd->wsrep_retry_counter,
                    wsrep_thd_query(thd));
        wsrep_prepare_for_autocommit_retry(thd, rawbuf, length, parser_state);
        if (thd->lex->explain)
          delete_explain_query(thd->lex);
        retry_autocommit= true;
      }
      else
      {
        WSREP_DEBUG("%s, thd: %llu is_AC: %d, retry: %lu - %lu SQL: %s",
                    wsrep_thd_transaction_state_str(thd),
                    thd->thread_id,
                    is_autocommit,
                    thd->wsrep_retry_counter,
                    thd->variables.wsrep_retry_autocommit,
                    wsrep_thd_query(thd));
        my_error(ER_LOCK_DEADLOCK, MYF(0));
        thd->reset_kill_query();
        thd->wsrep_retry_counter= 0;             //  reset
      }
    }
    else
    {
      set_if_smaller(thd->wsrep_retry_counter, 0); // reset; eventually ok
    }
  }  while (retry_autocommit);

  if (thd->wsrep_retry_query)
  {
    WSREP_DEBUG("releasing retry_query: "
                "conf %s sent %d kill %d  errno %d SQL %s",
                wsrep_thd_transaction_state_str(thd),
                thd->get_stmt_da()->is_sent(),
                thd->killed,
                thd->get_stmt_da()->is_error() ?
                thd->get_stmt_da()->sql_errno() : 0,
                thd->wsrep_retry_query);
    my_free(thd->wsrep_retry_query);
    thd->wsrep_retry_query      = NULL;
    thd->wsrep_retry_query_len  = 0;
    thd->wsrep_retry_command    = COM_CONNECT;
  }
  return false;
}
#endif /* WITH_WSREP */


/*
  When you modify mysql_parse(), you may need to modify
  mysql_test_parse_for_slave() in this same file.
*/

/**
  Parse a query.

  @param       thd     Current thread
  @param       rawbuf  Begining of the query text
  @param       length  Length of the query text
*/

void mysql_parse(THD *thd, char *rawbuf, uint length,
                 Parser_state *parser_state)
{
  DBUG_ENTER("mysql_parse");
  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on_MYSQLparse(););
  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on_ORAparse(););

  /*
    Warning.
    The purpose of query_cache_send_result_to_client() is to lookup the
    query in the query cache first, to avoid parsing and executing it.
    So, the natural implementation would be to:
    - first, call query_cache_send_result_to_client,
    - second, if caching failed, initialise the lexical and syntactic parser.
    The problem is that the query cache depends on a clean initialization
    of (among others) lex->safe_to_cache_query and thd->server_status,
    which are reset respectively in
    - lex_start()
    - THD::reset_for_next_command()
    So, initializing the lexical analyser *before* using the query cache
    is required for the cache to work properly.
    FIXME: cleanup the dependencies in the code to simplify this.
  */
  lex_start(thd);
  thd->reset_for_next_command();

  if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
  {
    LEX *lex= thd->lex;

    bool err= parse_sql(thd, parser_state, NULL, true);

    if (likely(!err))
    {
      thd->m_statement_psi=
        MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                               sql_statement_info[thd->lex->sql_command].
                               m_key);
#ifndef NO_EMBEDDED_ACCESS_CHECKS
      if (mqh_used && thd->user_connect &&
	  check_mqh(thd, lex->sql_command))
      {
	thd->net.error = 0;
      }
      else
#endif
      {
	if (likely(! thd->is_error()))
	{
          const char *found_semicolon= parser_state->m_lip.found_semicolon;
          /*
            Binlog logs a string starting from thd->query and having length
            thd->query_length; so we set thd->query_length correctly (to not
            log several statements in one event, when we executed only first).
            We set it to not see the ';' (otherwise it would get into binlog
            and Query_log_event::print() would give ';;' output).
            This also helps display only the current query in SHOW
            PROCESSLIST.
          */
          if (found_semicolon && (ulong) (found_semicolon - thd->query()))
            thd->set_query(thd->query(),
                           (uint32) (found_semicolon - thd->query() - 1),
                           thd->charset());
          /* Actually execute the query */
          if (found_semicolon)
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
          lex->set_trg_event_type_for_tables();
          MYSQL_QUERY_EXEC_START(thd->query(),
                                 thd->thread_id,
                                 thd->get_db(),
                                 &thd->security_ctx->priv_user[0],
                                 (char *) thd->security_ctx->host_or_ip,
                                 0);

          int error __attribute__((unused));
          error= mysql_execute_command(thd);
          MYSQL_QUERY_EXEC_DONE(error);
	}
      }
    }
    else
    {
      /* Instrument this broken statement as "statement/sql/error" */
      thd->m_statement_psi=
        MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                               sql_statement_info[SQLCOM_END].m_key);
      DBUG_ASSERT(thd->is_error());
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
			 thd->is_fatal_error));

      query_cache_abort(thd, &thd->query_cache_tls);
    }
    THD_STAGE_INFO(thd, stage_freeing_items);
    sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
    sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
    sp_cache_enforce_limit(thd->sp_package_spec_cache, stored_program_cache_size);
    sp_cache_enforce_limit(thd->sp_package_body_cache, stored_program_cache_size);
    thd->end_statement();
    thd->Item_change_list::rollback_item_tree_changes();
    thd->cleanup_after_query();
  }
  else
  {
    /* Update statistics for getting the query from the cache */
    thd->lex->sql_command= SQLCOM_SELECT;
    thd->m_statement_psi=
      MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                             sql_statement_info[SQLCOM_SELECT].m_key);
    status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]);
    thd->update_stats();
#ifdef WITH_WSREP
    if (WSREP_CLIENT(thd))
    {
      thd->wsrep_sync_wait_gtid= WSREP_GTID_UNDEFINED;
    }
#endif /* WITH_WSREP */
  }
  DBUG_VOID_RETURN;
}


#ifdef HAVE_REPLICATION
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

  @retval
    0	cannot be ignored
  @retval
    1	can be ignored
*/

bool mysql_test_parse_for_slave(THD *thd, char *rawbuf, uint length)
{
  LEX *lex= thd->lex;
  bool error= 0;
  DBUG_ENTER("mysql_test_parse_for_slave");

  Parser_state parser_state;
  if (likely(!(error= parser_state.init(thd, rawbuf, length))))
  {
    lex_start(thd);
    thd->reset_for_next_command();

    if (!parse_sql(thd, & parser_state, NULL, true) &&
        all_tables_not_ok(thd, lex->first_select_lex()->table_list.first))
      error= 1;                  /* Ignore question */
    thd->end_statement();
  }
  thd->cleanup_after_query();
  DBUG_RETURN(error);
}
#endif


bool
add_proc_to_list(THD* thd, Item *item)
{
  ORDER *order;
  Item	**item_ptr;

  if (unlikely(!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*)))))
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
  thd->lex->proc_list.link_in_list(order, &order->next);
  return 0;
}


/**
  save order by and tables in own lists.
*/

bool add_to_list(THD *thd, SQL_I_List<ORDER> &list, Item *item,bool asc)
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
  if (unlikely(!(order = (ORDER *) thd->alloc(sizeof(ORDER)))))
    DBUG_RETURN(1);
  order->item_ptr= item;
  order->item= &order->item_ptr;
  order->direction= (asc ? ORDER::ORDER_ASC : ORDER::ORDER_DESC);
  order->used=0;
  order->counter_used= 0;
  order->fast_field_copier_setup= 0; 
  list.link_in_list(order, &order->next);
  DBUG_RETURN(0);
}


/**
  Add a table to list of used tables.

  @param table		Table to add
  @param alias		alias for table (or null if no alias)
  @param table_options	A set of the following bits:
                         - TL_OPTION_UPDATING : Table will be updated
                         - TL_OPTION_FORCE_INDEX : Force usage of index
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
  @param lock_type	How table should be locked
  @param mdl_type       Type of metadata lock to acquire on the table.
  @param use_index	List of indexed used in USE INDEX
  @param ignore_index	List of indexed used in IGNORE INDEX

  @retval
      0		Error
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
*/

TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
					     LEX_CSTRING *alias,
					     ulong table_options,
					     thr_lock_type lock_type,
					     enum_mdl_type mdl_type,
					     List<Index_hint> *index_hints_arg,
                                             List<String> *partition_names,
                                             LEX_STRING *option)
{
  TABLE_LIST *ptr;
  TABLE_LIST *UNINIT_VAR(previous_table_ref); /* The table preceding the current one. */
  LEX_CSTRING alias_str;
  LEX *lex= thd->lex;
  DBUG_ENTER("add_table_to_list");
  DBUG_PRINT("enter", ("Table '%s' (%p)  Select %p (%u)",
                        (alias ? alias->str : table->table.str),
                        table,
                        this, select_number));
  DBUG_ASSERT(!is_service_select  || (table_options & TL_OPTION_SEQUENCE));

  if (unlikely(!table))
    DBUG_RETURN(0);				// End of memory
  alias_str= alias ? *alias : table->table;
  DBUG_ASSERT(alias_str.str);
  if (!MY_TEST(table_options & TL_OPTION_ALIAS) &&
      unlikely(check_table_name(table->table.str, table->table.length, FALSE)))
  {
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
    DBUG_RETURN(0);
  }

  if (unlikely(table->is_derived_table() == FALSE && table->db.str &&
               !(table_options & TL_OPTION_TABLE_FUNCTION) &&
               check_db_name((LEX_STRING*) &table->db)))
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
    DBUG_RETURN(0);
  }

  if (!alias)                            /* Alias is case sensitive */
  {
    if (unlikely(table->sel))
    {
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
                 ER_THD(thd, ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
      DBUG_RETURN(0);
    }
    /* alias_str points to table->table;  Let's make a copy */
    if (unlikely(!(alias_str.str= (char*) thd->memdup(alias_str.str, alias_str.length+1))))
      DBUG_RETURN(0);
  }
  if (unlikely(!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST)))))
    DBUG_RETURN(0);				/* purecov: inspected */
  if (table->db.str)
  {
    ptr->is_fqtn= TRUE;
    ptr->db= table->db;
  }
  else if (!lex->with_cte_resolution && lex->copy_db_to(&ptr->db))
    DBUG_RETURN(0);
  else
    ptr->is_fqtn= FALSE;

  ptr->alias= alias_str;
  ptr->is_alias= alias ? TRUE : FALSE;
  if (lower_case_table_names)
  {
    if (table->table.length)
      table->table.length= my_casedn_str(files_charset_info,
                                         (char*) table->table.str);
    if (ptr->db.length && ptr->db.str != any_db.str)
      ptr->db.length= my_casedn_str(files_charset_info, (char*) ptr->db.str);
  }

  ptr->table_name= table->table;
  ptr->lock_type= lock_type;
  ptr->mdl_type= mdl_type;
  ptr->table_options= table_options;
  ptr->updating=    MY_TEST(table_options & TL_OPTION_UPDATING);
  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
  ptr->force_index= MY_TEST(table_options & TL_OPTION_FORCE_INDEX);
  ptr->ignore_leaves= MY_TEST(table_options & TL_OPTION_IGNORE_LEAVES);
  ptr->sequence=      MY_TEST(table_options & TL_OPTION_SEQUENCE);
  ptr->derived=	    table->sel;
  if (!ptr->derived && is_infoschema_db(&ptr->db))
  {
    if (ptr->updating &&
        /* Special cases which are processed by commands itself */
        lex->sql_command != SQLCOM_CHECK &&
        lex->sql_command != SQLCOM_CHECKSUM)
    {
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               INFORMATION_SCHEMA_NAME.str);
      DBUG_RETURN(0);
    }
    ST_SCHEMA_TABLE *schema_table;
    schema_table= find_schema_table(thd, &ptr->table_name);
    ptr->schema_table_name= ptr->table_name;
    ptr->schema_table= schema_table;
  }
  ptr->select_lex= this;
  /*
    We can't cache internal temporary tables between prepares as the
    table may be deleted before next exection.
 */
  ptr->cacheable_table= !table->is_derived_table();
  ptr->index_hints= index_hints_arg;
  ptr->option= option ? option->str : 0;
  /* check that used name is unique. Sequences are ignored */
  if (lock_type != TL_IGNORE && !ptr->sequence)
  {
    TABLE_LIST *first_table= table_list.first;
    if (lex->sql_command == SQLCOM_CREATE_VIEW)
      first_table= first_table ? first_table->next_local : NULL;
    for (TABLE_LIST *tables= first_table ;
	 tables ;
	 tables=tables->next_local)
    {
      if (unlikely(!my_strcasecmp(table_alias_charset, alias_str.str,
                                  tables->alias.str) &&
                   (tables->db.str == any_db.str || ptr->db.str == any_db.str ||
                    !cmp(&ptr->db, &tables->db)) &&
                   !tables->sequence))
      {
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str.str); /* purecov: tested */
	DBUG_RETURN(0);				/* purecov: tested */
      }
    }
  }
  /* Store the table reference preceding the current one. */
  if (table_list.elements > 0 && likely(!ptr->sequence))
  {
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
      We don't use the offsetof() macro here to avoid warnings from gcc
    */
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
    /*
      Set next_name_resolution_table of the previous table reference to point
      to the current table reference. In effect the list
      TABLE_LIST::next_name_resolution_table coincides with
      TABLE_LIST::next_local. Later this may be changed in
      store_top_level_join_columns() for NATURAL/USING joins.
    */
    previous_table_ref->next_name_resolution_table= ptr;
  }

  /*
    Link the current table reference in a local list (list for current select).
    Notice that as a side effect here we set the next_local field of the
    previous table reference to 'ptr'. Here we also add one element to the
    list 'table_list'.
    We don't store sequences into the local list to hide them from INSERT
    and SELECT.
  */
  if (likely(!ptr->sequence))
    table_list.link_in_list(ptr, &ptr->next_local);
  ptr->next_name_resolution_table= NULL;
#ifdef WITH_PARTITION_STORAGE_ENGINE
  ptr->partition_names= partition_names;
#endif /* WITH_PARTITION_STORAGE_ENGINE */
  /* Link table in global list (all used tables) */
  lex->add_to_query_tables(ptr);

  // Pure table aliases do not need to be locked:
  if (ptr->db.str && !(table_options & TL_OPTION_ALIAS))
  {
    MDL_REQUEST_INIT(&ptr->mdl_request, MDL_key::TABLE, ptr->db.str,
                     ptr->table_name.str, mdl_type, MDL_TRANSACTION);
  }
  DBUG_RETURN(ptr);
}


/**
  Initialize a new table list for a nested join.

    The function initializes a structure of the TABLE_LIST type
    for a nested join. It sets up its nested join list as empty.
    The created structure is added to the front of the current
    join list in the st_select_lex object. Then the function
    changes the current nest level for joins to refer to the newly
    created empty list after having saved the info on the old level
    in the initialized structure.

  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
*/

bool st_select_lex::init_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
  DBUG_ENTER("init_nested_join");

  if (unlikely(!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                                sizeof(NESTED_JOIN)))))
    DBUG_RETURN(1);
  nested_join= ptr->nested_join=
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));

  ptr->embedding= embedding;
  ptr->join_list= join_list;
  ptr->alias.str="(nested_join)";
  ptr->alias.length= sizeof("(nested_join)")-1;
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


/**
  End a nested join table list.

    The function returns to the previous join nest level.
    If the current level contains only one member, the function
    moves it one level up, eliminating the nest.

  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
  DBUG_ENTER("end_nested_join");

  DBUG_ASSERT(embedding);
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
  nested_join= ptr->nested_join;
  if (nested_join->join_list.elements == 1)
  {
    TABLE_LIST *embedded= nested_join->join_list.head();
    join_list->pop();
    embedded->join_list= join_list;
    embedded->embedding= embedding;
    join_list->push_front(embedded, thd->mem_root);
    ptr= embedded;
    embedded->lifted= 1;
  }
  else if (nested_join->join_list.elements == 0)
  {
    join_list->pop();
    ptr= 0;                                     // return value
  }
  DBUG_RETURN(ptr);
}


/**
  Nest last join operation.

    The function nest last join operation as if it was enclosed in braces.

  @param thd         current thread

  @retval
    0  Error
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
  List<TABLE_LIST> *embedded_list;
  DBUG_ENTER("nest_last_join");

  TABLE_LIST *head= join_list->head();
  if (head->nested_join && (head->nested_join->nest_type & REBALANCED_NEST))
  {
    head= join_list->pop();
    DBUG_RETURN(head);
  }

  if (unlikely(!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                                sizeof(NESTED_JOIN)))))
    DBUG_RETURN(0);
  nested_join= ptr->nested_join=
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));

  ptr->embedding= embedding;
  ptr->join_list= join_list;
  ptr->alias.str= "(nest_last_join)";
  ptr->alias.length= sizeof("(nest_last_join)")-1;
  embedded_list= &nested_join->join_list;
  embedded_list->empty();
  nested_join->nest_type= JOIN_OP_NEST;

  for (uint i=0; i < 2; i++)
  {
    TABLE_LIST *table= join_list->pop();
    if (unlikely(!table))
      DBUG_RETURN(NULL);
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
    if (table->natural_join)
    {
      ptr->is_natural_join= TRUE;
      /*
        If this is a JOIN ... USING, move the list of joined fields to the
        table reference that describes the join.
      */
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
    }
  }
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


/**
  Add a table to the current join list.

    The function puts a table in front of the current join list
    of st_select_lex object.
    Thus, joined tables are put into this list in the reverse order
    (the most outer join operation follows first).

  @param table       the table to add

  @return
    None
*/

void st_select_lex::add_joined_table(TABLE_LIST *table)
{
  DBUG_ENTER("add_joined_table");
  join_list->push_front(table, parent_lex->thd->mem_root);
  table->join_list= join_list;
  table->embedding= embedding;
  DBUG_VOID_RETURN;
}


/**
  @brief
    Create a node for JOIN/INNER JOIN/CROSS JOIN/STRAIGHT_JOIN operation

  @param left_op     the node for the left operand constructed by the parser
  @param right_op    the node for the right operand constructed by the parser
  @param straight_fl TRUE if STRAIGHT_JOIN is used

  @retval
    false on success
    true  otherwise

  @details

    JOIN operator can be left-associative with other join operators in one
    context and right-associative in another context.

    In this query
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a  (Q1)
    JOIN is left-associative and the query Q1 is interpreted as
      SELECT * FROM (t1 JOIN t2) LEFT JOIN t3 ON t2.a=t3.a.
    While in this query
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a ON t1.b=t2.b (Q2)
    JOIN is right-associative and the query Q2 is interpreted as
      SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) ON t1.b=t2.b

    JOIN is right-associative if it is used with ON clause or with USING clause.
    Otherwise it is left-associative.
    When parsing a join expression with JOIN operator we can't determine
    whether this operation left or right associative until either we read the
    corresponding ON clause or we reach the end of the expression. This creates
    a problem for the parser to build a proper internal representation of the
    used join expression.

    For Q1 and Q2 the trees representing the used join expressions look like

            LJ - ON                   J - ON
           /  \                      / \
          J    t3   (TQ1)          t1   LJ - ON      (TQ2)
         / \                           /  \
       t1   t2                       t2    t3

    To build TQ1 the parser has to reduce the expression for JOIN right after
    it has read the reference to t2. To build TQ2 the parser reduces JOIN
    when he has read the whole join expression. There is no way to determine
    whether an early reduction is needed until the whole join expression is
    read.
    A solution here is always to do a late reduction. In this case the parser
    first builds an incorrect tree TQ1* that has to be rebalanced right after
    it has been constructed.

             J                               LJ - ON
            / \                             /  \
          t1   LJ - ON    (TQ1*)    =>     J    t3
              /  \                        / \
            t2    t3                    t1   t2

    Actually the transformation is performed over the nodes t1 and LJ before the
    node for J is created in the function st_select_lex::add_cross_joined_table.
    The function creates a node for J which replaces the node t2. Then it
    attaches the nodes t1 and t2 to this newly created node. The node LJ becomes
    the top node of the tree.

    For the query
      SELECT * FROM t1 JOIN t2 RIGHT JOIN t3 ON t2.a=t3.a  (Q3)
    the transformation looks slightly differently because the parser
    replaces the RIGHT JOIN tree for an equivalent LEFT JOIN tree.

             J                               LJ - ON
            / \                             /  \
          t1   LJ - ON    (TQ3*)    =>    t3    J
              /  \                             / \
            t3    t2                         t1   t2

    With several left associative JOINs
      SELECT * FROM t1 JOIN t2 JOIN t3 LEFT JOIN t4 ON t3.a=t4.a (Q4)
    the newly created node for JOIN replaces the left most node of the tree:

          J1                         LJ - ON
         /  \                       /  \
       t1    J2                    J2   t4
            /  \          =>      /  \
           t2  LJ - ON          J1    t3
              /  \             /  \
            t3   t4          t1    t2

    Here's another example:
      SELECT *
      FROM t1 JOIN t2 LEFT JOIN t3 JOIN t4 ON t3.a=t4.a ON t2.b=t3.b (Q5)

          J                       LJ - ON
         / \                     /   \
       t1   LJ - ON             J     J - ON
           /  \          =>    / \   / \
         t2    J - ON         t1 t2 t3 t4
              / \
            t3   t4

    If the transformed nested join node node is a natural join node like in
    the following query
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 USING(a)  (Q6)
    the transformation additionally has to take care about setting proper
    references in the field natural_join for both operands of the natural
    join operation.

    The queries that combine comma syntax for join operation with
    JOIN expression require a special care. Consider the query
      SELECT * FROM t1, t2 JOIN t3 LEFT JOIN t4 ON t3.a=t4.a (Q7)
    This query is equivalent to the query
      SELECT * FROM (t1, t2) JOIN t3 LEFT JOIN t4 ON t3.a=t4.a
    The latter is transformed in the same way as query Q1

             J                               LJ - ON
            / \                             /  \
      (t1,t2)  LJ - ON      =>             J    t4
              /  \                        / \
            t3    t4                (t1,t2)   t3

    A transformation similar to the transformation for Q3 is done for
    the following query with RIGHT JOIN
      SELECT * FROM t1, t2 JOIN t3 RIGHT JOIN t4 ON t3.a=t4.a (Q8)

             J                               LJ - ON
            / \                             /  \
          t3   LJ - ON      =>            t4    J
              /  \                             / \
            t4   (t1,t2)                 (t1,t2)  t3

    The function also has to change the name resolution context for ON
    expressions used in the transformed join expression to take into
    account the tables of the left_op node.

  TODO:
    A more elegant solution would be to implement the transformation that
    eliminates nests for cross join operations. For Q7 it would work like this:

             J                               LJ - ON
            / \                             /  \
      (t1,t2)  LJ - ON      =>     (t1,t2,t3)   t4
              /  \
            t3    t4

    For Q8 with RIGHT JOIN the transformation would work similarly:

             J                               LJ - ON
            / \                             /  \
          t3   LJ - ON      =>            t4   (t1,t2,t3)
              /  \
            t4   (t1,t2)

*/

bool st_select_lex::add_cross_joined_table(TABLE_LIST *left_op,
                                           TABLE_LIST *right_op,
                                           bool straight_fl)
{
  DBUG_ENTER("add_cross_joined_table");
  THD *thd= parent_lex->thd;
  if (!(right_op->nested_join &&
	(right_op->nested_join->nest_type & JOIN_OP_NEST)))
  {
    /*
      This handles the cases when the right operand is not a nested join.
      like in queries
        SELECT * FROM t1 JOIN t2;
        SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.a JOIN t3
    */
    add_joined_table(left_op);
    add_joined_table(right_op);
    right_op->straight= straight_fl;
    DBUG_RETURN(false);
  }

  TABLE_LIST *tbl;
  List<TABLE_LIST> *right_op_jl= right_op->join_list;
  TABLE_LIST *cj_nest;

  /*
    Create the node NJ for a new nested join for the future inclusion
    of left_op in it. Initially the nest is empty.
  */
  if (unlikely(!(cj_nest=
                 (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                           sizeof(NESTED_JOIN)))))
    DBUG_RETURN(true);
  cj_nest->nested_join=
    ((NESTED_JOIN*) ((uchar*) cj_nest + ALIGN_SIZE(sizeof(TABLE_LIST))));
  cj_nest->nested_join->nest_type= JOIN_OP_NEST;
  List<TABLE_LIST> *cjl=  &cj_nest->nested_join->join_list;
  cjl->empty();

  List<TABLE_LIST> *jl= &right_op->nested_join->join_list;
  DBUG_ASSERT(jl->elements == 2);
  /* Look for the left most node tbl of the right_op tree */
  for ( ; ; )
  {
    TABLE_LIST *pair_tbl= 0;  /* useful only for operands of natural joins */

    List_iterator<TABLE_LIST> li(*jl);
    tbl= li++;

    /* Expand name resolution context */
    Name_resolution_context *on_context;
    if ((on_context= tbl->on_context))
    {
      on_context->first_name_resolution_table=
        left_op->first_leaf_for_name_resolution();
    }

    if (!(tbl->outer_join & JOIN_TYPE_RIGHT))
    {
      pair_tbl= tbl;
      tbl= li++;
    }
    if (tbl->nested_join &&
        tbl->nested_join->nest_type & JOIN_OP_NEST)
    {
      jl= &tbl->nested_join->join_list;
      continue;
    }

    /* Replace the tbl node in the tree for the newly created NJ node */
    cj_nest->outer_join= tbl->outer_join;
    cj_nest->on_expr= tbl->on_expr;
    cj_nest->embedding= tbl->embedding;
    cj_nest->join_list= jl;
    cj_nest->alias.str= "(nest_last_join)";
    cj_nest->alias.length= sizeof("(nest_last_join)")-1;
    li.replace(cj_nest);

    /*
      If tbl is an operand of a natural join set properly the references
      in the fields natural_join for both operands of the operation.
    */
    if(tbl->embedding && tbl->embedding->is_natural_join)
    {
      if (!pair_tbl)
        pair_tbl= li++;
      pair_tbl->natural_join= cj_nest;
      cj_nest->natural_join= pair_tbl;
    }
    break;
  }

  /* Attach tbl as the right operand of NJ */
  if (unlikely(cjl->push_back(tbl, thd->mem_root)))
    DBUG_RETURN(true);
  tbl->outer_join= 0;
  tbl->on_expr= 0;
  tbl->straight= straight_fl;
  tbl->natural_join= 0;
  tbl->embedding= cj_nest;
  tbl->join_list= cjl;

  /* Add left_op as the left operand of NJ */
  if (unlikely(cjl->push_back(left_op, thd->mem_root)))
    DBUG_RETURN(true);
  left_op->embedding= cj_nest;
  left_op->join_list= cjl;

  /*
    Mark right_op as a rebalanced nested join in order not to
    create a new top level nested join node.
  */
  right_op->nested_join->nest_type|= REBALANCED_NEST;
  if (unlikely(right_op_jl->push_front(right_op)))
    DBUG_RETURN(true);
  DBUG_RETURN(false);
}


/**
  Convert a right join into equivalent left join.

    The function takes the current join list t[0],t[1] ... and
    effectively converts it into the list t[1],t[0] ...
    Although the outer_join flag for the new nested table contains
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
    operation.

  EXAMPLES
  @verbatim
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr

    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
   @endverbatim

  @param thd         current thread

  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
*/

TABLE_LIST *st_select_lex::convert_right_join()
{
  TABLE_LIST *tab2= join_list->pop();
  TABLE_LIST *tab1= join_list->pop();
  DBUG_ENTER("convert_right_join");

  join_list->push_front(tab2, parent_lex->thd->mem_root);
  join_list->push_front(tab1, parent_lex->thd->mem_root);
  tab1->outer_join|= JOIN_TYPE_RIGHT;

  DBUG_RETURN(tab1);
}


void st_select_lex::prepare_add_window_spec(THD *thd)
{
  LEX *lex= thd->lex;
  save_group_list= group_list;
  save_order_list= order_list;
  lex->win_ref= NULL;
  lex->win_frame= NULL;
  lex->frame_top_bound= NULL;
  lex->frame_bottom_bound= NULL;
  group_list.empty();
  order_list.empty();
}

bool st_select_lex::add_window_def(THD *thd,
                                   LEX_CSTRING *win_name,
                                   LEX_CSTRING *win_ref,
                                   SQL_I_List<ORDER> win_partition_list,
                                   SQL_I_List<ORDER> win_order_list,
                                   Window_frame *win_frame)
{
  SQL_I_List<ORDER> *win_part_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_partition_list);
  SQL_I_List<ORDER> *win_order_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_order_list);
  if (!(win_part_list_ptr && win_order_list_ptr))
    return true;
  Window_def *win_def= new (thd->mem_root) Window_def(win_name,
                                                      win_ref,
                                                      win_part_list_ptr,
                                                      win_order_list_ptr,
                                                      win_frame);
  group_list= save_group_list;
  order_list= save_order_list;
  if (parsing_place != SELECT_LIST)
  {
    fields_in_window_functions+= win_part_list_ptr->elements +
                                 win_order_list_ptr->elements;
  }
  win_def->win_spec_number= window_specs.elements;
  return (win_def == NULL || window_specs.push_back(win_def));
}

bool st_select_lex::add_window_spec(THD *thd, 
                                    LEX_CSTRING *win_ref,
                                    SQL_I_List<ORDER> win_partition_list,
                                    SQL_I_List<ORDER> win_order_list,
                                    Window_frame *win_frame)
{
  SQL_I_List<ORDER> *win_part_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_partition_list);
  SQL_I_List<ORDER> *win_order_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_order_list);
  if (!(win_part_list_ptr && win_order_list_ptr))
    return true;
  Window_spec *win_spec= new (thd->mem_root) Window_spec(win_ref,
                                                         win_part_list_ptr,
                                                         win_order_list_ptr,
                                                         win_frame);
  group_list= save_group_list;
  order_list= save_order_list;
  if (parsing_place != SELECT_LIST)
  {
    fields_in_window_functions+= win_part_list_ptr->elements +
                                 win_order_list_ptr->elements;
  }
  thd->lex->win_spec= win_spec;
  win_spec->win_spec_number= window_specs.elements;
  return (win_spec == NULL || window_specs.push_back(win_spec));
}

/**
  Set lock for all tables in current select level.

  @param lock_type		Lock to set for tables
  @param skip_locked		(SELECT {FOR UPDATE/LOCK IN SHARED MODE} SKIP LOCKED)

  @note
    If lock is a write lock, then tables->updating is set 1
    This is to get tables_ok to know that the table is updated by the
    query
*/

void st_select_lex::set_lock_for_tables(thr_lock_type lock_type, bool for_update,
					bool skip_locked_arg)
{
  DBUG_ENTER("set_lock_for_tables");
  DBUG_PRINT("enter", ("lock_type: %d  for_update: %d  skip_locked %d",
                       lock_type, for_update, skip_locked));
  skip_locked= skip_locked_arg;
  for (TABLE_LIST *tables= table_list.first;
       tables;
       tables= tables->next_local)
  {
    tables->lock_type= lock_type;
    tables->skip_locked= skip_locked;
    tables->updating=  for_update;

    if (tables->db.length)
      tables->mdl_request.set_type((lock_type >= TL_FIRST_WRITE) ?
                                   MDL_SHARED_WRITE : MDL_SHARED_READ);
  }
  DBUG_VOID_RETURN;
}


/**
  Create a fake SELECT_LEX for a unit.

    The method create a fake SELECT_LEX object for a unit.
    This object is created for any union construct containing a union
    operation and also for any single select union construct of the form
    @verbatim
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
    @endvarbatim
    or of the form
    @varbatim
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
    @endvarbatim
  
  @param thd_arg		   thread handle

  @note
    The object is used to retrieve rows from the temporary table
    where the result on the union is obtained.

  @retval
    1     on failure to create the object
  @retval
    0     on success
*/

bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
{
  SELECT_LEX *first_sl= first_select();
  DBUG_ENTER("st_select_lex_unit::add_fake_select_lex");
  DBUG_ASSERT(!fake_select_lex);

  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
      DBUG_RETURN(1);
  fake_select_lex->include_standalone(this, 
                                      (SELECT_LEX_NODE**)&fake_select_lex);
  fake_select_lex->select_number= FAKE_SELECT_LEX_ID;
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
  fake_select_lex->make_empty_select();
  fake_select_lex->set_linkage(GLOBAL_OPTIONS_TYPE);

  fake_select_lex->no_table_names_allowed= 1;

  fake_select_lex->context.outer_context=first_sl->context.outer_context;
  /* allow item list resolving in fake select for ORDER BY */
  fake_select_lex->context.resolve_in_select_list= TRUE;
  fake_select_lex->context.select_lex= fake_select_lex;  

  fake_select_lex->nest_level_base= first_select()->nest_level_base;
  if (fake_select_lex->set_nest_level(first_select()->nest_level))
    DBUG_RETURN(1);

  if (!is_unit_op())
  {
    /* 
      This works only for 
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
      just before the parser starts processing order_list
    */ 
    fake_select_lex->no_table_names_allowed= 1;
    thd_arg->lex->current_select= fake_select_lex;
  }
  //thd_arg->lex->pop_context("add fake");
  DBUG_RETURN(0);
}


/**
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.

    Create a new name resolution context for a JOIN ... ON clause,
    set the first and last leaves of the list of table references
    to be used for name resolution, and push the newly created
    context to the stack of contexts of the query.

  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

  @seealso
    push_table_function_arg_context() serves similar purpose for table
    functions

  @retval
    FALSE  if all is OK
  @retval
    TRUE   if a memory allocation error occurred
*/

bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
{
  Name_resolution_context *on_context;
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
    return TRUE;
  on_context->first_name_resolution_table=
    left_op->first_leaf_for_name_resolution();
  on_context->last_name_resolution_table=
    right_op->last_leaf_for_name_resolution();
  LEX *lex= thd->lex;
  on_context->select_lex = lex->current_select;
  st_select_lex *outer_sel= lex->parser_current_outer_select();
  on_context->outer_context = outer_sel ? &outer_sel->context : 0;
  return lex->push_context(on_context);
}


/**
  Fix condition which contains only field (f turns to  f <> 0 )

  @param cond            The condition to fix

  @return fixed condition
*/

Item *normalize_cond(THD *thd, Item *cond)
{
  if (cond)
  {
    Item::Type type= cond->type();
    if (type == Item::FIELD_ITEM || type == Item::REF_ITEM)
    {
      cond= new (thd->mem_root) Item_func_ne(thd, cond, new (thd->mem_root) Item_int(thd, 0));
    }
  }
  return cond;
}


/**
  Add an ON condition to the second operand of a JOIN ... ON.

    Add an ON condition to the right operand of a JOIN ... ON clause.

  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause

  @retval
    FALSE  if there was some error
  @retval
    TRUE   if all is OK
*/

void add_join_on(THD *thd, TABLE_LIST *b, Item *expr)
{
  if (expr)
  {
    expr= normalize_cond(thd, expr);
    if (!b->on_expr)
      b->on_expr= expr;
    else
    {
      /*
        If called from the parser, this happens if you have both a
        right and left join. If called later, it happens if we add more
        than one condition to the ON clause.
      */
      b->on_expr= new (thd->mem_root) Item_cond_and(thd, b->on_expr,expr);
    }
    b->on_expr->top_level_item();
  }
}


/**
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.

    This function marks that table b should be joined with a either via
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
    cases of each other, so we treat them together. The function
    setup_conds() creates a list of equal condition between all fields
    of the same name for NATURAL JOIN or the fields in 'using_fields'
    for JOIN ... USING. The list of equality conditions is stored
    either in b->on_expr, or in JOIN::conds, depending on whether there
    was an outer join.

  EXAMPLE
  @verbatim
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )

    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)

    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
   @endverbatim

  @param a		  Left join argumentex
  @param b		  Right join argument
  @param using_fields    Field names from USING clause
*/

void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
{
  b->natural_join= a;
  lex->prev_join_using= using_fields;
}


/**
  Find a thread by id and return it, locking it LOCK_thd_kill

  @param id  Identifier of the thread we're looking for
  @param query_id If true, search by query_id instead of thread_id

  @return NULL    - not found
          pointer - thread found, and its LOCK_thd_kill is locked.
*/

struct find_thread_callback_arg
{
  find_thread_callback_arg(longlong id_arg, bool query_id_arg):
    thd(0), id(id_arg), query_id(query_id_arg) {}
  THD *thd;
  longlong id;
  bool query_id;
};


static my_bool find_thread_callback(THD *thd, find_thread_callback_arg *arg)
{
  if (arg->id == (arg->query_id ? thd->query_id : (longlong) thd->thread_id))
  {
    mysql_mutex_lock(&thd->LOCK_thd_kill);    // Lock from delete
    arg->thd= thd;
    return 1;
  }
  return 0;
}


THD *find_thread_by_id(longlong id, bool query_id)
{
  find_thread_callback_arg arg(id, query_id);
  server_threads.iterate(find_thread_callback, &arg);
  return arg.thd;
}


/**
  kill one thread.

  @param thd			Thread class
  @param id                     Thread id or query id
  @param kill_signal            Should it kill the query or the connection
  @param type                   Type of id: thread id or query id
*/

uint
kill_one_thread(THD *thd, my_thread_id id, killed_state kill_signal, killed_type type)
{
  THD *tmp;
  uint error= (type == KILL_TYPE_QUERY ? ER_NO_SUCH_QUERY : ER_NO_SUCH_THREAD);
  DBUG_ENTER("kill_one_thread");
  DBUG_PRINT("enter", ("id: %lld  signal: %d", (long long) id, kill_signal));
  tmp= find_thread_by_id(id, type == KILL_TYPE_QUERY);
  if (!tmp)
    DBUG_RETURN(error);
  DEBUG_SYNC(thd, "found_killee");
  if (tmp->get_command() != COM_DAEMON)
  {
    /*
      If we're SUPER, we can KILL anything, including system-threads.
      No further checks.

      KILLer: thd->security_ctx->user could in theory be NULL while
      we're still in "unauthenticated" state. This is a theoretical
      case (the code suggests this could happen, so we play it safe).

      KILLee: tmp->security_ctx->user will be NULL for system threads.
      We need to check so Jane Random User doesn't crash the server
      when trying to kill a) system threads or b) unauthenticated users'
      threads (Bug#43748).

      If user of both killer and killee are non-NULL, proceed with
      slayage if both are string-equal.

      It's ok to also kill DELAYED threads with KILL_CONNECTION instead of
      KILL_SYSTEM_THREAD; The difference is that KILL_CONNECTION may be
      faster and do a harder kill than KILL_SYSTEM_THREAD;
    */

    mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from concurrent usage

#ifdef WITH_WSREP
    if (((thd->security_ctx->master_access & PRIV_KILL_OTHER_USER_PROCESS) ||
        thd->security_ctx->user_matches(tmp->security_ctx)) &&
        !wsrep_thd_is_BF(tmp, false) && !tmp->wsrep_applier)
#else
    if ((thd->security_ctx->master_access & PRIV_KILL_OTHER_USER_PROCESS) ||
        thd->security_ctx->user_matches(tmp->security_ctx))
#endif /* WITH_WSREP */
    {
#ifdef WITH_WSREP
      DEBUG_SYNC(thd, "before_awake_no_mutex");
      if (tmp->wsrep_aborter && tmp->wsrep_aborter != thd->thread_id)
      {
        /* victim is in hit list already, bail out */
	WSREP_DEBUG("victim %lld has wsrep aborter: %lu, skipping awake()",
		    id, tmp->wsrep_aborter);
        error= 0;
      }
      else
#endif /* WITH_WSREP */
      {
        WSREP_DEBUG("kill_one_thread victim: %lld wsrep_aborter %lu"
                    " by signal %d",
                    id, tmp->wsrep_aborter, kill_signal);
        tmp->awake_no_mutex(kill_signal);
        error= 0;
      }
    }
    else
      error= (type == KILL_TYPE_QUERY ? ER_KILL_QUERY_DENIED_ERROR :
                                        ER_KILL_DENIED_ERROR);

    mysql_mutex_unlock(&tmp->LOCK_thd_data);
  }
  mysql_mutex_unlock(&tmp->LOCK_thd_kill);
  DBUG_PRINT("exit", ("%u", error));
  DBUG_RETURN(error);
}


/**
  kill all threads from one user

  @param thd			Thread class
  @param user_name		User name for threads we should kill
  @param only_kill_query        Should it kill the query or the connection

  @note
    If we can't kill all threads because of security issues, no threads
    are killed.
*/

struct kill_threads_callback_arg
{
  kill_threads_callback_arg(THD *thd_arg, LEX_USER *user_arg):
    thd(thd_arg), user(user_arg) {}
  THD *thd;
  LEX_USER *user;
  List<THD> threads_to_kill;
};


static my_bool kill_threads_callback(THD *thd, kill_threads_callback_arg *arg)
{
  if (thd->security_ctx->user)
  {
    /*
      Check that hostname (if given) and user name matches.

      host.str[0] == '%' means that host name was not given. See sql_yacc.yy
    */
    if (((arg->user->host.str[0] == '%' && !arg->user->host.str[1]) ||
         !strcmp(thd->security_ctx->host_or_ip, arg->user->host.str)) &&
        !strcmp(thd->security_ctx->user, arg->user->user.str))
    {
      if (!(arg->thd->security_ctx->master_access &
            PRIV_KILL_OTHER_USER_PROCESS) &&
          !arg->thd->security_ctx->user_matches(thd->security_ctx))
        return 1;
      if (!arg->threads_to_kill.push_back(thd, arg->thd->mem_root))
      {
        mysql_mutex_lock(&thd->LOCK_thd_kill); // Lock from delete
        mysql_mutex_lock(&thd->LOCK_thd_data);
      }
    }
  }
  return 0;
}


static uint kill_threads_for_user(THD *thd, LEX_USER *user,
                                  killed_state kill_signal, ha_rows *rows)
{
  kill_threads_callback_arg arg(thd, user);
  DBUG_ENTER("kill_threads_for_user");

  *rows= 0;

  if (unlikely(thd->is_fatal_error))        // If we run out of memory
    DBUG_RETURN(ER_OUT_OF_RESOURCES);

  DBUG_PRINT("enter", ("user: %s  signal: %u", user->user.str,
                       (uint) kill_signal));

  if (server_threads.iterate(kill_threads_callback, &arg))
    DBUG_RETURN(ER_KILL_DENIED_ERROR);

  if (!arg.threads_to_kill.is_empty())
  {
    List_iterator_fast<THD> it2(arg.threads_to_kill);
    THD *next_ptr;
    THD *ptr= it2++;
    do
    {
      ptr->awake_no_mutex(kill_signal);
      /*
        Careful here: The list nodes are allocated on the memroots of the
        THDs to be awakened.
        But those THDs may be terminated and deleted as soon as we release
        LOCK_thd_kill, which will make the list nodes invalid.
        Since the operation "it++" dereferences the "next" pointer of the
        previous list node, we need to do this while holding LOCK_thd_kill.
      */
      next_ptr= it2++;
      mysql_mutex_unlock(&ptr->LOCK_thd_kill);
      mysql_mutex_unlock(&ptr->LOCK_thd_data);
      (*rows)++;
    } while ((ptr= next_ptr));
  }
  DBUG_RETURN(0);
}


/**
  kills a thread and sends response.

  @param thd                    Thread class
  @param id                     Thread id or query id
  @param state                  Should it kill the query or the connection
  @param type                   Type of id: thread id or query id
*/

static
void sql_kill(THD *thd, my_thread_id id, killed_state state, killed_type type)
{
  uint error;
#ifdef WITH_WSREP
  if (WSREP(thd))
  {
    WSREP_DEBUG("sql_kill called");
    if (thd->wsrep_applier)
    {
      WSREP_DEBUG("KILL in applying, bailing out here");
      return;
    }
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL)
  }
#endif /* WITH_WSREP */
  if (likely(!(error= kill_one_thread(thd, id, state, type))))
  {
    if (!thd->killed)
      my_ok(thd);
    else
      thd->send_kill_message();
  }
  else
    my_error(error, MYF(0), id);
#ifdef WITH_WSREP
  return;
 wsrep_error_label:
  my_error(ER_KILL_DENIED_ERROR, MYF(0), (long long) thd->thread_id);
#endif /* WITH_WSREP */
}


static void __attribute__ ((noinline))
sql_kill_user(THD *thd, LEX_USER *user, killed_state state)
{
  uint error;
  ha_rows rows;
#ifdef WITH_WSREP
  if (WSREP(thd))
  {
    WSREP_DEBUG("sql_kill_user called");
    if (thd->wsrep_applier)
    {
      WSREP_DEBUG("KILL in applying, bailing out here");
      return;
    }
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL)
  }
#endif /* WITH_WSREP */
  switch (error= kill_threads_for_user(thd, user, state, &rows))
  {
  case 0:
    my_ok(thd, rows);
    break;
  case ER_KILL_DENIED_ERROR:
    my_error(error, MYF(0), (long long) thd->thread_id);
    break;
  case ER_OUT_OF_RESOURCES:
  default:
    my_error(error, MYF(0));
  }
#ifdef WITH_WSREP
  return;
 wsrep_error_label:
  my_error(ER_KILL_DENIED_ERROR, MYF(0), (long long) thd->thread_id);
#endif /* WITH_WSREP */
}


/** If pointer is not a null pointer, append filename to it. */

bool append_file_to_dir(THD *thd, const char **filename_ptr,
                        const LEX_CSTRING *table_name)
{
  char buff[FN_REFLEN],*ptr, *end;
  if (!*filename_ptr)
    return 0;					// nothing to do

  /* Check that the filename is not too long and it's a hard path */
  if (strlen(*filename_ptr)+table_name->length >= FN_REFLEN-1 ||
      !test_if_hard_path(*filename_ptr))
  {
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
  end=convert_dirname(buff, *filename_ptr, NullS);
  if (unlikely(!(ptr= (char*) thd->alloc((size_t) (end-buff) +
                                         table_name->length + 1))))
    return 1;					// End of memory
  *filename_ptr=ptr;
  strxmov(ptr,buff,table_name->str,NullS);
  return 0;
}


Comp_creator *comp_eq_creator(bool invert)
{
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
}


Comp_creator *comp_ge_creator(bool invert)
{
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
}


Comp_creator *comp_gt_creator(bool invert)
{
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
}


Comp_creator *comp_le_creator(bool invert)
{
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
}


Comp_creator *comp_lt_creator(bool invert)
{
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
}


Comp_creator *comp_ne_creator(bool invert)
{
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
}


/**
  Construct ALL/ANY/SOME subquery Item.

  @param left_expr   pointer to left expression
  @param cmp         compare function creator
  @param all         true if we create ALL subquery
  @param select_lex  pointer on parsed subquery structure

  @return
    constructed Item (or 0 if out of memory)
*/
Item * all_any_subquery_creator(THD *thd, Item *left_expr,
				chooser_compare_func_creator cmp,
				bool all,
				SELECT_LEX *select_lex)
{
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
    return new (thd->mem_root) Item_in_subselect(thd, left_expr, select_lex);

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
    return new (thd->mem_root) Item_func_not(thd,
             new (thd->mem_root) Item_in_subselect(thd, left_expr, select_lex));

  Item_allany_subselect *it=
    new (thd->mem_root) Item_allany_subselect(thd, left_expr, cmp, select_lex,
                                              all);
  if (all) /* ALL */
    return it->upper_item= new (thd->mem_root) Item_func_not_all(thd, it);

  /* ANY/SOME */
  return it->upper_item= new (thd->mem_root) Item_func_nop_all(thd, it);
}


/**
  Multi update query pre-check.

  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)

  @retval
    FALSE OK
  @retval
    TRUE  Error
*/

bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
{
  TABLE_LIST *table;
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= lex->first_select_lex();
  DBUG_ENTER("multi_update_precheck");

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
    DBUG_RETURN(TRUE);
  }
  /*
    Ensure that we have UPDATE or SELECT privilege for each table
    The exact privilege is checked in mysql_multi_update()
  */
  for (table= tables; table; table= table->next_local)
  {
    if (table->is_jtbm())
      continue;
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
    else if ((check_access(thd, UPDATE_ACL, table->db.str,
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 1) ||
              check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
             (check_access(thd, SELECT_ACL, table->db.str,
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 0) ||
              check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
      DBUG_RETURN(TRUE);

    table->grant.orig_want_privilege= NO_ACL;
    table->table_in_first_from_clause= 1;
  }
  /*
    Is there tables of subqueries?
  */
  if (lex->first_select_lex() != lex->all_selects_list)
  {
    DBUG_PRINT("info",("Checking sub query list"));
    for (table= tables; table; table= table->next_global)
    {
      if (!table->table_in_first_from_clause)
      {
	if (check_access(thd, SELECT_ACL, table->db.str,
                         &table->grant.privilege,
                         &table->grant.m_internal,
                         0, 0) ||
	    check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
	  DBUG_RETURN(TRUE);
      }
    }
  }

  DBUG_RETURN(FALSE);
}

/**
  Multi delete query pre-check.

  @param thd			Thread handler
  @param tables		Global/local table list

  @retval
    FALSE OK
  @retval
    TRUE  error
*/

bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
{
  SELECT_LEX *select_lex= thd->lex->first_select_lex();
  TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
  DBUG_ENTER("multi_delete_precheck");

  /*
    Temporary tables are pre-opened in 'tables' list only. Here we need to
    initialize TABLE instances in 'aux_tables' list.
  */
  for (TABLE_LIST *tl= aux_tables; tl; tl= tl->next_global)
  {
    if (tl->table)
      continue;

    if (tl->correspondent_table)
      tl->table= tl->correspondent_table->table;
  }

  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
    DBUG_RETURN(TRUE);

  /*
    Since aux_tables list is not part of LEX::query_tables list we
    have to juggle with LEX::query_tables_own_last value to be able
    call check_table_access() safely.
  */
  thd->lex->query_tables_own_last= 0;
  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
    DBUG_RETURN(TRUE);
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where)
  {
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
               ER_THD(thd, ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
    DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
}


/*
  Given a table in the source list, find a correspondent table in the
  table references list.

  @param lex Pointer to LEX representing multi-delete.
  @param src Source table to match.
  @param ref Table references list.

  @remark The source table list (tables listed before the FROM clause
  or tables listed in the FROM clause before the USING clause) may
  contain table names or aliases that must match unambiguously one,
  and only one, table in the target table list (table references list,
  after FROM/USING clause).

  @return Matching table, NULL otherwise.
*/

static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
                                            TABLE_LIST *tables)
{
  TABLE_LIST *match= NULL;
  DBUG_ENTER("multi_delete_table_match");

  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
  {
    int res;

    if (tbl->is_fqtn && elem->is_alias)
      continue; /* no match */
    if (tbl->is_fqtn && elem->is_fqtn)
      res= (my_strcasecmp(table_alias_charset, tbl->table_name.str, elem->table_name.str) ||
            cmp(&tbl->db, &elem->db));
    else if (elem->is_alias)
      res= my_strcasecmp(table_alias_charset, tbl->alias.str, elem->alias.str);
    else
      res= (my_strcasecmp(table_alias_charset, tbl->table_name.str, elem->table_name.str) ||
            cmp(&tbl->db, &elem->db));

    if (res)
      continue;

    if (match)
    {
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias.str);
      DBUG_RETURN(NULL);
    }

    match= elem;
  }

  if (!match)
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name.str, "MULTI DELETE");

  DBUG_RETURN(match);
}


/**
  Link tables in auxilary table list of multi-delete with corresponding
  elements in main table list, and set proper locks for them.

  @param lex   pointer to LEX representing multi-delete

  @retval
    FALSE   success
  @retval
    TRUE    error
*/

bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
{
  TABLE_LIST *tables= lex->first_select_lex()->table_list.first;
  TABLE_LIST *target_tbl;
  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");

  lex->table_count_update= 0;

  for (target_tbl= lex->auxiliary_table_list.first;
       target_tbl; target_tbl= target_tbl->next_local)
  {
    lex->table_count_update++;
    /* All tables in aux_tables must be found in FROM PART */
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
    if (!walk)
      DBUG_RETURN(TRUE);
    if (!walk->derived)
      target_tbl->table_name= walk->table_name;
    walk->updating= target_tbl->updating;
    walk->lock_type= target_tbl->lock_type;
    /* We can assume that tables to be deleted from are locked for write. */
    DBUG_ASSERT(walk->lock_type >= TL_FIRST_WRITE);
    walk->mdl_request.set_type(MDL_SHARED_WRITE);
    target_tbl->correspondent_table= walk;	// Remember corresponding table
  }
  DBUG_RETURN(FALSE);
}


/**
  simple UPDATE query pre-check.

  @param thd		Thread handler
  @param tables	Global table list

  @retval
    FALSE OK
  @retval
    TRUE  Error
*/

bool update_precheck(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("update_precheck");
  if (thd->lex->first_select_lex()->item_list.elements !=
      thd->lex->value_list.elements)
  {
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
    DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
}


/**
  simple DELETE query pre-check.

  @param thd		Thread handler
  @param tables	Global table list

  @retval
    FALSE  OK
  @retval
    TRUE   error
*/

bool delete_precheck(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("delete_precheck");
  if (tables->vers_conditions.delete_history)
  {
    if (check_one_table_access(thd, DELETE_HISTORY_ACL, tables))
      DBUG_RETURN(TRUE);
  }
  else
  {
    if (check_one_table_access(thd, DELETE_ACL, tables))
      DBUG_RETURN(TRUE);
    /* Set privilege for the WHERE clause */
    tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
  }
  DBUG_RETURN(FALSE);
}


/**
  simple INSERT query pre-check.

  @param thd		Thread handler
  @param tables	Global table list

  @retval
    FALSE  OK
  @retval
    TRUE   error
*/

bool insert_precheck(THD *thd, TABLE_LIST *tables)
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
  privilege_t privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : NO_ACL) |
                    (lex->value_list.elements ? UPDATE_ACL : NO_ACL));

  if (check_one_table_access(thd, privilege, tables))
    DBUG_RETURN(TRUE);

  if (lex->update_list.elements != lex->value_list.elements)
  {
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
    DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
}


/**
   Set proper open mode and table type for element representing target table
   of CREATE TABLE statement, also adjust statement table list if necessary.
*/

void create_table_set_open_action_and_adjust_tables(LEX *lex)
{
  TABLE_LIST *create_table= lex->query_tables;

  if (lex->tmp_table())
    create_table->open_type= OT_TEMPORARY_ONLY;
  else
    create_table->open_type= OT_BASE_ONLY;

  if (!lex->first_select_lex()->item_list.elements)
  {
    /*
      Avoid opening and locking target table for ordinary CREATE TABLE
      or CREATE TABLE LIKE for write (unlike in CREATE ... SELECT we
      won't do any insertions in it anyway). Not doing this causes
      problems when running CREATE TABLE IF NOT EXISTS for already
      existing log table.
    */
    create_table->lock_type= TL_READ;
  }
}


/**
  CREATE TABLE query pre-check.

  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created

  @retval
    FALSE   OK
  @retval
    TRUE   Error
*/

bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
{
  LEX *lex= thd->lex;
  SELECT_LEX *select_lex= lex->first_select_lex();
  privilege_t want_priv{CREATE_ACL};
  bool error= TRUE;                                 // Error message is given
  DBUG_ENTER("create_table_precheck");

  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

  if (lex->tmp_table())
    want_priv= CREATE_TMP_ACL;
  else if (select_lex->item_list.elements || select_lex->tvc)
    want_priv|= INSERT_ACL;

  /* CREATE OR REPLACE on not temporary tables require DROP_ACL */
  if (lex->create_info.or_replace() && !lex->tmp_table())
    want_priv|= DROP_ACL;
                          
  if (check_access(thd, want_priv, create_table->db.str,
                   &create_table->grant.privilege,
                   &create_table->grant.m_internal,
                   0, 0))
    goto err;

  /* If it is a merge table, check privileges for merge children. */
  if (lex->create_info.merge_list)
  {
    /*
      The user must have (SELECT_ACL | UPDATE_ACL | DELETE_ACL) on the
      underlying base tables, even if there are temporary tables with the same
      names.

      From user's point of view, it might look as if the user must have these
      privileges on temporary tables to create a merge table over them. This is
      one of two cases when a set of privileges is required for operations on
      temporary tables (see also CREATE TABLE).

      The reason for this behavior stems from the following facts:

        - For merge tables, the underlying table privileges are checked only
          at CREATE TABLE / ALTER TABLE time.

          In other words, once a merge table is created, the privileges of
          the underlying tables can be revoked, but the user will still have
          access to the merge table (provided that the user has privileges on
          the merge table itself). 

        - Temporary tables shadow base tables.

          I.e. there might be temporary and base tables with the same name, and
          the temporary table takes the precedence in all operations.

        - For temporary MERGE tables we do not track if their child tables are
          base or temporary. As result we can't guarantee that privilege check
          which was done in presence of temporary child will stay relevant
          later as this temporary table might be removed.

      If SELECT_ACL | UPDATE_ACL | DELETE_ACL privileges were not checked for
      the underlying *base* tables, it would create a security breach as in
      Bug#12771903.
    */

    if (check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
                           lex->create_info.merge_list, FALSE, UINT_MAX, FALSE))
      goto err;
  }

  if (want_priv != CREATE_TMP_ACL &&
      check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
    goto err;

  if (select_lex->item_list.elements)
  {
    /* Check permissions for used tables in CREATE TABLE ... SELECT */
    if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
                                     UINT_MAX, FALSE))
      goto err;
  }
  else if (lex->create_info.like())
  {
    if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
      goto err;
  }

  if (check_fk_parent_table_access(thd, &lex->create_info, &lex->alter_info,
                                   create_table->db.str))
    goto err;

  error= FALSE;

err:
  DBUG_RETURN(error);
}


/**
  Check privileges for LOCK TABLES statement.

  @param thd     Thread context.
  @param tables  List of tables to be locked.

  @retval FALSE - Success.
  @retval TRUE  - Failure.
*/

static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables)
{
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();

  for (TABLE_LIST *table= tables; table != first_not_own_table && table;
       table= table->next_global)
  {
    if (is_temporary_table(table))
      continue;

    if (check_table_access(thd, PRIV_LOCK_TABLES, table,
                           FALSE, 1, FALSE))
      return TRUE;
  }

  return FALSE;
}


/**
  negate given expression.

  @param thd  thread handler
  @param expr expression for negation

  @return
    negated expression
*/

Item *negate_expression(THD *thd, Item *expr)
{
  Item *negated;
  if (expr->type() == Item::FUNC_ITEM &&
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
  {
    /* it is NOT(NOT( ... )) */
    Item *arg= ((Item_func *) expr)->arguments()[0];
    const Type_handler *fh= arg->fixed_type_handler();
    enum_parsing_place place= thd->lex->current_select->parsing_place;
    if ((fh && fh->is_bool_type()) || place == IN_WHERE || place == IN_HAVING)
      return arg;
    /*
      if it is not boolean function then we have to emulate value of
      not(not(a)), it will be a != 0
    */
    return new (thd->mem_root) Item_func_ne(thd, arg, new (thd->mem_root) Item_int(thd, (char*) "0", 0, 1));
  }

  if ((negated= expr->neg_transformer(thd)) != 0)
    return negated;
  return new (thd->mem_root) Item_func_not(thd, expr);
}

/**
  Set the specified definer to the default value, which is the
  current user in the thread.
 
  @param[in]  thd       thread handler
  @param[out] definer   definer
*/
 
void get_default_definer(THD *thd, LEX_USER *definer, bool role)
{
  const Security_context *sctx= thd->security_ctx;

  if (role)
  {
    definer->user.str= const_cast<char*>(sctx->priv_role);
    definer->host= empty_clex_str;
  }
  else
  {
    definer->user.str= const_cast<char*>(sctx->priv_user);
    definer->host.str= const_cast<char*>(sctx->priv_host);
    definer->host.length= strlen(definer->host.str);
  }
  definer->user.length= strlen(definer->user.str);
  definer->auth= NULL;
}


/**
  Create default definer for the specified THD.

  @param[in] thd         thread handler

  @return
    - On success, return a valid pointer to the created and initialized
    LEX_USER, which contains definer information.
    - On error, return 0.
*/

LEX_USER *create_default_definer(THD *thd, bool role)
{
  LEX_USER *definer;

  if (unlikely(! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))))
    return 0;

  thd->get_definer(definer, role);

  if (role && definer->user.length == 0)
  {
    my_error(ER_MALFORMED_DEFINER, MYF(0));
    return 0;
  }
  else
    return definer;
}


/**
  Create definer with the given user and host names.

  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name

  @return
    - On success, return a valid pointer to the created and initialized
    LEX_USER, which contains definer information.
    - On error, return 0.
*/

LEX_USER *create_definer(THD *thd, LEX_CSTRING *user_name,
                         LEX_CSTRING *host_name)
{
  LEX_USER *definer;

  /* Create and initialize. */

  if (unlikely(!(definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))))
    return 0;

  definer->user= *user_name;
  definer->host= *host_name;
  definer->auth= NULL;

  return definer;
}


/**
  Check that byte length of a string does not exceed some limit.

  @param str         string to be checked
  @param err_msg     Number of error message to be displayed if the string
		     is too long.  0 if empty error message.
  @param max_length  max length

  @retval
    FALSE   the passed string is not longer than max_length
  @retval
    TRUE    the passed string is longer than max_length

  NOTE
    The function is not used in existing code but can be useful later?
*/

bool check_string_byte_length(const LEX_CSTRING *str, uint err_msg,
                              size_t max_byte_length)
{
  if (str->length <= max_byte_length)
    return FALSE;

  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str,
           err_msg ? ER(err_msg) : "", max_byte_length);

  return TRUE;
}


/*
  Check that char length of a string does not exceed some limit.

  SYNOPSIS
  check_string_char_length()
      str              string to be checked
      err_msg          Number of error message to be displayed if the string
		       is too long.  0 if empty error message.
      max_char_length  max length in symbols
      cs               string charset

  RETURN
    FALSE   the passed string is not longer than max_char_length
    TRUE    the passed string is longer than max_char_length
*/


bool check_string_char_length(const LEX_CSTRING *str, uint err_msg,
                              size_t max_char_length, CHARSET_INFO *cs,
                              bool no_error)
{
  Well_formed_prefix prefix(cs, str->str, str->length, max_char_length);
  if (likely(!prefix.well_formed_error_pos() &&
             str->length == prefix.length()))
    return FALSE;

  if (!no_error)
  {
    ErrConvString err(str->str, str->length, cs);
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(),
             err_msg ? ER(err_msg) : "",
             max_char_length);
  }
  return TRUE;
}


bool check_ident_length(const LEX_CSTRING *ident)
{
  if (check_string_char_length(ident, 0, NAME_CHAR_LEN, system_charset_info, 1))
  {
    my_error(ER_TOO_LONG_IDENT, MYF(0), ident->str);
    return 1;
  }
  return 0;
}


/*
  Check if path does not contain mysql data home directory

  SYNOPSIS
    path_starts_from_data_home_dir()
    dir                     directory, with all symlinks resolved

  RETURN VALUES
    0	ok
    1	error ;  Given path contains data directory
*/
extern "C" {

int path_starts_from_data_home_dir(const char *path)
{
  size_t dir_len= strlen(path);
  DBUG_ENTER("path_starts_from_data_home_dir");

  if (mysql_unpacked_real_data_home_len<= dir_len)
  {
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

    if (lower_case_file_system)
    {
      if (!default_charset_info->strnncoll(path,
                                           mysql_unpacked_real_data_home_len,
                                           mysql_unpacked_real_data_home,
                                           mysql_unpacked_real_data_home_len))
      {
        DBUG_PRINT("error", ("Path is part of mysql_real_data_home"));
        DBUG_RETURN(1);
      }
    }
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
    {
      DBUG_PRINT("error", ("Path is part of mysql_real_data_home"));
      DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}

}

/*
  Check if path does not contain mysql data home directory

  SYNOPSIS
    test_if_data_home_dir()
    dir                     directory

  RETURN VALUES
    0	ok
    1	error ;  Given path contains data directory
*/

int test_if_data_home_dir(const char *dir)
{
  char path[FN_REFLEN];
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "", MY_RETURN_REAL_PATH);
  DBUG_RETURN(path_starts_from_data_home_dir(path));
}


int error_if_data_home_dir(const char *path, const char *what)
{
  size_t dirlen;
  char   dirpath[FN_REFLEN];
  if (path)
  {
    dirname_part(dirpath, path, &dirlen);
    if (test_if_data_home_dir(dirpath))
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), what);
      return 1;
    }
  }
  return 0;
}

/**
  Check that host name string is valid.

  @param[in] str string to be checked

  @return             Operation status
    @retval  FALSE    host name is ok
    @retval  TRUE     host name string is longer than max_length or
                      has invalid symbols
*/

bool check_host_name(LEX_CSTRING *str)
{
  const char *name= str->str;
  const char *end= str->str + str->length;
  if (check_string_byte_length(str, ER_HOSTNAME, HOSTNAME_LENGTH))
    return TRUE;

  while (name != end)
  {
    if (*name == '@')
    {
      my_printf_error(ER_UNKNOWN_ERROR, 
                      "Malformed hostname (illegal symbol: '%c')", MYF(0),
                      *name);
      return TRUE;
    }
    name++;
  }
  return FALSE;
}


extern int MYSQLparse(THD *thd); // from yy_mariadb.cc
extern int ORAparse(THD *thd);   // from yy_oracle.cc


/**
  This is a wrapper of MYSQLparse(). All the code should call parse_sql()
  instead of MYSQLparse().

  @param thd Thread context.
  @param parser_state Parser state.
  @param creation_ctx Object creation context.

  @return Error status.
    @retval FALSE on success.
    @retval TRUE on parsing error.
*/

bool parse_sql(THD *thd, Parser_state *parser_state,
               Object_creation_ctx *creation_ctx, bool do_pfs_digest)
{
  bool ret_value;
  DBUG_ENTER("parse_sql");
  DBUG_ASSERT(thd->m_parser_state == NULL);
  DBUG_ASSERT(thd->lex->m_sql_cmd == NULL);

  MYSQL_QUERY_PARSE_START(thd->query());
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

  if (creation_ctx)
    backup_ctx= creation_ctx->set_n_backup(thd);

  /* Set parser state. */

  thd->m_parser_state= parser_state;

  parser_state->m_digest_psi= NULL;
  parser_state->m_lip.m_digest= NULL;

  if (do_pfs_digest)
  {
    /* Start Digest */
    parser_state->m_digest_psi= MYSQL_DIGEST_START(thd->m_statement_psi);

    if (parser_state->m_digest_psi != NULL)
    {
      /*
        If either:
        - the caller wants to compute a digest
        - the performance schema wants to compute a digest
        set the digest listener in the lexer.
      */
      parser_state->m_lip.m_digest= thd->m_digest;
      parser_state->m_lip.m_digest->m_digest_storage.m_charset_number= thd->charset()->number;
    }
  }

  /* Parse the query. */

  bool mysql_parse_status= thd->variables.sql_mode & MODE_ORACLE
                           ? ORAparse(thd) : MYSQLparse(thd);
  DBUG_ASSERT(opt_bootstrap || mysql_parse_status ||
              thd->lex->select_stack_top == 0);
  thd->lex->current_select= thd->lex->first_select_lex();

  /*
    Check that if MYSQLparse() failed either thd->is_error() is set, or an
    internal error handler is set.

    The assert will not catch a situation where parsing fails without an
    error reported if an error handler exists. The problem is that the
    error handler might have intercepted the error, so thd->is_error() is
    not set. However, there is no way to be 100% sure here (the error
    handler might be for other errors than parsing one).
  */

  DBUG_ASSERT(!mysql_parse_status ||
              thd->is_error() ||
              thd->get_internal_handler());

  /* Reset parser state. */

  thd->m_parser_state= NULL;

  /* Restore creation context. */

  if (creation_ctx)
    creation_ctx->restore_env(thd, backup_ctx);

  /* That's it. */

  ret_value= mysql_parse_status || thd->is_fatal_error;

  if ((ret_value == 0) && (parser_state->m_digest_psi != NULL))
  {
    /*
      On parsing success, record the digest in the performance schema.
    */
    DBUG_ASSERT(do_pfs_digest);
    DBUG_ASSERT(thd->m_digest != NULL);
    MYSQL_DIGEST_END(parser_state->m_digest_psi,
                     & thd->m_digest->m_digest_storage);
  }

  MYSQL_QUERY_PARSE_DONE(ret_value);
  DBUG_RETURN(ret_value);
}

/**
  @} (end of group Runtime_Environment)
*/


void LEX::mark_first_table_as_inserting()
{
  TABLE_LIST *t= first_select_lex()->table_list.first;
  DBUG_ENTER("Query_tables_list::mark_tables_with_important_flags");
  DBUG_ASSERT(sql_command_flags[sql_command] & CF_INSERTS_DATA);
  t->for_insert_data= TRUE;
  DBUG_PRINT("info", ("table_list: %p  name: %s  db: %s  command: %u",
                      t, t->table_name.str,t->db.str, sql_command));
  DBUG_VOID_RETURN;
}