File: command.cc

package info (click to toggle)
mysql-8.0 8.0.45-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,048 kB
  • sloc: cpp: 4,685,434; ansic: 412,712; pascal: 108,396; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; python: 21,816; sh: 17,285; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,083; makefile: 1,793; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (2838 lines) | stat: -rw-r--r-- 99,913 bytes parent folder | download
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
/*
 * Copyright (c) 2017, 2025, Oracle and/or its affiliates.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2.0,
 * as published by the Free Software Foundation.
 *
 * This program is designed to work with certain software (including
 * but not limited to OpenSSL) that is licensed under separate terms,
 * as designated in a particular file or component or in included license
 * documentation.  The authors of MySQL hereby grant you an additional
 * permission to link the program and your derivative works with the
 * separately licensed software that they have either included with
 * the program or referenced in the documentation.
 *
 * 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, version 2.0, 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-1301  USA
 */

#include "plugin/x/tests/driver/processor/commands/command.h"

#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <signal.h>
#include <sys/types.h>

#include <my_macros.h>  // NOLINT(build/include_subdir)
#include <mysql.h>      // NOLINT(build/include_subdir)

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <limits>
#include <set>
#include <sstream>
#include <stdexcept>

#include "mysqld_error.h"  // NOLINT(build/include_subdir)

#include "plugin/x/protocol/stream/compression_output_stream.h"
#include "plugin/x/src/helper/to_string.h"
#include "plugin/x/tests/driver/common/message_matcher.h"
#include "plugin/x/tests/driver/connector/mysqlx_all_msgs.h"
#include "plugin/x/tests/driver/connector/warning.h"
#include "plugin/x/tests/driver/formatters/message_formatter.h"
#include "plugin/x/tests/driver/json_to_any_handler.h"
#include "plugin/x/tests/driver/parsers/message_parser.h"
#include "plugin/x/tests/driver/processor/commands/mysqlxtest_error_names.h"
#include "plugin/x/tests/driver/processor/comment_processor.h"
#include "plugin/x/tests/driver/processor/indigestion_processor.h"
#include "plugin/x/tests/driver/processor/macro_block_processor.h"
#include "plugin/x/tests/driver/processor/stream_processor.h"
#include "plugin/x/tests/driver/processor/variable_names.h"

#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif

namespace {

const char *const CMD_ARG_BE_QUIET = "be-quiet";
const char *const CMD_ARG_SHOW_RECEIVED = "show-received";
const char *const CMD_ARG_KEEP_SESSION = "keep-session";
const char CMD_ARG_SEPARATOR = '\t';
const std::string CMD_PREFIX = "-->";

std::string bindump_to_data(const std::string &bindump,
                            const Script_stack *stack, const Console &console) {
  std::string res;
  for (size_t i = 0; i < bindump.length(); i++) {
    if (bindump[i] == '\\') {
      if (bindump[i + 1] == '\\') {
        res.push_back('\\');
        ++i;
      } else if (bindump[i + 1] == 'x') {
        int value = 0;
        const char *hex = aux::ALLOWED_HEX_CHARACTERS.c_str();
        const char *p = strchr(hex, bindump[i + 2]);
        if (p) {
          value = static_cast<int>(p - hex) << 4;
        } else {
          console.print_error(*stack, "Invalid bindump char at ", i + 2, '\n');
          break;
        }
        p = strchr(hex, bindump[i + 3]);
        if (p) {
          value |= p - hex;
        } else {
          console.print_error(*stack, "Invalid bindump char at ", i + 3, '\n');
          break;
        }
        i += 3;
        res.push_back(value);
      }
    } else {
      res.push_back(bindump[i]);
    }
  }
  return res;
}

std::string data_to_bindump(const std::string &bindump) {
  std::string res;

  for (size_t i = 0; i < bindump.length(); i++) {
    unsigned char ch = bindump[i];

    if (i >= 5 && ch == '\\') {
      res.push_back('\\');
      res.push_back('\\');
    } else if (i >= 5 && isprint(ch) && !isblank(ch)) {
      res.push_back(ch);
    } else {
      res.append("\\x");
      res.push_back(aux::ALLOWED_HEX_CHARACTERS[(ch >> 4) & 0xf]);
      res.push_back(aux::ALLOWED_HEX_CHARACTERS[ch & 0xf]);
    }
  }

  return res;
}

template <typename T>
class Backup_and_restore {
 public:
  Backup_and_restore(T *variable, const T &temporaru_value)
      : m_variable(variable), m_value(*variable) {
    *m_variable = temporaru_value;
  }

  ~Backup_and_restore() { *m_variable = m_value; }

 private:
  T *m_variable;
  T m_value;
};

template <typename Operator>
class Numeric_values {
 public:
  bool operator()(const std::string &lhs, const std::string &rhs) const {
    char *end;
    const auto lhs_numeric = std::strtoll(lhs.c_str(), &end, 10);
    const auto rhs_numeric = std::strtoll(rhs.c_str(), &end, 10);
    return m_operator(lhs_numeric, rhs_numeric);
  }

  Operator m_operator;
};

}  // namespace

xpl::chrono::Time_point Command::m_start_measure;

Command::Command() {
  m_commands["title"] = &Command::cmd_title;
  m_commands["echo"] = &Command::cmd_echo;
  m_commands["recvtype"] = &Command::cmd_recvtype;
  m_commands["recvok"] = &Command::cmd_recvok;
  m_commands["recvmessage"] = &Command::cmd_recvmessage;
  m_commands["recverror"] = &Command::cmd_recverror;
  m_commands["recvresult"] = &Command::cmd_recvresult;
  m_commands["recvtovar"] = &Command::cmd_recvtovar;
  m_commands["recvuntil"] = &Command::cmd_recvuntil;
  m_commands["recvuntildisc"] = &Command::cmd_recv_all_until_disc;
  m_commands["do_ssl_handshake"] = &Command::cmd_do_ssl_handshake;
  m_commands["sleep"] = &Command::cmd_sleep;
  m_commands["login"] = &Command::cmd_login;
  m_commands["stmtadmin"] = &Command::cmd_stmtadmin;
  m_commands["stmtsql"] = &Command::cmd_stmtsql;
  m_commands["loginerror"] = &Command::cmd_loginerror;
  m_commands["repeat"] = &Command::cmd_repeat;
  m_commands["endrepeat"] = &Command::cmd_endrepeat;
  m_commands["system"] = &Command::cmd_system;
  m_commands["system_in_background"] = &Command::cmd_system;
  m_commands["peerdisc"] = &Command::cmd_peerdisc;
  m_commands["enable_compression"] = &Command::cmd_enable_compression;
  m_commands["recv"] = &Command::cmd_recv;
  m_commands["env"] = &Command::cmd_env;
  m_commands["exit"] = &Command::cmd_exit;
  m_commands["abort"] = &Command::cmd_abort;
  m_commands["shutdown_server"] = &Command::cmd_shutdown_server;
  m_commands["reconnect"] = &Command::cmd_reconnect;
  m_commands["nowarnings"] = &Command::cmd_nowarnings;
  m_commands["yeswarnings"] = &Command::cmd_yeswarnings;
  m_commands["fatalerrors"] = &Command::cmd_fatalerrors;
  m_commands["nofatalerrors"] = &Command::cmd_nofatalerrors;
  m_commands["fatalwarnings"] = &Command::cmd_fatalwarnings;
  m_commands["newsession"] = &Command::cmd_newsession;
  m_commands["newsession_plain"] = &Command::cmd_newsession_plain;
  m_commands["newsession_mysql41"] = &Command::cmd_newsession_mysql41;
  m_commands["newsession_memory"] = &Command::cmd_newsession_memory;
  m_commands["setsession"] = &Command::cmd_setsession;
  m_commands["closesession"] = &Command::cmd_closesession;
  m_commands["expecterror"] = &Command::cmd_expecterror;
  m_commands["expectwarnings"] = &Command::cmd_expectwarnings;
  m_commands["measure"] = &Command::cmd_measure;
  m_commands["endmeasure"] = &Command::cmd_endmeasure;
  m_commands["quiet"] = &Command::cmd_quiet;
  m_commands["noquiet"] = &Command::cmd_noquiet;
  m_commands["varfile"] = &Command::cmd_varfile;
  m_commands["varlet"] = &Command::cmd_varlet;
  m_commands["varinc"] = &Command::cmd_varinc;
  m_commands["varsub"] = &Command::cmd_varsub;
  m_commands["varreplace"] = &Command::cmd_varreplace;
  m_commands["vargen"] = &Command::cmd_vargen;
  m_commands["varescape"] = &Command::cmd_varescape;
  m_commands["binsend"] = &Command::cmd_binsend;
  m_commands["hexsend"] = &Command::cmd_hexsend;
  m_commands["binsendoffset"] = &Command::cmd_binsendoffset;
  m_commands["callmacro"] = &Command::cmd_callmacro;
  m_commands["macro_delimiter_compress"] =
      &Command::cmd_macro_delimiter_compress;
  m_commands["import"] = &Command::cmd_import;
  m_commands["assert_eq"] = &Command::cmd_assert_eq;
  m_commands["assert_ne"] = &Command::cmd_assert_ne;
  m_commands["assert_gt"] = &Command::cmd_assert_gt;
  m_commands["assert_ge"] = &Command::cmd_assert_ge;
  m_commands["query_result"] = &Command::cmd_query;
  m_commands["noquery_result"] = &Command::cmd_noquery;
  m_commands["wait_for"] = &Command::cmd_wait_for;
  m_commands["received"] = &Command::cmd_received;
  m_commands["compress_bin"] = &Command::cmd_compress;
  m_commands["compress_hex"] = &Command::cmd_compress;
  m_commands["clear_received"] = &Command::cmd_clear_received;
  m_commands["recvresult_store_metadata"] =
      &Command::cmd_recvresult_store_metadata;
  m_commands["recv_with_stored_metadata"] =
      &Command::cmd_recv_with_stored_metadata;
  m_commands["clear_stored_metadata"] = &Command::cmd_clear_stored_metadata;
  m_commands["assert"] = &Command::cmd_assert;
}

bool Command::is_command_registred(const std::string &command_line,
                                   std::string *out_command_name,
                                   bool *out_is_single_line_command) const {
  auto command_name_start = command_line.begin();
  const bool has_prefix = 0 == strncmp(command_line.c_str(), CMD_PREFIX.c_str(),
                                       CMD_PREFIX.length());

  if (out_is_single_line_command) *out_is_single_line_command = has_prefix;

  if (has_prefix) command_name_start += CMD_PREFIX.length();

  const auto command_name_end = std::find_if(
      command_line.begin(), command_line.end(), [](const char element) -> bool {
        return element == ' ' || element == ';';
      });

  std::string command_name(command_name_start, command_name_end);

  if (out_command_name) *out_command_name = command_name;

  return m_commands.count(command_name) > 0;
}

Command::Result Command::process(std::istream &input,
                                 Execution_context *context,
                                 const std::string &command_line) {
  std::string out_command_name;
  bool out_has_prefix;

  if (!is_command_registred(command_line, &out_command_name, &out_has_prefix)) {
    context->print_error("Unknown command_line \"", command_line, "\"\n");
    return Result::Stop_with_failure;
  }

  const char *arguments = command_line.c_str() + out_command_name.length();

  if (out_has_prefix) arguments += CMD_PREFIX.length();
  if (' ' == *arguments) arguments++;

  context->print_verbose("Execute ", command_line, "\n");
  context->m_command_name = out_command_name;
  context->m_command_arguments = arguments;

  return (this->*m_commands[out_command_name])(input, context,
                                               context->m_command_arguments);
}

Command::Result Command::cmd_echo(std::istream &input,
                                  Execution_context *context,
                                  const std::string &args) {
  std::string s = args;
  context->m_variables->replace(&s);
  context->print(s, "\n");

  return Result::Continue;
}

Command::Result Command::cmd_title(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  if (!args.empty()) {
    std::string s = args.substr(1);
    context->m_variables->replace(&s);
    context->print("\n", s, "\n");
    std::string sep(s.length(), args[0]);
    context->print(sep, "\n");
  } else {
    context->print("\n\n");
  }

  return Result::Continue;
}

Command::Result Command::cmd_recvtype(std::istream &input,
                                      Execution_context *context,
                                      const std::string &args) {
  std::string s = args;
  context->m_variables->replace(&s);

  std::vector<std::string> vargs;
  aux::split(vargs, s, " ", true);

  if (1 != vargs.size() && 2 != vargs.size() && 3 != vargs.size()) {
    std::stringstream error_message;
    error_message << "Received wrong number of arguments, got:" << vargs.size();
    throw std::logic_error(error_message.str());
  }

  bool be_quiet = false;
  xcl::XProtocol::Server_message_type_id msgid;
  xcl::XError error;
  const std::string expected_message_name = vargs[0];
  const bool is_msgid = server_msgs_by_name.count(expected_message_name);
  const bool is_msgtype = server_msgs_by_full_name.count(expected_message_name);

  if (!is_msgid && !is_msgtype) {
    context->print_error(
        "'recvtype' command, invalid message name/id specified as command "
        "argument:",
        expected_message_name, "\n");
    return Result::Stop_with_failure;
  }

  Message_ptr msg;

  if (is_msgtype) {
    msg =
        context->session()->get_protocol().recv_single_message(&msgid, &error);
  } else {
    xcl::XProtocol::Header_message_type_id message_type_id;
    uint8_t *buffer = nullptr;
    size_t buffer_size;

    error = context->session()->get_protocol().recv(&message_type_id, &buffer,
                                                    &buffer_size);

    msgid =
        static_cast<xcl::XProtocol::Server_message_type_id>(message_type_id);

    if (buffer) delete[] buffer;
  }

  int number_of_arguments = static_cast<int>(vargs.size()) - 1;
  if (1 < vargs.size()) {
    if (vargs[number_of_arguments] == CMD_ARG_BE_QUIET) {
      be_quiet = true;
      --number_of_arguments;
    }
  }

  if (nullptr == msg.get() && is_msgtype) {
    return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                             : Result::Continue;
  }

  if (error) {
    context->print_error("'recvtype' command, failed with I/O error: ", error,
                         "\n");
    return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                             : Result::Continue;
  }

  try {
    std::string command_output;
    if (is_msgtype) {
      const std::string field_filter = number_of_arguments > 0 ? vargs[1] : "";
      const std::string expected_field_value =
          number_of_arguments > 1 ? vargs[2] : "";
      bool is_ok = msg->GetDescriptor()->full_name() == expected_message_name;

      if (!expected_field_value.empty()) {
        const bool k_dont_show_message_name = false;
        const std::string field_value =
            context->m_variables->unreplace(formatter::message_to_text(
                *msg, field_filter, k_dont_show_message_name));

        if (field_value != expected_field_value) {
          is_ok = false;
        }
      }

      if (!is_ok) {
        const std::string message_in_text = formatter::message_to_text(*msg);
        std::string expected_message = expected_message_name;

        if (!field_filter.empty()) expected_message += "(" + field_filter + ")";
        if (!expected_field_value.empty())
          expected_message += " = " + expected_field_value;

        context->m_variables->clear_unreplace();

        context->print("Received unexpected message type. Was expecting:\n    ",
                       expected_message, "\nbut got:\n");
        context->print(message_in_text, "\n");

        return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                                 : Result::Continue;
      }

      command_output = formatter::message_to_text(*msg, field_filter);
    } else {
      const auto received_message_id_name = server_msgs_by_id[msgid].second;

      if (received_message_id_name != expected_message_name) {
        context->m_variables->clear_unreplace();

        context->print("Received unexpected message type. Was expecting:\n    ",
                       expected_message_name, "\nbut got:\n");
        context->print(received_message_id_name, "\n");

        return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                                 : Result::Continue;
      }
    }

    if (context->m_options.m_show_query_result && !be_quiet) {
      const std::string message_in_text =
          context->m_variables->unreplace(command_output);
      context->print(message_in_text, "\n");
    }

    context->m_variables->clear_unreplace();
  } catch (std::exception &e) {
    context->print_error_red(context->m_script_stack, e, '\n');
    if (context->m_options.m_fatal_errors) return Result::Stop_with_success;
  }

  return Result::Continue;
}

Command::Result Command::cmd_recvok(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  xcl::XError error;
  xcl::XProtocol::Server_message_type_id out_msgid;

  Message_ptr msg{context->session()->get_protocol().recv_single_message(
      &out_msgid, &error)};

  context->print("RUN recvok\n");

  if (error) {
    context->m_console.print_error(error);

    return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                             : Result::Continue;
  }

  if (nullptr == msg.get()) {
    context->print("Command recvok didn't receive any data.\n");
    return Result::Stop_with_failure;
  }

  if (Mysqlx::ServerMessages::OK != out_msgid) {
    if (Mysqlx::ServerMessages::ERROR != out_msgid) {
      context->print("Got unexpected message:\n");
      context->print(formatter::message_to_text(*msg), "\n");

      return context->m_options.m_fatal_errors ? Result::Stop_with_failure
                                               : Result::Continue;
    }

    auto msg_error = static_cast<Mysqlx::Error *>(msg.get());

    if (!context->m_expected_error.check_error(
            xcl::XError(msg_error->code(), msg_error->msg())))
      return Result::Stop_with_failure;
  } else {
    if (!context->m_expected_error.check_ok()) return Result::Stop_with_failure;
  }

  return Result::Continue;
}

Command::Result Command::cmd_recvmessage(std::istream &input,
                                         Execution_context *context,
                                         const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'recvmessage' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string expected_msg_name;
  std::string expected_msg_body;
  std::string parsing_error;
  xcl::XProtocol::Server_message_type_id expected_msgid;
  std::string tmp = args;
  context->m_variables->replace(&tmp);

  if (!parser::get_name_and_body_from_text(tmp, &expected_msg_name,
                                           &expected_msg_body, true)) {
    context->print_error("Command 'recvmessage' has an invalid argument.\n");
    context->m_variables->clear_unreplace();
    return Result::Stop_with_failure;
  }

  Message_ptr expected_msg{parser::get_server_message_from_text(
      expected_msg_name, expected_msg_body, &expected_msgid, &parsing_error,
      true)};
  if (nullptr == expected_msg.get()) {
    context->print_error(
        "Command 'recvmessage' coundn't parse expected message.\n");
    context->print_error(parsing_error, '\n');
    context->m_variables->clear_unreplace();
    return Result::Stop_with_failure;
  }

  xcl::XError error;
  xcl::XProtocol::Server_message_type_id out_received_msgid;

  Message_ptr received_msg{
      context->session()->get_protocol().recv_single_message(
          &out_received_msgid, &error)};

  if (nullptr == received_msg.get()) {
    context->print_error("Command 'recvmessage' didn't receive any data.\n");
    context->print_error("I/O operation ended with error: ", error);
    context->m_variables->clear_unreplace();
    return Result::Stop_with_failure;
  }

  if (!message_match_with_expectations(*expected_msg, *received_msg)) {
    context->print_error(
        "Received messages: ", formatter::message_to_text(*received_msg),
        "\nDoesn't match the expectations: ",
        formatter::message_to_text(*expected_msg), "\n");
    context->m_variables->clear_unreplace();
    return Result::Stop_with_failure;
  }

  if (context->m_options.m_show_query_result) {
    const std::string message_in_text = context->m_variables->unreplace(
        formatter::message_to_text(*received_msg));
    context->print(message_in_text, "\n");
  }

  context->m_variables->clear_unreplace();

  return Result::Continue;
}

Command::Result Command::cmd_recverror(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  xcl::XProtocol::Server_message_type_id msgid;
  xcl::XError xerror;

  if (args.empty()) {
    context->print_error(
        "'recverror' command, requires an integer argument.\n");
    return Result::Stop_with_failure;
  }

  Message_ptr msg(
      context->session()->get_protocol().recv_single_message(&msgid, &xerror));

  if (nullptr == msg.get()) {
    context->print_error(context->m_script_stack, "Was expecting Error ", args,
                         ", but got I/O error:", xerror.error(),
                         ", message:", xerror.what(), "\n");
    return Result::Stop_with_failure;
  }

  bool failed = false;
  try {
    const int expected_error_code = mysqlxtest::get_error_code_by_text(args);
    if (msg->GetDescriptor()->full_name() != "Mysqlx.Error" ||
        expected_error_code !=
            static_cast<int>(static_cast<Mysqlx::Error *>(msg.get())->code())) {
      context->print_error(context->m_script_stack, "Was expecting Error ",
                           args, ", but got:\n");
      failed = true;
    } else {
      context->print("Got expected error:\n");
    }

    context->print(*msg, "\n");

    if (failed && context->m_options.m_fatal_errors) {
      return Result::Stop_with_success;
    }
  } catch (std::exception &e) {
    context->print_error_red(context->m_script_stack, e, '\n');
    if (context->m_options.m_fatal_errors) return Result::Stop_with_success;
  }

  return Result::Continue;
}

Command::Result Command::cmd_recvtovar(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  if (args.empty()) {
    context->print_error("'recvtovar' command, requires an argument.\n");
    return Result::Stop_with_failure;
  }

  std::string args_cmd = args;
  std::vector<std::string> args_array;
  aux::trim(args_cmd);

  aux::split(args_array, args_cmd, " ", false);

  args_cmd = CMD_ARG_BE_QUIET;

  if (args_array.size() > 1) {
    args_cmd += " ";
    args_cmd += args_array.at(1);
  }

  cmd_recvresult(input, context, args_cmd,
                 std::bind(&Variable_container::set, context->m_variables,
                           args_array.at(0), std::placeholders::_1));

  return Result::Continue;
}

Command::Result Command::cmd_recvresult(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  return cmd_recvresult(input, context, args, Value_callback());
}

Command::Result Command::cmd_recvresult(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args,
                                        Value_callback value_callback,
                                        const Metadata_policy metadata_policy) {
  context->m_variables->set(k_variable_result_rows_affected, "0");
  context->m_variables->set(k_variable_result_last_insert_id, "0");

  try {
    std::vector<std::string> columns;
    std::string cmd_args = args;

    aux::trim(cmd_args);

    if (cmd_args.size()) aux::split(columns, cmd_args, " ", false);

    std::vector<std::string>::iterator i =
        std::find(columns.begin(), columns.end(), "print-columnsinfo");
    const bool print_colinfo = i != columns.end();
    if (print_colinfo) columns.erase(i);

    i = std::find(columns.begin(), columns.end(), CMD_ARG_BE_QUIET);
    const bool quiet = i != columns.end();
    if (quiet) columns.erase(i);

    Result_fetcher result{context->session()->get_protocol().recv_resultset()};
    if (metadata_policy != Metadata_policy::Default) {
      if (columns.size() == 0) {
        context->print_error("No metadata tag given");
        return Result::Stop_with_failure;
      }
      auto metadata_tag = *columns.begin();
      columns.clear();
      if (metadata_policy == Metadata_policy::Use_stored)
        result.set_metadata(context->m_stored_metadata[metadata_tag]);
      else if (metadata_policy == Metadata_policy::Store)
        context->m_stored_metadata[metadata_tag] = result.column_metadata();
    }

    std::vector<Warning> warnings;

    const bool force_quiet = !context->m_options.m_show_query_result || quiet;
    print_resultset(context, &result, columns, value_callback, force_quiet,
                    print_colinfo);

    auto error = result.get_last_error();

    if (error) {
      if (!context->m_expected_error.check_error(error)) {
        return Result::Stop_with_failure;
      }

      return Result::Continue;
    }

    context->m_variables->clear_unreplace();

    const auto rows = result.affected_rows();
    const auto insert_id = result.last_insert_id();

    context->m_variables->set(k_variable_result_rows_affected,
                              std::to_string(rows));
    context->m_variables->set(k_variable_result_last_insert_id,
                              std::to_string(insert_id));

    if (!force_quiet) {
      if (rows >= 0)
        context->print(rows, " rows affected\n");
      else
        context->print("command ok\n");
      if (insert_id > 0) context->print("last insert id: ", insert_id, "\n");

      std::vector<std::string> document_ids = result.generated_document_ids();
      if (!document_ids.empty()) {
        context->print("auto-generated id(s): ");
        std::vector<std::string>::const_iterator i = document_ids.begin();
        context->print(*i++);
        for (; i != document_ids.end(); ++i) context->print(",", *i);
        context->print("\n");
      }

      if (!result.info_message().empty())
        context->print(result.info_message(), "\n");

      auto current_warnings(result.get_warnings());

      if (!current_warnings.empty()) context->print("Warnings generated:\n");

      for (const auto &w : current_warnings) {
        warnings.push_back(w);
        context->print(w, "\n");
      }
    }

    if (!context->m_expected_error.check_ok()) return Result::Stop_with_failure;

    if (!context->m_expected_warnings.check_warnings(warnings))
      return Result::Stop_with_failure;
  } catch (xcl::XError &) {
  }
  return Result::Continue;
}

Command::Result Command::cmd_recvuntil(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'recvuntil' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  xcl::XProtocol::Server_message_type_id msgid;
  std::vector<std::string> argl;

  aux::split(argl, args, " ", true);

  bool show = true, stop = false;

  if (argl.size() > 1) {
    const char *argument_do_not_print = argl[1].c_str();
    show = false;

    if (0 != strcmp(argument_do_not_print, "do_not_show_intermediate")) {
      context->print_error("Invalid argument received: ", argl[1], '\n');
      return Result::Stop_with_failure;
    }
  }

  Message_by_full_name::iterator iterator_msg_name =
      server_msgs_by_full_name.find(argl[0]);

  if (server_msgs_by_full_name.end() == iterator_msg_name) {
    context->print_error("Unknown message name: ", argl[0], " ",
                         server_msgs_by_full_name.size(), '\n');
    return Result::Stop_with_failure;
  }

  Message_server_by_name::iterator iterator_msg_id =
      server_msgs_by_name.find(iterator_msg_name->second);

  if (server_msgs_by_name.end() == iterator_msg_id) {
    context->print_error(
        "Invalid data in internal message list, entry not found:",
        iterator_msg_name->second, '\n');
    return Result::Stop_with_failure;
  }

  const xcl::XProtocol::Server_message_type_id expected_msg_id{
      iterator_msg_id->second.second};

  do {
    xcl::XError error;
    Message_ptr msg(
        context->session()->get_protocol().recv_single_message(&msgid, &error));

    if (error) {
      context->print_error_red(context->m_script_stack, error, '\n');
      return Result::Stop_with_failure;
    }

    if (msg.get()) {
      if (msg->GetDescriptor()->full_name() == argl[0] ||
          msgid == Mysqlx::ServerMessages::ERROR) {
        show = true;
        stop = true;
      }

      try {
        if (show) context->print(*msg, "\n");
      } catch (std::exception &e) {
        context->print_error_red(context->m_script_stack, e, '\n');
        if (context->m_options.m_fatal_errors) return Result::Stop_with_success;
      }
    }
  } while (!stop);

  context->m_variables->clear_unreplace();

  if (Mysqlx::ServerMessages::ERROR == msgid &&
      Mysqlx::ServerMessages::ERROR != expected_msg_id)
    return Result::Stop_with_failure;

  return Result::Continue;
}

Command::Result Command::cmd_do_ssl_handshake(std::istream &input,
                                              Execution_context *context,
                                              const std::string &args) {
  xcl::XError error =
      context->session()->get_protocol().get_connection().activate_tls();
  if (error) {
    context->print_error_red(context->m_script_stack, error, '\n');
    return Result::Stop_with_failure;
  }

  return Result::Continue;
}

Command::Result Command::cmd_stmtsql(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  if (args.empty()) {
    context->print_error("'stmtsql' command, requires a string argument.\n");
    return Result::Stop_with_failure;
  }

  Mysqlx::Sql::StmtExecute stmt;

  std::string command = args;
  context->m_variables->replace(&command);

  stmt.set_stmt(command);
  stmt.set_namespace_("sql");

  context->session()->get_protocol().send(stmt);

  if (!context->m_options.m_quiet) context->print("RUN ", command, "\n");

  return Result::Continue;
}

Command::Result Command::cmd_stmtadmin(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'stmtadmin' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string tmp = args;
  context->m_variables->replace(&tmp);
  std::vector<std::string> params;
  aux::split(params, tmp, "\t", true);
  if (params.empty()) {
    context->print_error("Invalid empty admin command", '\n');
    return Result::Stop_with_failure;
  }

  aux::trim(params[0]);

  Mysqlx::Sql::StmtExecute stmt;
  stmt.set_stmt(params[0]);
  stmt.set_namespace_("mysqlx");

  if (params.size() == 2) {
    Any obj;
    if (!json_string_to_any(params[1], &obj)) {
      context->print_error("Invalid argument for '", params[0],
                           "' command; json object expected\n");
      return Result::Stop_with_failure;
    }
    stmt.add_args()->CopyFrom(obj);
  }

  context->session()->get_protocol().send(stmt);

  return Result::Continue;
}

Command::Result Command::cmd_sleep(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  if (args.empty()) {
    context->print_error("'sleep' command, requires an integer argument.\n");
    return Result::Stop_with_failure;
  }

  std::string tmp = args;
  context->m_variables->replace(&tmp);
  const double delay_in_seconds = std::stod(tmp);
#ifdef _WIN32
  const int delay_in_milliseconds = static_cast<int>(delay_in_seconds * 1000);
  Sleep(delay_in_milliseconds);
#else
  const int delay_in_microseconds =
      static_cast<int>(delay_in_seconds * 1000000);
  usleep(delay_in_microseconds);
#endif
  return Result::Continue;
}

Command::Result Command::cmd_login(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  std::string user, pass, db, auth_meth = "MYSQL41";

  if (args.empty()) {
    context->m_connection->get_credentials(&user, &pass);
  } else {
    std::string s = args;
    context->m_variables->replace(&s);

    std::string::size_type p = s.find(CMD_ARG_SEPARATOR);
    if (p != std::string::npos) {
      user = s.substr(0, p);
      s = s.substr(p + 1);
      p = s.find(CMD_ARG_SEPARATOR);
      if (p != std::string::npos) {
        pass = s.substr(0, p);
        s = s.substr(p + 1);
        p = s.find(CMD_ARG_SEPARATOR);
        if (p != std::string::npos) {
          db = s.substr(0, p);
          auth_meth = s.substr(p + 1);
        } else {
          db = s;
        }
      } else {
        pass = s;
      }
    } else {
      user = s;
    }
  }

  auto protocol = context->m_connection->active_xprotocol();

  for (auto &c : auth_meth) c = toupper(c);

  auto error = protocol->execute_authenticate(user, pass, db, auth_meth);

  context->m_connection->active_holder().remove_notice_handler();

  if (error) {
    if (CR_X_UNSUPPORTED_OPTION_VALUE == error.error()) {
      context->print_error("Wrong authentication method", '\n');
      return Result::Stop_with_failure;
    }

    if (!context->m_expected_error.check_error(error)) {
      return Result::Stop_with_failure;
    }

    return Result::Continue;
  }

  context->m_connection->setup_variables(
      context->m_connection->active_xsession());

  context->print("Login OK\n");
  return Result::Continue;
}

Command::Result Command::cmd_repeat(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  if (args.empty()) {
    context->print_error("'repeat' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string variable_name = "";
  std::vector<std::string> argl;

  aux::split(argl, args, "\t", true);

  if (argl.size() > 1) {
    variable_name = argl[1];
  }

  // Allow use of variables as a source of number of iterations
  context->m_variables->replace(&argl[0]);

  Loop_do loop = {input.tellg(), std::stoi(argl[0]), 0, variable_name};

  m_loop_stack.push_back(loop);

  if (variable_name.length())
    context->m_variables->set(variable_name, xpl::to_string(loop.value));

  return Result::Continue;
}

Command::Result Command::cmd_endrepeat(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  while (m_loop_stack.size()) {
    Loop_do &ld = m_loop_stack.back();

    --ld.iterations;
    ++ld.value;

    if (ld.variable_name.length())
      context->m_variables->set(ld.variable_name, xpl::to_string(ld.value));

    if (1 > ld.iterations) {
      m_loop_stack.pop_back();
      break;
    }

    input.seekg(ld.block_begin);
    break;
  }

  return Result::Continue;
}

Command::Result Command::cmd_loginerror(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  std::string s = args;
  std::string expected, user, pass, db;
  int expected_error_code = 0;

  context->m_variables->replace(&s);
  std::string::size_type p = s.find('\t');
  if (p != std::string::npos) {
    expected = s.substr(0, p);
    s = s.substr(p + 1);
    p = s.find('\t');
    if (p != std::string::npos) {
      user = s.substr(0, p);
      s = s.substr(p + 1);
      p = s.find('\t');
      if (p != std::string::npos) {
        pass = s.substr(0, p + 1);
        db = s.substr(p + 1);
      } else {
        pass = s;
      }
    } else {
      user = s;
    }
  } else {
    context->print_error(context->m_script_stack,
                         "Missing arguments to -->loginerror\n");
    return Result::Stop_with_failure;
  }
  try {
    context->m_variables->replace(&expected);
    aux::trim(expected);
    auto protocol = context->m_connection->active_xprotocol();
    expected_error_code = mysqlxtest::get_error_code_by_text(expected);
    auto err = protocol->execute_authenticate(user, pass, db, "MYSQL41");
    context->m_connection->active_holder().remove_notice_handler();
    if (err) {
      if (err.error() == expected_error_code) {
        context->print("error (as expected): ", err, "\n");
      } else {
        context->print_error(context->m_script_stack,
                             "was expecting: ", expected_error_code,
                             " but got: ", err, '\n');
        if (context->m_options.m_fatal_errors) return Result::Stop_with_failure;
      }
      return Result::Continue;
    }
    context->print_error(context->m_script_stack,
                         "Login succeeded, but an error was expected\n");
    if (context->m_options.m_fatal_errors) return Result::Stop_with_failure;
  } catch (const std::exception &e) {
    context->print_error(e, '\n');
    return Result::Stop_with_failure;
  }

  return Result::Continue;
}

#ifdef _WIN32
static void replace_crlf_with_lf(char *buf) {
  char *replace = buf;
  while (*buf) {
    *replace = *buf++;
    if (!((*replace == '\x0D') && (*buf == '\x0A'))) {
      replace++;
    }
  }
  *replace = '\x0';
}
#endif

Command::Result Command::cmd_system(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  const bool run_in_background =
      std::string::npos != context->m_command_name.find("background");

  if (args.empty()) {
    context->print_error("'system' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  // command used only at dev level
  // example of usage
  // -->system (sleep 3; echo "Killing"; ps aux | grep mysqld | egrep -v "gdb
  // .+mysqld" | grep -v  "kdeinit4"| awk '{print($2)}' | xargs kill -s
  // SIGQUIT)&

  std::string s = args;

  context->m_variables->replace(&s);

  if (run_in_background) {
#ifdef _WIN32
    s.insert(0, "START /B ");
#else
    s.append(" &");
#endif
  }

  const char *mode = IF_WIN("rb", "r");

  FILE *res_file = popen(s.c_str(), mode);
  if (nullptr == res_file) {
    context->print_error("Can't execute, following command: ", s);
    return Result::Stop_with_failure;
  }

  if (!run_in_background) {
    char buf[512];
    std::string str;
    while (std::fgets(buf, sizeof(buf), res_file)) {
      if (std::strlen(buf) < 1) continue;

#ifdef _WIN32
      // Replace CRLF char with LF.
      // See bug#22608247 and bug#22811243
      assert(!std::strcmp(mode, "rb"));
      replace_crlf_with_lf(buf);
#endif
      context->print(buf);
    }
  }

  pclose(res_file);

  return Result::Continue;
}

Command::Result Command::cmd_recv_all_until_disc(std::istream &input,
                                                 Execution_context *context,
                                                 const std::string &args) {
  xcl::XProtocol::Server_message_type_id msgid;
  xcl::XError error;
  std::vector<std::string> out_arguments;
  std::string copy_args = args;
  aux::trim(copy_args, " \t");

  if (!copy_args.empty()) aux::split(out_arguments, copy_args, " \t,", true);

  const auto k_show_received =
      aux::remove_if(out_arguments, CMD_ARG_SHOW_RECEIVED);
  const auto k_keep_session =
      aux::remove_if(out_arguments, CMD_ARG_KEEP_SESSION);

  if (out_arguments.size()) {
    context->print_error(
        "'recvuntildisc' command received unknown arguments: ", out_arguments,
        ". Acceptable value for the arguments are \"", CMD_ARG_SHOW_RECEIVED,
        "\",\"", CMD_ARG_KEEP_SESSION, "\"\n");
    return Result::Stop_with_failure;
  }

  try {
    while (true) {
      Message_ptr msg{
          context->m_connection->active_xprotocol()->recv_single_message(
              &msgid, &error)};

      if (error) throw error;

      if (msg.get() && k_show_received)
        context->print(context->m_variables->unreplace(
                           formatter::message_to_text(*msg), true),
                       "\n");
    }
  } catch (xcl::XError &) {
    context->print_error("Server disconnected", '\n');
  }

  /* Ensure that connection is closed. This is going to stop XSession from
   executing disconnection flow */
  context->m_connection->active_xconnection()->close();

  if (!k_keep_session) {
    if (context->m_connection->is_default_active()) {
      return Result::Stop_with_success;
    }

    context->m_connection->close_active(false);
  }

  return Result::Continue;
}

Command::Result Command::cmd_enable_compression(std::istream &input,
                                                Execution_context *context,
                                                const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'enable_compression' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::vector<std::string> arg_list;
  aux::split(arg_list, args, "\t", true);

  std::string algo = arg_list[0];
  context->m_variables->replace(&algo);
  std::transform(algo.begin(), algo.end(), algo.begin(), ::tolower);

  static const std::map<std::string, xcl::Compression_algorithm> k_algo{
      {"deflate_stream", xcl::Compression_algorithm::k_deflate},
      {"lz4_message", xcl::Compression_algorithm::k_lz4},
      {"zstd_stream", xcl::Compression_algorithm::k_zstd}};

  if (0 == k_algo.count(algo)) {
    context->print_error("ERROR: Invalid algorithm used: \"", arg_list[0],
                         "\"\n");

    return Result::Stop_with_failure;
  }

  int64_t level = std::numeric_limits<int64_t>::min();
  if (arg_list.size() > 1) {
    try {
      std::string str_level = arg_list[1];
      context->m_variables->replace(&str_level);
      level = std::stol(str_level);
    } catch (...) {
      context->print_error(
          "ERROR: Invalid compression level used: ", arg_list[1], "\n");
      return Result::Stop_with_failure;
    }
  }

  context->m_connection->active_holder().enable_compression(k_algo.at(algo),
                                                            level);
  return Result::Continue;
}

Command::Result Command::cmd_peerdisc(std::istream &input,
                                      Execution_context *context,
                                      const std::string &args) {
  int expected_delta_time;
  int tolerance;
  int result = sscanf(args.c_str(), "%i %i", &expected_delta_time, &tolerance);

  if (result < 1 || result > 2) {
    context->print_error("ERROR: Invalid use of command", '\n');

    return Result::Stop_with_failure;
  }

  if (1 == result) {
    tolerance = 10 * expected_delta_time / 100;
  }

  xpl::chrono::Time_point start_time = xpl::chrono::now();
  try {
    xcl::XProtocol::Server_message_type_id msgid;
    context->m_connection->active_xconnection()->set_read_timeout(
        2 * expected_delta_time);

    xcl::XError err;
    Message_ptr msg(
        context->m_connection->active_xprotocol()->recv_single_message(&msgid,
                                                                       &err));
    if (err) throw err;

    if (msg.get()) {
      context->print_error("ERROR: Received unexpected message.\n", *msg, '\n');
    } else {
      context->print_error(
          "ERROR: Timeout occur while waiting for disconnection.\n");
    }

    return Result::Stop_with_failure;
  } catch (const xcl::XError &ec) {
    if (CR_SERVER_GONE_ERROR != ec.error()) {
      /** Peer disconnected, connector shouldn't try
      to execute closure flow. Lets close it. */
      context->m_connection->active_xconnection()->close();
      context->m_console.print_error_red(context->m_script_stack, ec, '\n');
      return Result::Stop_with_failure;
    }
  }

  int execution_delta_time = static_cast<int>(
      xpl::chrono::to_milliseconds(xpl::chrono::now() - start_time));

  if (abs(execution_delta_time - expected_delta_time) > tolerance) {
    context->print_error(
        "ERROR: Peer disconnected after: ", execution_delta_time,
        "[ms], expected: ", expected_delta_time, "[ms]\n");
    return Result::Stop_with_failure;
  }

  context->m_connection->active_xconnection()->close();

  if (context->m_connection->is_default_active()) {
    return Result::Stop_with_success;
  }

  context->m_connection->close_active(false);

  return Result::Continue;
}

Command::Result Command::cmd_recv(std::istream &input,
                                  Execution_context *context,
                                  const std::string &args) {
  xcl::XProtocol::Server_message_type_id msgid;
  bool quiet = false;
  std::string args_copy(args);

  aux::trim(args_copy);

  if ("quiet" == args_copy) {
    quiet = true;
    args_copy = "";
  }

  try {
    xcl::XError error;

    Message_ptr msg{
        context->m_connection->active_xprotocol()->recv_single_message(&msgid,
                                                                       &error)};

    if (error) {
      if (!quiet &&
          !context->m_expected_error.check_error(error))  // TODO(owner) do we
                                                          // need this !quiet ?
        return Result::Stop_with_failure;
      return Result::Continue;
    }

    if (msg.get() && (context->m_options.m_show_query_result && !quiet))
      context->print(context->m_variables->unreplace(
                         formatter::message_to_text(*msg, args_copy), true),
                     "\n");

    if (!context->m_expected_error.check_ok()) return Result::Stop_with_failure;
  } catch (std::exception &e) {
    context->print_error("ERROR: ", e, '\n');

    if (context->m_options.m_fatal_errors) return Result::Stop_with_failure;
  }
  return Result::Continue;
}

Command::Result Command::cmd_exit(std::istream &input,
                                  Execution_context *context,
                                  const std::string &args) {
  return Result::Stop_with_success;
}

Command::Result Command::cmd_abort(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  exit(2);
  return Result::Stop_with_success;
}

static bool kill_process(int pid) {
  bool killed = true;
#ifdef _WIN32
  HANDLE proc;
  proc = OpenProcess(PROCESS_TERMINATE, false, pid);
  if (nullptr == proc) return true; /* Process could not be found. */

  if (!TerminateProcess(proc, 201)) killed = false;

  CloseHandle(proc);
#else
  killed = (kill(pid, SIGKILL) == 0);
#endif
  return killed;
}

Command::Result Command::cmd_shutdown_server(std::istream &input,
                                             Execution_context *context,
                                             const std::string &args) {
  int timeout_seconds = 0;

  if (args.size() > 0) timeout_seconds = std::stoi(args);

  if (0 != timeout_seconds) {
    context->m_console.print_error(
        "First argument to 'shutdown_server' command can be only set to "
        "'0'.\n");
    return Result::Stop_with_failure;
  }

  try {
    std::string pid_file;
    Backup_and_restore<bool> backup_and_restore_fatal_errors(
        &context->m_options.m_fatal_errors, true);
    Backup_and_restore<bool> backup_and_restore_query(
        &context->m_options.m_show_query_result, false);
    Backup_and_restore<bool> backup_and_restore_quiet(
        &context->m_options.m_quiet, true);
    Backup_and_restore<std::string> backup_and_restore_command_name(
        &context->m_command_name, "sql");

    try_result(cmd_stmtsql(input, context, "SELECT @@GLOBAL.pid_file"));
    try_result(cmd_recvresult(input, context, "",
                              [&pid_file](const std::string result) {
                                pid_file = result;
                                return true;
                              }));
    try_result(cmd_varfile(input, context, "__%VAR% " + pid_file));

    const auto pid = std::stoi(context->m_variables->get("__%VAR%"));

    if (0 == pid) {
      context->m_console.print_error("Pid-file doesn't contain valid PID.\n");
      return Result::Stop_with_failure;
    }

    if (!kill_process(pid)) {
      context->m_console.print_error("Server coudn't be killed.\n");
      return Result::Stop_with_failure;
    }
  } catch (const Result result) {
    if (Result::Continue != result) {
      return Result::Stop_with_failure;
    }
  }

  return Result::Continue;
}

Command::Result Command::cmd_reconnect(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  auto &holder = context->m_connection->active_holder();
  xcl::XError error;
  std::set<int> expected_errors{0,
                                ER_SERVER_SHUTDOWN,
                                CR_CONNECTION_ERROR,
                                CR_CONN_HOST_ERROR,
                                CR_SERVER_GONE_ERROR,
                                CR_SERVER_LOST,
                                ER_ACCESS_DENIED_ERROR,
                                ER_SECURE_TRANSPORT_REQUIRED};

  do {
    context->m_console.print_verbose("Try reconnecting, last error:", error,
                                     "\n");
    context->m_connection->active_xconnection()->close();
    cmd_sleep(input, context, "1");
    error = holder.reconnect();

    if (0 == expected_errors.count(error.error())) {
      context->m_console.print_error("Received unexpected error ",
                                     error.error(), '\n');
      return Result::Stop_with_failure;
    }
  } while (error.error());

  return Result::Continue;
}

Command::Result Command::cmd_nowarnings(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  context->m_options.m_show_warnings = false;
  return Result::Continue;
}

Command::Result Command::cmd_yeswarnings(std::istream &input,
                                         Execution_context *context,
                                         const std::string &args) {
  context->m_options.m_show_warnings = true;
  return Result::Continue;
}

Command::Result Command::cmd_fatalerrors(std::istream &input,
                                         Execution_context *context,
                                         const std::string &args) {
  context->m_options.m_fatal_errors = true;
  return Result::Continue;
}

Command::Result Command::cmd_fatalwarnings(std::istream &input,
                                           Execution_context *context,
                                           const std::string &args) {
  bool value = true;

  if (!args.empty()) {
    static const std::map<std::string, bool> allowed_values{
        {"YES", true},    {"TRUE", true}, {"NO", false},
        {"FALSE", false}, {"1", true},    {"0", false}};

    std::string upper_case_args;

    for (const auto c : args) {
      upper_case_args.push_back(toupper(c));
    }

    if (0 == allowed_values.count(upper_case_args)) {
      context->m_console.print_error("Argument has invalid value ", args, '\n');
      return Result::Stop_with_failure;
    }

    value = allowed_values.at(upper_case_args);
  }

  context->m_options.m_fatal_warnings = value;
  return Result::Continue;
}

Command::Result Command::cmd_nofatalerrors(std::istream &input,
                                           Execution_context *context,
                                           const std::string &args) {
  context->m_options.m_fatal_errors = false;
  return Result::Continue;
}

Command::Result Command::cmd_newsession_memory(std::istream &input,
                                               Execution_context *context,
                                               const std::string &args) {
  return do_newsession(input, context, args, {"SHA256_MEMORY"});
}

Command::Result Command::cmd_newsession_mysql41(std::istream &input,
                                                Execution_context *context,
                                                const std::string &args) {
  return do_newsession(input, context, args, {"MYSQL41"});
}

Command::Result Command::cmd_newsession_plain(std::istream &input,
                                              Execution_context *context,
                                              const std::string &args) {
  return do_newsession(input, context, args, {"PLAIN"});
}

Command::Result Command::cmd_newsession(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  return do_newsession(input, context, args, {});
}

Command::Result Command::do_newsession(
    std::istream &input, Execution_context *context, const std::string &args,
    const std::vector<std::string> &auth_methods) {
  if (args.empty()) {
    context->print_error(
        "'newsession' command, requires at "
        "last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string s = args;
  std::string user, pass, db, name;

  context->m_variables->replace(&s);

  std::string::size_type p = s.find(CMD_ARG_SEPARATOR);

  if (p != std::string::npos) {
    name = s.substr(0, p);
    s = s.substr(p + 1);
    p = s.find(CMD_ARG_SEPARATOR);
    if (p != std::string::npos) {
      user = s.substr(0, p);
      s = s.substr(p + 1);
      p = s.find(CMD_ARG_SEPARATOR);
      if (p != std::string::npos) {
        pass = s.substr(0, p);
        db = s.substr(p + 1);
      } else {
        pass = s;
      }
    } else {
      user = s;
    }
  } else {
    name = s;
  }

  try {
    const bool is_raw_connection = user == "-";

    context->m_console.print("connecting...\n");
    context->m_connection->create(name, user, pass, db, auth_methods,
                                  is_raw_connection);
    context->m_console.print("active session is now '", name, "'\n");

    if (!context->m_expected_error.check_ok()) return Result::Stop_with_failure;
  } catch (xcl::XError &err) {
    if (!context->m_expected_error.check_error(err)) {
      return Result::Stop_with_failure;
    }
  }

  return Result::Continue;
}

Command::Result Command::cmd_setsession(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  std::string s = args;

  context->m_variables->replace(&s);

  if (!s.empty() && (s[0] == ' ' || s[0] == '\t'))
    context->m_connection->set_active(s.substr(1), context->m_options.m_quiet);
  else
    context->m_connection->set_active(s, context->m_options.m_quiet);
  return Result::Continue;
}

Command::Result Command::cmd_closesession(std::istream &input,
                                          Execution_context *context,
                                          const std::string &args) {
  try {
    if (args == "abort")
      context->m_connection->abort_active();
    else
      context->m_connection->close_active();

    if (!context->m_expected_error.check_ok()) {
      return Result::Stop_with_failure;
    }
  } catch (xcl::XError &err) {
    if (!context->m_expected_error.check_error(err)) {
      return Result::Stop_with_failure;
    }
  }
  return Result::Continue;
}

Command::Result Command::cmd_expecterror(std::istream &input,
                                         Execution_context *context,
                                         const std::string &args) {
  if (args.empty()) {
    context->print_error("'expecterror' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  try {
    std::vector<std::string> argl;

    aux::split(argl, args, ",", true);

    for (std::vector<std::string>::const_iterator arg = argl.begin();
         arg != argl.end(); ++arg) {
      std::string value = *arg;

      context->m_variables->replace(&value);
      aux::trim(value);

      const int error_code = mysqlxtest::get_error_code_by_text(value);

      context->m_expected_error.expect_errno(error_code);
    }
  } catch (const std::exception &e) {
    context->print_error(e, '\n');

    return Result::Stop_with_failure;
  }

  return Result::Continue;
}

Command::Result Command::cmd_measure(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  m_start_measure = xpl::chrono::now();
  return Result::Continue;
}

Command::Result Command::cmd_endmeasure(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  if (!xpl::chrono::is_valid(m_start_measure)) {
    context->print_error("Time measurement, wasn't initialized", '\n');
    return Result::Stop_with_failure;
  }

  std::vector<std::string> argl;
  aux::split(argl, args, " ", true);
  if (argl.size() != 2 && argl.size() != 1) {
    context->print_error(
        "Invalid number of arguments for command endmeasure\n");
    return Result::Stop_with_failure;
  }

  const int64_t expected_msec = std::stoi(argl[0]);
  const int64_t msec =
      xpl::chrono::to_milliseconds(xpl::chrono::now() - m_start_measure);

  int64_t tolerance = expected_msec * 10 / 100;

  if (2 == argl.size()) tolerance = std::stoi(argl[1]);

  if (abs(static_cast<int>(expected_msec - msec)) > tolerance) {
    context->print_error("Timeout should occur after ", expected_msec,
                         "ms, but it was ", msec, "ms.  \n");
    return Result::Stop_with_failure;
  }

  m_start_measure = xpl::chrono::Time_point();
  return Result::Continue;
}

Command::Result Command::cmd_quiet(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  context->m_options.m_quiet = true;

  return Result::Continue;
}

Command::Result Command::cmd_noquiet(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  context->m_options.m_quiet = false;

  return Result::Continue;
}

Command::Result Command::cmd_varsub(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  if (args.empty()) {
    context->print_error("'varsub' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  context->m_variables->push_unreplace(args);
  return Result::Continue;
}
Command::Result Command::cmd_varreplace(std::istream &input,
                                        Execution_context *context,
                                        const std::string &args) {
  std::vector<std::string> argl;
  aux::split(argl, args, "\t", true);

  if (3 != argl.size()) {
    context->print_error(
        "'cmd_varreplace' command, requires three arguments, still received '",
        args, "'\n");
    return Result::Stop_with_failure;
  }
  context->m_variables->replace(&argl[1]);
  context->m_variables->replace(&argl[2]);

  std::string value = context->m_variables->get(argl[0]);
  aux::replace_all(value, argl[1], argl[2], 1);
  context->m_variables->set(argl[0], value);

  return Result::Continue;
}

Command::Result Command::cmd_varlet(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  if (args.empty()) {
    context->print_error("'varlet' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string::size_type p = args.find(' ');

  if (p == std::string::npos) {
    context->m_variables->set(args, "");
  } else {
    const std::string name = args.substr(0, p);
    std::string value = args.substr(p + 1);

    context->m_variables->replace(&value);

    if (!context->m_variables->set(name, value)) {
      context->print_error("'varlet' command failed, when setting the '", name,
                           "' variable to '", value, "'.\n");

      return Result::Stop_with_failure;
    }
  }
  return Result::Continue;
}

Command::Result Command::cmd_varinc(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  std::vector<std::string> argl;
  aux::split(argl, args, " ", true);
  if (argl.size() != 2) {
    context->print_error("Invalid number of arguments for command varinc\n");
    return Result::Stop_with_failure;
  }

  if (!context->m_variables->is_present(argl[0])) {
    context->print_error("Invalid variable ", argl[0], '\n');
    return Result::Stop_with_failure;
  }

  std::string val = context->m_variables->get(argl[0]);
  char *c;
  std::string inc_by = argl[1].c_str();

  context->m_variables->replace(&inc_by);

  int64_t int_val = strtol(val.c_str(), &c, 10);
  int64_t int_n = strtol(inc_by.c_str(), &c, 10);
  int_val += int_n;
  val = xpl::to_string(int_val);
  context->m_variables->set(argl[0], val);

  return Result::Continue;
}

Command::Result Command::cmd_vargen(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  std::vector<std::string> argl;
  aux::split(argl, args, " ", true);
  if (argl.size() != 3) {
    context->print_error("Invalid number of arguments for command vargen\n");
    return Result::Stop_with_failure;
  }
  std::string data(std::stoi(argl[2]), *argl[1].c_str());
  context->m_variables->set(argl[0], data);
  return Result::Continue;
}

Command::Result Command::cmd_varfile(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  std::vector<std::string> argl;
  aux::split(argl, args, " ", true);
  if (argl.size() != 2) {
    context->print_error("Invalid number of arguments for command varfile ",
                         args, '\n');
    return Result::Stop_with_failure;
  }

  std::string path_to_file = argl[1];
  context->m_variables->replace(&path_to_file);

  std::ifstream file(path_to_file.c_str());
  if (!file.is_open()) {
    context->print_error("Couldn't not open file ", path_to_file, '\n');
    return Result::Stop_with_failure;
  }

  file.seekg(0, file.end);
  size_t len = file.tellg();
  file.seekg(0);

  char *buffer = new char[len];
  file.read(buffer, len);
  context->m_variables->set(argl[0], std::string(buffer, len));
  delete[] buffer;

  return Result::Continue;
}

Command::Result Command::cmd_varescape(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  if (args.empty()) {
    context->print_error("'varescape' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  if (!context->m_variables->is_present(args)) {
    context->print_error("'varescape' command,",
                         "argument needs to be a variable.\n");
    return Result::Stop_with_failure;
  }

  std::string variable_value = context->m_variables->get(args);

  aux::replace_all(variable_value, "\"", "\\\"");
  aux::replace_all(variable_value, "\n", "\\n");

  context->m_variables->set(args, variable_value);

  return Result::Continue;
}

Command::Result Command::cmd_binsend(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  if (args.empty()) {
    context->print_error("'binsend' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string args_copy = args;
  context->m_variables->replace(&args_copy);
  std::string data =
      bindump_to_data(args_copy, &context->m_script_stack, context->m_console);

  context->print("Sending ", data.length(), " bytes raw data...\n");
  context->m_connection->active_xconnection()->write(
      reinterpret_cast<const uint8_t *>(data.c_str()), data.length());

  return Result::Continue;
}

Command::Result Command::cmd_hexsend(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  std::string args_copy = args;
  context->m_variables->replace(&args_copy);

  if (0 == args_copy.length()) {
    context->print_error("Data should not be present", '\n');
    return Result::Stop_with_failure;
  }

  if (0 != args_copy.length() % 2) {
    context->print_error(
        "Size of data should be a multiplication of two, current length:",
        args_copy.length(), ", data:'", args_copy, "'\n");
    return Result::Stop_with_failure;
  }

  std::string data;
  try {
    aux::unhex(args_copy, data);
  } catch (const std::exception &) {
    context->print_error("Hex string is invalid", '\n');
    return Result::Stop_with_failure;
  }

  context->print("Sending ", data.length(), " bytes raw data...\n");
  context->m_connection->active_xconnection()->write(
      reinterpret_cast<const uint8_t *>(data.c_str()), data.length());

  return Result::Continue;
}

size_t Command::value_to_offset(const std::string &data,
                                const size_t maximum_value) {
  if ('%' == *data.rbegin()) {
    size_t percent = std::stoi(data);

    return maximum_value * percent / 100;
  }

  return std::stoi(data);
}

Command::Result Command::cmd_binsendoffset(std::istream &input,
                                           Execution_context *context,
                                           const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'binsendoffset' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string args_copy = args;
  context->m_variables->replace(&args_copy);

  std::vector<std::string> argl;
  aux::split(argl, args_copy, " ", true);

  size_t begin_bin = 0;
  size_t end_bin = 0;
  std::string data;

  try {
    data =
        bindump_to_data(argl[0], &context->m_script_stack, context->m_console);
    end_bin = data.length();

    if (argl.size() > 1) {
      begin_bin = value_to_offset(argl[1], data.length());
      if (argl.size() > 2) {
        end_bin = value_to_offset(argl[2], data.length());

        if (argl.size() > 3) throw std::out_of_range("Too many arguments");
      }
    }
  } catch (const std::out_of_range &) {
    context->print_error(
        "Invalid number of arguments for command binsendoffset:", argl.size(),
        '\n');
    return Result::Stop_with_failure;
  }

  context->print("Sending ", end_bin, " bytes raw data...\n");
  data = data.substr(begin_bin, end_bin - begin_bin);

  context->m_connection->active_xconnection()->write(
      reinterpret_cast<const uint8_t *>(data.c_str()), data.length());

  return Result::Continue;
}

Command::Result Command::cmd_callmacro(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'callmacro' command, requires at last one argument.\n");
    return Result::Stop_with_failure;
  }

  if (context->m_macros.call(context, args)) return Result::Continue;

  return Result::Stop_with_failure;
}

Command::Result Command::cmd_macro_delimiter_compress(
    std::istream &input, Execution_context *context, const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'macro_delimiter_compress' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string copy_args = args;
  aux::trim(copy_args);

  std::map<std::string, bool> allowed_values{
      {"true", true}, {"false", false}, {"0", false}, {"1", true}};

  if (0 == allowed_values.count(copy_args)) {
    context->print_error(
        "'macro_delimiter_compress' received unknown argument value '",
        copy_args, "'.\n");
    return Result::Stop_with_failure;
  }

  context->m_macros.set_compress_option(allowed_values[copy_args]);

  return Result::Continue;
}

Command::Result Command::cmd_assert_eq(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<std::equal_to<>>(input, context, args);
}

Command::Result Command::cmd_assert_ne(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<std::not_equal_to<>>(input, context, args);
}

Command::Result Command::cmd_assert_gt(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<Numeric_values<std::greater<>>>(input, context,
                                                            args);
}

Command::Result Command::cmd_assert_le(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<Numeric_values<std::less_equal<>>>(input, context,
                                                               args);
}

Command::Result Command::cmd_assert_lt(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<Numeric_values<std::less<>>>(input, context, args);
}

Command::Result Command::cmd_assert_ge(std::istream &input,
                                       Execution_context *context,
                                       const std::string &args) {
  return cmd_assert_generic<Numeric_values<std::greater_equal<>>>(
      input, context, args);
}

Command::Result Command::cmd_assert(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  std::vector<std::string> vargs;

  aux::split(vargs, args, "\t", true);

  if (3 != vargs.size()) {
    context->print_error(
        context->m_script_stack,
        "Specified invalid number of arguments for command assert:",
        vargs.size(), " expecting 3\n");
    return Result::Stop_with_failure;
  }

  static std::map<std::string, Command_method> assert_methods{
      {"!=", &Command::cmd_assert_ne}, {"==", &Command::cmd_assert_eq},
      {"=", &Command::cmd_assert_eq},  {">", &Command::cmd_assert_gt},
      {">=", &Command::cmd_assert_ge}, {"<", &Command::cmd_assert_lt},
      {"<=", &Command::cmd_assert_le}};

  if (0 == assert_methods.count(vargs[1])) {
    std::string ops;
    for (const auto &kv : assert_methods) {
      if (!ops.empty()) ops += ", ";

      ops += kv.first;
    }

    context->print_error(context->m_script_stack,
                         "Used invalid operator in second argument:", vargs[1],
                         " expecting one of: ", ops, "\n");
    return Result::Stop_with_failure;
  }

  auto method = assert_methods[vargs[1]];

  return (this->*method)(input, context, vargs[0] + "\t" + vargs[2]);
}

Command::Result Command::cmd_query(std::istream &input,
                                   Execution_context *context,
                                   const std::string &args) {
  context->m_options.m_show_query_result = true;
  return Result::Continue;
}

Command::Result Command::cmd_noquery(std::istream &input,
                                     Execution_context *context,
                                     const std::string &args) {
  context->m_options.m_show_query_result = false;
  return Result::Continue;
}

Command::Result Command::cmd_wait_for(std::istream &input,
                                      Execution_context *context,
                                      const std::string &args) {
  bool match = false;
  const int countdown_start_value = 30;
  int countdown_retries = countdown_start_value;

  std::string args_variables_replaced = args;
  std::vector<std::string> vargs;

  context->m_variables->replace(&args_variables_replaced);
  aux::split(vargs, args_variables_replaced, "\t", true);

  if (2 != vargs.size()) {
    context->print_error(
        "Specified invalid number of arguments for command wait_for:",
        vargs.size(), " expecting 2\n");
    return Result::Stop_with_failure;
  }

  const std::string &expected_value = vargs[0];
  std::string value;

  try {
    do {
      Backup_and_restore<bool> backup_and_restore_fatal_errors(
          &context->m_options.m_fatal_errors, true);
      Backup_and_restore<bool> backup_and_restore_query(
          &context->m_options.m_show_query_result, false);
      Backup_and_restore<std::string> backup_and_restore_command_name(
          &context->m_command_name, "sql");
      bool has_row = false;

      try_result(cmd_stmtsql(input, context, vargs[1]));
      try_result(
          cmd_recvresult(input, context, "",
                         [&value, &has_row](const std::string &result_value) {
                           value = result_value;
                           has_row = true;
                           return true;
                         }));

      match = has_row && (value == expected_value);

      if (!match) try_result(cmd_sleep(input, context, "1"));
    } while (!match && --countdown_retries);
  } catch (const Result result) {
    context->print_error(
        "'Wait_for' failed because one of subsequent commands failed\n");
    return result;
  }

  if (!match) {
    context->print_error("Query didn't return expected value, tried ",
                         countdown_start_value, " times\n", "Expected '",
                         expected_value, "', received '", value, "'\n");
    return Result::Stop_with_failure;
  }

  return Result::Continue;
}

Command::Result Command::cmd_clear_received(std::istream &input,
                                            Execution_context *context,
                                            const std::string &args) {
  context->m_connection->active_holder().clear_received_messages();

  return Result::Continue;
}

Command::Result Command::cmd_received(std::istream &input,
                                      Execution_context *context,
                                      const std::string &args) {
  std::string cargs(args);
  std::vector<std::string> vargs;
  aux::split(vargs, cargs, " \t", true);
  context->m_variables->replace(&vargs[0]);

  if (2 != vargs.size()) {
    context->print_error(
        "Specified invalid number of arguments for command received:",
        vargs.size(), " expecting 2 or 1\n");
    return Result::Stop_with_failure;
  }

  context->m_variables->set(
      vargs[1],
      xpl::to_string(
          context->m_connection->active_session_messages_received(vargs[0])));

  return Result::Continue;
}

Command::Result Command::cmd_expectwarnings(std::istream &input,
                                            Execution_context *context,
                                            const std::string &args) {
  if (args.empty()) {
    context->print_error("'expectwarning' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  try {
    std::vector<std::string> argl;

    aux::split(argl, args, ",", true);

    for (std::vector<std::string>::const_iterator arg = argl.begin();
         arg != argl.end(); ++arg) {
      std::string value = *arg;

      context->m_variables->replace(&value);
      aux::trim(value);

      const int error_code = mysqlxtest::get_error_code_by_text(value);

      context->m_expected_warnings.expect_warning(error_code);
    }
  } catch (const std::exception &e) {
    context->print_error(e, '\n');

    return Result::Stop_with_failure;
  }

  return Result::Continue;
}

Command::Result Command::cmd_recvresult_store_metadata(
    std::istream &input, Execution_context *context, const std::string &args) {
  return cmd_recvresult(input, context, args, Value_callback(),
                        Metadata_policy::Store);
}

Command::Result Command::cmd_recv_with_stored_metadata(
    std::istream &input, Execution_context *context, const std::string &args) {
  if (args.empty()) {
    context->print_error(
        "'recv_with_stored_metadata' command requires one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string metadata_tag(args);
  if (context->m_stored_metadata.count(args) == 0) {
    context->print_error("No metadata stored with the given METADATA_TAG\n");
    return Result::Stop_with_failure;
  }
  return cmd_recvresult(input, context, args, Value_callback(),
                        Metadata_policy::Use_stored);
}

Command::Result Command::cmd_compress(std::istream &input,
                                      Execution_context *context,
                                      const std::string &args) {
  std::vector<std::string> argl;

  aux::split(argl, args, " ", true);

  const bool is_hex = context->m_command_name.find("hex") != std::string::npos;

  if (argl.size() != 2) {
    context->print_error("'compress' command requires two arguments.\n");
    return Result::Stop_with_failure;
  }

  context->m_variables->replace(&argl[1]);

  std::string raw;
  std::string compressed;

  if (is_hex) {
    aux::unhex(argl[1], raw);
  } else {
    raw =
        bindump_to_data(argl[1], &context->m_script_stack, context->m_console);
  }

  auto algorithm = context->m_connection->active_holder().get_algorithm();

  if (!algorithm) {
    context->print_error(
        "Algorithm not selected, please call first 'enable_compression' "
        "command.\n");
    return Result::Stop_with_failure;
  }

  {
    google::protobuf::io::StringOutputStream sos(&compressed);
    protocol::Compression_output_stream pos(algorithm, &sos);

    uint8_t *dst;
    int dst_size;
    int raw_offset = 0;
    int source_size = raw.length();
    algorithm->set_pledged_source_size(source_size);

    while (source_size &&
           pos.Next(reinterpret_cast<void **>(&dst), &dst_size)) {
      int to_copy = std::min(dst_size, source_size);
      int left_in_next = dst_size - to_copy;
      memcpy(dst, &raw[raw_offset], to_copy);
      source_size -= to_copy;

      if (left_in_next > 0) pos.BackUp(left_in_next);
    }
  }

  raw.clear();
  if (is_hex) {
    aux::hex(compressed, raw);
  } else {
    raw = data_to_bindump(compressed);
  }

  context->m_variables->set(argl[0], raw);

  return Result::Continue;
}

Command::Result Command::cmd_clear_stored_metadata(std::istream &input,
                                                   Execution_context *context,
                                                   const std::string &args) {
  context->m_stored_metadata.clear();
  return Result::Continue;
}

bool Command::json_string_to_any(const std::string &json_string,
                                 Any *any) const {
  Json_to_any_handler handler(any);
  rapidjson::Reader reader;
  rapidjson::StringStream ss(json_string.c_str());
  return !reader.Parse(ss, handler).IsError();
}

static bool try_open_file_on_different_paths(
    std::ifstream &stream, const std::string &filename,
    const std::vector<std::string> &paths) {
  for (const auto &path : paths) {
    stream.open(path + filename);

    // Lets access the file to make the "fs.flags" contain
    // valid values.
    stream.peek();

    if (stream.good()) return true;
  }

  return stream.good();
}

Command::Result Command::cmd_import(std::istream &input,
                                    Execution_context *context,
                                    const std::string &args) {
  if (args.empty()) {
    context->print_error("'import' command, requires one argument.\n");
    return Result::Stop_with_failure;
  }

  std::string filename(args);
  context->m_variables->replace(&filename);

  std::ifstream stream;

  try_open_file_on_different_paths(stream, filename,
                                   {context->m_options.m_import_path, ""});

  // After the "peek", good can be checked
  if (!stream.good()) {
    context->print_error(context->m_script_stack, "Could not open macro file ",
                         args, " (aka ", filename, ")\n");
    return Result::Stop_with_failure;
  }

  context->m_script_stack.push({0, args});

  std::vector<Block_processor_ptr> processors{
      std::make_shared<Macro_block_processor>(context),
      std::make_shared<Comment_processor>(),
      std::make_shared<Indigestion_processor>(context)};

  bool r = process_client_input(stream, &processors, &context->m_script_stack,
                                context->m_console) == 0;
  context->m_script_stack.pop();

  return r ? Result::Continue : Result::Stop_with_failure;
}

Command::Result Command::cmd_env(std::istream &input,
                                 Execution_context *context,
                                 const std::string &args) {
  std::vector<std::string> argl;
  aux::split(argl, args, " ", true);

  if (argl.size() != 2) {
    context->print_error("'ENV' command failed, it requires two arguments.\n");

    return Result::Stop_with_failure;
  }

  auto env = std::getenv(argl[1].c_str());

  if (nullptr == env) {
    context->print_error("'ENV' command failed, following env-variable '",
                         argl[1], "', doesn't exist.\n");

    return Result::Stop_with_failure;
  }

  context->m_variables->set(argl[0], env);

  return Result::Continue;
}

void Command::print_resultset(Execution_context *context,
                              Result_fetcher *result,
                              const std::vector<std::string> &columns,
                              Value_callback value_callback, const bool quiet,
                              const bool print_column_info) {
  do {
    std::vector<xcl::Column_metadata> meta(result->column_metadata());

    if (result->get_last_error()) return;

    std::vector<int> column_indexes;
    int column_index = -1;
    bool first = true;

    for (auto col = meta.begin(); col != meta.end(); ++col) {
      ++column_index;

      if (!first) {
        if (!quiet) context->print("\t");
      } else {
        first = false;
      }

      if (!columns.empty() &&
          columns.end() == std::find(columns.begin(), columns.end(), col->name))
        continue;

      column_indexes.push_back(column_index);
      if (!quiet) context->print(col->name);
    }
    if (!quiet) context->print("\n");

    for (;;) {
      const xcl::XRow *row(result->next());

      if (!row) break;

      try {
        std::vector<int>::iterator i = column_indexes.begin();
        const auto field_count = row->get_number_of_fields();
        for (; i != column_indexes.end() && (*i) < field_count; ++i) {
          std::string out_result;

          if (!row->get_field_as_string(*i, &out_result))
            throw std::runtime_error("Data decoder failed");

          int field = (*i);
          if (field != 0)
            if (!quiet) context->print("\t");
          std::string str = context->m_variables->unreplace(out_result, false);
          if (!quiet) context->print(str);
          if (value_callback) {
            value_callback(str);
            Value_callback().swap(value_callback);
          }
        }
      } catch (std::exception &e) {
        context->print_error("ERROR: ", e, '\n');
      }
      if (!quiet) context->print("\n");
    }

    if (print_column_info) context->print(hide_container(meta));
  } while (result->next_data_set());
}

void Command::try_result(Result result) {
  if (result != Result::Continue) throw result;
}

Command::Result Command::get_sql_variable(Execution_context *context,
                                          const std::string &name,
                                          std::string *out_var) {
  try {
    std::istringstream dummy_input;
    std::string sql = "SELECT @@GLOBAL.";
    sql += name;
    try_result(cmd_stmtsql(dummy_input, context, sql));
    try_result(cmd_recvresult(dummy_input, context, "",
                              [out_var](const std::string result) {
                                *out_var = result;
                                return true;
                              }));
    std::string assign = "%__VAR_LAST% ";
    assign += *out_var;
    try_result(cmd_varlet(dummy_input, context, assign));

    return Result::Continue;
  } catch (const Result result) {
    return result;
  }
}

void print_help_commands() {
  std::cout << "Input may be a file (or if no --file is specified, it stdin "
               "will be used)\n";
  std::cout << "The following commands may appear in the input script:\n";
  std::cout << "-->echo <text>\n";
  std::cout << "  Prints the text (allows variables)\n";
  std::cout << "-->title <c><text>\n";
  std::cout << "  Prints the text with an underline, using the character <c>\n";
  std::cout << "-->sql\n";
  std::cout << "  Begins SQL block. SQL statements that appear will be "
               "executed and results printed (allows variables).\n";
  std::cout << "-->endsql\n";
  std::cout << "  End SQL block. End a block of SQL started by -->sql\n";
  std::cout << "-->begin_compress\n";
  std::cout << "  Begins block of protobuf messages to compress and\n"
               "  encapsulate inside single 'Compressed' message.\n";
  std::cout << "-->end_compress\n";
  std::cout << "  End compressed message block. End a block started by "
               "-->begin_compress\n";
  std::cout << "-->macro <macroname> <argname1> ...\n";
  std::cout << "  Start a block of text to be defined as a macro. Must be "
               "terminated with -->endmacro\n";
  std::cout << "-->endmacro\n";
  std::cout << "  Ends a macro block\n";
  std::cout << "-->callmacro <macro>\t<argvalue1>\t...\n";
  std::cout << "  Executes the macro text, substituting argument values with "
               "the provided ones (args separated by tabs).\n";
  std::cout << "-->import <macrofile>\n";
  std::cout << "  Loads macros from the specified file. The file must be in "
               "the directory specified by --import option in command "
               "line.\n";
  std::cout << "-->macro_delimiter_compress TRUE|FALSE|0|1\n";
  std::cout << "  Enable/disable grouping of adjacent delimiters into\n";
  std::cout << "  single one at \"callmacro\" command.\n";
  std::cout << "-->do_ssl_handshake\n";
  std::cout << "  Execute SSL handshake, enables SSL on current connection\n";
  std::cout << "<protomsg>\n";
  std::cout << "  Encodes the text format protobuf message and sends it to "
               "the server (allows variables).\n";
  std::cout << "-->enable_compression deflate_stream|lz4_message|zstd_stream"
               " [#level]\n";
  std::cout << "  Enable compression\n";
  std::cout << "-->recv [quiet|<FIELD PATH>]\n";
  std::cout << "  quiet        - received message isn't printed\n";
  std::cout
      << "  <FIELD PATH> - print only selected part of the message using\n";
  std::cout << "                 \"field-path\" filter:\n";
  std::cout << "                 * field_name1\n";
  std::cout << "                 * field_name1.field_name2\n";
  std::cout << "                 * repeated_field_name1[1].field_name1\n";

  std::cout << "-->recvresult [print-columnsinfo] [" << CMD_ARG_BE_QUIET
            << "]\n";
  std::cout << "  Read and print one resultset from the server; if "
               "print-columnsinfo is present also print short columns "
               "status\n";
  std::cout << "-->recvtovar <varname> [COLUMN_NAME]\n";
  std::cout << "  Read first row and first column (or column with name "
               "COLUMN_NAME) of resultset\n";
  std::cout << "  and set the variable <varname>\n";
  std::cout << "-->recverror <errno>\n";
  std::cout << "  Read a message and ensure that it's an error of the "
               "expected type\n";
  std::cout << "-->recvtype (<msgtype> [<msg_fied>] [<expected_field_value>] ["
            << CMD_ARG_BE_QUIET << "])|<msgid>"
            << "\n";
  std::cout << "  - In case when user specified <msgtype> - read one message "
               "and print it,\n"
               "    checks if its type is <msgtype>, additionally its fields "
               "may be matched.\n"
               "    Compressed messages are decompressed, thus user will "
               "receive inner X Protocol messages.\n";
  std::cout << "  - In case when user specified <msgid> - read one message and "
               "print the ID,\n"
               "    checks the RAW message ID if its match <msgid>.\n"
               "    Compressed messages are not decompressed, thus their IDs "
               "may be matched against <msgid>.\n";
  std::cout << "-->recvok\n";
  std::cout << "  Expect to receive 'Mysqlx.Ok' message. Works with "
               "'expecterror' command.\n";
  std::cout << "-->recvuntil <msgtype> [do_not_show_intermediate]\n";
  std::cout << "  Read messages and print them, until a msg of the specified "
               "type (or Error) is received\n";
  std::cout << "  do_not_show_intermediate - if this argument is present "
               "then printing of intermediate message should be omitted\n";
  std::cout << "-->repeat <N> [<VARIABLE_NAME>]\n";
  std::cout
      << "  Begin block of instructions that should be repeated N times\n";
  std::cout << "-->endrepeat\n";
  std::cout << "  End block of instructions that should be repeated - next "
               "iteration\n";
  std::cout << "-->stmtsql <CMD>\n";
  std::cout << "  Send StmtExecute with sql command\n";
  std::cout << "-->env <XVARIABLE> <ENV>\n";
  std::cout << "  Assign environment variable to X variable.\n";
  std::cout << "-->stmtadmin <CMD> [json_string]\n";
  std::cout << "  Send StmtExecute with admin command with given aguments "
               "(formated as json object)\n";
  std::cout << "-->system_in_background <CMD>\n";
  std::cout << "  Execute application or script.\n";
  std::cout << "-->system <CMD>\n";
  std::cout << "  Execute application or script\n";
  std::cout << "-->exit\n";
  std::cout << "  Stops reading commands, disconnects and exits (same as "
               "<eof>/^D)\n";
  std::cout << "-->abort\n";
  std::cout << "  Exit immediately, without performing cleanup\n";
  std::cout << "-->shutdown_server [timeout]\n";
  std::cout << "  Kills the server associated with current session.\n";
  std::cout << "-->nowarnings/-->yeswarnings\n";
  std::cout << "  Whether to print warnings generated by the statement "
               "(default no)\n";
  std::cout << "-->recvuntildisc [" << CMD_ARG_SHOW_RECEIVED << ", "
            << CMD_ARG_KEEP_SESSION << "]...\n";
  std::cout
      << "  Receive all messages until server drops current connection.\n";
  std::cout << "  " << CMD_ARG_SHOW_RECEIVED
            << " - received messages are printed to standard output.\n";
  std::cout << "  " << CMD_ARG_KEEP_SESSION
            << " - session descriptor is not released in mysqlxtest, user may "
               "execute 'reconnect'.\n";
  std::cout << "-->peerdisc <MILLISECONDS> [TOLERANCE]\n";
  std::cout << "  Expect that xplugin disconnects after given number of "
               "milliseconds and tolerance\n";
  std::cout << "-->sleep <SECONDS>\n";
  std::cout << "  Stops execution of mysqlxtest for given number of seconds "
               "(may be fractional)\n";
  std::cout
      << "-->login <user>\t<pass>\t<db>\t<mysql41|plain|sha256_memory>]\n";
  std::cout << "  Performs authentication steps (use with --no-auth)\n";
  std::cout << "-->loginerror <errno>\t<user>\t<pass>\t<db>\n";
  std::cout << "  Performs authentication steps expecting an error (use with "
               "--no-auth)\n";
  std::cout << "-->fatalerrors/nofatalerrors\n";
  std::cout << "  Whether to immediately exit on MySQL errors.\n";
  std::cout << "  All expected errors are ignored.\n";
  std::cout << "-->fatalwarnings [yes|no|true|false|1|0]\n";
  std::cout << "  Whether to immediately exit on MySQL warnings.\n";
  std::cout << "  All expected warnings are ignored.\n";
  std::cout << "-->expectwarnings <errno>[,<errno>[,<errno>...]]\n";
  std::cout << "  Expect a specific warning for the next command. Fails if "
               "warning other than specified occurred.\n";
  std::cout
      << "  When this command was not used then all warnings are expected.\n";
  std::cout << "  Works for: recvresult, SQL\n";
  std::cout << "-->expecterror <errno>[,<errno>[,<errno>...]]\n";
  std::cout << "  Expect a specific error for the next command. Fails if "
               "error other than specified occurred\n";
  std::cout
      << "  Works for: newsession, closesession, recvresult, recvok, SQL\n";
  std::cout << "-->newsession <name>\t<user>\t<pass>\t<db>\n";
  std::cout << "  Create a new connection which is going to be authenticate"
               " using sequence of mechanisms (AUTO). Use '-' in place of"
               " the user for raw connection.\n";
  std::cout << "-->newsession_mysql41 <name>\t<user>\t<pass>\t<db>\n";
  std::cout << "  Create a new connection which is going to be authenticate"
               " using MYSQL41 mechanism.\n";
  std::cout << "-->newsession_memory <name>\t<user>\t<pass>\t<db>\n";
  std::cout << "  Create a new connection which is going to be authenticate"
               " using SHA256_MEMORY mechanism.\n";
  std::cout << "-->newsession_plain <name>\t<user>\t<pass>\t<db>\n";
  std::cout << "  Create a new connection which is going to be authenticate"
               " using PLAIN mechanism.\n";
  std::cout << "-->reconnect\n";
  std::cout << "  Try to restore the connection/session. Default connection"
               "  is restored or session established by '-->newsession*'.\n";
  std::cout << "-->setsession <name>\n";
  std::cout << "  Activate the named session\n";
  std::cout << "-->closesession [abort]\n";
  std::cout << "  Close the active session (unless its the default session)\n";
  std::cout << "-->wait_for <VALUE_EXPECTED>\t<SQL QUERY>\n";
  std::cout << "  Wait until SQL query returns value matches expected value "
               "(time limit 30 second)\n";
  std::cout << "-->assert <VALUE_EXPECTED>\t<OP>\t<VALUE_TESTED>\n";
  std::cout << "  Ensure that expression described by argument parameters "
               "is true\n";
  std::cout << "  <OP> can take following values:\n"
               "  \"==\" ensures that expected value and tested value "
               "are equal\n";
  std::cout << "  \"!=\" ensures that expected value and tested value "
               "are not equal\n";
  std::cout << "  \">=\" ensures that expected value is greater or equal "
               "to tested value\n";
  std::cout << "  \"<=\" ensures that expected value is less or equal "
               "to tested value\n";
  std::cout << "  \"<\" ensures that expected value is less than"
               " tested value\n";
  std::cout << "  \">\" ensures that expected value is grater than"
               " tested value\n";
  std::cout << "\n";
  std::cout << "  For example: -->assert 1 < %SOME_VARIABLE%\n";
  std::cout << "               -->assert %V1% == %V2%\n";
  std::cout << "-->assert_eq <VALUE_EXPECTED>\t<VALUE_TESTED>\n";
  std::cout << "  Ensure that 'TESTED' value equals 'EXPECTED' by comparing "
               "strings lexicographically\n";
  std::cout << "-->assert_ne <VALUE_EXPECTED>\t<VALUE_TESTED>\n";
  std::cout << "  Ensure that 'TESTED' value doesn't equals 'EXPECTED' by"
               " comparing strings lexicographically\n";
  std::cout << "-->assert_gt <VALUE_EXPECTED>\t<VALUE_TESTED>\n";
  std::cout << "  Ensure that 'TESTED' value is greater than 'EXPECTED' "
               "(only when the both are numeric values)\n";
  std::cout << "-->assert_ge <VALUE_EXPECTED>\t<VALUE_TESTED>\n";
  std::cout << "  Ensure that 'TESTED' value is greater  or equal to "
               "'EXPECTED' (only when the both are numeric values)\n";
  std::cout << "-->varfile <varname> <datafile>\n";
  std::cout << "  Assigns the contents of the file to the named variable\n";
  std::cout << "-->varlet <varname> <value>\n";
  std::cout << "  Assign the value (can be another variable) to the variable\n";
  std::cout << "-->varinc <varname> <n>\n";
  std::cout << "  Increment the value of varname by n (assuming both "
               "convert to integral)\n";
  std::cout << "-->varsub <varname>\n";
  std::cout << "  Add a variable to the list of variables to replace for "
               "the next recv or sql command (value is replaced by the "
               "name)\n";
  std::cout << "-->varreplace <varname>\t<old_txt>\t<new_txt>\n";
  std::cout << "  Replace all occurrence of <old_txt> with <new_txt> in "
               "<varname> value.\n";
  std::cout << "-->varescape <varname>\n";
  std::cout << "  Escape end-line and backslash characters.\n";
  std::cout << "-->compress_bin <VAR> <bindump>\n";
  std::cout << "  Compress <bindump> using output-compression context\n";
  std::cout << "  and put the output to <VAR> encoded using bindump\n";
  std::cout << "  (compatible with protobuf text format).\n";
  std::cout << "-->compress_hex <VAR> <hexdump>\n";
  std::cout << "  Compress <hexdump> using output-compression context\n";
  std::cout
      << "  and put the output to <VAR> encoded using hexdecimal string.\n";
  std::cout << "-->binsend <bindump>[<bindump>...]\n";
  std::cout << "  Sends one or more binary message dumps to the server "
               "(generate those with --bindump)\n";
  std::cout << "-->binsendoffset <srcvar> [offset-begin[percent]> "
               "[offset-end[percent]]]\n";
  std::cout
      << "  Same as binsend with begin and end offset of data to be send\n";
  std::cout << "-->binparse <VAR_NAME> MESSAGE.NAME {\n";
  std::cout << "    MESSAGE.DATA\n";
  std::cout << "}\n";
  std::cout << "  Dump given message to variable <VAR_NAME>, encoded as \n";
  std::cout << "  binary string (compatible with protobuf text format).\n";
  std::cout << "-->hexparse <VAR_NAME> MESSAGE.NAME {\n";
  std::cout << "    MESSAGE.DATA\n";
  std::cout << "}\n";
  std::cout << "  Dump given message to variable <VAR_NAME>, encoded as \n";
  std::cout << "  hexdecimal string.\n";
  std::cout << "-->quiet/noquiet\n";
  std::cout << "  Toggle verbose messages\n";
  std::cout << "-->query_result/noquery_result\n";
  std::cout << "  Toggle visibility for query results\n";
  std::cout << "-->received <msgtype>\t<varname>\n";
  std::cout << "  Assigns number of received messages of indicated type (in "
               "active session) to a variable\n";
  std::cout << "-->clear_received\n";
  std::cout << "  Clear number of received messages.\n";
  std::cout << "-->recvresult_store_metadata <METADATA_TAG> [print-columnsinfo]"
               " ["
            << CMD_ARG_BE_QUIET << "]\n";
  std::cout << "  Receive result and store metadata for future use; if "
               "print-columnsinfo is present also print short columns "
               "status\n";
  std::cout << "-->recv_with_stored_metadata <METADATA_TAG>\n";
  std::cout << "  Receive a message using a previously stored metadata\n";
  std::cout << "-->clear_stored_metadata\n";
  std::cout << "  Clear metadata information stored by the "
               "recvresult_store_metadata\n";
  std::cout << "# comment\n";
}