aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Functions/parseDateTime.cpp
blob: fdab85c4640ecaa5f89097ff00b718e87a81fd5b (plain) (blame)
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
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnsDateTime.h>
#include <DataTypes/DataTypeDateTime.h>
#include <DataTypes/DataTypeString.h>

#include <Functions/FunctionFactory.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/FunctionsConversion.h>
#include <Functions/IFunction.h>
#include <Functions/castTypeToEither.h>
#include <Functions/numLiteralChars.h>

#include <IO/WriteHelpers.h>
#include <base/types.h>
#include <boost/algorithm/string/case_conv.hpp>

namespace DB
{
namespace ErrorCodes
{
    extern const int ILLEGAL_COLUMN;
    extern const int NOT_IMPLEMENTED;
    extern const int BAD_ARGUMENTS;
    extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE;
    extern const int CANNOT_PARSE_DATETIME;
    extern const int NOT_ENOUGH_SPACE;
}

namespace
{
    using Pos = const char *;

    constexpr Int32 minYear = 1970;
    constexpr Int32 maxYear = 2106;

    const std::unordered_map<String, std::pair<String, Int32>> dayOfWeekMap{
        {"mon", {"day", 1}},
        {"tue", {"sday", 2}},
        {"wed", {"nesday", 3}},
        {"thu", {"rsday", 4}},
        {"fri", {"day", 5}},
        {"sat", {"urday", 6}},
        {"sun", {"day", 7}},
    };

    const std::unordered_map<String, std::pair<String, Int32>> monthMap{
        {"jan", {"uary", 1}},
        {"feb", {"ruary", 2}},
        {"mar", {"ch", 3}},
        {"apr", {"il", 4}},
        {"may", {"", 5}},
        {"jun", {"e", 6}},
        {"jul", {"y", 7}},
        {"aug", {"ust", 8}},
        {"sep", {"tember", 9}},
        {"oct", {"ober", 10}},
        {"nov", {"ember", 11}},
        {"dec", {"ember", 12}},
    };

    /// key: month, value: total days of current month if current year is leap year.
    constexpr Int32 leapDays[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /// key: month, value: total days of current month if current year is not leap year.
    constexpr Int32 normalDays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /// key: month, value: cumulative days from January to current month(inclusive) if current year is leap year.
    constexpr Int32 cumulativeLeapDays[] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};

    /// key: month, value: cumulative days from January to current month(inclusive) if current year is not leap year.
    constexpr Int32 cumulativeDays[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};

    /// key: year, value: cumulative days from epoch(1970-01-01) to the first day of current year(exclusive).
    constexpr Int32 cumulativeYearDays[]
        = {0,     365,   730,   1096,  1461,  1826,  2191,  2557,  2922,  3287,  3652,  4018,  4383,  4748,  5113,  5479,  5844,  6209,
           6574,  6940,  7305,  7670,  8035,  8401,  8766,  9131,  9496,  9862,  10227, 10592, 10957, 11323, 11688, 12053, 12418, 12784,
           13149, 13514, 13879, 14245, 14610, 14975, 15340, 15706, 16071, 16436, 16801, 17167, 17532, 17897, 18262, 18628, 18993, 19358,
           19723, 20089, 20454, 20819, 21184, 21550, 21915, 22280, 22645, 23011, 23376, 23741, 24106, 24472, 24837, 25202, 25567, 25933,
           26298, 26663, 27028, 27394, 27759, 28124, 28489, 28855, 29220, 29585, 29950, 30316, 30681, 31046, 31411, 31777, 32142, 32507,
           32872, 33238, 33603, 33968, 34333, 34699, 35064, 35429, 35794, 36160, 36525, 36890, 37255, 37621, 37986, 38351, 38716, 39082,
           39447, 39812, 40177, 40543, 40908, 41273, 41638, 42004, 42369, 42734, 43099, 43465, 43830, 44195, 44560, 44926, 45291, 45656,
           46021, 46387, 46752, 47117, 47482, 47847, 48212, 48577, 48942, 49308, 49673};

    struct DateTime
    {
        /// If both week_date_format and week_date_format is false, date is composed of year, month and day
        Int32 year = 1970; /// year, range [1970, 2106]
        Int32 month = 1; /// month of year, range [1, 12]
        Int32 day = 1; /// day of month, range [1, 31]

        Int32 week = 1; /// ISO week of year, range [1, 53]
        Int32 day_of_week = 1; /// day of week, range [1, 7], 1 represents Monday, 2 represents Tuesday...
        bool week_date_format
            = false; /// If true, date is composed of week year(reuse year), week of year(use week) and day of week(use day_of_week)

        Int32 day_of_year = 1; /// day of year, range [1, 366]
        bool day_of_year_format = false; /// If true, date is composed of year(reuse year), day of year(use day_of_year)

        bool is_year_of_era = false; /// If true, year is calculated from era and year of era, the latter cannot be zero or negative.
        bool has_year = false; /// Whether year was explicitly specified.

        /// If hour_starts_at_1 = true, is_hour_of_half_day = true, hour's range is [1, 12]
        /// If hour_starts_at_1 = true, is_hour_of_half_day = false, hour's range is [1, 24]
        /// If hour_starts_at_1 = false, is_hour_of_half_day = true, hour's range is [0, 11]
        /// If hour_starts_at_1 = false, is_hour_of_half_day = false, hour's range is [0, 23]
        Int32 hour = 0;
        Int32 minute = 0; /// range [0, 59]
        Int32 second = 0; /// range [0, 59]

        bool is_am = true; /// If is_hour_of_half_day = true and is_am = false (i.e. pm) then add 12 hours to the result DateTime
        bool hour_starts_at_1 = false; /// Whether the hour is clockhour
        bool is_hour_of_half_day = false; /// Whether the hour is of half day

        bool has_time_zone_offset = false; /// If true, time zone offset is explicitly specified.
        Int64 time_zone_offset = 0; /// Offset in seconds between current timezone to UTC.

        void reset()
        {
            year = 1970;
            month = 1;
            day = 1;

            week = 1;
            day_of_week = 1;
            week_date_format = false;

            day_of_year = 1;
            day_of_year_format = false;

            is_year_of_era = false;
            has_year = false;

            hour = 0;
            minute = 0;
            second = 0;

            is_am = true;
            hour_starts_at_1 = false;
            is_hour_of_half_day = false;

            has_time_zone_offset = false;
            time_zone_offset = 0;
        }

        /// Input text is expected to be lowered by caller
        void setEra(const String & text) // NOLINT
        {
            if (text == "bc")
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Era BC exceeds the range of DateTime");
            else if (text != "ad")
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Unknown era {} (expected 'ad' or 'bc')", text);
        }

        void setCentury(Int32 century)
        {
            if (century < 19 || century > 21)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for century must be in the range [19, 21]", century);

            year = 100 * century;
            has_year = true;
        }

        void setYear(Int32 year_, bool is_year_of_era_ = false, bool is_week_year = false)
        {
            if (year_ < minYear || year_ > maxYear)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for year must be in the range [{}, {}]", year_, minYear, maxYear);

            year = year_;
            has_year = true;
            is_year_of_era = is_year_of_era_;
            if (is_week_year)
            {
                week_date_format = true;
                day_of_year_format = false;
            }
        }

        void setYear2(Int32 year_)
        {
            if (year_ >= 70 && year_ < 100)
                year_ += 1900;
            else if (year_ >= 0 && year_ < 70)
                year_ += 2000;
            else
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for year2 must be in the range [0, 99]", year_);

            setYear(year_, false, false);
        }

        void setMonth(Int32 month_)
        {
            if (month_ < 1 || month_ > 12)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for month of year must be in the range [1, 12]", month_);

            month = month_;
            week_date_format = false;
            day_of_year_format = false;
            if (!has_year)
            {
                has_year = true;
                year = 2000;
            }
        }

        void setWeek(Int32 week_)
        {
            if (week_ < 1 || week_ > 53)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for week of week year must be in the range [1, 53]", week_);

            week = week_;
            week_date_format = true;
            day_of_year_format = false;
            if (!has_year)
            {
                has_year = true;
                year = 2000;
            }
        }

        void setDayOfYear(Int32 day_of_year_)
        {
            if (day_of_year_ < 1 || day_of_year_ > 366)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for day of year must be in the range [1, 366]", day_of_year_);

            day_of_year = day_of_year_;
            day_of_year_format = true;
            week_date_format = false;
            if (!has_year)
            {
                has_year = true;
                year = 2000;
            }
        }

        void setDayOfMonth(Int32 day_of_month)
        {
            if (day_of_month < 1 || day_of_month > 31)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for day of month must be in the range [1, 31]", day_of_month);

            day = day_of_month;
            week_date_format = false;
            day_of_year_format = false;
            if (!has_year)
            {
                has_year = true;
                year = 2000;
            }
        }

        void setDayOfWeek(Int32 day_of_week_)
        {
            if (day_of_week_ < 1 || day_of_week_ > 7)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for day of week must be in the range [1, 7]", day_of_week_);

            day_of_week = day_of_week_;
            week_date_format = true;
            day_of_year_format = false;
            if (!has_year)
            {
                has_year = true;
                year = 2000;
            }
        }

        /// Input text is expected to be lowered by caller
        void setAMPM(const String & text)
        {
            if (text == "am")
                is_am = true;
            else if (text == "pm")
                is_am = false;
            else
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Unknown half day of day: {}", text);
        }

        void setHour(Int32 hour_, bool is_hour_of_half_day_ = false, bool hour_starts_at_1_ = false)
        {
            Int32 max_hour;
            Int32 min_hour;
            Int32 new_hour = hour_;
            if (!is_hour_of_half_day_ && !hour_starts_at_1_)
            {
                max_hour = 23;
                min_hour = 0;
            }
            else if (!is_hour_of_half_day_ && hour_starts_at_1_)
            {
                max_hour = 24;
                min_hour = 1;
                new_hour = hour_ % 24;
            }
            else if (is_hour_of_half_day_ && !hour_starts_at_1_)
            {
                max_hour = 11;
                min_hour = 0;
            }
            else
            {
                max_hour = 12;
                min_hour = 1;
                new_hour = hour_ % 12;
            }

            if (hour_ < min_hour || hour_ > max_hour)
                throw Exception(
                    ErrorCodes::CANNOT_PARSE_DATETIME,
                    "Value {} for hour must be in the range [{}, {}] if_hour_of_half_day={} and hour_starts_at_1={}",
                    hour,
                    max_hour,
                    min_hour,
                    is_hour_of_half_day_,
                    hour_starts_at_1_);

            hour = new_hour;
            is_hour_of_half_day = is_hour_of_half_day_;
            hour_starts_at_1 = hour_starts_at_1_;
        }

        void setMinute(Int32 minute_)
        {
            if (minute_ < 0 || minute_ > 59)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for minute must be in the range [0, 59]", minute_);

            minute = minute_;
        }

        void setSecond(Int32 second_)
        {
            if (second_ < 0 || second_ > 59)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Value {} for second must be in the range [0, 59]", second_);

            second = second_;
        }

        /// For debug
        [[maybe_unused]] String toString() const
        {
            String res;
            res += "year:" + std::to_string(year);
            res += ",";
            res += "month:" + std::to_string(month);
            res += ",";
            res += "day:" + std::to_string(day);
            res += ",";
            res += "hour:" + std::to_string(hour);
            res += ",";
            res += "minute:" + std::to_string(minute);
            res += ",";
            res += "second:" + std::to_string(second);
            res += ",";
            res += "AM:" + std::to_string(is_am);
            return res;
        }

        static bool isLeapYear(Int32 year_) { return year_ % 4 == 0 && (year_ % 100 != 0 || year_ % 400 == 0); }

        static bool isDateValid(Int32 year_, Int32 month_, Int32 day_)
        {
            /// The range of month[1, 12] and day[1, 31] already checked before
            bool leap = isLeapYear(year_);
            return (year_ >= minYear && year_ <= maxYear) && ((leap && day_ <= leapDays[month_]) || (!leap && day_ <= normalDays[month_]));
        }

        static bool isDayOfYearValid(Int32 year_, Int32 day_of_year_)
        {
            /// The range of day_of_year[1, 366] already checked before
            bool leap = isLeapYear(year_);
            return (year_ >= minYear && year_ <= maxYear) && (day_of_year_ <= 365 + (leap ? 1 : 0));
        }

        static Int32 extractISODayOfTheWeek(Int32 days_since_epoch)
        {
            if (days_since_epoch < 0)
            {
                // negative date: start off at 4 and cycle downwards
                return (7 - ((-days_since_epoch + 3) % 7));
            }
            else
            {
                // positive date: start off at 4 and cycle upwards
                return ((days_since_epoch + 3) % 7) + 1;
            }
        }

        static Int32 daysSinceEpochFromWeekDate(int32_t week_year_, int32_t week_of_year_, int32_t day_of_week_)
        {
            /// The range of week_of_year[1, 53], day_of_week[1, 7] already checked before
            if (week_year_ < minYear || week_year_ > maxYear)
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Invalid week year {}", week_year_);

            Int32 days_since_epoch_of_jan_fourth = daysSinceEpochFromDate(week_year_, 1, 4);
            Int32 first_day_of_week_year = extractISODayOfTheWeek(days_since_epoch_of_jan_fourth);
            return days_since_epoch_of_jan_fourth - (first_day_of_week_year - 1) + 7 * (week_of_year_ - 1) + day_of_week_ - 1;
        }

        static Int32 daysSinceEpochFromDayOfYear(Int32 year_, Int32 day_of_year_)
        {
            if (!isDayOfYearValid(year_, day_of_year_))
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Invalid day of year, out of range (year: {} day of year: {})", year_, day_of_year_);

            Int32 res = daysSinceEpochFromDate(year_, 1, 1);
            res += day_of_year_ - 1;
            return res;
        }

        static Int32 daysSinceEpochFromDate(Int32 year_, Int32 month_, Int32 day_)
        {
            if (!isDateValid(year_, month_, day_))
                throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Invalid date, out of range (year: {} month: {} day_of_month: {})", year_, month_, day_);

            Int32 res = cumulativeYearDays[year_ - 1970];
            res += isLeapYear(year_) ? cumulativeLeapDays[month_ - 1] : cumulativeDays[month_ - 1];
            res += day_ - 1;
            return res;
        }

        Int64 buildDateTime(const DateLUTImpl & time_zone)
        {
            if (is_hour_of_half_day && !is_am)
                hour += 12;

            // Convert the parsed date/time into a timestamp.
            Int32 days_since_epoch;
            if (week_date_format)
                days_since_epoch = daysSinceEpochFromWeekDate(year, week, day_of_week);
            else if (day_of_year_format)
                days_since_epoch = daysSinceEpochFromDayOfYear(year, day_of_year);
            else
                days_since_epoch = daysSinceEpochFromDate(year, month, day);

            Int64 seconds_since_epoch = days_since_epoch * 86400UZ + hour * 3600UZ + minute * 60UZ + second;

            /// Time zone is not specified, use local time zone
            if (!has_time_zone_offset)
                time_zone_offset = time_zone.timezoneOffset(seconds_since_epoch);

            /// Time zone is specified in format string.
            if (seconds_since_epoch >= time_zone_offset)
                seconds_since_epoch -= time_zone_offset;
            else
                throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "Seconds since epoch is negative");

            return seconds_since_epoch;
        }
    };

    enum class ParseSyntax
    {
        MySQL,
        Joda
    };

    enum class ErrorHandling
    {
        Exception,
        Zero,
        Null
    };

    /// _FUNC_(str[, format, timezone])
    template <typename Name, ParseSyntax parse_syntax, ErrorHandling error_handling>
    class FunctionParseDateTimeImpl : public IFunction
    {
    public:
        const bool mysql_M_is_month_name;

        static constexpr auto name = Name::name;
        static FunctionPtr create(ContextPtr context) { return std::make_shared<FunctionParseDateTimeImpl>(context); }

        explicit FunctionParseDateTimeImpl(ContextPtr context)
            : mysql_M_is_month_name(context->getSettings().formatdatetime_parsedatetime_m_is_month_name)
        {
        }

        String getName() const override { return name; }

        bool useDefaultImplementationForConstants() const override { return true; }
        bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }

        ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; }
        bool isVariadic() const override { return true; }
        size_t getNumberOfArguments() const override { return 0; }

        DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
        {
            FunctionArgumentDescriptors mandatory_args{
                {"time", &isString<IDataType>, nullptr, "String"},
                {"format", &isString<IDataType>, nullptr, "String"}
            };

            FunctionArgumentDescriptors optional_args{
                {"timezone", &isString<IDataType>, &isColumnConst, "const String"}
            };

            validateFunctionArgumentTypes(*this, arguments, mandatory_args, optional_args);

            String time_zone_name = getTimeZone(arguments).getTimeZone();
            DataTypePtr date_type = std::make_shared<DataTypeDateTime>(time_zone_name);
            if (error_handling == ErrorHandling::Null)
                return std::make_shared<DataTypeNullable>(date_type);
            else
                return date_type;
        }

        ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & /*result_type*/, size_t input_rows_count) const override
        {
            const auto * col_str = checkAndGetColumn<ColumnString>(arguments[0].column.get());
            if (!col_str)
                throw Exception(
                    ErrorCodes::ILLEGAL_COLUMN,
                    "Illegal column {} of first ('str') argument of function {}. Must be string.",
                    arguments[0].column->getName(),
                    getName());

            String format = getFormat(arguments);
            const auto & time_zone = getTimeZone(arguments);
            std::vector<Instruction> instructions = parseFormat(format);

            auto col_res = ColumnDateTime::create(input_rows_count);

            ColumnUInt8::MutablePtr col_null_map;
            if constexpr (error_handling == ErrorHandling::Null)
                col_null_map = ColumnUInt8::create(input_rows_count, 0);

            auto & res_data = col_res->getData();

            /// Make datetime fit in a cache line.
            alignas(64) DateTime datetime;
            for (size_t i = 0; i < input_rows_count; ++i)
            {
                datetime.reset();
                StringRef str_ref = col_str->getDataAt(i);
                Pos cur = str_ref.data;
                Pos end = str_ref.data + str_ref.size;
                bool error = false;

                for (const auto & instruction : instructions)
                {
                    try
                    {
                        cur = instruction.perform(cur, end, datetime);
                    }
                    catch (...)
                    {
                        if constexpr (error_handling == ErrorHandling::Zero)
                        {
                            res_data[i] = 0;
                            error = true;
                            break;
                        }
                        else if constexpr (error_handling == ErrorHandling::Null)
                        {
                            res_data[i] = 0;
                            col_null_map->getData()[i] = 1;
                            error = true;
                            break;
                        }
                        else
                        {
                            static_assert(error_handling == ErrorHandling::Exception);
                            throw;
                        }
                    }
                }

                if (error)
                    continue;

                try
                {
                    /// Ensure all input was consumed
                    if (cur < end)
                        throw Exception(
                            ErrorCodes::CANNOT_PARSE_DATETIME,
                            "Invalid format input {} is malformed at {}",
                            str_ref.toView(),
                            std::string_view(cur, end - cur));
                    Int64 time = datetime.buildDateTime(time_zone);
                    res_data[i] = static_cast<UInt32>(time);
                }
                catch (...)
                {
                    if constexpr (error_handling == ErrorHandling::Zero)
                        res_data[i] = 0;
                    else if constexpr (error_handling == ErrorHandling::Null)
                    {
                        res_data[i] = 0;
                        col_null_map->getData()[i] = 1;
                    }
                    else
                    {
                        static_assert(error_handling == ErrorHandling::Exception);
                        throw;
                    }
                }
            }

            if constexpr (error_handling == ErrorHandling::Null)
                return ColumnNullable::create(std::move(col_res), std::move(col_null_map));
            else
                return col_res;
            }


    private:
        class Instruction
        {
        private:
            enum class NeedCheckSpace
            {
                Yes,
                No
            };

            using Func = std::conditional_t<
                parse_syntax == ParseSyntax::MySQL,
                Pos (*)(Pos, Pos, const String &, DateTime &),
                std::function<Pos(Pos, Pos, const String &, DateTime &)>>;
            const Func func{};
            const String func_name;
            const String literal; /// Only used when current instruction parses literal
            const String fragment; /// Parsed fragments in MySQL or Joda format string

        public:
            explicit Instruction(Func && func_, const char * func_name_, const std::string_view & fragment_)
                : func(std::move(func_)), func_name(func_name_), fragment(fragment_)
            {
            }

            explicit Instruction(const String & literal_) : literal(literal_), fragment("LITERAL") { }
            explicit Instruction(String && literal_) : literal(std::move(literal_)), fragment("LITERAL") { }

            /// For debug
            [[maybe_unused]] String toString() const
            {
                if (func)
                    return "func:" + func_name + ",fragment:" + fragment;
                else
                    return "literal:" + literal + ",fragment:" + fragment;
            }

            Pos perform(Pos cur, Pos end, DateTime & date) const
            {
                if (func)
                    return func(cur, end, fragment, date);
                else
                {
                    /// literal:
                    checkSpace(cur, end, literal.size(), "insufficient space to parse literal", fragment);
                    if (std::string_view(cur, literal.size()) != literal)
                        throw Exception(
                            ErrorCodes::CANNOT_PARSE_DATETIME,
                            "Unable to parse fragment {} from {} because literal {} is expected but {} provided",
                            fragment,
                            std::string_view(cur, end - cur),
                            literal,
                            std::string_view(cur, literal.size()));
                    cur += literal.size();
                    return cur;
                }
            }

            template <typename T, NeedCheckSpace need_check_space>
            static Pos readNumber2(Pos cur, Pos end, [[maybe_unused]] const String & fragment, T & res)
            {
                if constexpr (need_check_space == NeedCheckSpace::Yes)
                    checkSpace(cur, end, 2, "readNumber2 requires size >= 2", fragment);

                res = (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                return cur;
            }

            template <typename T, NeedCheckSpace need_check_space>
            static Pos readNumber3(Pos cur, Pos end, [[maybe_unused]] const String & fragment, T & res)
            {
                if constexpr (need_check_space == NeedCheckSpace::Yes)
                    checkSpace(cur, end, 3, "readNumber4 requires size >= 3", fragment);

                res = (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                return cur;
            }

            template <typename T, NeedCheckSpace need_check_space>
            static Pos readNumber4(Pos cur, Pos end, [[maybe_unused]] const String & fragment, T & res)
            {
                if constexpr (need_check_space == NeedCheckSpace::Yes)
                    checkSpace(cur, end, 4, "readNumber4 requires size >= 4", fragment);

                res = (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                res = res * 10 + (*cur - '0');
                ++cur;
                return cur;
            }

            static void checkSpace(Pos cur, Pos end, size_t len, const String & msg, const String & fragment)
            {
                if (cur > end || cur + len > end) [[unlikely]]
                    throw Exception(
                        ErrorCodes::NOT_ENOUGH_SPACE,
                        "Unable to parse fragment {} from {} because {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        msg);
            }

            template <NeedCheckSpace need_check_space>
            static Pos assertChar(Pos cur, Pos end, char expected, const String & fragment)
            {
                if constexpr (need_check_space == NeedCheckSpace::Yes)
                    checkSpace(cur, end, 1, "assertChar requires size >= 1", fragment);

                if (*cur != expected) [[unlikely]]
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because char {} is expected but {} provided",
                        fragment,
                        std::string_view(cur, end - cur),
                        String(expected, 1),
                        String(*cur, 1));

                ++cur;
                return cur;
            }

            template <NeedCheckSpace need_check_space>
            static Pos assertNumber(Pos cur, Pos end, const String & fragment)
            {
                if constexpr (need_check_space == NeedCheckSpace::Yes)
                    checkSpace(cur, end, 1, "assertChar requires size >= 1", fragment);

                if (*cur < '0' || *cur > '9') [[unlikely]]
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because {} is not a number",
                        fragment,
                        std::string_view(cur, end - cur),
                        String(*cur, 1));

                ++cur;
                return cur;
            }

            static Pos mysqlDayOfWeekTextShort(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 3, "mysqlDayOfWeekTextShort requires size >= 3", fragment);

                String text(cur, 3);
                boost::to_lower(text);
                auto it = dayOfWeekMap.find(text);
                if (it == dayOfWeekMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because of unknown day of week short text {} ",
                        fragment,
                        std::string_view(cur, end - cur),
                        text);
                date.setDayOfWeek(it->second.second);
                cur += 3;
                return cur;
            }

            static Pos mysqlMonthOfYearTextShort(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 3, "mysqlMonthOfYearTextShort requires size >= 3", fragment);

                String text(cur, 3);
                boost::to_lower(text);
                auto it = monthMap.find(text);
                if (it == monthMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because of unknown month of year short text {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text);

                date.setMonth(it->second.second);
                cur += 3;
                return cur;
            }

            static Pos mysqlMonthOfYearTextLong(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 3, "mysqlMonthOfYearTextLong requires size >= 3", fragment);
                String text1(cur, 3);
                boost::to_lower(text1);
                auto it = monthMap.find(text1);
                if (it == monthMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse first part of fragment {} from {} because of unknown month of year text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1);
                cur += 3;

                size_t expected_remaining_size = it->second.first.size();
                checkSpace(cur, end, expected_remaining_size, "mysqlMonthOfYearTextLong requires the second parg size >= " + std::to_string(expected_remaining_size), fragment);
                String text2(cur, expected_remaining_size);
                boost::to_lower(text2);
                if (text2 != it->second.first)
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse second part of fragment {} from {} because of unknown month of year text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1 + text2);
                cur += expected_remaining_size;

                date.setMonth(it->second.second);
                return cur;
            }

            static Pos mysqlMonth(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 month;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, month);
                date.setMonth(month);
                return cur;
            }

            static Pos mysqlCentury(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 century;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, century);
                date.setCentury(century);
                return cur;
            }

            static Pos mysqlDayOfMonth(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 day_of_month;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, day_of_month);
                date.setDayOfMonth(day_of_month);
                return cur;
            }

            static Pos mysqlAmericanDate(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 8, "mysqlAmericanDate requires size >= 8", fragment);

                Int32 month;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, month);
                cur = assertChar<NeedCheckSpace::No>(cur, end, '/', fragment);
                date.setMonth(month);

                Int32 day;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, day);
                cur = assertChar<NeedCheckSpace::No>(cur, end, '/', fragment);
                date.setDayOfMonth(day);

                Int32 year;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, year);
                date.setYear(year);
                return cur;
            }

            static Pos mysqlDayOfMonthSpacePadded(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 2, "mysqlDayOfMonthSpacePadded requires size >= 2", fragment);

                Int32 day_of_month = *cur == ' ' ? 0 : (*cur - '0');
                ++cur;

                day_of_month = 10 * day_of_month + (*cur - '0');
                ++cur;

                date.setDayOfMonth(day_of_month);
                return cur;
            }

            static Pos mysqlISO8601Date(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 10, "mysqlISO8601Date requires size >= 10", fragment);

                Int32 year;
                Int32 month;
                Int32 day;
                cur = readNumber4<Int32, NeedCheckSpace::No>(cur, end, fragment, year);
                cur = assertChar<NeedCheckSpace::No>(cur, end, '-', fragment);
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, month);
                cur = assertChar<NeedCheckSpace::No>(cur, end, '-', fragment);
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, day);

                date.setYear(year);
                date.setMonth(month);
                date.setDayOfMonth(day);
                return cur;
            }

            static Pos mysqlISO8601Year2(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year2;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, year2);
                date.setYear2(year2);
                return cur;
            }

            static Pos mysqlISO8601Year4(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year;
                cur = readNumber4<Int32, NeedCheckSpace::Yes>(cur, end, fragment, year);
                date.setYear(year);
                return cur;
            }

            static Pos mysqlDayOfYear(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 day_of_year;
                cur = readNumber3<Int32, NeedCheckSpace::Yes>(cur, end, fragment, day_of_year);
                date.setDayOfYear(day_of_year);
                return cur;
            }

            static Pos mysqlDayOfWeek(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 1, "mysqlDayOfWeek requires size >= 1", fragment);
                date.setDayOfWeek(*cur - '0');
                ++cur;
                return cur;
            }

            static Pos mysqlISO8601Week(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 week;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, week);
                date.setWeek(week);
                return cur;
            }

            static Pos mysqlDayOfWeek0To6(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 1, "mysqlDayOfWeek requires size >= 1", fragment);

                Int32 day_of_week = *cur - '0';
                if (day_of_week == 0)
                    day_of_week = 7;

                date.setDayOfWeek(day_of_week);
                ++cur;
                return cur;
            }

            static Pos mysqlDayOfWeekTextLong(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 6, "mysqlDayOfWeekTextLong requires size >= 6", fragment);
                String text1(cur, 3);
                boost::to_lower(text1);
                auto it = dayOfWeekMap.find(text1);
                if (it == dayOfWeekMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse first part of fragment {} from {} because of unknown day of week text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1);
                cur += 3;

                size_t expected_remaining_size = it->second.first.size();
                checkSpace(cur, end, expected_remaining_size, "mysqlDayOfWeekTextLong requires the second parg size >= " + std::to_string(expected_remaining_size), fragment);
                String text2(cur, expected_remaining_size);
                boost::to_lower(text2);
                if (text2 != it->second.first)
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse second part of fragment {} from {} because of unknown day of week text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1 + text2);
                cur += expected_remaining_size;

                date.setDayOfWeek(it->second.second);
                return cur;
            }

            static Pos mysqlYear2(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year2;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, year2);
                date.setYear2(year2);
                return cur;
            }

            static Pos mysqlYear4(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year;
                cur = readNumber4<Int32, NeedCheckSpace::Yes>(cur, end, fragment, year);
                date.setYear(year);
                return cur;
            }

            static Pos mysqlTimezoneOffset(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 5, "mysqlTimezoneOffset requires size >= 5", fragment);

                Int32 sign;
                if (*cur == '-')
                    sign = -1;
                else if (*cur == '+')
                    sign = 1;
                else
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because of unknown sign time zone offset: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        std::string_view(cur, 1));
                ++cur;

                Int32 hour;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, hour);

                Int32 minute;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, minute);

                date.has_time_zone_offset = true;
                date.time_zone_offset = sign * (hour * 3600 + minute * 60);
                return cur;
            }

            static Pos mysqlMinute(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 minute;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, minute);
                date.setMinute(minute);
                return cur;
            }

            static Pos mysqlAMPM(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 2, "mysqlAMPM requires size >= 2", fragment);

                String text(cur, 2);
                boost::to_lower(text);
                date.setAMPM(text);
                cur += 2;
                return cur;
            }

            static Pos mysqlHHMM12(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 8, "mysqlHHMM12 requires size >= 8", fragment);

                Int32 hour;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, hour);
                cur = assertChar<NeedCheckSpace::No>(cur, end, ':', fragment);
                date.setHour(hour, true, true);

                Int32 minute;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, minute);
                cur = assertChar<NeedCheckSpace::No>(cur, end, ' ', fragment);
                date.setMinute(minute);

                cur = mysqlAMPM(cur, end, fragment, date);
                return cur;
            }

            static Pos mysqlHHMM24(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 5, "mysqlHHMM24 requires size >= 5", fragment);

                Int32 hour;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, hour);
                cur = assertChar<NeedCheckSpace::No>(cur, end, ':', fragment);
                date.setHour(hour, false, false);

                Int32 minute;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, minute);
                date.setMinute(minute);
                return cur;
            }

            static Pos mysqlSecond(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 second;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, second);
                date.setSecond(second);
                return cur;
            }

            static Pos mysqlMicrosecond(Pos cur, Pos end, const String & fragment, DateTime & /*date*/)
            {
                checkSpace(cur, end, 6, "mysqlMicrosecond requires size >= 6", fragment);

                for (size_t i = 0; i < 6; ++i)
                    cur = assertNumber<NeedCheckSpace::No>(cur, end, fragment);

                return cur;
            }

            static Pos mysqlISO8601Time(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 8, "mysqlISO8601Time requires size >= 8", fragment);

                Int32 hour;
                Int32 minute;
                Int32 second;
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, hour);
                cur = assertChar<NeedCheckSpace::No>(cur, end, ':', fragment);
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, minute);
                cur = assertChar<NeedCheckSpace::No>(cur, end, ':', fragment);
                cur = readNumber2<Int32, NeedCheckSpace::No>(cur, end, fragment, second);

                date.setHour(hour, false, false);
                date.setMinute(minute);
                date.setSecond(second);
                return cur;
            }

            static Pos mysqlHour12(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, hour);
                date.setHour(hour, true, true);
                return cur;
            }

            static Pos mysqlHour24(Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumber2<Int32, NeedCheckSpace::Yes>(cur, end, fragment, hour);
                date.setHour(hour, false, false);
                return cur;
            }

            static Pos readNumberWithVariableLength(
                Pos cur,
                Pos end,
                bool allow_negative,
                bool allow_plus_sign,
                bool is_year,
                size_t repetitions,
                size_t max_digits_to_read,
                const String & fragment,
                Int32 & result)
            {

                bool negative = false;
                if (allow_negative && cur < end && *cur == '-')
                {
                    negative = true;
                    ++cur;
                }
                else if (allow_plus_sign && cur < end && *cur == '+')
                {
                    negative = false;
                    ++cur;
                }

                Int64 number = 0;
                const Pos start = cur;

                /// Avoid integer overflow in (*)
                if (max_digits_to_read >= std::numeric_limits<decltype(number)>::digits10) [[unlikely]]
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because max_digits_to_read is too big",
                        fragment,
                        std::string_view(start, cur - start));

                if (is_year && repetitions == 2)
                {
                    // If abbreviated two year digit is provided in format string, try to read
                    // in two digits of year and convert to appropriate full length year The
                    // two-digit mapping is as follows: [00, 69] -> [2000, 2069]
                    //                                  [70, 99] -> [1970, 1999]
                    // If more than two digits are provided, then simply read in full year
                    // normally without conversion
                    size_t count = 0;
                    while (cur < end && cur < start + max_digits_to_read && *cur >= '0' && *cur <= '9')
                    {
                        number = number * 10 + (*cur - '0'); /// (*)
                        ++cur;
                        ++count;
                    }
                    if (count == 2)
                    {
                        if (number >= 70)
                            number += 1900;
                        else if (number >= 0 && number < 70)
                            number += 2000;
                    }
                    else
                    {
                        while (cur < end && cur < start + max_digits_to_read && *cur >= '0' && *cur <= '9')
                        {
                            number = number * 10 + (*cur - '0'); /// (*)
                            ++cur;
                        }
                    }
                }
                else
                {
                    while (cur < end && cur < start + max_digits_to_read && *cur >= '0' && *cur <= '9')
                    {
                        number = number * 10 + (*cur - '0');
                        ++cur;
                    }
                }

                if (negative)
                    number *= -1;

                /// Need to have read at least one digit.
                if (cur == start) [[unlikely]]
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because read number failed",
                        fragment,
                        std::string_view(cur, end - cur));

                /// Check if number exceeds the range of Int32
                if (number < std::numeric_limits<Int32>::min() || number > std::numeric_limits<Int32>::max()) [[unlikely]]
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because number is out of range of Int32",
                        fragment,
                        std::string_view(start, cur - start));

                result = static_cast<Int32>(number);

                return cur;
            }

            static Pos jodaEra(int, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 2, "jodaEra requires size >= 2", fragment);

                String era(cur, 2);
                boost::to_lower(era);
                date.setEra(era);
                cur += 2;
                return cur;
            }

            static Pos jodaCenturyOfEra(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 century;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, repetitions, fragment, century);
                date.setCentury(century);
                return cur;
            }

            static Pos jodaYearOfEra(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year_of_era;
                cur = readNumberWithVariableLength(cur, end, false, false, true, repetitions, repetitions, fragment, year_of_era);
                date.setYear(year_of_era, true);
                return cur;
            }

            static Pos jodaWeekYear(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 week_year;
                cur = readNumberWithVariableLength(cur, end, true, true, true, repetitions, repetitions, fragment, week_year);
                date.setYear(week_year, false, true);
                return cur;
            }

            static Pos jodaWeekOfWeekYear(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 week;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, week);
                date.setWeek(week);
                return cur;
            }

            static Pos jodaDayOfWeek1Based(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 day_of_week;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, repetitions, fragment, day_of_week);
                date.setDayOfWeek(day_of_week);
                return cur;
            }

            static Pos
            jodaDayOfWeekText(size_t /*min_represent_digits*/, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 3, "jodaDayOfWeekText requires size >= 3", fragment);

                String text1(cur, 3);
                boost::to_lower(text1);
                auto it = dayOfWeekMap.find(text1);
                if (it == dayOfWeekMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because of unknown day of week text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1);
                cur += 3;
                date.setDayOfWeek(it->second.second);

                size_t expected_remaining_size = it->second.first.size();
                if (cur + expected_remaining_size <= end)
                {
                    String text2(cur, expected_remaining_size);
                    boost::to_lower(text2);
                    if (text2 == it->second.first)
                    {
                        cur += expected_remaining_size;
                        return cur;
                    }
                }
                return cur;
            }

            static Pos jodaYear(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 year;
                cur = readNumberWithVariableLength(cur, end, true, true, true, repetitions, repetitions, fragment, year);
                date.setYear(year);
                return cur;
            }

            static Pos jodaDayOfYear(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 day_of_year;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 3uz), fragment, day_of_year);
                date.setDayOfYear(day_of_year);
                return cur;
            }

            static Pos jodaMonthOfYear(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 month;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, 2, fragment, month);
                date.setMonth(month);
                return cur;
            }

            static Pos jodaMonthOfYearText(int, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 3, "jodaMonthOfYearText requires size >= 3", fragment);
                String text1(cur, 3);
                boost::to_lower(text1);
                auto it = monthMap.find(text1);
                if (it == monthMap.end())
                    throw Exception(
                        ErrorCodes::CANNOT_PARSE_DATETIME,
                        "Unable to parse fragment {} from {} because of unknown month of year text: {}",
                        fragment,
                        std::string_view(cur, end - cur),
                        text1);
                cur += 3;
                date.setMonth(it->second.second);

                size_t expected_remaining_size = it->second.first.size();
                if (cur + expected_remaining_size <= end)
                {
                    String text2(cur, expected_remaining_size);
                    boost::to_lower(text2);
                    if (text2 == it->second.first)
                    {
                        cur += expected_remaining_size;
                        return cur;
                    }
                }
                return cur;
            }

            static Pos jodaDayOfMonth(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 day_of_month;
                cur = readNumberWithVariableLength(
                    cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, day_of_month);
                date.setDayOfMonth(day_of_month);
                return cur;
            }

            static Pos jodaHalfDayOfDay(int, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                checkSpace(cur, end, 2, "jodaHalfDayOfDay requires size >= 2", fragment);

                String text(cur, 2);
                boost::to_lower(text);
                date.setAMPM(text);
                cur += 2;
                return cur;
            }

            static Pos jodaHourOfHalfDay(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, hour);
                date.setHour(hour, true, false);
                return cur;
            }

            static Pos jodaClockHourOfHalfDay(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, hour);
                date.setHour(hour, true, true);
                return cur;
            }

            static Pos jodaHourOfDay(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, hour);
                date.setHour(hour, false, false);
                return cur;
            }

            static Pos jodaClockHourOfDay(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 hour;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, hour);
                date.setHour(hour, false, true);
                return cur;
            }

            static Pos jodaMinuteOfHour(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 minute;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, minute);
                date.setMinute(minute);
                return cur;
            }

            static Pos jodaSecondOfMinute(size_t repetitions, Pos cur, Pos end, const String & fragment, DateTime & date)
            {
                Int32 second;
                cur = readNumberWithVariableLength(cur, end, false, false, false, repetitions, std::max(repetitions, 2uz), fragment, second);
                date.setSecond(second);
                return cur;
            }
        };

        std::vector<Instruction> parseFormat(const String & format) const
        {
            static_assert(
                parse_syntax == ParseSyntax::MySQL || parse_syntax == ParseSyntax::Joda,
                "parse syntax must be one of MySQL or Joda");

            if constexpr (parse_syntax == ParseSyntax::MySQL)
                return parseMysqlFormat(format);
            else
                return parseJodaFormat(format);
        }

        std::vector<Instruction> parseMysqlFormat(const String & format) const
        {
#define ACTION_ARGS(func) &(func), #func, std::string_view(pos - 1, 2)

            Pos pos = format.data();
            Pos end = format.data() + format.size();

            std::vector<Instruction> instructions;
            while (true)
            {
                Pos next_percent_pos = find_first_symbols<'%'>(pos, end);

                if (next_percent_pos < end)
                {
                    if (pos < next_percent_pos)
                        instructions.emplace_back(String(pos, next_percent_pos - pos));

                    pos = next_percent_pos + 1;
                    if (pos >= end)
                        throw Exception(
                            ErrorCodes::BAD_ARGUMENTS, "'%' must not be the last character in the format string, use '%%' instead");

                    switch (*pos)
                    {
                        // Abbreviated weekday [Mon...Sun]
                        case 'a':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfWeekTextShort));
                            break;

                        // Abbreviated month [Jan...Dec]
                        case 'b':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMonthOfYearTextShort));
                            break;

                        // Month as a decimal number (01-12)
                        case 'c':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMonth));
                            break;

                        // Year, divided by 100, zero-padded
                        case 'C':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlCentury));
                            break;

                        // Day of month, zero-padded (01-31)
                        case 'd':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfMonth));
                            break;

                        // Short MM/DD/YY date, equivalent to %m/%d/%y
                        case 'D':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlAmericanDate));
                            break;

                        // Day of month, space-padded ( 1-31)  23
                        case 'e':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfMonthSpacePadded));
                            break;

                        // Fractional seconds
                        case 'f':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMicrosecond));
                            break;

                        // Short YYYY-MM-DD date, equivalent to %Y-%m-%d   2001-08-23
                        case 'F':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlISO8601Date));
                            break;

                        // Last two digits of year of ISO 8601 week number (see %G)
                        case 'g':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlISO8601Year2));
                            break;

                        // Year of ISO 8601 week number (see %V)
                        case 'G':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlISO8601Year4));
                            break;

                        // Day of the year (001-366)   235
                        case 'j':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfYear));
                            break;

                        // Month as a decimal number (01-12)
                        case 'm':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMonth));
                            break;

                        // ISO 8601 weekday as number with Monday as 1 (1-7)
                        case 'u':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfWeek));
                            break;

                        // ISO 8601 week number (01-53)
                        case 'V':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlISO8601Week));
                            break;

                        // Weekday as a integer number with Sunday as 0 (0-6)  4
                        case 'w':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfWeek0To6));
                            break;

                        // Full weekday [Monday...Sunday]
                        case 'W':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlDayOfWeekTextLong));
                            break;

                        // Two digits year
                        case 'y':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlYear2));
                            break;

                        // Four digits year
                        case 'Y':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlYear4));
                            break;

                        // Quarter (1-4)
                        case 'Q':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for quarter");
                            break;

                        // Offset from UTC timezone as +hhmm or -hhmm
                        case 'z':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlTimezoneOffset));
                            break;

                        // Depending on a setting
                        // - Full month [January...December]
                        // - Minute (00-59) OR
                        case 'M':
                            if (mysql_M_is_month_name)
                                instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMonthOfYearTextLong));
                            else
                                instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMinute));
                            break;

                        // AM or PM
                        case 'p':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlAMPM));
                            break;

                        // 12-hour HH:MM time, equivalent to %h:%i %p 2:55 PM
                        case 'r':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHHMM12));
                            break;

                        // 24-hour HH:MM time, equivalent to %H:%i 14:55
                        case 'R':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHHMM24));
                            break;

                        // Seconds
                        case 's':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlSecond));
                            break;

                        // Seconds
                        case 'S':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlSecond));
                            break;

                        // ISO 8601 time format (HH:MM:SS), equivalent to %H:%i:%S 14:55:02
                        case 'T':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlISO8601Time));
                            break;

                        // Hour in 12h format (01-12)
                        case 'h':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHour12));
                            break;

                        // Hour in 24h format (00-23)
                        case 'H':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHour24));
                            break;

                        // Minute of hour range [0, 59]
                        case 'i':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlMinute));
                            break;

                        // Hour in 12h format (01-12)
                        case 'I':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHour12));
                            break;

                        // Hour in 24h format (00-23)
                        case 'k':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHour24));
                            break;

                        // Hour in 12h format (01-12)
                        case 'l':
                            instructions.emplace_back(ACTION_ARGS(Instruction::mysqlHour12));
                            break;

                        case 't':
                            instructions.emplace_back("\t");
                            break;

                        case 'n':
                            instructions.emplace_back("\n");
                            break;

                        // Escaped literal characters.
                        case '%':
                            instructions.emplace_back("%");
                            break;

                        /// Unimplemented

                        /// Fractional seconds
                        case 'U':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for WEEK (Sun-Sat)");
                        case 'v':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for WEEK (Mon-Sun)");
                        case 'x':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for YEAR for week (Mon-Sun)");
                        case 'X':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for YEAR for week (Sun-Sat)");
                        default:
                            throw Exception(
                                ErrorCodes::BAD_ARGUMENTS,
                                "Incorrect syntax '{}', symbol is not supported '{}' for function {}",
                                format,
                                *pos,
                                getName());
                    }

                    ++pos;
                }
                else
                {
                    /// Handle characters after last %
                    if (pos < end)
                        instructions.emplace_back(String(pos, end - pos));
                    break;
                }
            }
            return instructions;
#undef ACTION_ARGS
        }

        std::vector<Instruction> parseJodaFormat(const String & format) const
        {
#define ACTION_ARGS_WITH_BIND(func, arg) std::bind_front(&(func), (arg)), #func, std::string_view(cur_token, repetitions)

            Pos pos = format.data();
            Pos end = format.data() + format.size();

            std::vector<Instruction> instructions;
            while (pos < end)
            {
                Pos cur_token = pos;

                // Literal case
                if (*cur_token == '\'')
                {
                    // Case 1: 2 consecutive single quote
                    if (pos + 1 < end && *(pos + 1) == '\'')
                    {
                        instructions.emplace_back(String(cur_token, 1));
                        pos += 2;
                    }
                    else
                    {
                        // Case 2: find closing single quote
                        Int64 count = numLiteralChars(cur_token + 1, end);
                        if (count == -1)
                            throw Exception(ErrorCodes::BAD_ARGUMENTS, "No closing single quote for literal");
                        else
                        {
                            for (Int64 i = 1; i <= count; i++)
                            {
                                instructions.emplace_back(String(cur_token + i, 1));
                                if (*(cur_token + i) == '\'')
                                    i += 1;
                            }
                            pos += count + 2;
                        }
                    }
                }
                else
                {
                    size_t repetitions = 1;
                    ++pos;
                    while (pos < end && *cur_token == *pos)
                    {
                        ++repetitions;
                        ++pos;
                    }
                    switch (*cur_token)
                    {
                        case 'G':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaEra, repetitions));
                            break;
                        case 'C':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaCenturyOfEra, repetitions));
                            break;
                        case 'Y':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaYearOfEra, repetitions));
                            break;
                        case 'x':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaWeekYear, repetitions));
                            break;
                        case 'w':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaWeekOfWeekYear, repetitions));
                            break;
                        case 'e':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaDayOfWeek1Based, repetitions));
                            break;
                        case 'E':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaDayOfWeekText, repetitions));
                            break;
                        case 'y':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaYear, repetitions));
                            break;
                        case 'D':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaDayOfYear, repetitions));
                            break;
                        case 'M':
                            if (repetitions <= 2)
                                instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaMonthOfYear, repetitions));
                            else
                                instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaMonthOfYearText, repetitions));
                            break;
                        case 'd':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaDayOfMonth, repetitions));
                            break;
                        case 'a':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaHalfDayOfDay, repetitions));
                            break;
                        case 'K':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaHourOfHalfDay, repetitions));
                            break;
                        case 'h':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaClockHourOfHalfDay, repetitions));
                            break;
                        case 'H':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaHourOfDay, repetitions));
                            break;
                        case 'k':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaClockHourOfDay, repetitions));
                            break;
                        case 'm':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaMinuteOfHour, repetitions));
                            break;
                        case 's':
                            instructions.emplace_back(ACTION_ARGS_WITH_BIND(Instruction::jodaSecondOfMinute, repetitions));
                            break;
                        case 'S':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for fractional seconds");
                        case 'z':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for timezone");
                        case 'Z':
                            throw Exception(ErrorCodes::NOT_IMPLEMENTED, "format is not supported for timezone offset id");
                        default:
                            if (isalpha(*cur_token))
                                throw Exception(
                                    ErrorCodes::NOT_IMPLEMENTED, "format is not supported for {}", String(cur_token, repetitions));

                            instructions.emplace_back(String(cur_token, pos - cur_token));
                            break;
                    }
                }
            }
            return instructions;
#undef ACTION_ARGS_WITH_BIND
        }


        String getFormat(const ColumnsWithTypeAndName & arguments) const
        {
            const auto * format_column = checkAndGetColumnConst<ColumnString>(arguments[1].column.get());
            if (!format_column)
                throw Exception(
                    ErrorCodes::ILLEGAL_COLUMN,
                    "Illegal column {} of second ('format') argument of function {}. Must be constant string.",
                    arguments[1].column->getName(),
                    getName());
            return format_column->getValue<String>();
        }

        const DateLUTImpl & getTimeZone(const ColumnsWithTypeAndName & arguments) const
        {
            if (arguments.size() < 3)
                return DateLUT::instance();

            const auto * col = checkAndGetColumnConst<ColumnString>(arguments[2].column.get());
            if (!col)
                throw Exception(
                    ErrorCodes::ILLEGAL_COLUMN,
                    "Illegal column {} of third ('timezone') argument of function {}. Must be constant String.",
                    arguments[2].column->getName(),
                    getName());

            String time_zone = col->getValue<String>();
            return DateLUT::instance(time_zone);
        }
    };

    struct NameParseDateTime
    {
        static constexpr auto name = "parseDateTime";
    };

    struct NameParseDateTimeOrZero
    {
        static constexpr auto name = "parseDateTimeOrZero";
    };

    struct NameParseDateTimeOrNull
    {
        static constexpr auto name = "parseDateTimeOrNull";
    };

    struct NameParseDateTimeInJodaSyntax
    {
        static constexpr auto name = "parseDateTimeInJodaSyntax";
    };

    struct NameParseDateTimeInJodaSyntaxOrZero
    {
        static constexpr auto name = "parseDateTimeInJodaSyntaxOrZero";
    };

    struct NameParseDateTimeInJodaSyntaxOrNull
    {
        static constexpr auto name = "parseDateTimeInJodaSyntaxOrNull";
    };

    using FunctionParseDateTime = FunctionParseDateTimeImpl<NameParseDateTime, ParseSyntax::MySQL, ErrorHandling::Exception>;
    using FunctionParseDateTimeOrZero = FunctionParseDateTimeImpl<NameParseDateTimeOrZero, ParseSyntax::MySQL, ErrorHandling::Zero>;
    using FunctionParseDateTimeOrNull = FunctionParseDateTimeImpl<NameParseDateTimeOrNull, ParseSyntax::MySQL, ErrorHandling::Null>;
    using FunctionParseDateTimeInJodaSyntax = FunctionParseDateTimeImpl<NameParseDateTimeInJodaSyntax, ParseSyntax::Joda, ErrorHandling::Exception>;
    using FunctionParseDateTimeInJodaSyntaxOrZero = FunctionParseDateTimeImpl<NameParseDateTimeInJodaSyntaxOrZero, ParseSyntax::Joda, ErrorHandling::Zero>;
    using FunctionParseDateTimeInJodaSyntaxOrNull = FunctionParseDateTimeImpl<NameParseDateTimeInJodaSyntaxOrNull, ParseSyntax::Joda, ErrorHandling::Null>;
}

REGISTER_FUNCTION(ParseDateTime)
{
    factory.registerFunction<FunctionParseDateTime>();
    factory.registerAlias("TO_UNIXTIME", FunctionParseDateTime::name);
    factory.registerFunction<FunctionParseDateTimeOrZero>();
    factory.registerFunction<FunctionParseDateTimeOrNull>();
    factory.registerAlias("str_to_date", FunctionParseDateTimeOrNull::name, FunctionFactory::CaseInsensitive);

    factory.registerFunction<FunctionParseDateTimeInJodaSyntax>();
    factory.registerFunction<FunctionParseDateTimeInJodaSyntaxOrZero>();
    factory.registerFunction<FunctionParseDateTimeInJodaSyntaxOrNull>();
}


}